blob: 46f741d15940a7bead32d30f2d9532265e9e7376 [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
drh0fcef5e2005-07-19 17:38:22 +000036/* Forward reference
37*/
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;
drhc63367e2013-06-10 20:46:50 +000048
49/*
50** Cost X is tracked as 10*log2(X) stored in a 16-bit integer. The
drh3b48e8c2013-06-12 20:18:16 +000051** maximum cost for ordinary tables is 64*(2**63) which becomes 6900.
52** (Virtual tables can return a larger cost, but let's assume they do not.)
53** So all costs can be stored in a 16-bit unsigned integer without risk
54** of overflow.
55**
56** Costs are estimates, so don't go to the computational trouble to compute
57** 10*log2(X) exactly. Instead, a close estimate is used. Any value of
58** X<=1 is stored as 0. X=2 is 10. X=3 is 16. X=1000 is 99. etc.
59**
drhe1e2e9a2013-06-13 15:16:53 +000060** The tool/wherecosttest.c source file implements a command-line program
61** that will convert between WhereCost to integers and do addition and
62** multiplication on WhereCost values. That command-line program is a
63** useful utility to have around when working with this module.
drhc63367e2013-06-10 20:46:50 +000064*/
65typedef unsigned short int WhereCost;
drhf1b5f5b2013-05-02 00:15:01 +000066
67/*
drh3b48e8c2013-06-12 20:18:16 +000068** This object contains information needed to implement a single nestd
69** loop in WHERE clause.
drh6f328482013-06-05 23:39:34 +000070**
drh3b48e8c2013-06-12 20:18:16 +000071** Contrast this object with WhereLoop. This object describes the
72** implementation of the loop. WhereLoop describes the algorithm.
73** This object contains a pointer to the WhereLoop algorithm as one of
74** its elements.
75**
76** The WhereInfo object contains a single instance of this object for
77** each term in the FROM clause (which is to say, for each of the
78** nested loops as implemented). The order of WhereLevel objects determines
79** the loop nested order, with WhereInfo.a[0] being the outer loop and
80** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
drh6f328482013-06-05 23:39:34 +000081*/
82struct WhereLevel {
83 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
84 int iTabCur; /* The VDBE cursor used to access the table */
85 int iIdxCur; /* The VDBE cursor used to access pIdx */
86 int addrBrk; /* Jump here to break out of the loop */
87 int addrNxt; /* Jump here to start the next IN combination */
88 int addrCont; /* Jump here to continue with the next loop cycle */
89 int addrFirst; /* First instruction of interior of the loop */
drhe217efc2013-06-12 03:48:41 +000090 u8 iFrom; /* Which entry in the FROM clause */
drh6f328482013-06-05 23:39:34 +000091 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
92 int p1, p2; /* Operands of the opcode used to ends the loop */
drh37ca0482013-06-12 17:17:45 +000093 union { /* Information that depends on pWLoop->wsFlags */
drh6f328482013-06-05 23:39:34 +000094 struct {
95 int nIn; /* Number of entries in aInLoop[] */
96 struct InLoop {
97 int iCur; /* The VDBE cursor used by this IN operator */
98 int addrInTop; /* Top of the IN loop */
99 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
100 } *aInLoop; /* Information about each nested IN operator */
drh37ca0482013-06-12 17:17:45 +0000101 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
drh6f328482013-06-05 23:39:34 +0000102 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
103 } u;
104 struct WhereLoop *pWLoop; /* The selected WhereLoop object */
105};
106
107/*
drh3b48e8c2013-06-12 20:18:16 +0000108** Each instance of this object represents an algorithm for evaluating one
109** term of a join. Every term of the FROM clause will have at least
110** one corresponding WhereLoop object (unless INDEXED BY constraints
111** prevent a query solution - which is an error) and many terms of the
112** FROM clause will have multiple WhereLoop objects, each describing a
113** potential way of implementing that FROM-clause term, together with
114** dependencies and cost estimates for using the chosen algorithm.
115**
116** Query planning consists of building up a collection of these WhereLoop
117** objects, then computing a particular sequence of WhereLoop objects, with
118** one WhereLoop object per FROM clause term, that satisfy all dependencies
119** and that minimize the overall cost.
drhf1b5f5b2013-05-02 00:15:01 +0000120*/
121struct WhereLoop {
122 Bitmask prereq; /* Bitmask of other loops that must run first */
drha18f3d22013-05-08 03:05:41 +0000123 Bitmask maskSelf; /* Bitmask identifying table iTab */
drhd15cb172013-05-21 19:23:10 +0000124#ifdef SQLITE_DEBUG
125 char cId; /* Symbolic ID of this loop for debugging use */
126#endif
drh7ba39a92013-05-30 17:43:19 +0000127 u8 iTab; /* Position in FROM clause of table for this loop */
drh23f98da2013-05-21 15:52:07 +0000128 u8 iSortIdx; /* Sorting index number. 0==None */
drh4efc9292013-06-06 23:02:03 +0000129 WhereCost rSetup; /* One-time setup cost (ex: create transient index) */
130 WhereCost rRun; /* Cost of running each loop */
131 WhereCost nOut; /* Estimated number of output rows */
drh5346e952013-05-08 14:14:26 +0000132 union {
133 struct { /* Information for internal btree tables */
134 int nEq; /* Number of equality constraints */
135 Index *pIndex; /* Index used, or NULL */
136 } btree;
drh6b7157b2013-05-10 02:00:35 +0000137 struct { /* Information for virtual tables */
drh5346e952013-05-08 14:14:26 +0000138 int idxNum; /* Index number */
drh6b7157b2013-05-10 02:00:35 +0000139 u8 needFree; /* True if sqlite3_free(idxStr) is needed */
140 u8 isOrdered; /* True if satisfies ORDER BY */
drh3bd26f02013-05-24 14:52:03 +0000141 u16 omitMask; /* Terms that may be omitted */
drh5346e952013-05-08 14:14:26 +0000142 char *idxStr; /* Index identifier string */
143 } vtab;
144 } u;
drha2014152013-06-07 00:29:23 +0000145 u32 wsFlags; /* WHERE_* flags describing the plan */
146 u16 nLTerm; /* Number of entries in aLTerm[] */
147 /**** whereLoopXfer() copies fields above ***********************/
148# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
149 u16 nLSlot; /* Number of slots allocated for aLTerm[] */
drh4efc9292013-06-06 23:02:03 +0000150 WhereTerm **aLTerm; /* WhereTerms used */
drhf1b5f5b2013-05-02 00:15:01 +0000151 WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
drh4efc9292013-06-06 23:02:03 +0000152 WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
drhf1b5f5b2013-05-02 00:15:01 +0000153};
154
drh4efc9292013-06-06 23:02:03 +0000155/* Forward declaration of methods */
156static int whereLoopResize(sqlite3*, WhereLoop*, int);
157
drhf1b5f5b2013-05-02 00:15:01 +0000158/*
159** Each instance of this object holds a sequence of WhereLoop objects
drh3b48e8c2013-06-12 20:18:16 +0000160** that implement some or all of a query plan.
161**
162** Think of each WhereLoop objects as a node in a graph, which arcs
163** showing dependences and costs for travelling between nodes. (That is
164** not a completely accurate description because WhereLoop costs are a
165** vector, not a scalar, and because dependences are many-to-one, not
166** one-to-one as are graph nodes. But it is a useful visualization aid.)
167** Then a WherePath object is a path through the graph that visits some
168** or all of the WhereLoop objects once.
169**
170** The "solver" works by creating the N best WherePath objects of length
171** 1. Then using those as a basis to compute the N best WherePath objects
172** of length 2. And so forth until the length of WherePaths equals the
173** number of nodes in the FROM clause. The best (lowest cost) WherePath
174** at the end is the choosen query plan.
drhf1b5f5b2013-05-02 00:15:01 +0000175*/
176struct WherePath {
177 Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
drh319f6772013-05-14 15:31:07 +0000178 Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
drh4efc9292013-06-06 23:02:03 +0000179 WhereCost nRow; /* Estimated number of rows generated by this path */
180 WhereCost rCost; /* Total cost of this path */
drh6b7157b2013-05-10 02:00:35 +0000181 u8 isOrdered; /* True if this path satisfies ORDER BY */
182 u8 isOrderedValid; /* True if the isOrdered field is valid */
drha18f3d22013-05-08 03:05:41 +0000183 WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
drhf1b5f5b2013-05-02 00:15:01 +0000184};
drh0aa74ed2005-07-16 13:33:20 +0000185
186/*
drh75897232000-05-29 14:26:00 +0000187** The query generator uses an array of instances of this structure to
188** help it analyze the subexpressions of the WHERE clause. Each WHERE
drh61495262009-04-22 15:32:59 +0000189** clause subexpression is separated from the others by AND operators,
190** usually, or sometimes subexpressions separated by OR.
drh51669862004-12-18 18:40:26 +0000191**
drh0fcef5e2005-07-19 17:38:22 +0000192** All WhereTerms are collected into a single WhereClause structure.
193** The following identity holds:
drh51669862004-12-18 18:40:26 +0000194**
drh0fcef5e2005-07-19 17:38:22 +0000195** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
drh51669862004-12-18 18:40:26 +0000196**
drh0fcef5e2005-07-19 17:38:22 +0000197** When a term is of the form:
198**
199** X <op> <expr>
200**
201** where X is a column name and <op> is one of certain operators,
drh700a2262008-12-17 19:22:15 +0000202** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
203** cursor number and column number for X. WhereTerm.eOperator records
drh51147ba2005-07-23 22:59:55 +0000204** the <op> using a bitmask encoding defined by WO_xxx below. The
205** use of a bitmask encoding for the operator allows us to search
206** quickly for terms that match any of several different operators.
drh0fcef5e2005-07-19 17:38:22 +0000207**
drh700a2262008-12-17 19:22:15 +0000208** A WhereTerm might also be two or more subterms connected by OR:
209**
210** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
211**
212** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
213** and the WhereTerm.u.pOrInfo field points to auxiliary information that
214** is collected about the
215**
216** If a term in the WHERE clause does not match either of the two previous
217** categories, then eOperator==0. The WhereTerm.pExpr field is still set
218** to the original subexpression content and wtFlags is set up appropriately
219** but no other fields in the WhereTerm object are meaningful.
220**
221** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
drh111a6a72008-12-21 03:51:16 +0000222** but they do so indirectly. A single WhereMaskSet structure translates
drh51669862004-12-18 18:40:26 +0000223** cursor number into bits and the translated bit is stored in the prereq
224** fields. The translation is used in order to maximize the number of
225** bits that will fit in a Bitmask. The VDBE cursor numbers might be
226** spread out over the non-negative integers. For example, the cursor
drh111a6a72008-12-21 03:51:16 +0000227** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
drh51669862004-12-18 18:40:26 +0000228** translates these sparse cursor numbers into consecutive integers
229** beginning with 0 in order to make the best possible use of the available
230** bits in the Bitmask. So, in the example above, the cursor numbers
231** would be mapped into integers 0 through 7.
drh6a1e0712008-12-05 15:24:15 +0000232**
233** The number of terms in a join is limited by the number of bits
234** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
235** is only able to process joins with 64 or fewer tables.
drh75897232000-05-29 14:26:00 +0000236*/
drh0aa74ed2005-07-16 13:33:20 +0000237struct WhereTerm {
drh165be382008-12-05 02:36:33 +0000238 Expr *pExpr; /* Pointer to the subexpression that is this term */
drhec1724e2008-12-09 01:32:03 +0000239 int iParent; /* Disable pWC->a[iParent] when this term disabled */
240 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
drh700a2262008-12-17 19:22:15 +0000241 union {
242 int leftColumn; /* Column number of X in "X <op> <expr>" */
drh7a5bcc02013-01-16 17:08:58 +0000243 WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
244 WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
drh700a2262008-12-17 19:22:15 +0000245 } u;
drhb52076c2006-01-23 13:22:09 +0000246 u16 eOperator; /* A WO_xx value describing <op> */
drh165be382008-12-05 02:36:33 +0000247 u8 wtFlags; /* TERM_xxx bit flags. See below */
drh45b1ee42005-08-02 17:48:22 +0000248 u8 nChild; /* Number of children that must disable us */
drh0fcef5e2005-07-19 17:38:22 +0000249 WhereClause *pWC; /* The clause this term is part of */
drh165be382008-12-05 02:36:33 +0000250 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
251 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
drh75897232000-05-29 14:26:00 +0000252};
253
254/*
drh165be382008-12-05 02:36:33 +0000255** Allowed values of WhereTerm.wtFlags
drh0aa74ed2005-07-16 13:33:20 +0000256*/
drh633e6d52008-07-28 19:34:53 +0000257#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
drh6c30be82005-07-29 15:10:17 +0000258#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
259#define TERM_CODED 0x04 /* This term is already coded */
drh45b1ee42005-08-02 17:48:22 +0000260#define TERM_COPIED 0x08 /* Has a child */
drh700a2262008-12-17 19:22:15 +0000261#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
262#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
263#define TERM_OR_OK 0x40 /* Used during OR-clause processing */
drhfaacf172011-08-12 01:51:45 +0000264#ifdef SQLITE_ENABLE_STAT3
drh59b61882011-02-11 02:43:14 +0000265# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
266#else
drhd3ed7342011-09-21 00:09:41 +0000267# define TERM_VNULL 0x00 /* Disabled if not using stat3 */
drh59b61882011-02-11 02:43:14 +0000268#endif
drh0aa74ed2005-07-16 13:33:20 +0000269
270/*
drh1c8148f2013-05-04 20:25:23 +0000271** An instance of the WhereScan object is used as an iterator for locating
272** terms in the WHERE clause that are useful to the query planner.
273*/
274struct WhereScan {
drh1c8148f2013-05-04 20:25:23 +0000275 WhereClause *pOrigWC; /* Original, innermost WhereClause */
276 WhereClause *pWC; /* WhereClause currently being scanned */
drh7ba39a92013-05-30 17:43:19 +0000277 char *zCollName; /* Required collating sequence, if not NULL */
drh1c8148f2013-05-04 20:25:23 +0000278 char idxaff; /* Must match this affinity, if zCollName!=NULL */
279 unsigned char nEquiv; /* Number of entries in aEquiv[] */
280 unsigned char iEquiv; /* Next unused slot in aEquiv[] */
281 u32 opMask; /* Acceptable operators */
282 int k; /* Resume scanning at this->pWC->a[this->k] */
283 int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
284};
285
286/*
drh0aa74ed2005-07-16 13:33:20 +0000287** An instance of the following structure holds all information about a
288** WHERE clause. Mostly this is a container for one or more WhereTerms.
drh8871ef52011-10-07 13:33:10 +0000289**
290** Explanation of pOuter: For a WHERE clause of the form
291**
292** a AND ((b AND c) OR (d AND e)) AND f
293**
294** There are separate WhereClause objects for the whole clause and for
295** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
296** subclauses points to the WhereClause object for the whole clause.
drh0aa74ed2005-07-16 13:33:20 +0000297*/
drh0aa74ed2005-07-16 13:33:20 +0000298struct WhereClause {
drh70d18342013-06-06 19:16:33 +0000299 WhereInfo *pWInfo; /* WHERE clause processing context */
drh8871ef52011-10-07 13:33:10 +0000300 WhereClause *pOuter; /* Outer conjunction */
drh29435252008-12-28 18:35:08 +0000301 u8 op; /* Split operator. TK_AND or TK_OR */
drh0aa74ed2005-07-16 13:33:20 +0000302 int nTerm; /* Number of terms */
303 int nSlot; /* Number of entries in a[] */
drh51147ba2005-07-23 22:59:55 +0000304 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
drh50d654d2009-06-03 01:24:54 +0000305#if defined(SQLITE_SMALL_STACK)
306 WhereTerm aStatic[1]; /* Initial static space for a[] */
307#else
308 WhereTerm aStatic[8]; /* Initial static space for a[] */
309#endif
drhe23399f2005-07-22 00:31:39 +0000310};
311
312/*
drh700a2262008-12-17 19:22:15 +0000313** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
314** a dynamically allocated instance of the following structure.
315*/
316struct WhereOrInfo {
drh111a6a72008-12-21 03:51:16 +0000317 WhereClause wc; /* Decomposition into subterms */
drh1a58fe02008-12-20 02:06:13 +0000318 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
drh700a2262008-12-17 19:22:15 +0000319};
320
321/*
322** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
323** a dynamically allocated instance of the following structure.
324*/
325struct WhereAndInfo {
drh29435252008-12-28 18:35:08 +0000326 WhereClause wc; /* The subexpression broken out */
drh700a2262008-12-17 19:22:15 +0000327};
328
329/*
drh6a3ea0e2003-05-02 14:32:12 +0000330** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000331** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000332**
333** The VDBE cursor numbers are small integers contained in
334** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
335** clause, the cursor numbers might not begin with 0 and they might
336** contain gaps in the numbering sequence. But we want to make maximum
337** use of the bits in our bitmasks. This structure provides a mapping
338** from the sparse cursor numbers into consecutive integers beginning
339** with 0.
340**
drh111a6a72008-12-21 03:51:16 +0000341** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
drh51669862004-12-18 18:40:26 +0000342** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
343**
344** For example, if the WHERE clause expression used these VDBE
drh111a6a72008-12-21 03:51:16 +0000345** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
drh51669862004-12-18 18:40:26 +0000346** would map those cursor numbers into bits 0 through 5.
347**
348** Note that the mapping is not necessarily ordered. In the example
349** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
350** 57->5, 73->4. Or one of 719 other combinations might be used. It
351** does not really matter. What is important is that sparse cursor
352** numbers all get mapped into bit numbers that begin with 0 and contain
353** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000354*/
drh111a6a72008-12-21 03:51:16 +0000355struct WhereMaskSet {
drh1398ad32005-01-19 23:24:50 +0000356 int n; /* Number of assigned cursor values */
danielk197723432972008-11-17 16:42:00 +0000357 int ix[BMS]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000358};
359
drh111a6a72008-12-21 03:51:16 +0000360/*
drh3b48e8c2013-06-12 20:18:16 +0000361** This object is a convenience wrapper holding all information needed
362** to construct WhereLoop objects for a particular query.
drh1c8148f2013-05-04 20:25:23 +0000363*/
364struct WhereLoopBuilder {
365 WhereInfo *pWInfo; /* Information about this WHERE */
drh1c8148f2013-05-04 20:25:23 +0000366 WhereClause *pWC; /* WHERE clause terms */
drh1c8148f2013-05-04 20:25:23 +0000367 ExprList *pOrderBy; /* ORDER BY clause */
368 WhereLoop *pNew; /* Template WhereLoop */
drhcf8fa7a2013-05-10 20:26:22 +0000369 WhereLoop *pBest; /* If non-NULL, store single best loop here */
drh1c8148f2013-05-04 20:25:23 +0000370};
371
372/*
drh70d18342013-06-06 19:16:33 +0000373** The WHERE clause processing routine has two halves. The
374** first part does the start of the WHERE loop and the second
375** half does the tail of the WHERE loop. An instance of
376** this structure is returned by the first half and passed
377** into the second half to give some continuity.
drh3b48e8c2013-06-12 20:18:16 +0000378**
379** An instance of this object holds the complete state of the query
380** planner.
drh70d18342013-06-06 19:16:33 +0000381*/
382struct WhereInfo {
383 Parse *pParse; /* Parsing and code generating context */
384 SrcList *pTabList; /* List of tables in the join */
385 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
386 ExprList *pDistinct; /* DISTINCT ON values, or NULL */
drh4f402f22013-06-11 18:59:38 +0000387 WhereLoop *pLoops; /* List of all WhereLoop objects */
drh70d18342013-06-06 19:16:33 +0000388 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
drh4f402f22013-06-11 18:59:38 +0000389 WhereCost nRowOut; /* Estimated number of output rows */
drh70d18342013-06-06 19:16:33 +0000390 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
drh4f402f22013-06-11 18:59:38 +0000391 u8 bOBSat; /* ORDER BY satisfied by indices */
drh70d18342013-06-06 19:16:33 +0000392 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
393 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
394 u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
395 int iTop; /* The very beginning of the WHERE loop */
396 int iContinue; /* Jump here to continue with next record */
397 int iBreak; /* Jump here to break out of the loop */
398 int nLevel; /* Number of nested loop */
drh4f402f22013-06-11 18:59:38 +0000399 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
drh70d18342013-06-06 19:16:33 +0000400 WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
401 WhereClause sWC; /* Decomposition of the WHERE clause */
drh70d18342013-06-06 19:16:33 +0000402 WhereLevel a[1]; /* Information about each nest loop in WHERE */
403};
404
405/*
drh3b48e8c2013-06-12 20:18:16 +0000406** Bitmasks for the operators on WhereTerm objects. These are all
407** operators that are of interest to the query planner. An
drh51147ba2005-07-23 22:59:55 +0000408** OR-ed combination of these values can be used when searching for
drh3b48e8c2013-06-12 20:18:16 +0000409** particular WhereTerms within a WhereClause.
drh51147ba2005-07-23 22:59:55 +0000410*/
drh165be382008-12-05 02:36:33 +0000411#define WO_IN 0x001
412#define WO_EQ 0x002
drh51147ba2005-07-23 22:59:55 +0000413#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
414#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
415#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
416#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
drh165be382008-12-05 02:36:33 +0000417#define WO_MATCH 0x040
418#define WO_ISNULL 0x080
drh700a2262008-12-17 19:22:15 +0000419#define WO_OR 0x100 /* Two or more OR-connected terms */
420#define WO_AND 0x200 /* Two or more AND-connected terms */
drh7a5bcc02013-01-16 17:08:58 +0000421#define WO_EQUIV 0x400 /* Of the form A==B, both columns */
drh534230c2011-01-22 00:10:45 +0000422#define WO_NOOP 0x800 /* This term does not restrict search space */
drh51147ba2005-07-23 22:59:55 +0000423
drhec1724e2008-12-09 01:32:03 +0000424#define WO_ALL 0xfff /* Mask of all possible WO_* values */
drh1a58fe02008-12-20 02:06:13 +0000425#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
drhec1724e2008-12-09 01:32:03 +0000426
drh51147ba2005-07-23 22:59:55 +0000427/*
drh3b48e8c2013-06-12 20:18:16 +0000428** These are definitions of bits in the WhereLoop.wsFlags field.
429** The particular combination of bits in each WhereLoop help to
430** determine the algorithm that WhereLoop represents.
drh51147ba2005-07-23 22:59:55 +0000431*/
drh6fa978d2013-05-30 19:29:19 +0000432#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR or x IN (...) or x IS NULL */
433#define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
434#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
435#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
drhef71c1f2013-06-04 12:58:02 +0000436#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
drh6fa978d2013-05-30 19:29:19 +0000437#define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
438#define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
439#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
440#define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
441#define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
442#define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
443#define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
444#define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
drh7699d1c2013-06-04 12:42:29 +0000445#define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
drh6fa978d2013-05-30 19:29:19 +0000446#define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
447#define WHERE_TEMP_INDEX 0x00004000 /* Uses an ephemeral index */
drh51147ba2005-07-23 22:59:55 +0000448
drhc63367e2013-06-10 20:46:50 +0000449
450/* Convert a WhereCost value (10 times log2(X)) into its integer value X.
drh3b48e8c2013-06-12 20:18:16 +0000451** A rough approximation is used. The value returned is not exact.
drhc63367e2013-06-10 20:46:50 +0000452*/
453static u64 whereCostToInt(WhereCost x){
454 u64 n;
drh12ffbc72013-06-13 14:51:53 +0000455 if( x<10 ) return 1;
drhc63367e2013-06-10 20:46:50 +0000456 n = x%10;
457 x /= 10;
458 if( n>=5 ) n -= 2;
459 else if( n>=1 ) n -= 1;
460 if( x>=3 ) return (n+8)<<(x-3);
461 return (n+8)>>(3-x);
462}
463
drh51147ba2005-07-23 22:59:55 +0000464/*
drh6f328482013-06-05 23:39:34 +0000465** Return the estimated number of output rows from a WHERE clause
466*/
drhc63367e2013-06-10 20:46:50 +0000467u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
468 return whereCostToInt(pWInfo->nRowOut);
drh6f328482013-06-05 23:39:34 +0000469}
470
471/*
472** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
473** WHERE clause returns outputs for DISTINCT processing.
474*/
475int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
476 return pWInfo->eDistinct;
477}
478
479/*
480** Return TRUE if the WHERE clause returns rows in ORDER BY order.
481** Return FALSE if the output needs to be sorted.
482*/
483int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
drh4f402f22013-06-11 18:59:38 +0000484 return pWInfo->bOBSat!=0;
drh6f328482013-06-05 23:39:34 +0000485}
486
487/*
488** Return the VDBE address or label to jump to in order to continue
489** immediately with the next row of a WHERE clause.
490*/
491int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
492 return pWInfo->iContinue;
493}
494
495/*
496** Return the VDBE address or label to jump to in order to break
497** out of a WHERE loop.
498*/
499int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
500 return pWInfo->iBreak;
501}
502
503/*
504** Return TRUE if an UPDATE or DELETE statement can operate directly on
505** the rowids returned by a WHERE clause. Return FALSE if doing an
506** UPDATE or DELETE might change subsequent WHERE clause results.
507*/
508int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
509 return pWInfo->okOnePass;
510}
511
512/*
drh0aa74ed2005-07-16 13:33:20 +0000513** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000514*/
drh7b4fc6a2007-02-06 13:26:32 +0000515static void whereClauseInit(
516 WhereClause *pWC, /* The WhereClause to be initialized */
drh70d18342013-06-06 19:16:33 +0000517 WhereInfo *pWInfo /* The WHERE processing context */
drh7b4fc6a2007-02-06 13:26:32 +0000518){
drh70d18342013-06-06 19:16:33 +0000519 pWC->pWInfo = pWInfo;
drh8871ef52011-10-07 13:33:10 +0000520 pWC->pOuter = 0;
drh0aa74ed2005-07-16 13:33:20 +0000521 pWC->nTerm = 0;
drhcad651e2007-04-20 12:22:01 +0000522 pWC->nSlot = ArraySize(pWC->aStatic);
drh0aa74ed2005-07-16 13:33:20 +0000523 pWC->a = pWC->aStatic;
524}
525
drh700a2262008-12-17 19:22:15 +0000526/* Forward reference */
527static void whereClauseClear(WhereClause*);
528
529/*
530** Deallocate all memory associated with a WhereOrInfo object.
531*/
532static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000533 whereClauseClear(&p->wc);
534 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000535}
536
537/*
538** Deallocate all memory associated with a WhereAndInfo object.
539*/
540static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000541 whereClauseClear(&p->wc);
542 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000543}
544
drh0aa74ed2005-07-16 13:33:20 +0000545/*
546** Deallocate a WhereClause structure. The WhereClause structure
547** itself is not freed. This routine is the inverse of whereClauseInit().
548*/
549static void whereClauseClear(WhereClause *pWC){
550 int i;
551 WhereTerm *a;
drh70d18342013-06-06 19:16:33 +0000552 sqlite3 *db = pWC->pWInfo->pParse->db;
drh0aa74ed2005-07-16 13:33:20 +0000553 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
drh165be382008-12-05 02:36:33 +0000554 if( a->wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000555 sqlite3ExprDelete(db, a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000556 }
drh700a2262008-12-17 19:22:15 +0000557 if( a->wtFlags & TERM_ORINFO ){
558 whereOrInfoDelete(db, a->u.pOrInfo);
559 }else if( a->wtFlags & TERM_ANDINFO ){
560 whereAndInfoDelete(db, a->u.pAndInfo);
561 }
drh0aa74ed2005-07-16 13:33:20 +0000562 }
563 if( pWC->a!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000564 sqlite3DbFree(db, pWC->a);
drh0aa74ed2005-07-16 13:33:20 +0000565 }
566}
567
568/*
drh6a1e0712008-12-05 15:24:15 +0000569** Add a single new WhereTerm entry to the WhereClause object pWC.
570** The new WhereTerm object is constructed from Expr p and with wtFlags.
571** The index in pWC->a[] of the new WhereTerm is returned on success.
572** 0 is returned if the new WhereTerm could not be added due to a memory
573** allocation error. The memory allocation failure will be recorded in
574** the db->mallocFailed flag so that higher-level functions can detect it.
575**
576** This routine will increase the size of the pWC->a[] array as necessary.
drh9eb20282005-08-24 03:52:18 +0000577**
drh165be382008-12-05 02:36:33 +0000578** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
drh6a1e0712008-12-05 15:24:15 +0000579** for freeing the expression p is assumed by the WhereClause object pWC.
580** This is true even if this routine fails to allocate a new WhereTerm.
drhb63a53d2007-03-31 01:34:44 +0000581**
drh9eb20282005-08-24 03:52:18 +0000582** WARNING: This routine might reallocate the space used to store
drh909626d2008-05-30 14:58:37 +0000583** WhereTerms. All pointers to WhereTerms should be invalidated after
drh9eb20282005-08-24 03:52:18 +0000584** calling this routine. Such pointers may be reinitialized by referencing
585** the pWC->a[] array.
drh0aa74ed2005-07-16 13:33:20 +0000586*/
drhec1724e2008-12-09 01:32:03 +0000587static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
drh0aa74ed2005-07-16 13:33:20 +0000588 WhereTerm *pTerm;
drh9eb20282005-08-24 03:52:18 +0000589 int idx;
drhe9cdcea2010-07-22 22:40:03 +0000590 testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
drh0aa74ed2005-07-16 13:33:20 +0000591 if( pWC->nTerm>=pWC->nSlot ){
592 WhereTerm *pOld = pWC->a;
drh70d18342013-06-06 19:16:33 +0000593 sqlite3 *db = pWC->pWInfo->pParse->db;
drh633e6d52008-07-28 19:34:53 +0000594 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
drhb63a53d2007-03-31 01:34:44 +0000595 if( pWC->a==0 ){
drh165be382008-12-05 02:36:33 +0000596 if( wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000597 sqlite3ExprDelete(db, p);
drhb63a53d2007-03-31 01:34:44 +0000598 }
drhf998b732007-11-26 13:36:00 +0000599 pWC->a = pOld;
drhb63a53d2007-03-31 01:34:44 +0000600 return 0;
601 }
drh0aa74ed2005-07-16 13:33:20 +0000602 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
603 if( pOld!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000604 sqlite3DbFree(db, pOld);
drh0aa74ed2005-07-16 13:33:20 +0000605 }
drh6a1e0712008-12-05 15:24:15 +0000606 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
drh0aa74ed2005-07-16 13:33:20 +0000607 }
drh6a1e0712008-12-05 15:24:15 +0000608 pTerm = &pWC->a[idx = pWC->nTerm++];
drh7ee751d2012-12-19 15:53:51 +0000609 pTerm->pExpr = sqlite3ExprSkipCollate(p);
drh165be382008-12-05 02:36:33 +0000610 pTerm->wtFlags = wtFlags;
drh0fcef5e2005-07-19 17:38:22 +0000611 pTerm->pWC = pWC;
drh45b1ee42005-08-02 17:48:22 +0000612 pTerm->iParent = -1;
drh9eb20282005-08-24 03:52:18 +0000613 return idx;
drh0aa74ed2005-07-16 13:33:20 +0000614}
drh75897232000-05-29 14:26:00 +0000615
616/*
drh51669862004-12-18 18:40:26 +0000617** This routine identifies subexpressions in the WHERE clause where
drhb6fb62d2005-09-20 08:47:20 +0000618** each subexpression is separated by the AND operator or some other
drh6c30be82005-07-29 15:10:17 +0000619** operator specified in the op parameter. The WhereClause structure
620** is filled with pointers to subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000621**
drh51669862004-12-18 18:40:26 +0000622** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
623** \________/ \_______________/ \________________/
624** slot[0] slot[1] slot[2]
625**
626** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000627** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000628**
drh51147ba2005-07-23 22:59:55 +0000629** In the previous sentence and in the diagram, "slot[]" refers to
drh902b9ee2008-12-05 17:17:07 +0000630** the WhereClause.a[] array. The slot[] array grows as needed to contain
drh51147ba2005-07-23 22:59:55 +0000631** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000632*/
drh6c30be82005-07-29 15:10:17 +0000633static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
drh29435252008-12-28 18:35:08 +0000634 pWC->op = (u8)op;
drh0aa74ed2005-07-16 13:33:20 +0000635 if( pExpr==0 ) return;
drh6c30be82005-07-29 15:10:17 +0000636 if( pExpr->op!=op ){
drh0aa74ed2005-07-16 13:33:20 +0000637 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000638 }else{
drh6c30be82005-07-29 15:10:17 +0000639 whereSplit(pWC, pExpr->pLeft, op);
640 whereSplit(pWC, pExpr->pRight, op);
drh75897232000-05-29 14:26:00 +0000641 }
drh75897232000-05-29 14:26:00 +0000642}
643
644/*
drh3b48e8c2013-06-12 20:18:16 +0000645** Initialize a WhereMaskSet object
drh6a3ea0e2003-05-02 14:32:12 +0000646*/
drhfd5874d2013-06-12 14:52:39 +0000647#define initMaskSet(P) (P)->n=0
drh6a3ea0e2003-05-02 14:32:12 +0000648
649/*
drh1398ad32005-01-19 23:24:50 +0000650** Return the bitmask for the given cursor number. Return 0 if
651** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000652*/
drh111a6a72008-12-21 03:51:16 +0000653static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000654 int i;
drhfcd71b62011-04-05 22:08:24 +0000655 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
drh6a3ea0e2003-05-02 14:32:12 +0000656 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000657 if( pMaskSet->ix[i]==iCursor ){
drh7699d1c2013-06-04 12:42:29 +0000658 return MASKBIT(i);
drh51669862004-12-18 18:40:26 +0000659 }
drh6a3ea0e2003-05-02 14:32:12 +0000660 }
drh6a3ea0e2003-05-02 14:32:12 +0000661 return 0;
662}
663
664/*
drh1398ad32005-01-19 23:24:50 +0000665** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000666**
667** There is one cursor per table in the FROM clause. The number of
668** tables in the FROM clause is limited by a test early in the
drhb6fb62d2005-09-20 08:47:20 +0000669** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
drh0fcef5e2005-07-19 17:38:22 +0000670** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000671*/
drh111a6a72008-12-21 03:51:16 +0000672static void createMask(WhereMaskSet *pMaskSet, int iCursor){
drhcad651e2007-04-20 12:22:01 +0000673 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
drh0fcef5e2005-07-19 17:38:22 +0000674 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000675}
676
677/*
drh3b48e8c2013-06-12 20:18:16 +0000678** These routine walk (recursively) an expression tree and generates
drh75897232000-05-29 14:26:00 +0000679** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000680** tree.
drh75897232000-05-29 14:26:00 +0000681*/
drh111a6a72008-12-21 03:51:16 +0000682static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
683static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
684static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
drh51669862004-12-18 18:40:26 +0000685 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000686 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000687 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000688 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000689 return mask;
drh75897232000-05-29 14:26:00 +0000690 }
danielk1977b3bce662005-01-29 08:32:43 +0000691 mask = exprTableUsage(pMaskSet, p->pRight);
692 mask |= exprTableUsage(pMaskSet, p->pLeft);
danielk19776ab3a2e2009-02-19 14:39:25 +0000693 if( ExprHasProperty(p, EP_xIsSelect) ){
694 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
695 }else{
696 mask |= exprListTableUsage(pMaskSet, p->x.pList);
697 }
danielk1977b3bce662005-01-29 08:32:43 +0000698 return mask;
699}
drh111a6a72008-12-21 03:51:16 +0000700static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
danielk1977b3bce662005-01-29 08:32:43 +0000701 int i;
702 Bitmask mask = 0;
703 if( pList ){
704 for(i=0; i<pList->nExpr; i++){
705 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000706 }
707 }
drh75897232000-05-29 14:26:00 +0000708 return mask;
709}
drh111a6a72008-12-21 03:51:16 +0000710static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
drha430ae82007-09-12 15:41:01 +0000711 Bitmask mask = 0;
712 while( pS ){
drha464c232011-09-16 19:04:03 +0000713 SrcList *pSrc = pS->pSrc;
drha430ae82007-09-12 15:41:01 +0000714 mask |= exprListTableUsage(pMaskSet, pS->pEList);
drhf5b11382005-09-17 13:07:13 +0000715 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
716 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
717 mask |= exprTableUsage(pMaskSet, pS->pWhere);
718 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drha464c232011-09-16 19:04:03 +0000719 if( ALWAYS(pSrc!=0) ){
drh88501772011-09-16 17:43:06 +0000720 int i;
721 for(i=0; i<pSrc->nSrc; i++){
722 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
723 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
724 }
725 }
drha430ae82007-09-12 15:41:01 +0000726 pS = pS->pPrior;
drhf5b11382005-09-17 13:07:13 +0000727 }
728 return mask;
729}
drh75897232000-05-29 14:26:00 +0000730
731/*
drh487ab3c2001-11-08 00:45:21 +0000732** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000733** allowed for an indexable WHERE clause term. The allowed operators are
drh3b48e8c2013-06-12 20:18:16 +0000734** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
drhe9cdcea2010-07-22 22:40:03 +0000735**
736** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
737** of one of the following forms: column = expression column > expression
738** column >= expression column < expression column <= expression
739** expression = column expression > column expression >= column
740** expression < column expression <= column column IN
741** (expression-list) column IN (subquery) column IS NULL
drh487ab3c2001-11-08 00:45:21 +0000742*/
743static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000744 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
745 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
746 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
747 assert( TK_GE==TK_EQ+4 );
drh50b39962006-10-28 00:28:09 +0000748 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
drh487ab3c2001-11-08 00:45:21 +0000749}
750
751/*
drh902b9ee2008-12-05 17:17:07 +0000752** Swap two objects of type TYPE.
drh193bd772004-07-20 18:23:14 +0000753*/
754#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
755
756/*
drh909626d2008-05-30 14:58:37 +0000757** Commute a comparison operator. Expressions of the form "X op Y"
drh0fcef5e2005-07-19 17:38:22 +0000758** are converted into "Y op X".
danielk1977eb5453d2007-07-30 14:40:48 +0000759**
mistachkin48864df2013-03-21 21:20:32 +0000760** If left/right precedence rules come into play when determining the
drh3b48e8c2013-06-12 20:18:16 +0000761** collating sequence, then COLLATE operators are adjusted to ensure
762** that the collating sequence does not change. For example:
763** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
danielk1977eb5453d2007-07-30 14:40:48 +0000764** the left hand side of a comparison overrides any collation sequence
drhae80dde2012-12-06 21:16:43 +0000765** attached to the right. For the same reason the EP_Collate flag
danielk1977eb5453d2007-07-30 14:40:48 +0000766** is not commuted.
drh193bd772004-07-20 18:23:14 +0000767*/
drh7d10d5a2008-08-20 16:35:10 +0000768static void exprCommute(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000769 u16 expRight = (pExpr->pRight->flags & EP_Collate);
770 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
drhfe05af82005-07-21 03:14:59 +0000771 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drhae80dde2012-12-06 21:16:43 +0000772 if( expRight==expLeft ){
773 /* Either X and Y both have COLLATE operator or neither do */
774 if( expRight ){
775 /* Both X and Y have COLLATE operators. Make sure X is always
776 ** used by clearing the EP_Collate flag from Y. */
777 pExpr->pRight->flags &= ~EP_Collate;
778 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
779 /* Neither X nor Y have COLLATE operators, but X has a non-default
780 ** collating sequence. So add the EP_Collate marker on X to cause
781 ** it to be searched first. */
782 pExpr->pLeft->flags |= EP_Collate;
783 }
784 }
drh0fcef5e2005-07-19 17:38:22 +0000785 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
786 if( pExpr->op>=TK_GT ){
787 assert( TK_LT==TK_GT+2 );
788 assert( TK_GE==TK_LE+2 );
789 assert( TK_GT>TK_EQ );
790 assert( TK_GT<TK_LE );
791 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
792 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000793 }
drh193bd772004-07-20 18:23:14 +0000794}
795
796/*
drhfe05af82005-07-21 03:14:59 +0000797** Translate from TK_xx operator to WO_xx bitmask.
798*/
drhec1724e2008-12-09 01:32:03 +0000799static u16 operatorMask(int op){
800 u16 c;
drhfe05af82005-07-21 03:14:59 +0000801 assert( allowedOp(op) );
802 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000803 c = WO_IN;
drh50b39962006-10-28 00:28:09 +0000804 }else if( op==TK_ISNULL ){
805 c = WO_ISNULL;
drhfe05af82005-07-21 03:14:59 +0000806 }else{
drhec1724e2008-12-09 01:32:03 +0000807 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
808 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000809 }
drh50b39962006-10-28 00:28:09 +0000810 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000811 assert( op!=TK_IN || c==WO_IN );
812 assert( op!=TK_EQ || c==WO_EQ );
813 assert( op!=TK_LT || c==WO_LT );
814 assert( op!=TK_LE || c==WO_LE );
815 assert( op!=TK_GT || c==WO_GT );
816 assert( op!=TK_GE || c==WO_GE );
817 return c;
drhfe05af82005-07-21 03:14:59 +0000818}
819
820/*
drh1c8148f2013-05-04 20:25:23 +0000821** Advance to the next WhereTerm that matches according to the criteria
822** established when the pScan object was initialized by whereScanInit().
823** Return NULL if there are no more matching WhereTerms.
824*/
825WhereTerm *whereScanNext(WhereScan *pScan){
826 int iCur; /* The cursor on the LHS of the term */
827 int iColumn; /* The column on the LHS of the term. -1 for IPK */
828 Expr *pX; /* An expression being tested */
829 WhereClause *pWC; /* Shorthand for pScan->pWC */
830 WhereTerm *pTerm; /* The term being tested */
drh43b85ef2013-06-10 12:34:45 +0000831 int k = pScan->k; /* Where to start scanning */
drh1c8148f2013-05-04 20:25:23 +0000832
833 while( pScan->iEquiv<=pScan->nEquiv ){
834 iCur = pScan->aEquiv[pScan->iEquiv-2];
835 iColumn = pScan->aEquiv[pScan->iEquiv-1];
836 while( (pWC = pScan->pWC)!=0 ){
drh43b85ef2013-06-10 12:34:45 +0000837 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
drh1c8148f2013-05-04 20:25:23 +0000838 if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
839 if( (pTerm->eOperator & WO_EQUIV)!=0
840 && pScan->nEquiv<ArraySize(pScan->aEquiv)
841 ){
842 int j;
843 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
844 assert( pX->op==TK_COLUMN );
845 for(j=0; j<pScan->nEquiv; j+=2){
846 if( pScan->aEquiv[j]==pX->iTable
847 && pScan->aEquiv[j+1]==pX->iColumn ){
848 break;
849 }
850 }
851 if( j==pScan->nEquiv ){
852 pScan->aEquiv[j] = pX->iTable;
853 pScan->aEquiv[j+1] = pX->iColumn;
854 pScan->nEquiv += 2;
855 }
856 }
857 if( (pTerm->eOperator & pScan->opMask)!=0 ){
858 /* Verify the affinity and collating sequence match */
859 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
860 CollSeq *pColl;
drh70d18342013-06-06 19:16:33 +0000861 Parse *pParse = pWC->pWInfo->pParse;
drh1c8148f2013-05-04 20:25:23 +0000862 pX = pTerm->pExpr;
863 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
864 continue;
865 }
866 assert(pX->pLeft);
drh70d18342013-06-06 19:16:33 +0000867 pColl = sqlite3BinaryCompareCollSeq(pParse,
drh1c8148f2013-05-04 20:25:23 +0000868 pX->pLeft, pX->pRight);
drh70d18342013-06-06 19:16:33 +0000869 if( pColl==0 ) pColl = pParse->db->pDfltColl;
drh1c8148f2013-05-04 20:25:23 +0000870 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
871 continue;
872 }
873 }
drha184fb82013-05-08 04:22:59 +0000874 if( (pTerm->eOperator & WO_EQ)!=0
875 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
876 && pX->iTable==pScan->aEquiv[0]
877 && pX->iColumn==pScan->aEquiv[1]
878 ){
879 continue;
880 }
drh43b85ef2013-06-10 12:34:45 +0000881 pScan->k = k+1;
drh1c8148f2013-05-04 20:25:23 +0000882 return pTerm;
883 }
884 }
885 }
886 pWC = pScan->pWC = pScan->pWC->pOuter;
drh43b85ef2013-06-10 12:34:45 +0000887 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000888 }
889 pScan->pWC = pScan->pOrigWC;
drh43b85ef2013-06-10 12:34:45 +0000890 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000891 pScan->iEquiv += 2;
892 }
drh1c8148f2013-05-04 20:25:23 +0000893 return 0;
894}
895
896/*
897** Initialize a WHERE clause scanner object. Return a pointer to the
898** first match. Return NULL if there are no matches.
899**
900** The scanner will be searching the WHERE clause pWC. It will look
901** for terms of the form "X <op> <expr>" where X is column iColumn of table
902** iCur. The <op> must be one of the operators described by opMask.
903**
drh3b48e8c2013-06-12 20:18:16 +0000904** If the search is for X and the WHERE clause contains terms of the
905** form X=Y then this routine might also return terms of the form
906** "Y <op> <expr>". The number of levels of transitivity is limited,
907** but is enough to handle most commonly occurring SQL statements.
908**
drh1c8148f2013-05-04 20:25:23 +0000909** If X is not the INTEGER PRIMARY KEY then X must be compatible with
910** index pIdx.
911*/
912WhereTerm *whereScanInit(
913 WhereScan *pScan, /* The WhereScan object being initialized */
914 WhereClause *pWC, /* The WHERE clause to be scanned */
915 int iCur, /* Cursor to scan for */
916 int iColumn, /* Column to scan for */
917 u32 opMask, /* Operator(s) to scan for */
918 Index *pIdx /* Must be compatible with this index */
919){
920 int j;
921
drhe9d935a2013-06-05 16:19:59 +0000922 /* memset(pScan, 0, sizeof(*pScan)); */
drh1c8148f2013-05-04 20:25:23 +0000923 pScan->pOrigWC = pWC;
924 pScan->pWC = pWC;
925 if( pIdx && iColumn>=0 ){
926 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
927 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
928 if( NEVER(j>=pIdx->nColumn) ) return 0;
929 }
930 pScan->zCollName = pIdx->azColl[j];
drhe9d935a2013-06-05 16:19:59 +0000931 }else{
932 pScan->idxaff = 0;
933 pScan->zCollName = 0;
drh1c8148f2013-05-04 20:25:23 +0000934 }
935 pScan->opMask = opMask;
drhe9d935a2013-06-05 16:19:59 +0000936 pScan->k = 0;
drh1c8148f2013-05-04 20:25:23 +0000937 pScan->aEquiv[0] = iCur;
938 pScan->aEquiv[1] = iColumn;
939 pScan->nEquiv = 2;
940 pScan->iEquiv = 2;
941 return whereScanNext(pScan);
942}
943
944/*
drhfe05af82005-07-21 03:14:59 +0000945** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
946** where X is a reference to the iColumn of table iCur and <op> is one of
947** the WO_xx operator codes specified by the op parameter.
948** Return a pointer to the term. Return 0 if not found.
drh58eb1c02013-01-17 00:08:42 +0000949**
950** The term returned might by Y=<expr> if there is another constraint in
951** the WHERE clause that specifies that X=Y. Any such constraints will be
952** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
953** aEquiv[] array holds X and all its equivalents, with each SQL variable
954** taking up two slots in aEquiv[]. The first slot is for the cursor number
955** and the second is for the column number. There are 22 slots in aEquiv[]
956** so that means we can look for X plus up to 10 other equivalent values.
957** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
958** and ... and A9=A10 and A10=<expr>.
959**
960** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
961** then try for the one with no dependencies on <expr> - in other words where
962** <expr> is a constant expression of some kind. Only return entries of
963** the form "X <op> Y" where Y is a column in another table if no terms of
drh459f63e2013-03-06 01:55:27 +0000964** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
965** exist, try to return a term that does not use WO_EQUIV.
drhfe05af82005-07-21 03:14:59 +0000966*/
967static WhereTerm *findTerm(
968 WhereClause *pWC, /* The WHERE clause to be searched */
969 int iCur, /* Cursor number of LHS */
970 int iColumn, /* Column number of LHS */
971 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +0000972 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000973 Index *pIdx /* Must be compatible with this index, if not NULL */
974){
drh1c8148f2013-05-04 20:25:23 +0000975 WhereTerm *pResult = 0;
976 WhereTerm *p;
977 WhereScan scan;
drh7a5bcc02013-01-16 17:08:58 +0000978
drh1c8148f2013-05-04 20:25:23 +0000979 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
980 while( p ){
981 if( (p->prereqRight & notReady)==0 ){
982 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
983 return p;
drhfe05af82005-07-21 03:14:59 +0000984 }
drh1c8148f2013-05-04 20:25:23 +0000985 if( pResult==0 ) pResult = p;
drhfe05af82005-07-21 03:14:59 +0000986 }
drh1c8148f2013-05-04 20:25:23 +0000987 p = whereScanNext(&scan);
drhfe05af82005-07-21 03:14:59 +0000988 }
drh7a5bcc02013-01-16 17:08:58 +0000989 return pResult;
drhfe05af82005-07-21 03:14:59 +0000990}
991
drh6c30be82005-07-29 15:10:17 +0000992/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +0000993static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +0000994
995/*
996** Call exprAnalyze on all terms in a WHERE clause.
drh6c30be82005-07-29 15:10:17 +0000997*/
998static void exprAnalyzeAll(
999 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +00001000 WhereClause *pWC /* the WHERE clause to be analyzed */
1001){
drh6c30be82005-07-29 15:10:17 +00001002 int i;
drh9eb20282005-08-24 03:52:18 +00001003 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +00001004 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +00001005 }
1006}
1007
drhd2687b72005-08-12 22:56:09 +00001008#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1009/*
1010** Check to see if the given expression is a LIKE or GLOB operator that
1011** can be optimized using inequality constraints. Return TRUE if it is
1012** so and false if not.
1013**
1014** In order for the operator to be optimizible, the RHS must be a string
1015** literal that does not begin with a wildcard.
1016*/
1017static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +00001018 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +00001019 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +00001020 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +00001021 int *pisComplete, /* True if the only wildcard is % in the last character */
1022 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +00001023){
dan937d0de2009-10-15 18:35:38 +00001024 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +00001025 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
1026 ExprList *pList; /* List of operands to the LIKE operator */
1027 int c; /* One character in z[] */
1028 int cnt; /* Number of non-wildcard prefix characters */
1029 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +00001030 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +00001031 sqlite3_value *pVal = 0;
1032 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +00001033
drh9f504ea2008-02-23 21:55:39 +00001034 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +00001035 return 0;
1036 }
drh9f504ea2008-02-23 21:55:39 +00001037#ifdef SQLITE_EBCDIC
1038 if( *pnoCase ) return 0;
1039#endif
danielk19776ab3a2e2009-02-19 14:39:25 +00001040 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +00001041 pLeft = pList->a[1].pExpr;
danc68939e2012-03-29 14:29:07 +00001042 if( pLeft->op!=TK_COLUMN
1043 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
1044 || IsVirtual(pLeft->pTab)
1045 ){
drhd91ca492009-10-22 20:50:36 +00001046 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
1047 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +00001048 return 0;
1049 }
drhd91ca492009-10-22 20:50:36 +00001050 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +00001051
1052 pRight = pList->a[0].pExpr;
1053 op = pRight->op;
1054 if( op==TK_REGISTER ){
1055 op = pRight->op2;
1056 }
1057 if( op==TK_VARIABLE ){
1058 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +00001059 int iCol = pRight->iColumn;
1060 pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
dan937d0de2009-10-15 18:35:38 +00001061 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
1062 z = (char *)sqlite3_value_text(pVal);
1063 }
drhf9b22ca2011-10-21 16:47:31 +00001064 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +00001065 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
1066 }else if( op==TK_STRING ){
1067 z = pRight->u.zToken;
1068 }
1069 if( z ){
shane85095702009-06-15 16:27:08 +00001070 cnt = 0;
drhb7916a72009-05-27 10:31:29 +00001071 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +00001072 cnt++;
1073 }
drh93ee23c2010-07-22 12:33:57 +00001074 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +00001075 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +00001076 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +00001077 pPrefix = sqlite3Expr(db, TK_STRING, z);
1078 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
1079 *ppPrefix = pPrefix;
1080 if( op==TK_VARIABLE ){
1081 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +00001082 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +00001083 if( *pisComplete && pRight->u.zToken[1] ){
1084 /* If the rhs of the LIKE expression is a variable, and the current
1085 ** value of the variable means there is no need to invoke the LIKE
1086 ** function, then no OP_Variable will be added to the program.
1087 ** This causes problems for the sqlite3_bind_parameter_name()
drhbec451f2009-10-17 13:13:02 +00001088 ** API. To workaround them, add a dummy OP_Variable here.
1089 */
1090 int r1 = sqlite3GetTempReg(pParse);
1091 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +00001092 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +00001093 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +00001094 }
1095 }
1096 }else{
1097 z = 0;
shane85095702009-06-15 16:27:08 +00001098 }
drhf998b732007-11-26 13:36:00 +00001099 }
dan937d0de2009-10-15 18:35:38 +00001100
1101 sqlite3ValueFree(pVal);
1102 return (z!=0);
drhd2687b72005-08-12 22:56:09 +00001103}
1104#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1105
drhedb193b2006-06-27 13:20:21 +00001106
1107#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +00001108/*
drh7f375902006-06-13 17:38:59 +00001109** Check to see if the given expression is of the form
1110**
1111** column MATCH expr
1112**
1113** If it is then return TRUE. If not, return FALSE.
1114*/
1115static int isMatchOfColumn(
1116 Expr *pExpr /* Test this expression */
1117){
1118 ExprList *pList;
1119
1120 if( pExpr->op!=TK_FUNCTION ){
1121 return 0;
1122 }
drh33e619f2009-05-28 01:00:55 +00001123 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +00001124 return 0;
1125 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001126 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +00001127 if( pList->nExpr!=2 ){
1128 return 0;
1129 }
1130 if( pList->a[1].pExpr->op != TK_COLUMN ){
1131 return 0;
1132 }
1133 return 1;
1134}
drhedb193b2006-06-27 13:20:21 +00001135#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +00001136
1137/*
drh54a167d2005-11-26 14:08:07 +00001138** If the pBase expression originated in the ON or USING clause of
1139** a join, then transfer the appropriate markings over to derived.
1140*/
1141static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
1142 pDerived->flags |= pBase->flags & EP_FromJoin;
1143 pDerived->iRightJoinTable = pBase->iRightJoinTable;
1144}
1145
drh3e355802007-02-23 23:13:33 +00001146#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1147/*
drh1a58fe02008-12-20 02:06:13 +00001148** Analyze a term that consists of two or more OR-connected
1149** subterms. So in:
drh3e355802007-02-23 23:13:33 +00001150**
drh1a58fe02008-12-20 02:06:13 +00001151** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
1152** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +00001153**
drh1a58fe02008-12-20 02:06:13 +00001154** This routine analyzes terms such as the middle term in the above example.
1155** A WhereOrTerm object is computed and attached to the term under
1156** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +00001157**
drh1a58fe02008-12-20 02:06:13 +00001158** WhereTerm.wtFlags |= TERM_ORINFO
1159** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +00001160**
drh1a58fe02008-12-20 02:06:13 +00001161** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +00001162** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +00001163** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +00001164**
drh1a58fe02008-12-20 02:06:13 +00001165** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
1166** (B) x=expr1 OR expr2=x OR x=expr3
1167** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
1168** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
1169** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
drh3e355802007-02-23 23:13:33 +00001170**
drh1a58fe02008-12-20 02:06:13 +00001171** CASE 1:
1172**
drhc3e552f2013-02-08 16:04:19 +00001173** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +00001174** a single table T (as shown in example B above) then create a new virtual
1175** term that is an equivalent IN expression. In other words, if the term
1176** being analyzed is:
1177**
1178** x = expr1 OR expr2 = x OR x = expr3
1179**
1180** then create a new virtual term like this:
1181**
1182** x IN (expr1,expr2,expr3)
1183**
1184** CASE 2:
1185**
1186** If all subterms are indexable by a single table T, then set
1187**
1188** WhereTerm.eOperator = WO_OR
1189** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
1190**
1191** A subterm is "indexable" if it is of the form
1192** "T.C <op> <expr>" where C is any column of table T and
1193** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
1194** A subterm is also indexable if it is an AND of two or more
1195** subsubterms at least one of which is indexable. Indexable AND
1196** subterms have their eOperator set to WO_AND and they have
1197** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
1198**
1199** From another point of view, "indexable" means that the subterm could
1200** potentially be used with an index if an appropriate index exists.
1201** This analysis does not consider whether or not the index exists; that
1202** is something the bestIndex() routine will determine. This analysis
1203** only looks at whether subterms appropriate for indexing exist.
1204**
1205** All examples A through E above all satisfy case 2. But if a term
1206** also statisfies case 1 (such as B) we know that the optimizer will
1207** always prefer case 1, so in that case we pretend that case 2 is not
1208** satisfied.
1209**
1210** It might be the case that multiple tables are indexable. For example,
1211** (E) above is indexable on tables P, Q, and R.
1212**
1213** Terms that satisfy case 2 are candidates for lookup by using
1214** separate indices to find rowids for each subterm and composing
1215** the union of all rowids using a RowSet object. This is similar
1216** to "bitmap indices" in other database engines.
1217**
1218** OTHERWISE:
1219**
1220** If neither case 1 nor case 2 apply, then leave the eOperator set to
1221** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +00001222*/
drh1a58fe02008-12-20 02:06:13 +00001223static void exprAnalyzeOrTerm(
1224 SrcList *pSrc, /* the FROM clause */
1225 WhereClause *pWC, /* the complete WHERE clause */
1226 int idxTerm /* Index of the OR-term to be analyzed */
1227){
drh70d18342013-06-06 19:16:33 +00001228 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
1229 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +00001230 sqlite3 *db = pParse->db; /* Database connection */
1231 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
1232 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +00001233 int i; /* Loop counters */
1234 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
1235 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
1236 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
1237 Bitmask chngToIN; /* Tables that might satisfy case 1 */
1238 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +00001239
drh1a58fe02008-12-20 02:06:13 +00001240 /*
1241 ** Break the OR clause into its separate subterms. The subterms are
1242 ** stored in a WhereClause structure containing within the WhereOrInfo
1243 ** object that is attached to the original OR clause term.
1244 */
1245 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
1246 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +00001247 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +00001248 if( pOrInfo==0 ) return;
1249 pTerm->wtFlags |= TERM_ORINFO;
1250 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +00001251 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +00001252 whereSplit(pOrWc, pExpr, TK_OR);
1253 exprAnalyzeAll(pSrc, pOrWc);
1254 if( db->mallocFailed ) return;
1255 assert( pOrWc->nTerm>=2 );
1256
1257 /*
1258 ** Compute the set of tables that might satisfy cases 1 or 2.
1259 */
danielk1977e672c8e2009-05-22 15:43:26 +00001260 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +00001261 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +00001262 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
1263 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +00001264 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +00001265 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +00001266 chngToIN = 0;
drh29435252008-12-28 18:35:08 +00001267 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
1268 if( pAndInfo ){
1269 WhereClause *pAndWC;
1270 WhereTerm *pAndTerm;
1271 int j;
1272 Bitmask b = 0;
1273 pOrTerm->u.pAndInfo = pAndInfo;
1274 pOrTerm->wtFlags |= TERM_ANDINFO;
1275 pOrTerm->eOperator = WO_AND;
1276 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +00001277 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +00001278 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
1279 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +00001280 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +00001281 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +00001282 if( !db->mallocFailed ){
1283 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
1284 assert( pAndTerm->pExpr );
1285 if( allowedOp(pAndTerm->pExpr->op) ){
drh70d18342013-06-06 19:16:33 +00001286 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +00001287 }
drh29435252008-12-28 18:35:08 +00001288 }
1289 }
1290 indexable &= b;
1291 }
drh1a58fe02008-12-20 02:06:13 +00001292 }else if( pOrTerm->wtFlags & TERM_COPIED ){
1293 /* Skip this term for now. We revisit it when we process the
1294 ** corresponding TERM_VIRTUAL term */
1295 }else{
1296 Bitmask b;
drh70d18342013-06-06 19:16:33 +00001297 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001298 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
1299 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh70d18342013-06-06 19:16:33 +00001300 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001301 }
1302 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +00001303 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +00001304 chngToIN = 0;
1305 }else{
1306 chngToIN &= b;
1307 }
1308 }
drh3e355802007-02-23 23:13:33 +00001309 }
drh1a58fe02008-12-20 02:06:13 +00001310
1311 /*
1312 ** Record the set of tables that satisfy case 2. The set might be
drh111a6a72008-12-21 03:51:16 +00001313 ** empty.
drh1a58fe02008-12-20 02:06:13 +00001314 */
1315 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +00001316 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +00001317
1318 /*
1319 ** chngToIN holds a set of tables that *might* satisfy case 1. But
1320 ** we have to do some additional checking to see if case 1 really
1321 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +00001322 **
1323 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
1324 ** that there is no possibility of transforming the OR clause into an
1325 ** IN operator because one or more terms in the OR clause contain
1326 ** something other than == on a column in the single table. The 1-bit
1327 ** case means that every term of the OR clause is of the form
1328 ** "table.column=expr" for some single table. The one bit that is set
1329 ** will correspond to the common table. We still need to check to make
1330 ** sure the same column is used on all terms. The 2-bit case is when
1331 ** the all terms are of the form "table1.column=table2.column". It
1332 ** might be possible to form an IN operator with either table1.column
1333 ** or table2.column as the LHS if either is common to every term of
1334 ** the OR clause.
1335 **
1336 ** Note that terms of the form "table.column1=table.column2" (the
1337 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +00001338 */
1339 if( chngToIN ){
1340 int okToChngToIN = 0; /* True if the conversion to IN is valid */
1341 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +00001342 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +00001343 int j = 0; /* Loop counter */
1344
1345 /* Search for a table and column that appears on one side or the
1346 ** other of the == operator in every subterm. That table and column
1347 ** will be recorded in iCursor and iColumn. There might not be any
1348 ** such table and column. Set okToChngToIN if an appropriate table
1349 ** and column is found but leave okToChngToIN false if not found.
1350 */
1351 for(j=0; j<2 && !okToChngToIN; j++){
1352 pOrTerm = pOrWc->a;
1353 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001354 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001355 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +00001356 if( pOrTerm->leftCursor==iCursor ){
1357 /* This is the 2-bit case and we are on the second iteration and
1358 ** current term is from the first iteration. So skip this term. */
1359 assert( j==1 );
1360 continue;
1361 }
drh70d18342013-06-06 19:16:33 +00001362 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +00001363 /* This term must be of the form t1.a==t2.b where t2 is in the
1364 ** chngToIN set but t1 is not. This term will be either preceeded
1365 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
1366 ** and use its inversion. */
1367 testcase( pOrTerm->wtFlags & TERM_COPIED );
1368 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
1369 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
1370 continue;
1371 }
drh1a58fe02008-12-20 02:06:13 +00001372 iColumn = pOrTerm->u.leftColumn;
1373 iCursor = pOrTerm->leftCursor;
1374 break;
1375 }
1376 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +00001377 /* No candidate table+column was found. This can only occur
1378 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +00001379 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +00001380 assert( IsPowerOfTwo(chngToIN) );
drh70d18342013-06-06 19:16:33 +00001381 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +00001382 break;
1383 }
drh4e8be3b2009-06-08 17:11:08 +00001384 testcase( j==1 );
1385
1386 /* We have found a candidate table and column. Check to see if that
1387 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001388 okToChngToIN = 1;
1389 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001390 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001391 if( pOrTerm->leftCursor!=iCursor ){
1392 pOrTerm->wtFlags &= ~TERM_OR_OK;
1393 }else if( pOrTerm->u.leftColumn!=iColumn ){
1394 okToChngToIN = 0;
1395 }else{
1396 int affLeft, affRight;
1397 /* If the right-hand side is also a column, then the affinities
1398 ** of both right and left sides must be such that no type
1399 ** conversions are required on the right. (Ticket #2249)
1400 */
1401 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1402 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1403 if( affRight!=0 && affRight!=affLeft ){
1404 okToChngToIN = 0;
1405 }else{
1406 pOrTerm->wtFlags |= TERM_OR_OK;
1407 }
1408 }
1409 }
1410 }
1411
1412 /* At this point, okToChngToIN is true if original pTerm satisfies
1413 ** case 1. In that case, construct a new virtual term that is
1414 ** pTerm converted into an IN operator.
drhe9cdcea2010-07-22 22:40:03 +00001415 **
1416 ** EV: R-00211-15100
drh1a58fe02008-12-20 02:06:13 +00001417 */
1418 if( okToChngToIN ){
1419 Expr *pDup; /* A transient duplicate expression */
1420 ExprList *pList = 0; /* The RHS of the IN operator */
1421 Expr *pLeft = 0; /* The LHS of the IN operator */
1422 Expr *pNew; /* The complete IN operator */
1423
1424 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1425 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001426 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001427 assert( pOrTerm->leftCursor==iCursor );
1428 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001429 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001430 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001431 pLeft = pOrTerm->pExpr->pLeft;
1432 }
1433 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001434 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001435 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001436 if( pNew ){
1437 int idxNew;
1438 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001439 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1440 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001441 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1442 testcase( idxNew==0 );
1443 exprAnalyze(pSrc, pWC, idxNew);
1444 pTerm = &pWC->a[idxTerm];
1445 pWC->a[idxNew].iParent = idxTerm;
1446 pTerm->nChild = 1;
1447 }else{
1448 sqlite3ExprListDelete(db, pList);
1449 }
drh534230c2011-01-22 00:10:45 +00001450 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
drh1a58fe02008-12-20 02:06:13 +00001451 }
drh3e355802007-02-23 23:13:33 +00001452 }
drh3e355802007-02-23 23:13:33 +00001453}
1454#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001455
drh7a5bcc02013-01-16 17:08:58 +00001456/*
drh0aa74ed2005-07-16 13:33:20 +00001457** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001458** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001459** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001460** structure.
drh51147ba2005-07-23 22:59:55 +00001461**
1462** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001463** to the standard form of "X <op> <expr>".
1464**
1465** If the expression is of the form "X <op> Y" where both X and Y are
1466** columns, then the original expression is unchanged and a new virtual
1467** term of the form "Y <op> X" is added to the WHERE clause and
1468** analyzed separately. The original term is marked with TERM_COPIED
1469** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1470** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1471** is a commuted copy of a prior term.) The original term has nChild=1
1472** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001473*/
drh0fcef5e2005-07-19 17:38:22 +00001474static void exprAnalyze(
1475 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001476 WhereClause *pWC, /* the WHERE clause */
1477 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001478){
drh70d18342013-06-06 19:16:33 +00001479 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001480 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001481 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001482 Expr *pExpr; /* The expression to be analyzed */
1483 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1484 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001485 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001486 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1487 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1488 int noCase = 0; /* LIKE/GLOB distinguishes case */
drh1a58fe02008-12-20 02:06:13 +00001489 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001490 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001491 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001492
drhf998b732007-11-26 13:36:00 +00001493 if( db->mallocFailed ){
1494 return;
1495 }
1496 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001497 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001498 pExpr = pTerm->pExpr;
1499 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001500 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001501 op = pExpr->op;
1502 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001503 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001504 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1505 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1506 }else{
1507 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1508 }
drh50b39962006-10-28 00:28:09 +00001509 }else if( op==TK_ISNULL ){
1510 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001511 }else{
1512 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1513 }
drh22d6a532005-09-19 21:05:48 +00001514 prereqAll = exprTableUsage(pMaskSet, pExpr);
1515 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001516 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1517 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001518 extraRight = x-1; /* ON clause terms may not be used with an index
1519 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001520 }
1521 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001522 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001523 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001524 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001525 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001526 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1527 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001528 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001529 if( pLeft->op==TK_COLUMN ){
1530 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001531 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001532 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001533 }
drh0fcef5e2005-07-19 17:38:22 +00001534 if( pRight && pRight->op==TK_COLUMN ){
1535 WhereTerm *pNew;
1536 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001537 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001538 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001539 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001540 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001541 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001542 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001543 return;
1544 }
drh9eb20282005-08-24 03:52:18 +00001545 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1546 if( idxNew==0 ) return;
1547 pNew = &pWC->a[idxNew];
1548 pNew->iParent = idxTerm;
1549 pTerm = &pWC->a[idxTerm];
drh45b1ee42005-08-02 17:48:22 +00001550 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001551 pTerm->wtFlags |= TERM_COPIED;
drheb5bc922013-01-17 16:43:33 +00001552 if( pExpr->op==TK_EQ
1553 && !ExprHasProperty(pExpr, EP_FromJoin)
1554 && OptimizationEnabled(db, SQLITE_Transitive)
1555 ){
drh7a5bcc02013-01-16 17:08:58 +00001556 pTerm->eOperator |= WO_EQUIV;
1557 eExtraOp = WO_EQUIV;
1558 }
drh0fcef5e2005-07-19 17:38:22 +00001559 }else{
1560 pDup = pExpr;
1561 pNew = pTerm;
1562 }
drh7d10d5a2008-08-20 16:35:10 +00001563 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001564 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001565 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001566 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001567 testcase( (prereqLeft | extraRight) != prereqLeft );
1568 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001569 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001570 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001571 }
1572 }
drhed378002005-07-28 23:12:08 +00001573
drhd2687b72005-08-12 22:56:09 +00001574#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001575 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001576 ** that define the range that the BETWEEN implements. For example:
1577 **
1578 ** a BETWEEN b AND c
1579 **
1580 ** is converted into:
1581 **
1582 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1583 **
1584 ** The two new terms are added onto the end of the WhereClause object.
1585 ** The new terms are "dynamic" and are children of the original BETWEEN
1586 ** term. That means that if the BETWEEN term is coded, the children are
1587 ** skipped. Or, if the children are satisfied by an index, the original
1588 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001589 */
drh29435252008-12-28 18:35:08 +00001590 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001591 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001592 int i;
1593 static const u8 ops[] = {TK_GE, TK_LE};
1594 assert( pList!=0 );
1595 assert( pList->nExpr==2 );
1596 for(i=0; i<2; i++){
1597 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001598 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001599 pNewExpr = sqlite3PExpr(pParse, ops[i],
1600 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001601 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drh9eb20282005-08-24 03:52:18 +00001602 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001603 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001604 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001605 pTerm = &pWC->a[idxTerm];
1606 pWC->a[idxNew].iParent = idxTerm;
drhed378002005-07-28 23:12:08 +00001607 }
drh45b1ee42005-08-02 17:48:22 +00001608 pTerm->nChild = 2;
drhed378002005-07-28 23:12:08 +00001609 }
drhd2687b72005-08-12 22:56:09 +00001610#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001611
danielk19771576cd92006-01-14 08:02:28 +00001612#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001613 /* Analyze a term that is composed of two or more subterms connected by
1614 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001615 */
1616 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001617 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001618 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001619 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001620 }
drhd2687b72005-08-12 22:56:09 +00001621#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1622
1623#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1624 /* Add constraints to reduce the search space on a LIKE or GLOB
1625 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001626 **
1627 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1628 **
1629 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
1630 **
1631 ** The last character of the prefix "abc" is incremented to form the
shane7bc71e52008-05-28 18:01:44 +00001632 ** termination condition "abd".
drhd2687b72005-08-12 22:56:09 +00001633 */
dan937d0de2009-10-15 18:35:38 +00001634 if( pWC->op==TK_AND
1635 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1636 ){
drh1d452e12009-11-01 19:26:59 +00001637 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1638 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1639 Expr *pNewExpr1;
1640 Expr *pNewExpr2;
1641 int idxNew1;
1642 int idxNew2;
drhae80dde2012-12-06 21:16:43 +00001643 Token sCollSeqName; /* Name of collating sequence */
drh9eb20282005-08-24 03:52:18 +00001644
danielk19776ab3a2e2009-02-19 14:39:25 +00001645 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001646 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drhf998b732007-11-26 13:36:00 +00001647 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001648 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001649 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001650 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001651 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001652 /* The point is to increment the last character before the first
1653 ** wildcard. But if we increment '@', that will push it into the
1654 ** alphabetic range where case conversions will mess up the
1655 ** inequality. To avoid this, make sure to also run the full
1656 ** LIKE on all candidate expressions by clearing the isComplete flag
1657 */
drhe9cdcea2010-07-22 22:40:03 +00001658 if( c=='A'-1 ) isComplete = 0; /* EV: R-64339-08207 */
1659
drh254993e2009-06-08 19:44:36 +00001660
drh02a50b72008-05-26 18:33:40 +00001661 c = sqlite3UpperToLower[c];
1662 }
drh9f504ea2008-02-23 21:55:39 +00001663 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001664 }
drhae80dde2012-12-06 21:16:43 +00001665 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1666 sCollSeqName.n = 6;
1667 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001668 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
drh0a8a4062012-12-07 18:38:16 +00001669 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001670 pStr1, 0);
drh9eb20282005-08-24 03:52:18 +00001671 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001672 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001673 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001674 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001675 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
drh0a8a4062012-12-07 18:38:16 +00001676 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001677 pStr2, 0);
drh9eb20282005-08-24 03:52:18 +00001678 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001679 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001680 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001681 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001682 if( isComplete ){
drh9eb20282005-08-24 03:52:18 +00001683 pWC->a[idxNew1].iParent = idxTerm;
1684 pWC->a[idxNew2].iParent = idxTerm;
drhd2687b72005-08-12 22:56:09 +00001685 pTerm->nChild = 2;
1686 }
1687 }
1688#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001689
1690#ifndef SQLITE_OMIT_VIRTUALTABLE
1691 /* Add a WO_MATCH auxiliary term to the constraint set if the
1692 ** current expression is of the form: column MATCH expr.
1693 ** This information is used by the xBestIndex methods of
1694 ** virtual tables. The native query optimizer does not attempt
1695 ** to do anything with MATCH functions.
1696 */
1697 if( isMatchOfColumn(pExpr) ){
1698 int idxNew;
1699 Expr *pRight, *pLeft;
1700 WhereTerm *pNewTerm;
1701 Bitmask prereqColumn, prereqExpr;
1702
danielk19776ab3a2e2009-02-19 14:39:25 +00001703 pRight = pExpr->x.pList->a[0].pExpr;
1704 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001705 prereqExpr = exprTableUsage(pMaskSet, pRight);
1706 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1707 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001708 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001709 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1710 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001711 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001712 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001713 pNewTerm = &pWC->a[idxNew];
1714 pNewTerm->prereqRight = prereqExpr;
1715 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001716 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001717 pNewTerm->eOperator = WO_MATCH;
1718 pNewTerm->iParent = idxTerm;
drhd2ca60d2006-06-27 02:36:58 +00001719 pTerm = &pWC->a[idxTerm];
drh7f375902006-06-13 17:38:59 +00001720 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001721 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001722 pNewTerm->prereqAll = pTerm->prereqAll;
1723 }
1724 }
1725#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001726
drhfaacf172011-08-12 01:51:45 +00001727#ifdef SQLITE_ENABLE_STAT3
drhd3ed7342011-09-21 00:09:41 +00001728 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001729 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1730 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1731 ** virtual term of that form.
1732 **
1733 ** Note that the virtual term must be tagged with TERM_VNULL. This
1734 ** TERM_VNULL tag will suppress the not-null check at the beginning
1735 ** of the loop. Without the TERM_VNULL flag, the not-null check at
1736 ** the start of the loop will prevent any results from being returned.
1737 */
drhea6dc442011-04-08 21:35:26 +00001738 if( pExpr->op==TK_NOTNULL
1739 && pExpr->pLeft->op==TK_COLUMN
1740 && pExpr->pLeft->iColumn>=0
1741 ){
drh534230c2011-01-22 00:10:45 +00001742 Expr *pNewExpr;
1743 Expr *pLeft = pExpr->pLeft;
1744 int idxNew;
1745 WhereTerm *pNewTerm;
1746
1747 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1748 sqlite3ExprDup(db, pLeft, 0),
1749 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1750
1751 idxNew = whereClauseInsert(pWC, pNewExpr,
1752 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001753 if( idxNew ){
1754 pNewTerm = &pWC->a[idxNew];
1755 pNewTerm->prereqRight = 0;
1756 pNewTerm->leftCursor = pLeft->iTable;
1757 pNewTerm->u.leftColumn = pLeft->iColumn;
1758 pNewTerm->eOperator = WO_GT;
1759 pNewTerm->iParent = idxTerm;
1760 pTerm = &pWC->a[idxTerm];
1761 pTerm->nChild = 1;
1762 pTerm->wtFlags |= TERM_COPIED;
1763 pNewTerm->prereqAll = pTerm->prereqAll;
1764 }
drh534230c2011-01-22 00:10:45 +00001765 }
drhfaacf172011-08-12 01:51:45 +00001766#endif /* SQLITE_ENABLE_STAT */
drh534230c2011-01-22 00:10:45 +00001767
drhdafc0ce2008-04-17 19:14:02 +00001768 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1769 ** an index for tables to the left of the join.
1770 */
1771 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001772}
1773
drh7b4fc6a2007-02-06 13:26:32 +00001774/*
drh3b48e8c2013-06-12 20:18:16 +00001775** This function searches pList for a entry that matches the iCol-th column
1776** of index pIdx.
dan6f343962011-07-01 18:26:40 +00001777**
1778** If such an expression is found, its index in pList->a[] is returned. If
1779** no expression is found, -1 is returned.
1780*/
1781static int findIndexCol(
1782 Parse *pParse, /* Parse context */
1783 ExprList *pList, /* Expression list to search */
1784 int iBase, /* Cursor for table associated with pIdx */
1785 Index *pIdx, /* Index to match column of */
1786 int iCol /* Column of index to match */
1787){
1788 int i;
1789 const char *zColl = pIdx->azColl[iCol];
1790
1791 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001792 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001793 if( p->op==TK_COLUMN
1794 && p->iColumn==pIdx->aiColumn[iCol]
1795 && p->iTable==iBase
1796 ){
drh580c8c12012-12-08 03:34:04 +00001797 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001798 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001799 return i;
1800 }
1801 }
1802 }
1803
1804 return -1;
1805}
1806
1807/*
dan6f343962011-07-01 18:26:40 +00001808** Return true if the DISTINCT expression-list passed as the third argument
drh4f402f22013-06-11 18:59:38 +00001809** is redundant.
1810**
drh3b48e8c2013-06-12 20:18:16 +00001811** A DISTINCT list is redundant if the database contains some subset of
drh4f402f22013-06-11 18:59:38 +00001812** columns that are unique and non-null.
dan6f343962011-07-01 18:26:40 +00001813*/
1814static int isDistinctRedundant(
drh4f402f22013-06-11 18:59:38 +00001815 Parse *pParse, /* Parsing context */
1816 SrcList *pTabList, /* The FROM clause */
1817 WhereClause *pWC, /* The WHERE clause */
1818 ExprList *pDistinct /* The result set that needs to be DISTINCT */
dan6f343962011-07-01 18:26:40 +00001819){
1820 Table *pTab;
1821 Index *pIdx;
1822 int i;
1823 int iBase;
1824
1825 /* If there is more than one table or sub-select in the FROM clause of
1826 ** this query, then it will not be possible to show that the DISTINCT
1827 ** clause is redundant. */
1828 if( pTabList->nSrc!=1 ) return 0;
1829 iBase = pTabList->a[0].iCursor;
1830 pTab = pTabList->a[0].pTab;
1831
dan94e08d92011-07-02 06:44:05 +00001832 /* If any of the expressions is an IPK column on table iBase, then return
1833 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1834 ** current SELECT is a correlated sub-query.
1835 */
dan6f343962011-07-01 18:26:40 +00001836 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001837 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001838 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001839 }
1840
1841 /* Loop through all indices on the table, checking each to see if it makes
1842 ** the DISTINCT qualifier redundant. It does so if:
1843 **
1844 ** 1. The index is itself UNIQUE, and
1845 **
1846 ** 2. All of the columns in the index are either part of the pDistinct
1847 ** list, or else the WHERE clause contains a term of the form "col=X",
1848 ** where X is a constant value. The collation sequences of the
1849 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001850 **
1851 ** 3. All of those index columns for which the WHERE clause does not
1852 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001853 */
1854 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1855 if( pIdx->onError==OE_None ) continue;
1856 for(i=0; i<pIdx->nColumn; i++){
1857 int iCol = pIdx->aiColumn[i];
dan6a36f432012-04-20 16:59:24 +00001858 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1859 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
1860 if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
1861 break;
1862 }
dan6f343962011-07-01 18:26:40 +00001863 }
1864 }
1865 if( i==pIdx->nColumn ){
1866 /* This index implies that the DISTINCT qualifier is redundant. */
1867 return 1;
1868 }
1869 }
1870
1871 return 0;
1872}
drh0fcef5e2005-07-19 17:38:22 +00001873
drhb8a8e8a2013-06-10 19:12:39 +00001874/*
drh3b48e8c2013-06-12 20:18:16 +00001875** The (an approximate) sum of two WhereCosts. This computation is
1876** not a simple "+" operator because WhereCost is stored as a logarithmic
1877** value.
1878**
drhb8a8e8a2013-06-10 19:12:39 +00001879*/
1880static WhereCost whereCostAdd(WhereCost a, WhereCost b){
1881 static const unsigned char x[] = {
1882 10, 10, /* 0,1 */
1883 9, 9, /* 2,3 */
1884 8, 8, /* 4,5 */
1885 7, 7, 7, /* 6,7,8 */
1886 6, 6, 6, /* 9,10,11 */
1887 5, 5, 5, /* 12-14 */
1888 4, 4, 4, 4, /* 15-18 */
1889 3, 3, 3, 3, 3, 3, /* 19-24 */
1890 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
1891 };
1892 if( a>=b ){
1893 if( a>b+49 ) return a;
1894 if( a>b+31 ) return a+1;
1895 return a+x[a-b];
1896 }else{
1897 if( b>a+49 ) return b;
1898 if( b>a+31 ) return b+1;
1899 return b+x[b-a];
1900 }
1901}
1902
1903/*
drh3b48e8c2013-06-12 20:18:16 +00001904** Convert an integer into a WhereCost. In other words, compute a
1905** good approximatation for 10*log2(x).
drhb8a8e8a2013-06-10 19:12:39 +00001906*/
drhe1e2e9a2013-06-13 15:16:53 +00001907static WhereCost whereCost(tRowcnt x){
drhb8a8e8a2013-06-10 19:12:39 +00001908 static WhereCost a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1909 WhereCost y = 40;
1910 if( x<8 ){
1911 if( x<2 ) return 0;
1912 while( x<8 ){ y -= 10; x <<= 1; }
1913 }else{
1914 while( x>255 ){ y += 40; x >>= 4; }
1915 while( x>15 ){ y += 10; x >>= 1; }
1916 }
1917 return a[x&7] + y - 10;
1918}
1919
drh8636e9c2013-06-11 01:50:08 +00001920#ifndef SQLITE_OMIT_VIRTUALTABLE
1921/*
1922** Convert a double (as received from xBestIndex of a virtual table)
drh3b48e8c2013-06-12 20:18:16 +00001923** into a WhereCost. In other words, compute an approximation for
1924** 10*log2(x).
drh8636e9c2013-06-11 01:50:08 +00001925*/
1926static WhereCost whereCostFromDouble(double x){
1927 u64 a;
1928 WhereCost e;
1929 assert( sizeof(x)==8 && sizeof(a)==8 );
1930 if( x<=1 ) return 0;
drhe1e2e9a2013-06-13 15:16:53 +00001931 if( x<=2000000000 ) return whereCost((tRowcnt)x);
drh8636e9c2013-06-11 01:50:08 +00001932 memcpy(&a, &x, 8);
1933 e = (a>>52) - 1022;
1934 return e*10;
1935}
1936#endif /* SQLITE_OMIT_VIRTUALTABLE */
1937
drh75897232000-05-29 14:26:00 +00001938/*
drh3b48e8c2013-06-12 20:18:16 +00001939** Estimate the logarithm of the input value to base 2.
drh28c4cf42005-07-27 20:41:43 +00001940*/
drh4efc9292013-06-06 23:02:03 +00001941static WhereCost estLog(WhereCost N){
drhe1e2e9a2013-06-13 15:16:53 +00001942 WhereCost x = whereCost(N);
drh4fe425a2013-06-12 17:08:06 +00001943 return x>33 ? x - 33 : 0;
drh28c4cf42005-07-27 20:41:43 +00001944}
1945
drh6d209d82006-06-27 01:54:26 +00001946/*
1947** Two routines for printing the content of an sqlite3_index_info
1948** structure. Used for testing and debugging only. If neither
1949** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1950** are no-ops.
1951*/
drhd15cb172013-05-21 19:23:10 +00001952#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00001953static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1954 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001955 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001956 for(i=0; i<p->nConstraint; i++){
1957 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1958 i,
1959 p->aConstraint[i].iColumn,
1960 p->aConstraint[i].iTermOffset,
1961 p->aConstraint[i].op,
1962 p->aConstraint[i].usable);
1963 }
1964 for(i=0; i<p->nOrderBy; i++){
1965 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1966 i,
1967 p->aOrderBy[i].iColumn,
1968 p->aOrderBy[i].desc);
1969 }
1970}
1971static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1972 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001973 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001974 for(i=0; i<p->nConstraint; i++){
1975 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1976 i,
1977 p->aConstraintUsage[i].argvIndex,
1978 p->aConstraintUsage[i].omit);
1979 }
1980 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1981 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1982 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1983 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
1984}
1985#else
1986#define TRACE_IDX_INPUTS(A)
1987#define TRACE_IDX_OUTPUTS(A)
1988#endif
1989
drhc6339082010-04-07 16:54:58 +00001990#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001991/*
drh4139c992010-04-07 14:59:45 +00001992** Return TRUE if the WHERE clause term pTerm is of a form where it
1993** could be used with an index to access pSrc, assuming an appropriate
1994** index existed.
1995*/
1996static int termCanDriveIndex(
1997 WhereTerm *pTerm, /* WHERE clause term to check */
1998 struct SrcList_item *pSrc, /* Table we are trying to access */
1999 Bitmask notReady /* Tables in outer loops of the join */
2000){
2001 char aff;
2002 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drh7a5bcc02013-01-16 17:08:58 +00002003 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00002004 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00002005 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00002006 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
2007 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
2008 return 1;
2009}
drhc6339082010-04-07 16:54:58 +00002010#endif
drh4139c992010-04-07 14:59:45 +00002011
drhc6339082010-04-07 16:54:58 +00002012
2013#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00002014/*
drhc6339082010-04-07 16:54:58 +00002015** Generate code to construct the Index object for an automatic index
2016** and to set up the WhereLevel object pLevel so that the code generator
2017** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00002018*/
drhc6339082010-04-07 16:54:58 +00002019static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00002020 Parse *pParse, /* The parsing context */
2021 WhereClause *pWC, /* The WHERE clause */
2022 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
2023 Bitmask notReady, /* Mask of cursors that are not available */
2024 WhereLevel *pLevel /* Write new index here */
2025){
2026 int nColumn; /* Number of columns in the constructed index */
2027 WhereTerm *pTerm; /* A single term of the WHERE clause */
2028 WhereTerm *pWCEnd; /* End of pWC->a[] */
2029 int nByte; /* Byte of memory needed for pIdx */
2030 Index *pIdx; /* Object describing the transient index */
2031 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00002032 int addrInit; /* Address of the initialization bypass jump */
2033 Table *pTable; /* The table being indexed */
2034 KeyInfo *pKeyinfo; /* Key information for the index */
2035 int addrTop; /* Top of the index fill loop */
2036 int regRecord; /* Register holding an index record */
2037 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00002038 int i; /* Loop counter */
2039 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00002040 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00002041 WhereLoop *pLoop; /* The Loop object */
drh4139c992010-04-07 14:59:45 +00002042 Bitmask idxCols; /* Bitmap of columns used for indexing */
2043 Bitmask extraCols; /* Bitmap of additional columns */
drh53b52f72013-05-31 11:57:39 +00002044 const int mxConstraint = 10; /* Maximum number of constraints */
drh8b307fb2010-04-06 15:57:05 +00002045
2046 /* Generate code to skip over the creation and initialization of the
2047 ** transient index on 2nd and subsequent iterations of the loop. */
2048 v = pParse->pVdbe;
2049 assert( v!=0 );
dan1d8cb212011-12-09 13:24:16 +00002050 addrInit = sqlite3CodeOnce(pParse);
drh8b307fb2010-04-06 15:57:05 +00002051
drh4139c992010-04-07 14:59:45 +00002052 /* Count the number of columns that will be added to the index
2053 ** and used to match WHERE clause constraints */
drh8b307fb2010-04-06 15:57:05 +00002054 nColumn = 0;
drh424aab82010-04-06 18:28:20 +00002055 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00002056 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00002057 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00002058 idxCols = 0;
drh4efc9292013-06-06 23:02:03 +00002059 for(pTerm=pWC->a; pTerm<pWCEnd && pLoop->nLTerm<mxConstraint; pTerm++){
drh4139c992010-04-07 14:59:45 +00002060 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
2061 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00002062 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00002063 testcase( iCol==BMS );
2064 testcase( iCol==BMS-1 );
drh0013e722010-04-08 00:40:15 +00002065 if( (idxCols & cMask)==0 ){
drh4efc9292013-06-06 23:02:03 +00002066 if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
2067 pLoop->aLTerm[nColumn++] = pTerm;
drh0013e722010-04-08 00:40:15 +00002068 idxCols |= cMask;
2069 }
drh8b307fb2010-04-06 15:57:05 +00002070 }
2071 }
2072 assert( nColumn>0 );
drh4efc9292013-06-06 23:02:03 +00002073 pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
drh53b52f72013-05-31 11:57:39 +00002074 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
2075 | WHERE_TEMP_INDEX;
drh4139c992010-04-07 14:59:45 +00002076
2077 /* Count the number of additional columns needed to create a
2078 ** covering index. A "covering index" is an index that contains all
2079 ** columns that are needed by the query. With a covering index, the
2080 ** original table never needs to be accessed. Automatic indices must
2081 ** be a covering index because the index will not be updated if the
2082 ** original table changes and the index and table cannot both be used
2083 ** if they go out of sync.
2084 */
drh7699d1c2013-06-04 12:42:29 +00002085 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drh4139c992010-04-07 14:59:45 +00002086 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
drh52ff8ea2010-04-08 14:15:56 +00002087 testcase( pTable->nCol==BMS-1 );
2088 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00002089 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00002090 if( extraCols & MASKBIT(i) ) nColumn++;
drh4139c992010-04-07 14:59:45 +00002091 }
drh7699d1c2013-06-04 12:42:29 +00002092 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00002093 nColumn += pTable->nCol - BMS + 1;
2094 }
drh7ba39a92013-05-30 17:43:19 +00002095 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
drh8b307fb2010-04-06 15:57:05 +00002096
2097 /* Construct the Index object to describe this index */
2098 nByte = sizeof(Index);
2099 nByte += nColumn*sizeof(int); /* Index.aiColumn */
2100 nByte += nColumn*sizeof(char*); /* Index.azColl */
2101 nByte += nColumn; /* Index.aSortOrder */
2102 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
2103 if( pIdx==0 ) return;
drh7ba39a92013-05-30 17:43:19 +00002104 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00002105 pIdx->azColl = (char**)&pIdx[1];
2106 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
2107 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
2108 pIdx->zName = "auto-index";
2109 pIdx->nColumn = nColumn;
drh424aab82010-04-06 18:28:20 +00002110 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00002111 n = 0;
drh0013e722010-04-08 00:40:15 +00002112 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00002113 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00002114 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00002115 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00002116 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh0013e722010-04-08 00:40:15 +00002117 if( (idxCols & cMask)==0 ){
2118 Expr *pX = pTerm->pExpr;
2119 idxCols |= cMask;
2120 pIdx->aiColumn[n] = pTerm->u.leftColumn;
2121 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh6f2e6c02011-02-17 13:33:15 +00002122 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00002123 n++;
2124 }
drh8b307fb2010-04-06 15:57:05 +00002125 }
2126 }
drh7ba39a92013-05-30 17:43:19 +00002127 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00002128
drhc6339082010-04-07 16:54:58 +00002129 /* Add additional columns needed to make the automatic index into
2130 ** a covering index */
drh4139c992010-04-07 14:59:45 +00002131 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00002132 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00002133 pIdx->aiColumn[n] = i;
2134 pIdx->azColl[n] = "BINARY";
2135 n++;
2136 }
2137 }
drh7699d1c2013-06-04 12:42:29 +00002138 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00002139 for(i=BMS-1; i<pTable->nCol; i++){
2140 pIdx->aiColumn[n] = i;
2141 pIdx->azColl[n] = "BINARY";
2142 n++;
2143 }
2144 }
2145 assert( n==nColumn );
drh8b307fb2010-04-06 15:57:05 +00002146
drhc6339082010-04-07 16:54:58 +00002147 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00002148 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
2149 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00002150 pLevel->iIdxCur = pParse->nTab++;
drha21a64d2010-04-06 22:33:55 +00002151 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
drh8b307fb2010-04-06 15:57:05 +00002152 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
drha21a64d2010-04-06 22:33:55 +00002153 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00002154
drhc6339082010-04-07 16:54:58 +00002155 /* Fill the automatic index with content */
drh8b307fb2010-04-06 15:57:05 +00002156 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
2157 regRecord = sqlite3GetTempReg(pParse);
2158 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
2159 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
2160 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2161 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
drha21a64d2010-04-06 22:33:55 +00002162 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00002163 sqlite3VdbeJumpHere(v, addrTop);
2164 sqlite3ReleaseTempReg(pParse, regRecord);
2165
2166 /* Jump here when skipping the initialization */
2167 sqlite3VdbeJumpHere(v, addrInit);
2168}
drhc6339082010-04-07 16:54:58 +00002169#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00002170
drh9eff6162006-06-12 21:59:13 +00002171#ifndef SQLITE_OMIT_VIRTUALTABLE
2172/*
danielk19771d461462009-04-21 09:02:45 +00002173** Allocate and populate an sqlite3_index_info structure. It is the
2174** responsibility of the caller to eventually release the structure
2175** by passing the pointer returned by this function to sqlite3_free().
2176*/
drh5346e952013-05-08 14:14:26 +00002177static sqlite3_index_info *allocateIndexInfo(
2178 Parse *pParse,
2179 WhereClause *pWC,
2180 struct SrcList_item *pSrc,
2181 ExprList *pOrderBy
2182){
danielk19771d461462009-04-21 09:02:45 +00002183 int i, j;
2184 int nTerm;
2185 struct sqlite3_index_constraint *pIdxCons;
2186 struct sqlite3_index_orderby *pIdxOrderBy;
2187 struct sqlite3_index_constraint_usage *pUsage;
2188 WhereTerm *pTerm;
2189 int nOrderBy;
2190 sqlite3_index_info *pIdxInfo;
2191
danielk19771d461462009-04-21 09:02:45 +00002192 /* Count the number of possible WHERE clause constraints referring
2193 ** to this virtual table */
2194 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
2195 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00002196 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2197 testcase( pTerm->eOperator & WO_IN );
2198 testcase( pTerm->eOperator & WO_ISNULL );
drh281bbe22012-10-16 23:17:14 +00002199 if( pTerm->eOperator & (WO_ISNULL) ) continue;
drhb4256992011-08-02 01:57:39 +00002200 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00002201 nTerm++;
2202 }
2203
2204 /* If the ORDER BY clause contains only columns in the current
2205 ** virtual table then allocate space for the aOrderBy part of
2206 ** the sqlite3_index_info structure.
2207 */
2208 nOrderBy = 0;
2209 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00002210 int n = pOrderBy->nExpr;
2211 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00002212 Expr *pExpr = pOrderBy->a[i].pExpr;
2213 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
2214 }
drh56f1b992012-09-25 14:29:39 +00002215 if( i==n){
2216 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00002217 }
2218 }
2219
2220 /* Allocate the sqlite3_index_info structure
2221 */
2222 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
2223 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
2224 + sizeof(*pIdxOrderBy)*nOrderBy );
2225 if( pIdxInfo==0 ){
2226 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00002227 return 0;
2228 }
2229
2230 /* Initialize the structure. The sqlite3_index_info structure contains
2231 ** many fields that are declared "const" to prevent xBestIndex from
2232 ** changing them. We have to do some funky casting in order to
2233 ** initialize those fields.
2234 */
2235 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
2236 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
2237 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
2238 *(int*)&pIdxInfo->nConstraint = nTerm;
2239 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
2240 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
2241 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
2242 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
2243 pUsage;
2244
2245 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00002246 u8 op;
danielk19771d461462009-04-21 09:02:45 +00002247 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00002248 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2249 testcase( pTerm->eOperator & WO_IN );
2250 testcase( pTerm->eOperator & WO_ISNULL );
drh281bbe22012-10-16 23:17:14 +00002251 if( pTerm->eOperator & (WO_ISNULL) ) continue;
drhb4256992011-08-02 01:57:39 +00002252 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00002253 pIdxCons[j].iColumn = pTerm->u.leftColumn;
2254 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00002255 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00002256 if( op==WO_IN ) op = WO_EQ;
2257 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00002258 /* The direct assignment in the previous line is possible only because
2259 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
2260 ** following asserts verify this fact. */
2261 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
2262 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
2263 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
2264 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
2265 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
2266 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00002267 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00002268 j++;
2269 }
2270 for(i=0; i<nOrderBy; i++){
2271 Expr *pExpr = pOrderBy->a[i].pExpr;
2272 pIdxOrderBy[i].iColumn = pExpr->iColumn;
2273 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
2274 }
2275
2276 return pIdxInfo;
2277}
2278
2279/*
2280** The table object reference passed as the second argument to this function
2281** must represent a virtual table. This function invokes the xBestIndex()
drh3b48e8c2013-06-12 20:18:16 +00002282** method of the virtual table with the sqlite3_index_info object that
2283** comes in as the 3rd argument to this function.
danielk19771d461462009-04-21 09:02:45 +00002284**
2285** If an error occurs, pParse is populated with an error message and a
2286** non-zero value is returned. Otherwise, 0 is returned and the output
2287** part of the sqlite3_index_info structure is left populated.
2288**
2289** Whether or not an error is returned, it is the responsibility of the
2290** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
2291** that this is required.
2292*/
2293static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00002294 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00002295 int i;
2296 int rc;
2297
danielk19771d461462009-04-21 09:02:45 +00002298 TRACE_IDX_INPUTS(p);
2299 rc = pVtab->pModule->xBestIndex(pVtab, p);
2300 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00002301
2302 if( rc!=SQLITE_OK ){
2303 if( rc==SQLITE_NOMEM ){
2304 pParse->db->mallocFailed = 1;
2305 }else if( !pVtab->zErrMsg ){
2306 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
2307 }else{
2308 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
2309 }
2310 }
drhb9755982010-07-24 16:34:37 +00002311 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00002312 pVtab->zErrMsg = 0;
2313
2314 for(i=0; i<p->nConstraint; i++){
2315 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
2316 sqlite3ErrorMsg(pParse,
2317 "table %s: xBestIndex returned an invalid plan", pTab->zName);
2318 }
2319 }
2320
2321 return pParse->nErr;
2322}
drh7ba39a92013-05-30 17:43:19 +00002323#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00002324
2325
drhfaacf172011-08-12 01:51:45 +00002326#ifdef SQLITE_ENABLE_STAT3
drh28c4cf42005-07-27 20:41:43 +00002327/*
drhfaacf172011-08-12 01:51:45 +00002328** Estimate the location of a particular key among all keys in an
2329** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00002330**
drhfaacf172011-08-12 01:51:45 +00002331** aStat[0] Est. number of rows less than pVal
2332** aStat[1] Est. number of rows equal to pVal
dan02fa4692009-08-17 17:06:58 +00002333**
drhfaacf172011-08-12 01:51:45 +00002334** Return SQLITE_OK on success.
dan02fa4692009-08-17 17:06:58 +00002335*/
drhfaacf172011-08-12 01:51:45 +00002336static int whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00002337 Parse *pParse, /* Database connection */
2338 Index *pIdx, /* Index to consider domain of */
2339 sqlite3_value *pVal, /* Value to consider */
drhfaacf172011-08-12 01:51:45 +00002340 int roundUp, /* Round up if true. Round down if false */
2341 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00002342){
drhfaacf172011-08-12 01:51:45 +00002343 tRowcnt n;
2344 IndexSample *aSample;
2345 int i, eType;
2346 int isEq = 0;
drh4e50c5e2011-08-13 19:35:19 +00002347 i64 v;
drhb8a8e8a2013-06-10 19:12:39 +00002348 double r, rS;
dan02fa4692009-08-17 17:06:58 +00002349
drhfaacf172011-08-12 01:51:45 +00002350 assert( roundUp==0 || roundUp==1 );
drh5c624862011-09-22 18:46:34 +00002351 assert( pIdx->nSample>0 );
drhfaacf172011-08-12 01:51:45 +00002352 if( pVal==0 ) return SQLITE_ERROR;
2353 n = pIdx->aiRowEst[0];
2354 aSample = pIdx->aSample;
drhfaacf172011-08-12 01:51:45 +00002355 eType = sqlite3_value_type(pVal);
2356
2357 if( eType==SQLITE_INTEGER ){
drh4e50c5e2011-08-13 19:35:19 +00002358 v = sqlite3_value_int64(pVal);
2359 r = (i64)v;
drhfaacf172011-08-12 01:51:45 +00002360 for(i=0; i<pIdx->nSample; i++){
2361 if( aSample[i].eType==SQLITE_NULL ) continue;
2362 if( aSample[i].eType>=SQLITE_TEXT ) break;
drh4e50c5e2011-08-13 19:35:19 +00002363 if( aSample[i].eType==SQLITE_INTEGER ){
2364 if( aSample[i].u.i>=v ){
2365 isEq = aSample[i].u.i==v;
2366 break;
2367 }
2368 }else{
2369 assert( aSample[i].eType==SQLITE_FLOAT );
2370 if( aSample[i].u.r>=r ){
2371 isEq = aSample[i].u.r==r;
2372 break;
2373 }
dan02fa4692009-08-17 17:06:58 +00002374 }
drhfaacf172011-08-12 01:51:45 +00002375 }
2376 }else if( eType==SQLITE_FLOAT ){
drh4e50c5e2011-08-13 19:35:19 +00002377 r = sqlite3_value_double(pVal);
drhfaacf172011-08-12 01:51:45 +00002378 for(i=0; i<pIdx->nSample; i++){
2379 if( aSample[i].eType==SQLITE_NULL ) continue;
2380 if( aSample[i].eType>=SQLITE_TEXT ) break;
drh4e50c5e2011-08-13 19:35:19 +00002381 if( aSample[i].eType==SQLITE_FLOAT ){
2382 rS = aSample[i].u.r;
2383 }else{
2384 rS = aSample[i].u.i;
2385 }
2386 if( rS>=r ){
2387 isEq = rS==r;
drhfaacf172011-08-12 01:51:45 +00002388 break;
drh9b3eb0a2011-01-21 14:37:04 +00002389 }
drhfaacf172011-08-12 01:51:45 +00002390 }
2391 }else if( eType==SQLITE_NULL ){
2392 i = 0;
drh5c624862011-09-22 18:46:34 +00002393 if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
drhfaacf172011-08-12 01:51:45 +00002394 }else{
2395 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
2396 for(i=0; i<pIdx->nSample; i++){
2397 if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
2398 break;
2399 }
2400 }
2401 if( i<pIdx->nSample ){
dan02fa4692009-08-17 17:06:58 +00002402 sqlite3 *db = pParse->db;
2403 CollSeq *pColl;
2404 const u8 *z;
dan02fa4692009-08-17 17:06:58 +00002405 if( eType==SQLITE_BLOB ){
2406 z = (const u8 *)sqlite3_value_blob(pVal);
2407 pColl = db->pDfltColl;
dane275dc32009-08-18 16:24:58 +00002408 assert( pColl->enc==SQLITE_UTF8 );
dan02fa4692009-08-17 17:06:58 +00002409 }else{
drh79e72a52012-10-05 14:43:40 +00002410 pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
drh9aeda792009-08-20 02:34:15 +00002411 if( pColl==0 ){
dane275dc32009-08-18 16:24:58 +00002412 return SQLITE_ERROR;
2413 }
dan02fa4692009-08-17 17:06:58 +00002414 z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
dane275dc32009-08-18 16:24:58 +00002415 if( !z ){
2416 return SQLITE_NOMEM;
2417 }
dan02fa4692009-08-17 17:06:58 +00002418 assert( z && pColl && pColl->xCmp );
2419 }
2420 n = sqlite3ValueBytes(pVal, pColl->enc);
drhfaacf172011-08-12 01:51:45 +00002421
2422 for(; i<pIdx->nSample; i++){
drhe847d322011-01-20 02:56:37 +00002423 int c;
dan02fa4692009-08-17 17:06:58 +00002424 int eSampletype = aSample[i].eType;
drhfaacf172011-08-12 01:51:45 +00002425 if( eSampletype<eType ) continue;
2426 if( eSampletype!=eType ) break;
dane83c4f32009-09-21 16:34:24 +00002427#ifndef SQLITE_OMIT_UTF16
2428 if( pColl->enc!=SQLITE_UTF8 ){
dane275dc32009-08-18 16:24:58 +00002429 int nSample;
2430 char *zSample = sqlite3Utf8to16(
dan02fa4692009-08-17 17:06:58 +00002431 db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
2432 );
dane275dc32009-08-18 16:24:58 +00002433 if( !zSample ){
2434 assert( db->mallocFailed );
2435 return SQLITE_NOMEM;
2436 }
drhe847d322011-01-20 02:56:37 +00002437 c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
dane275dc32009-08-18 16:24:58 +00002438 sqlite3DbFree(db, zSample);
dane83c4f32009-09-21 16:34:24 +00002439 }else
2440#endif
2441 {
drhe847d322011-01-20 02:56:37 +00002442 c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
dan02fa4692009-08-17 17:06:58 +00002443 }
drhfaacf172011-08-12 01:51:45 +00002444 if( c>=0 ){
2445 if( c==0 ) isEq = 1;
2446 break;
2447 }
dan02fa4692009-08-17 17:06:58 +00002448 }
2449 }
drhfaacf172011-08-12 01:51:45 +00002450 }
dan02fa4692009-08-17 17:06:58 +00002451
drhfaacf172011-08-12 01:51:45 +00002452 /* At this point, aSample[i] is the first sample that is greater than
2453 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
2454 ** than pVal. If aSample[i]==pVal, then isEq==1.
2455 */
2456 if( isEq ){
2457 assert( i<pIdx->nSample );
2458 aStat[0] = aSample[i].nLt;
2459 aStat[1] = aSample[i].nEq;
2460 }else{
2461 tRowcnt iLower, iUpper, iGap;
2462 if( i==0 ){
2463 iLower = 0;
2464 iUpper = aSample[0].nLt;
drhfaacf172011-08-12 01:51:45 +00002465 }else{
drh4e50c5e2011-08-13 19:35:19 +00002466 iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
drhfaacf172011-08-12 01:51:45 +00002467 iLower = aSample[i-1].nEq + aSample[i-1].nLt;
drhfaacf172011-08-12 01:51:45 +00002468 }
drh4e50c5e2011-08-13 19:35:19 +00002469 aStat[1] = pIdx->avgEq;
drhfaacf172011-08-12 01:51:45 +00002470 if( iLower>=iUpper ){
2471 iGap = 0;
2472 }else{
2473 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00002474 }
2475 if( roundUp ){
2476 iGap = (iGap*2)/3;
2477 }else{
2478 iGap = iGap/3;
2479 }
2480 aStat[0] = iLower + iGap;
dan02fa4692009-08-17 17:06:58 +00002481 }
2482 return SQLITE_OK;
2483}
drhfaacf172011-08-12 01:51:45 +00002484#endif /* SQLITE_ENABLE_STAT3 */
dan02fa4692009-08-17 17:06:58 +00002485
2486/*
dan937d0de2009-10-15 18:35:38 +00002487** If expression pExpr represents a literal value, set *pp to point to
2488** an sqlite3_value structure containing the same value, with affinity
2489** aff applied to it, before returning. It is the responsibility of the
2490** caller to eventually release this structure by passing it to
2491** sqlite3ValueFree().
2492**
2493** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
2494** is an SQL variable that currently has a non-NULL value bound to it,
2495** create an sqlite3_value structure containing this value, again with
2496** affinity aff applied to it, instead.
2497**
2498** If neither of the above apply, set *pp to NULL.
2499**
2500** If an error occurs, return an error code. Otherwise, SQLITE_OK.
2501*/
drhfaacf172011-08-12 01:51:45 +00002502#ifdef SQLITE_ENABLE_STAT3
dan937d0de2009-10-15 18:35:38 +00002503static int valueFromExpr(
2504 Parse *pParse,
2505 Expr *pExpr,
2506 u8 aff,
2507 sqlite3_value **pp
2508){
drh4278d532010-12-16 19:52:52 +00002509 if( pExpr->op==TK_VARIABLE
2510 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
2511 ){
dan937d0de2009-10-15 18:35:38 +00002512 int iVar = pExpr->iColumn;
drhf9b22ca2011-10-21 16:47:31 +00002513 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
dan937d0de2009-10-15 18:35:38 +00002514 *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
2515 return SQLITE_OK;
2516 }
2517 return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
2518}
danf7b0b0a2009-10-19 15:52:32 +00002519#endif
dan937d0de2009-10-15 18:35:38 +00002520
2521/*
dan02fa4692009-08-17 17:06:58 +00002522** This function is used to estimate the number of rows that will be visited
2523** by scanning an index for a range of values. The range may have an upper
2524** bound, a lower bound, or both. The WHERE clause terms that set the upper
2525** and lower bounds are represented by pLower and pUpper respectively. For
2526** example, assuming that index p is on t1(a):
2527**
2528** ... FROM t1 WHERE a > ? AND a < ? ...
2529** |_____| |_____|
2530** | |
2531** pLower pUpper
2532**
drh98cdf622009-08-20 18:14:42 +00002533** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00002534** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00002535**
2536** The nEq parameter is passed the index of the index column subject to the
2537** range constraint. Or, equivalently, the number of equality constraints
2538** optimized by the proposed index scan. For example, assuming index p is
2539** on t1(a, b), and the SQL query is:
2540**
2541** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2542**
2543** then nEq should be passed the value 1 (as the range restricted column,
2544** b, is the second left-most column of the index). Or, if the query is:
2545**
2546** ... FROM t1 WHERE a > ? AND a < ? ...
2547**
2548** then nEq should be passed 0.
2549**
drhfaacf172011-08-12 01:51:45 +00002550** The returned value is an integer divisor to reduce the estimated
2551** search space. A return value of 1 means that range constraints are
2552** no help at all. A return value of 2 means range constraints are
2553** expected to reduce the search space by half. And so forth...
drh98cdf622009-08-20 18:14:42 +00002554**
drhfaacf172011-08-12 01:51:45 +00002555** In the absence of sqlite_stat3 ANALYZE data, each range inequality
2556** reduces the search space by a factor of 4. Hence a single constraint (x>?)
2557** results in a return of 4 and a range constraint (x>? AND x<?) results
2558** in a return of 16.
dan02fa4692009-08-17 17:06:58 +00002559*/
2560static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002561 Parse *pParse, /* Parsing & code generating context */
2562 Index *p, /* The index containing the range-compared column; "x" */
2563 int nEq, /* index into p->aCol[] of the range-compared column */
2564 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2565 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
drh4efc9292013-06-06 23:02:03 +00002566 WhereCost *pRangeDiv /* OUT: Reduce search space by this divisor */
dan02fa4692009-08-17 17:06:58 +00002567){
dan69188d92009-08-19 08:18:32 +00002568 int rc = SQLITE_OK;
2569
drhfaacf172011-08-12 01:51:45 +00002570#ifdef SQLITE_ENABLE_STAT3
dan02fa4692009-08-17 17:06:58 +00002571
drhfaacf172011-08-12 01:51:45 +00002572 if( nEq==0 && p->nSample ){
2573 sqlite3_value *pRangeVal;
2574 tRowcnt iLower = 0;
2575 tRowcnt iUpper = p->aiRowEst[0];
2576 tRowcnt a[2];
dan937d0de2009-10-15 18:35:38 +00002577 u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
drh98cdf622009-08-20 18:14:42 +00002578
dan02fa4692009-08-17 17:06:58 +00002579 if( pLower ){
2580 Expr *pExpr = pLower->pExpr->pRight;
drhfaacf172011-08-12 01:51:45 +00002581 rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
drh7a5bcc02013-01-16 17:08:58 +00002582 assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
drhfaacf172011-08-12 01:51:45 +00002583 if( rc==SQLITE_OK
2584 && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
2585 ){
2586 iLower = a[0];
drh7a5bcc02013-01-16 17:08:58 +00002587 if( (pLower->eOperator & WO_GT)!=0 ) iLower += a[1];
drhfaacf172011-08-12 01:51:45 +00002588 }
2589 sqlite3ValueFree(pRangeVal);
dan02fa4692009-08-17 17:06:58 +00002590 }
drh98cdf622009-08-20 18:14:42 +00002591 if( rc==SQLITE_OK && pUpper ){
dan02fa4692009-08-17 17:06:58 +00002592 Expr *pExpr = pUpper->pExpr->pRight;
drhfaacf172011-08-12 01:51:45 +00002593 rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
drh7a5bcc02013-01-16 17:08:58 +00002594 assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
drhfaacf172011-08-12 01:51:45 +00002595 if( rc==SQLITE_OK
2596 && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
2597 ){
2598 iUpper = a[0];
drh7a5bcc02013-01-16 17:08:58 +00002599 if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
dan02fa4692009-08-17 17:06:58 +00002600 }
drhfaacf172011-08-12 01:51:45 +00002601 sqlite3ValueFree(pRangeVal);
dan02fa4692009-08-17 17:06:58 +00002602 }
drhfaacf172011-08-12 01:51:45 +00002603 if( rc==SQLITE_OK ){
drhe1e2e9a2013-06-13 15:16:53 +00002604 WhereCost iBase = whereCost(p->aiRowEst[0]);
drhb8a8e8a2013-06-10 19:12:39 +00002605 if( iUpper>iLower ){
drhe1e2e9a2013-06-13 15:16:53 +00002606 iBase -= whereCost(iUpper - iLower);
drhfaacf172011-08-12 01:51:45 +00002607 }
drhb8a8e8a2013-06-10 19:12:39 +00002608 *pRangeDiv = iBase;
drh3b48e8c2013-06-12 20:18:16 +00002609 WHERETRACE(0x100, ("range scan regions: %u..%u div=%d\n",
2610 (u32)iLower, (u32)iUpper, *pRangeDiv));
drhfaacf172011-08-12 01:51:45 +00002611 return SQLITE_OK;
drh98cdf622009-08-20 18:14:42 +00002612 }
dan02fa4692009-08-17 17:06:58 +00002613 }
drh3f022182009-09-09 16:10:50 +00002614#else
2615 UNUSED_PARAMETER(pParse);
2616 UNUSED_PARAMETER(p);
2617 UNUSED_PARAMETER(nEq);
dan69188d92009-08-19 08:18:32 +00002618#endif
dan02fa4692009-08-17 17:06:58 +00002619 assert( pLower || pUpper );
drhb8a8e8a2013-06-10 19:12:39 +00002620 *pRangeDiv = 0;
drhe1e2e9a2013-06-13 15:16:53 +00002621 /* TUNING: Each inequality constraint reduces the search space 4-fold.
2622 ** A BETWEEN operator, therefore, reduces the search space 16-fold */
drhb8a8e8a2013-06-10 19:12:39 +00002623 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00002624 *pRangeDiv += 20; assert( 20==whereCost(4) );
drhb8a8e8a2013-06-10 19:12:39 +00002625 }
2626 if( pUpper ){
drhe1e2e9a2013-06-13 15:16:53 +00002627 *pRangeDiv += 20; assert( 20==whereCost(4) );
drhb8a8e8a2013-06-10 19:12:39 +00002628 }
dan02fa4692009-08-17 17:06:58 +00002629 return rc;
2630}
2631
drhfaacf172011-08-12 01:51:45 +00002632#ifdef SQLITE_ENABLE_STAT3
drh82759752011-01-20 16:52:09 +00002633/*
2634** Estimate the number of rows that will be returned based on
2635** an equality constraint x=VALUE and where that VALUE occurs in
2636** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002637** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002638** for that index. When pExpr==NULL that means the constraint is
2639** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002640**
drh0c50fa02011-01-21 16:27:18 +00002641** Write the estimated row count into *pnRow and return SQLITE_OK.
2642** If unable to make an estimate, leave *pnRow unchanged and return
2643** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002644**
2645** This routine can fail if it is unable to load a collating sequence
2646** required for string comparison, or if unable to allocate memory
2647** for a UTF conversion required for comparison. The error is stored
2648** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002649*/
drh041e09f2011-04-07 19:56:21 +00002650static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002651 Parse *pParse, /* Parsing & code generating context */
2652 Index *p, /* The index whose left-most column is pTerm */
drh0c50fa02011-01-21 16:27:18 +00002653 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drhb8a8e8a2013-06-10 19:12:39 +00002654 tRowcnt *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002655){
2656 sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
drh82759752011-01-20 16:52:09 +00002657 u8 aff; /* Column affinity */
2658 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002659 tRowcnt a[2]; /* Statistics */
drh82759752011-01-20 16:52:09 +00002660
2661 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002662 assert( p->nSample>0 );
drh82759752011-01-20 16:52:09 +00002663 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
drh1f9c7662011-03-17 01:34:26 +00002664 if( pExpr ){
2665 rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
2666 if( rc ) goto whereEqualScanEst_cancel;
2667 }else{
2668 pRhs = sqlite3ValueNew(pParse->db);
2669 }
drh0c50fa02011-01-21 16:27:18 +00002670 if( pRhs==0 ) return SQLITE_NOTFOUND;
drhfaacf172011-08-12 01:51:45 +00002671 rc = whereKeyStats(pParse, p, pRhs, 0, a);
2672 if( rc==SQLITE_OK ){
drh3b48e8c2013-06-12 20:18:16 +00002673 WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
drhfaacf172011-08-12 01:51:45 +00002674 *pnRow = a[1];
drh82759752011-01-20 16:52:09 +00002675 }
drh0c50fa02011-01-21 16:27:18 +00002676whereEqualScanEst_cancel:
drh82759752011-01-20 16:52:09 +00002677 sqlite3ValueFree(pRhs);
drh0c50fa02011-01-21 16:27:18 +00002678 return rc;
2679}
drhfaacf172011-08-12 01:51:45 +00002680#endif /* defined(SQLITE_ENABLE_STAT3) */
drh0c50fa02011-01-21 16:27:18 +00002681
drhfaacf172011-08-12 01:51:45 +00002682#ifdef SQLITE_ENABLE_STAT3
drh0c50fa02011-01-21 16:27:18 +00002683/*
2684** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002685** an IN constraint where the right-hand side of the IN operator
2686** is a list of values. Example:
2687**
2688** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002689**
2690** Write the estimated row count into *pnRow and return SQLITE_OK.
2691** If unable to make an estimate, leave *pnRow unchanged and return
2692** non-zero.
2693**
2694** This routine can fail if it is unable to load a collating sequence
2695** required for string comparison, or if unable to allocate memory
2696** for a UTF conversion required for comparison. The error is stored
2697** in the pParse structure.
2698*/
drh041e09f2011-04-07 19:56:21 +00002699static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002700 Parse *pParse, /* Parsing & code generating context */
2701 Index *p, /* The index whose left-most column is pTerm */
2702 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drhb8a8e8a2013-06-10 19:12:39 +00002703 tRowcnt *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002704){
drhb8a8e8a2013-06-10 19:12:39 +00002705 int rc = SQLITE_OK; /* Subfunction return code */
2706 tRowcnt nEst; /* Number of rows for a single term */
2707 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2708 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002709
2710 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002711 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2712 nEst = p->aiRowEst[0];
2713 rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
2714 nRowEst += nEst;
drh0c50fa02011-01-21 16:27:18 +00002715 }
2716 if( rc==SQLITE_OK ){
drh0c50fa02011-01-21 16:27:18 +00002717 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
2718 *pnRow = nRowEst;
drh3b48e8c2013-06-12 20:18:16 +00002719 WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
drh0c50fa02011-01-21 16:27:18 +00002720 }
drh0c50fa02011-01-21 16:27:18 +00002721 return rc;
drh82759752011-01-20 16:52:09 +00002722}
drhfaacf172011-08-12 01:51:45 +00002723#endif /* defined(SQLITE_ENABLE_STAT3) */
drh82759752011-01-20 16:52:09 +00002724
drh46c35f92012-09-26 23:17:01 +00002725/*
drh2ffb1182004-07-19 19:14:01 +00002726** Disable a term in the WHERE clause. Except, do not disable the term
2727** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2728** or USING clause of that join.
2729**
2730** Consider the term t2.z='ok' in the following queries:
2731**
2732** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2733** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2734** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2735**
drh23bf66d2004-12-14 03:34:34 +00002736** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002737** in the ON clause. The term is disabled in (3) because it is not part
2738** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2739**
drhe9cdcea2010-07-22 22:40:03 +00002740** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
2741** completely satisfied by indices.
2742**
drh2ffb1182004-07-19 19:14:01 +00002743** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002744** of the join. Disabling is an optimization. When terms are satisfied
2745** by indices, we disable them to prevent redundant tests in the inner
2746** loop. We would get the correct results if nothing were ever disabled,
2747** but joins might run a little slower. The trick is to disable as much
2748** as we can without disabling too much. If we disabled in (1), we'd get
2749** the wrong answer. See ticket #813.
drh2ffb1182004-07-19 19:14:01 +00002750*/
drh0fcef5e2005-07-19 17:38:22 +00002751static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
2752 if( pTerm
drhbe837bd2010-04-30 21:03:24 +00002753 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002754 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
2755 ){
drh165be382008-12-05 02:36:33 +00002756 pTerm->wtFlags |= TERM_CODED;
drh45b1ee42005-08-02 17:48:22 +00002757 if( pTerm->iParent>=0 ){
2758 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
2759 if( (--pOther->nChild)==0 ){
drhed378002005-07-28 23:12:08 +00002760 disableTerm(pLevel, pOther);
2761 }
drh0fcef5e2005-07-19 17:38:22 +00002762 }
drh2ffb1182004-07-19 19:14:01 +00002763 }
2764}
2765
2766/*
dan69f8bb92009-08-13 19:21:16 +00002767** Code an OP_Affinity opcode to apply the column affinity string zAff
2768** to the n registers starting at base.
2769**
drh039fc322009-11-17 18:31:47 +00002770** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2771** beginning and end of zAff are ignored. If all entries in zAff are
2772** SQLITE_AFF_NONE, then no code gets generated.
2773**
2774** This routine makes its own copy of zAff so that the caller is free
2775** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002776*/
dan69f8bb92009-08-13 19:21:16 +00002777static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2778 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002779 if( zAff==0 ){
2780 assert( pParse->db->mallocFailed );
2781 return;
2782 }
dan69f8bb92009-08-13 19:21:16 +00002783 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002784
2785 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2786 ** and end of the affinity string.
2787 */
2788 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2789 n--;
2790 base++;
2791 zAff++;
2792 }
2793 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2794 n--;
2795 }
2796
2797 /* Code the OP_Affinity opcode if there is anything left to do. */
2798 if( n>0 ){
2799 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2800 sqlite3VdbeChangeP4(v, -1, zAff, n);
2801 sqlite3ExprCacheAffinityChange(pParse, base, n);
2802 }
drh94a11212004-09-25 13:12:14 +00002803}
2804
drhe8b97272005-07-19 22:22:12 +00002805
2806/*
drh51147ba2005-07-23 22:59:55 +00002807** Generate code for a single equality term of the WHERE clause. An equality
2808** term can be either X=expr or X IN (...). pTerm is the term to be
2809** coded.
2810**
drh1db639c2008-01-17 02:36:28 +00002811** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002812**
2813** For a constraint of the form X=expr, the expression is evaluated and its
2814** result is left on the stack. For constraints of the form X IN (...)
2815** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002816*/
drh678ccce2008-03-31 18:19:54 +00002817static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002818 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002819 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh0fe456b2013-03-12 18:34:50 +00002820 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
2821 int iEq, /* Index of the equality term within this level */
drh7ba39a92013-05-30 17:43:19 +00002822 int bRev, /* True for reverse-order IN operations */
drh678ccce2008-03-31 18:19:54 +00002823 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002824){
drh0fcef5e2005-07-19 17:38:22 +00002825 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002826 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002827 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002828
danielk19772d605492008-10-01 08:43:03 +00002829 assert( iTarget>0 );
drh50b39962006-10-28 00:28:09 +00002830 if( pX->op==TK_EQ ){
drh678ccce2008-03-31 18:19:54 +00002831 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002832 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002833 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002834 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002835#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002836 }else{
danielk19779a96b662007-11-29 17:05:18 +00002837 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002838 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002839 struct InLoop *pIn;
drh7ba39a92013-05-30 17:43:19 +00002840 WhereLoop *pLoop = pLevel->pWLoop;
danielk1977b3bce662005-01-29 08:32:43 +00002841
drh7ba39a92013-05-30 17:43:19 +00002842 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
2843 && pLoop->u.btree.pIndex!=0
2844 && pLoop->u.btree.pIndex->aSortOrder[iEq]
drhd3832162013-03-12 18:49:25 +00002845 ){
drh725e1ae2013-03-12 23:58:42 +00002846 testcase( iEq==0 );
drh725e1ae2013-03-12 23:58:42 +00002847 testcase( bRev );
drh1ccce442013-03-12 20:38:51 +00002848 bRev = !bRev;
drh0fe456b2013-03-12 18:34:50 +00002849 }
drh50b39962006-10-28 00:28:09 +00002850 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002851 iReg = iTarget;
danielk19770cdc0222008-06-26 18:04:03 +00002852 eType = sqlite3FindInIndex(pParse, pX, 0);
drh725e1ae2013-03-12 23:58:42 +00002853 if( eType==IN_INDEX_INDEX_DESC ){
2854 testcase( bRev );
2855 bRev = !bRev;
2856 }
danielk1977b3bce662005-01-29 08:32:43 +00002857 iTab = pX->iTable;
drh2d96b932013-02-08 18:48:23 +00002858 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
drh6fa978d2013-05-30 19:29:19 +00002859 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
2860 pLoop->wsFlags |= WHERE_IN_ABLE;
drh111a6a72008-12-21 03:51:16 +00002861 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002862 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00002863 }
drh111a6a72008-12-21 03:51:16 +00002864 pLevel->u.in.nIn++;
2865 pLevel->u.in.aInLoop =
2866 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2867 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2868 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00002869 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00002870 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00002871 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00002872 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00002873 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00002874 }else{
drhb3190c12008-12-08 21:37:14 +00002875 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00002876 }
drh2d96b932013-02-08 18:48:23 +00002877 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
drh1db639c2008-01-17 02:36:28 +00002878 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
drha6110402005-07-28 20:51:19 +00002879 }else{
drh111a6a72008-12-21 03:51:16 +00002880 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00002881 }
danielk1977b3bce662005-01-29 08:32:43 +00002882#endif
drh94a11212004-09-25 13:12:14 +00002883 }
drh0fcef5e2005-07-19 17:38:22 +00002884 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00002885 return iReg;
drh94a11212004-09-25 13:12:14 +00002886}
2887
drh51147ba2005-07-23 22:59:55 +00002888/*
2889** Generate code that will evaluate all == and IN constraints for an
drh039fc322009-11-17 18:31:47 +00002890** index.
drh51147ba2005-07-23 22:59:55 +00002891**
2892** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2893** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
2894** The index has as many as three equality constraints, but in this
2895** example, the third "c" value is an inequality. So only two
2896** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00002897** a==5 and b IN (1,2,3). The current values for a and b will be stored
2898** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00002899**
2900** In the example above nEq==2. But this subroutine works for any value
2901** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00002902** The only thing it does is allocate the pLevel->iMem memory cell and
2903** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00002904**
drh700a2262008-12-17 19:22:15 +00002905** This routine always allocates at least one memory cell and returns
2906** the index of that memory cell. The code that
2907** calls this routine will use that memory cell to store the termination
drh51147ba2005-07-23 22:59:55 +00002908** key value of the loop. If one or more IN operators appear, then
2909** this routine allocates an additional nEq memory cells for internal
2910** use.
dan69f8bb92009-08-13 19:21:16 +00002911**
2912** Before returning, *pzAff is set to point to a buffer containing a
2913** copy of the column affinity string of the index allocated using
2914** sqlite3DbMalloc(). Except, entries in the copy of the string associated
2915** with equality constraints that use NONE affinity are set to
2916** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
2917**
2918** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
2919** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
2920**
2921** In the example above, the index on t1(a) has TEXT affinity. But since
2922** the right hand side of the equality constraint (t2.b) has NONE affinity,
2923** no conversion should be attempted before using a t2.b value as part of
2924** a key to search the index. Hence the first byte in the returned affinity
2925** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00002926*/
drh1db639c2008-01-17 02:36:28 +00002927static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00002928 Parse *pParse, /* Parsing context */
2929 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
2930 WhereClause *pWC, /* The WHERE clause */
drh1db639c2008-01-17 02:36:28 +00002931 Bitmask notReady, /* Which parts of FROM have not yet been coded */
drh7ba39a92013-05-30 17:43:19 +00002932 int bRev, /* Reverse the order of IN operators */
dan69f8bb92009-08-13 19:21:16 +00002933 int nExtraReg, /* Number of extra registers to allocate */
2934 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00002935){
drh7ba39a92013-05-30 17:43:19 +00002936 int nEq; /* The number of == or IN constraints to code */
drh111a6a72008-12-21 03:51:16 +00002937 Vdbe *v = pParse->pVdbe; /* The vm under construction */
2938 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00002939 WhereTerm *pTerm; /* A single constraint term */
drh7ba39a92013-05-30 17:43:19 +00002940 WhereLoop *pLoop; /* The WhereLoop object */
drh51147ba2005-07-23 22:59:55 +00002941 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00002942 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00002943 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00002944 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00002945
drh111a6a72008-12-21 03:51:16 +00002946 /* This module is only called on query plans that use an index. */
drh7ba39a92013-05-30 17:43:19 +00002947 pLoop = pLevel->pWLoop;
2948 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
2949 nEq = pLoop->u.btree.nEq;
2950 pIdx = pLoop->u.btree.pIndex;
2951 assert( pIdx!=0 );
drh111a6a72008-12-21 03:51:16 +00002952
drh51147ba2005-07-23 22:59:55 +00002953 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00002954 */
drh700a2262008-12-17 19:22:15 +00002955 regBase = pParse->nMem + 1;
drh7ba39a92013-05-30 17:43:19 +00002956 nReg = pLoop->u.btree.nEq + nExtraReg;
drh6df2acd2008-12-28 16:55:25 +00002957 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00002958
dan69f8bb92009-08-13 19:21:16 +00002959 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
2960 if( !zAff ){
2961 pParse->db->mallocFailed = 1;
2962 }
2963
drh51147ba2005-07-23 22:59:55 +00002964 /* Evaluate the equality constraints
2965 */
drhc49de5d2007-01-19 01:06:01 +00002966 assert( pIdx->nColumn>=nEq );
2967 for(j=0; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00002968 int r1;
drh4efc9292013-06-06 23:02:03 +00002969 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00002970 assert( pTerm!=0 );
drhbe837bd2010-04-30 21:03:24 +00002971 /* The following true for indices with redundant columns.
2972 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
2973 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drhe9cdcea2010-07-22 22:40:03 +00002974 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh7ba39a92013-05-30 17:43:19 +00002975 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
drh678ccce2008-03-31 18:19:54 +00002976 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00002977 if( nReg==1 ){
2978 sqlite3ReleaseTempReg(pParse, regBase);
2979 regBase = r1;
2980 }else{
2981 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
2982 }
drh678ccce2008-03-31 18:19:54 +00002983 }
drh981642f2008-04-19 14:40:43 +00002984 testcase( pTerm->eOperator & WO_ISNULL );
2985 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00002986 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00002987 Expr *pRight = pTerm->pExpr->pRight;
drh2f2855b2009-11-18 01:25:26 +00002988 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
drh039fc322009-11-17 18:31:47 +00002989 if( zAff ){
2990 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
2991 zAff[j] = SQLITE_AFF_NONE;
2992 }
2993 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
2994 zAff[j] = SQLITE_AFF_NONE;
2995 }
dan69f8bb92009-08-13 19:21:16 +00002996 }
drh51147ba2005-07-23 22:59:55 +00002997 }
2998 }
dan69f8bb92009-08-13 19:21:16 +00002999 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00003000 return regBase;
drh51147ba2005-07-23 22:59:55 +00003001}
3002
dan2ce22452010-11-08 19:01:16 +00003003#ifndef SQLITE_OMIT_EXPLAIN
dan17c0bc02010-11-09 17:35:19 +00003004/*
drh69174c42010-11-12 15:35:59 +00003005** This routine is a helper for explainIndexRange() below
3006**
3007** pStr holds the text of an expression that we are building up one term
3008** at a time. This routine adds a new term to the end of the expression.
3009** Terms are separated by AND so add the "AND" text for second and subsequent
3010** terms only.
3011*/
3012static void explainAppendTerm(
3013 StrAccum *pStr, /* The text expression being built */
3014 int iTerm, /* Index of this term. First is zero */
3015 const char *zColumn, /* Name of the column */
3016 const char *zOp /* Name of the operator */
3017){
3018 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
3019 sqlite3StrAccumAppend(pStr, zColumn, -1);
3020 sqlite3StrAccumAppend(pStr, zOp, 1);
3021 sqlite3StrAccumAppend(pStr, "?", 1);
3022}
3023
3024/*
dan17c0bc02010-11-09 17:35:19 +00003025** Argument pLevel describes a strategy for scanning table pTab. This
3026** function returns a pointer to a string buffer containing a description
3027** of the subset of table rows scanned by the strategy in the form of an
3028** SQL expression. Or, if all rows are scanned, NULL is returned.
3029**
3030** For example, if the query:
3031**
3032** SELECT * FROM t1 WHERE a=1 AND b>2;
3033**
3034** is run and there is an index on (a, b), then this function returns a
3035** string similar to:
3036**
3037** "a=? AND b>?"
3038**
3039** The returned pointer points to memory obtained from sqlite3DbMalloc().
3040** It is the responsibility of the caller to free the buffer when it is
3041** no longer required.
3042*/
drhef866372013-05-22 20:49:02 +00003043static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
3044 Index *pIndex = pLoop->u.btree.pIndex;
3045 int nEq = pLoop->u.btree.nEq;
drh69174c42010-11-12 15:35:59 +00003046 int i, j;
3047 Column *aCol = pTab->aCol;
3048 int *aiColumn = pIndex->aiColumn;
3049 StrAccum txt;
dan2ce22452010-11-08 19:01:16 +00003050
drhef866372013-05-22 20:49:02 +00003051 if( pIndex==0 ) return 0;
3052 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
drh69174c42010-11-12 15:35:59 +00003053 return 0;
3054 }
3055 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
drh03b6df12010-11-15 16:29:30 +00003056 txt.db = db;
drh69174c42010-11-12 15:35:59 +00003057 sqlite3StrAccumAppend(&txt, " (", 2);
dan2ce22452010-11-08 19:01:16 +00003058 for(i=0; i<nEq; i++){
drh69174c42010-11-12 15:35:59 +00003059 explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
dan2ce22452010-11-08 19:01:16 +00003060 }
3061
drh69174c42010-11-12 15:35:59 +00003062 j = i;
drhef866372013-05-22 20:49:02 +00003063 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
dan0c733f62011-11-16 15:27:09 +00003064 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
3065 explainAppendTerm(&txt, i++, z, ">");
dan2ce22452010-11-08 19:01:16 +00003066 }
drhef866372013-05-22 20:49:02 +00003067 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
dan0c733f62011-11-16 15:27:09 +00003068 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
3069 explainAppendTerm(&txt, i, z, "<");
dan2ce22452010-11-08 19:01:16 +00003070 }
drh69174c42010-11-12 15:35:59 +00003071 sqlite3StrAccumAppend(&txt, ")", 1);
3072 return sqlite3StrAccumFinish(&txt);
dan2ce22452010-11-08 19:01:16 +00003073}
3074
dan17c0bc02010-11-09 17:35:19 +00003075/*
3076** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
3077** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
3078** record is added to the output to describe the table scan strategy in
3079** pLevel.
3080*/
3081static void explainOneScan(
dan2ce22452010-11-08 19:01:16 +00003082 Parse *pParse, /* Parse context */
3083 SrcList *pTabList, /* Table list this loop refers to */
3084 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
3085 int iLevel, /* Value for "level" column of output */
dan4a07e3d2010-11-09 14:48:59 +00003086 int iFrom, /* Value for "from" column of output */
3087 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
dan2ce22452010-11-08 19:01:16 +00003088){
3089 if( pParse->explain==2 ){
dan2ce22452010-11-08 19:01:16 +00003090 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
dan17c0bc02010-11-09 17:35:19 +00003091 Vdbe *v = pParse->pVdbe; /* VM being constructed */
3092 sqlite3 *db = pParse->db; /* Database handle */
3093 char *zMsg; /* Text to add to EQP output */
dan4a07e3d2010-11-09 14:48:59 +00003094 int iId = pParse->iSelectId; /* Select id (left-most output column) */
dan4bc39fa2010-11-13 16:42:27 +00003095 int isSearch; /* True for a SEARCH. False for SCAN. */
drhef866372013-05-22 20:49:02 +00003096 WhereLoop *pLoop; /* The controlling WhereLoop object */
3097 u32 flags; /* Flags that describe this loop */
dan2ce22452010-11-08 19:01:16 +00003098
drhef866372013-05-22 20:49:02 +00003099 pLoop = pLevel->pWLoop;
3100 flags = pLoop->wsFlags;
dan4a07e3d2010-11-09 14:48:59 +00003101 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
dan2ce22452010-11-08 19:01:16 +00003102
drhef866372013-05-22 20:49:02 +00003103 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
3104 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
3105 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
dan4bc39fa2010-11-13 16:42:27 +00003106
3107 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
dan4a07e3d2010-11-09 14:48:59 +00003108 if( pItem->pSelect ){
dan4bc39fa2010-11-13 16:42:27 +00003109 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
dan4a07e3d2010-11-09 14:48:59 +00003110 }else{
dan4bc39fa2010-11-13 16:42:27 +00003111 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
dan4a07e3d2010-11-09 14:48:59 +00003112 }
3113
dan2ce22452010-11-08 19:01:16 +00003114 if( pItem->zAlias ){
3115 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
3116 }
drhef866372013-05-22 20:49:02 +00003117 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
3118 && pLoop->u.btree.pIndex!=0
3119 ){
3120 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
dan4bc39fa2010-11-13 16:42:27 +00003121 zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
dan2ce22452010-11-08 19:01:16 +00003122 ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
3123 ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
3124 ((flags & WHERE_TEMP_INDEX)?"":" "),
drhef866372013-05-22 20:49:02 +00003125 ((flags & WHERE_TEMP_INDEX)?"": pLoop->u.btree.pIndex->zName),
dan2ce22452010-11-08 19:01:16 +00003126 zWhere
3127 );
3128 sqlite3DbFree(db, zWhere);
drhef71c1f2013-06-04 12:58:02 +00003129 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
dan4bc39fa2010-11-13 16:42:27 +00003130 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
dan2ce22452010-11-08 19:01:16 +00003131
drh8e23daf2013-06-11 13:30:04 +00003132 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
dan2ce22452010-11-08 19:01:16 +00003133 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
drh04098e62010-11-15 21:50:19 +00003134 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
dan2ce22452010-11-08 19:01:16 +00003135 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
3136 }else if( flags&WHERE_BTM_LIMIT ){
3137 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
3138 }else if( flags&WHERE_TOP_LIMIT ){
3139 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
3140 }
3141 }
3142#ifndef SQLITE_OMIT_VIRTUALTABLE
3143 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
dan2ce22452010-11-08 19:01:16 +00003144 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
drhef866372013-05-22 20:49:02 +00003145 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
dan2ce22452010-11-08 19:01:16 +00003146 }
3147#endif
drhb8a8e8a2013-06-10 19:12:39 +00003148 zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
dan4a07e3d2010-11-09 14:48:59 +00003149 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
dan2ce22452010-11-08 19:01:16 +00003150 }
3151}
3152#else
dan17c0bc02010-11-09 17:35:19 +00003153# define explainOneScan(u,v,w,x,y,z)
dan2ce22452010-11-08 19:01:16 +00003154#endif /* SQLITE_OMIT_EXPLAIN */
3155
3156
drh111a6a72008-12-21 03:51:16 +00003157/*
3158** Generate code for the start of the iLevel-th loop in the WHERE clause
3159** implementation described by pWInfo.
3160*/
3161static Bitmask codeOneLoopStart(
3162 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
3163 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh7a484802012-03-16 00:28:11 +00003164 Bitmask notReady /* Which tables are currently available */
drh111a6a72008-12-21 03:51:16 +00003165){
3166 int j, k; /* Loop counters */
3167 int iCur; /* The VDBE cursor for the table */
3168 int addrNxt; /* Where to jump to continue with the next IN case */
3169 int omitTable; /* True if we use the index only */
3170 int bRev; /* True if we need to scan in reverse order */
3171 WhereLevel *pLevel; /* The where level to be coded */
drh7ba39a92013-05-30 17:43:19 +00003172 WhereLoop *pLoop; /* The WhereLoop object being coded */
drh111a6a72008-12-21 03:51:16 +00003173 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
3174 WhereTerm *pTerm; /* A WHERE clause term */
3175 Parse *pParse; /* Parsing context */
3176 Vdbe *v; /* The prepared stmt under constructions */
3177 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00003178 int addrBrk; /* Jump here to break out of the loop */
3179 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00003180 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
3181 int iReleaseReg = 0; /* Temp register to free before returning */
drh0c41d222013-04-22 02:39:10 +00003182 Bitmask newNotReady; /* Return value */
drh111a6a72008-12-21 03:51:16 +00003183
3184 pParse = pWInfo->pParse;
3185 v = pParse->pVdbe;
drh70d18342013-06-06 19:16:33 +00003186 pWC = &pWInfo->sWC;
drh111a6a72008-12-21 03:51:16 +00003187 pLevel = &pWInfo->a[iLevel];
drh7ba39a92013-05-30 17:43:19 +00003188 pLoop = pLevel->pWLoop;
drh111a6a72008-12-21 03:51:16 +00003189 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
3190 iCur = pTabItem->iCursor;
drh7ba39a92013-05-30 17:43:19 +00003191 bRev = (pWInfo->revMask>>iLevel)&1;
3192 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drh70d18342013-06-06 19:16:33 +00003193 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
drh0c41d222013-04-22 02:39:10 +00003194 VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
drh111a6a72008-12-21 03:51:16 +00003195
3196 /* Create labels for the "break" and "continue" instructions
3197 ** for the current loop. Jump to addrBrk to break out of a loop.
3198 ** Jump to cont to go immediately to the next iteration of the
3199 ** loop.
3200 **
3201 ** When there is an IN operator, we also have a "addrNxt" label that
3202 ** means to continue with the next IN value combination. When
3203 ** there are no IN operators in the constraints, the "addrNxt" label
3204 ** is the same as "addrBrk".
3205 */
3206 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
3207 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
3208
3209 /* If this is the right table of a LEFT OUTER JOIN, allocate and
3210 ** initialize a memory cell that records if this table matches any
3211 ** row of the left table of the join.
3212 */
3213 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
3214 pLevel->iLeftJoin = ++pParse->nMem;
3215 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
3216 VdbeComment((v, "init LEFT JOIN no-match flag"));
3217 }
3218
drh21172c42012-10-30 00:29:07 +00003219 /* Special case of a FROM clause subquery implemented as a co-routine */
3220 if( pTabItem->viaCoroutine ){
3221 int regYield = pTabItem->regReturn;
3222 sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
3223 pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
3224 VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
3225 sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
3226 pLevel->op = OP_Goto;
3227 }else
3228
drh111a6a72008-12-21 03:51:16 +00003229#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00003230 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
3231 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
drh111a6a72008-12-21 03:51:16 +00003232 ** to access the data.
3233 */
3234 int iReg; /* P3 Value for OP_VFilter */
drh281bbe22012-10-16 23:17:14 +00003235 int addrNotFound;
drh4efc9292013-06-06 23:02:03 +00003236 int nConstraint = pLoop->nLTerm;
drh111a6a72008-12-21 03:51:16 +00003237
drha62bb8d2009-11-23 21:23:45 +00003238 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00003239 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh281bbe22012-10-16 23:17:14 +00003240 addrNotFound = pLevel->addrBrk;
drh111a6a72008-12-21 03:51:16 +00003241 for(j=0; j<nConstraint; j++){
drhe2250172013-05-31 18:13:50 +00003242 int iTarget = iReg+j+2;
drh4efc9292013-06-06 23:02:03 +00003243 pTerm = pLoop->aLTerm[j];
drh95ed68d2013-06-12 17:55:50 +00003244 if( pTerm==0 ) continue;
drh7ba39a92013-05-30 17:43:19 +00003245 if( pTerm->eOperator & WO_IN ){
3246 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
3247 addrNotFound = pLevel->addrNxt;
3248 }else{
3249 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
3250 }
3251 }
3252 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
drh7e47cb82013-05-31 17:55:27 +00003253 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
drh7ba39a92013-05-30 17:43:19 +00003254 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
3255 pLoop->u.vtab.idxStr,
3256 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
3257 pLoop->u.vtab.needFree = 0;
3258 for(j=0; j<nConstraint && j<16; j++){
3259 if( (pLoop->u.vtab.omitMask>>j)&1 ){
drh4efc9292013-06-06 23:02:03 +00003260 disableTerm(pLevel, pLoop->aLTerm[j]);
drh111a6a72008-12-21 03:51:16 +00003261 }
3262 }
3263 pLevel->op = OP_VNext;
3264 pLevel->p1 = iCur;
3265 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00003266 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drha62bb8d2009-11-23 21:23:45 +00003267 sqlite3ExprCachePop(pParse, 1);
drh111a6a72008-12-21 03:51:16 +00003268 }else
3269#endif /* SQLITE_OMIT_VIRTUALTABLE */
3270
drh7ba39a92013-05-30 17:43:19 +00003271 if( (pLoop->wsFlags & WHERE_IPK)!=0
3272 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
3273 ){
3274 /* Case 2: We can directly reference a single row using an
drh111a6a72008-12-21 03:51:16 +00003275 ** equality comparison against the ROWID field. Or
3276 ** we reference multiple rows using a "rowid IN (...)"
3277 ** construct.
3278 */
drh7ba39a92013-05-30 17:43:19 +00003279 assert( pLoop->u.btree.nEq==1 );
danielk19771d461462009-04-21 09:02:45 +00003280 iReleaseReg = sqlite3GetTempReg(pParse);
drh4efc9292013-06-06 23:02:03 +00003281 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003282 assert( pTerm!=0 );
3283 assert( pTerm->pExpr!=0 );
drh111a6a72008-12-21 03:51:16 +00003284 assert( omitTable==0 );
drhe9cdcea2010-07-22 22:40:03 +00003285 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh7ba39a92013-05-30 17:43:19 +00003286 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00003287 addrNxt = pLevel->addrNxt;
danielk19771d461462009-04-21 09:02:45 +00003288 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
3289 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drh459f63e2013-03-06 01:55:27 +00003290 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
drhceea3322009-04-23 13:22:42 +00003291 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00003292 VdbeComment((v, "pk"));
3293 pLevel->op = OP_Noop;
drh7ba39a92013-05-30 17:43:19 +00003294 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
3295 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
3296 ){
3297 /* Case 3: We have an inequality comparison against the ROWID field.
drh111a6a72008-12-21 03:51:16 +00003298 */
3299 int testOp = OP_Noop;
3300 int start;
3301 int memEndValue = 0;
3302 WhereTerm *pStart, *pEnd;
3303
3304 assert( omitTable==0 );
drh7ba39a92013-05-30 17:43:19 +00003305 j = 0;
3306 pStart = pEnd = 0;
drh4efc9292013-06-06 23:02:03 +00003307 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
3308 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
drh111a6a72008-12-21 03:51:16 +00003309 if( bRev ){
3310 pTerm = pStart;
3311 pStart = pEnd;
3312 pEnd = pTerm;
3313 }
3314 if( pStart ){
3315 Expr *pX; /* The expression that defines the start bound */
3316 int r1, rTemp; /* Registers for holding the start boundary */
3317
3318 /* The following constant maps TK_xx codes into corresponding
3319 ** seek opcodes. It depends on a particular ordering of TK_xx
3320 */
3321 const u8 aMoveOp[] = {
3322 /* TK_GT */ OP_SeekGt,
3323 /* TK_LE */ OP_SeekLe,
3324 /* TK_LT */ OP_SeekLt,
3325 /* TK_GE */ OP_SeekGe
3326 };
3327 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
3328 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
3329 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
3330
drhe9cdcea2010-07-22 22:40:03 +00003331 testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003332 pX = pStart->pExpr;
3333 assert( pX!=0 );
3334 assert( pStart->leftCursor==iCur );
3335 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
3336 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
3337 VdbeComment((v, "pk"));
3338 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
3339 sqlite3ReleaseTempReg(pParse, rTemp);
3340 disableTerm(pLevel, pStart);
3341 }else{
3342 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
3343 }
3344 if( pEnd ){
3345 Expr *pX;
3346 pX = pEnd->pExpr;
3347 assert( pX!=0 );
3348 assert( pEnd->leftCursor==iCur );
drhe9cdcea2010-07-22 22:40:03 +00003349 testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003350 memEndValue = ++pParse->nMem;
3351 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
3352 if( pX->op==TK_LT || pX->op==TK_GT ){
3353 testOp = bRev ? OP_Le : OP_Ge;
3354 }else{
3355 testOp = bRev ? OP_Lt : OP_Gt;
3356 }
3357 disableTerm(pLevel, pEnd);
3358 }
3359 start = sqlite3VdbeCurrentAddr(v);
3360 pLevel->op = bRev ? OP_Prev : OP_Next;
3361 pLevel->p1 = iCur;
3362 pLevel->p2 = start;
drhafc266a2010-03-31 17:47:44 +00003363 if( pStart==0 && pEnd==0 ){
3364 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3365 }else{
3366 assert( pLevel->p5==0 );
3367 }
danielk19771d461462009-04-21 09:02:45 +00003368 if( testOp!=OP_Noop ){
3369 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3370 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003371 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003372 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
3373 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003374 }
drh1b0f0262013-05-30 22:27:09 +00003375 }else if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00003376 /* Case 4: A scan using an index.
drh111a6a72008-12-21 03:51:16 +00003377 **
3378 ** The WHERE clause may contain zero or more equality
3379 ** terms ("==" or "IN" operators) that refer to the N
3380 ** left-most columns of the index. It may also contain
3381 ** inequality constraints (>, <, >= or <=) on the indexed
3382 ** column that immediately follows the N equalities. Only
3383 ** the right-most column can be an inequality - the rest must
3384 ** use the "==" and "IN" operators. For example, if the
3385 ** index is on (x,y,z), then the following clauses are all
3386 ** optimized:
3387 **
3388 ** x=5
3389 ** x=5 AND y=10
3390 ** x=5 AND y<10
3391 ** x=5 AND y>5 AND y<10
3392 ** x=5 AND y=5 AND z<=10
3393 **
3394 ** The z<10 term of the following cannot be used, only
3395 ** the x=5 term:
3396 **
3397 ** x=5 AND z<10
3398 **
3399 ** N may be zero if there are inequality constraints.
3400 ** If there are no inequality constraints, then N is at
3401 ** least one.
3402 **
3403 ** This case is also used when there are no WHERE clause
3404 ** constraints but an index is selected anyway, in order
3405 ** to force the output order to conform to an ORDER BY.
3406 */
drh3bb9b932010-08-06 02:10:00 +00003407 static const u8 aStartOp[] = {
drh111a6a72008-12-21 03:51:16 +00003408 0,
3409 0,
3410 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
3411 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
3412 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
3413 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
3414 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
3415 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
3416 };
drh3bb9b932010-08-06 02:10:00 +00003417 static const u8 aEndOp[] = {
drh111a6a72008-12-21 03:51:16 +00003418 OP_Noop, /* 0: (!end_constraints) */
3419 OP_IdxGE, /* 1: (end_constraints && !bRev) */
3420 OP_IdxLT /* 2: (end_constraints && bRev) */
3421 };
drh7ba39a92013-05-30 17:43:19 +00003422 int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
3423 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
drh111a6a72008-12-21 03:51:16 +00003424 int regBase; /* Base register holding constraint values */
3425 int r1; /* Temp register */
3426 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
3427 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
3428 int startEq; /* True if range start uses ==, >= or <= */
3429 int endEq; /* True if range end uses ==, >= or <= */
3430 int start_constraints; /* Start of range is constrained */
3431 int nConstraint; /* Number of constraint terms */
drh3bb9b932010-08-06 02:10:00 +00003432 Index *pIdx; /* The index we will be using */
3433 int iIdxCur; /* The VDBE cursor for the index */
3434 int nExtraReg = 0; /* Number of extra registers needed */
3435 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00003436 char *zStartAff; /* Affinity for start of range constraint */
3437 char *zEndAff; /* Affinity for end of range constraint */
drh111a6a72008-12-21 03:51:16 +00003438
drh7ba39a92013-05-30 17:43:19 +00003439 pIdx = pLoop->u.btree.pIndex;
drh111a6a72008-12-21 03:51:16 +00003440 iIdxCur = pLevel->iIdxCur;
dan0c733f62011-11-16 15:27:09 +00003441 k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
drh111a6a72008-12-21 03:51:16 +00003442
drh111a6a72008-12-21 03:51:16 +00003443 /* If this loop satisfies a sort order (pOrderBy) request that
3444 ** was passed to this function to implement a "SELECT min(x) ..."
3445 ** query, then the caller will only allow the loop to run for
3446 ** a single iteration. This means that the first row returned
3447 ** should not have a NULL value stored in 'x'. If column 'x' is
3448 ** the first one after the nEq equality constraints in the index,
3449 ** this requires some special handling.
3450 */
drh70d18342013-06-06 19:16:33 +00003451 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
drh4f402f22013-06-11 18:59:38 +00003452 && (pWInfo->bOBSat!=0)
drh111a6a72008-12-21 03:51:16 +00003453 && (pIdx->nColumn>nEq)
3454 ){
3455 /* assert( pOrderBy->nExpr==1 ); */
3456 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
3457 isMinQuery = 1;
drh6df2acd2008-12-28 16:55:25 +00003458 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003459 }
3460
3461 /* Find any inequality constraint terms for the start and end
3462 ** of the range.
3463 */
drh7ba39a92013-05-30 17:43:19 +00003464 j = nEq;
3465 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003466 pRangeStart = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003467 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003468 }
drh7ba39a92013-05-30 17:43:19 +00003469 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003470 pRangeEnd = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003471 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003472 }
3473
drh6df2acd2008-12-28 16:55:25 +00003474 /* Generate code to evaluate all constraint terms using == or IN
3475 ** and store the values of those terms in an array of registers
3476 ** starting at regBase.
3477 */
dan69f8bb92009-08-13 19:21:16 +00003478 regBase = codeAllEqualityTerms(
drh7ba39a92013-05-30 17:43:19 +00003479 pParse, pLevel, pWC, notReady, bRev, nExtraReg, &zStartAff
dan69f8bb92009-08-13 19:21:16 +00003480 );
dan6ac43392010-06-09 15:47:11 +00003481 zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
drh6df2acd2008-12-28 16:55:25 +00003482 addrNxt = pLevel->addrNxt;
3483
drh111a6a72008-12-21 03:51:16 +00003484 /* If we are doing a reverse order scan on an ascending index, or
3485 ** a forward order scan on a descending index, interchange the
3486 ** start and end terms (pRangeStart and pRangeEnd).
3487 */
dan0c733f62011-11-16 15:27:09 +00003488 if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3489 || (bRev && pIdx->nColumn==nEq)
3490 ){
drh111a6a72008-12-21 03:51:16 +00003491 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
3492 }
3493
3494 testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
3495 testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
3496 testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
3497 testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
3498 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3499 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3500 start_constraints = pRangeStart || nEq>0;
3501
3502 /* Seek the index cursor to the start of the range. */
3503 nConstraint = nEq;
3504 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003505 Expr *pRight = pRangeStart->pExpr->pRight;
3506 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003507 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
3508 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3509 }
dan6ac43392010-06-09 15:47:11 +00003510 if( zStartAff ){
3511 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003512 /* Since the comparison is to be performed with no conversions
3513 ** applied to the operands, set the affinity to apply to pRight to
3514 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003515 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003516 }
dan6ac43392010-06-09 15:47:11 +00003517 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3518 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003519 }
3520 }
drh111a6a72008-12-21 03:51:16 +00003521 nConstraint++;
drhe9cdcea2010-07-22 22:40:03 +00003522 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003523 }else if( isMinQuery ){
3524 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3525 nConstraint++;
3526 startEq = 0;
3527 start_constraints = 1;
3528 }
dan6ac43392010-06-09 15:47:11 +00003529 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003530 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3531 assert( op!=0 );
3532 testcase( op==OP_Rewind );
3533 testcase( op==OP_Last );
3534 testcase( op==OP_SeekGt );
3535 testcase( op==OP_SeekGe );
3536 testcase( op==OP_SeekLe );
3537 testcase( op==OP_SeekLt );
drh8cff69d2009-11-12 19:59:44 +00003538 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh111a6a72008-12-21 03:51:16 +00003539
3540 /* Load the value for the inequality constraint at the end of the
3541 ** range (if any).
3542 */
3543 nConstraint = nEq;
3544 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003545 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003546 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003547 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003548 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
3549 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3550 }
dan6ac43392010-06-09 15:47:11 +00003551 if( zEndAff ){
3552 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003553 /* Since the comparison is to be performed with no conversions
3554 ** applied to the operands, set the affinity to apply to pRight to
3555 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003556 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003557 }
dan6ac43392010-06-09 15:47:11 +00003558 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
3559 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003560 }
3561 }
dan6ac43392010-06-09 15:47:11 +00003562 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003563 nConstraint++;
drhe9cdcea2010-07-22 22:40:03 +00003564 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003565 }
dan6ac43392010-06-09 15:47:11 +00003566 sqlite3DbFree(pParse->db, zStartAff);
3567 sqlite3DbFree(pParse->db, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003568
3569 /* Top of the loop body */
3570 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3571
3572 /* Check if the index cursor is past the end of the range. */
3573 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
3574 testcase( op==OP_Noop );
3575 testcase( op==OP_IdxGE );
3576 testcase( op==OP_IdxLT );
drh6df2acd2008-12-28 16:55:25 +00003577 if( op!=OP_Noop ){
drh8cff69d2009-11-12 19:59:44 +00003578 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh6df2acd2008-12-28 16:55:25 +00003579 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
3580 }
drh111a6a72008-12-21 03:51:16 +00003581
3582 /* If there are inequality constraints, check that the value
3583 ** of the table column that the inequality contrains is not NULL.
3584 ** If it is, jump to the next iteration of the loop.
3585 */
3586 r1 = sqlite3GetTempReg(pParse);
drh37ca0482013-06-12 17:17:45 +00003587 testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
3588 testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
drh7ba39a92013-05-30 17:43:19 +00003589 if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
drh111a6a72008-12-21 03:51:16 +00003590 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
3591 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
3592 }
danielk19771d461462009-04-21 09:02:45 +00003593 sqlite3ReleaseTempReg(pParse, r1);
drh111a6a72008-12-21 03:51:16 +00003594
3595 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003596 disableTerm(pLevel, pRangeStart);
3597 disableTerm(pLevel, pRangeEnd);
danielk19771d461462009-04-21 09:02:45 +00003598 if( !omitTable ){
3599 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3600 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003601 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003602 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drh111a6a72008-12-21 03:51:16 +00003603 }
drh111a6a72008-12-21 03:51:16 +00003604
3605 /* Record the instruction used to terminate the loop. Disable
3606 ** WHERE clause terms made redundant by the index range scan.
3607 */
drh7699d1c2013-06-04 12:42:29 +00003608 if( pLoop->wsFlags & WHERE_ONEROW ){
drh95e037b2011-03-09 21:02:31 +00003609 pLevel->op = OP_Noop;
3610 }else if( bRev ){
3611 pLevel->op = OP_Prev;
3612 }else{
3613 pLevel->op = OP_Next;
3614 }
drh111a6a72008-12-21 03:51:16 +00003615 pLevel->p1 = iIdxCur;
drh53cfbe92013-06-13 17:28:22 +00003616 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
drh3f4d1d12012-09-15 18:45:54 +00003617 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3618 }else{
3619 assert( pLevel->p5==0 );
3620 }
drhdd5f5a62008-12-23 13:35:23 +00003621 }else
3622
drh23d04d52008-12-23 23:56:22 +00003623#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drh7ba39a92013-05-30 17:43:19 +00003624 if( pLoop->wsFlags & WHERE_MULTI_OR ){
3625 /* Case 5: Two or more separately indexed terms connected by OR
drh111a6a72008-12-21 03:51:16 +00003626 **
3627 ** Example:
3628 **
3629 ** CREATE TABLE t1(a,b,c,d);
3630 ** CREATE INDEX i1 ON t1(a);
3631 ** CREATE INDEX i2 ON t1(b);
3632 ** CREATE INDEX i3 ON t1(c);
3633 **
3634 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3635 **
3636 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003637 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003638 **
drh1b26c7c2009-04-22 02:15:47 +00003639 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003640 **
danielk19771d461462009-04-21 09:02:45 +00003641 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003642 ** RowSetTest are such that the rowid of the current row is inserted
3643 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003644 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003645 **
danielk19771d461462009-04-21 09:02:45 +00003646 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003647 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003648 ** Gosub 2 A
3649 ** sqlite3WhereEnd()
3650 **
3651 ** Following the above, code to terminate the loop. Label A, the target
3652 ** of the Gosub above, jumps to the instruction right after the Goto.
3653 **
drh1b26c7c2009-04-22 02:15:47 +00003654 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003655 ** Goto B # The loop is finished.
3656 **
3657 ** A: <loop body> # Return data, whatever.
3658 **
3659 ** Return 2 # Jump back to the Gosub
3660 **
3661 ** B: <after the loop>
3662 **
drh111a6a72008-12-21 03:51:16 +00003663 */
drh111a6a72008-12-21 03:51:16 +00003664 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
drhc01a3c12009-12-16 22:10:49 +00003665 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
dan0efb72c2012-08-24 18:44:56 +00003666 Index *pCov = 0; /* Potential covering index (or NULL) */
3667 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
danielk19771d461462009-04-21 09:02:45 +00003668
3669 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003670 int regRowset = 0; /* Register for RowSet object */
3671 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003672 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3673 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003674 int untestedTerms = 0; /* Some terms not completely tested */
drh8871ef52011-10-07 13:33:10 +00003675 int ii; /* Loop counter */
3676 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
drh111a6a72008-12-21 03:51:16 +00003677
drh4efc9292013-06-06 23:02:03 +00003678 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003679 assert( pTerm!=0 );
drh7a5bcc02013-01-16 17:08:58 +00003680 assert( pTerm->eOperator & WO_OR );
drh111a6a72008-12-21 03:51:16 +00003681 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3682 pOrWc = &pTerm->u.pOrInfo->wc;
drhc01a3c12009-12-16 22:10:49 +00003683 pLevel->op = OP_Return;
3684 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003685
danbfca6a42012-08-24 10:52:35 +00003686 /* Set up a new SrcList in pOrTab containing the table being scanned
drhc01a3c12009-12-16 22:10:49 +00003687 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3688 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3689 */
3690 if( pWInfo->nLevel>1 ){
3691 int nNotReady; /* The number of notReady tables */
3692 struct SrcList_item *origSrc; /* Original list of tables */
3693 nNotReady = pWInfo->nLevel - iLevel - 1;
3694 pOrTab = sqlite3StackAllocRaw(pParse->db,
3695 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3696 if( pOrTab==0 ) return notReady;
shaneh46aae3c2009-12-31 19:06:23 +00003697 pOrTab->nAlloc = (i16)(nNotReady + 1);
3698 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003699 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3700 origSrc = pWInfo->pTabList->a;
3701 for(k=1; k<=nNotReady; k++){
3702 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3703 }
3704 }else{
3705 pOrTab = pWInfo->pTabList;
3706 }
danielk19771d461462009-04-21 09:02:45 +00003707
drh1b26c7c2009-04-22 02:15:47 +00003708 /* Initialize the rowset register to contain NULL. An SQL NULL is
3709 ** equivalent to an empty rowset.
danielk19771d461462009-04-21 09:02:45 +00003710 **
3711 ** Also initialize regReturn to contain the address of the instruction
3712 ** immediately following the OP_Return at the bottom of the loop. This
3713 ** is required in a few obscure LEFT JOIN cases where control jumps
3714 ** over the top of the loop into the body of it. In this case the
3715 ** correct response for the end-of-loop code (the OP_Return) is to
3716 ** fall through to the next instruction, just as an OP_Next does if
3717 ** called on an uninitialized cursor.
3718 */
drh70d18342013-06-06 19:16:33 +00003719 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003720 regRowset = ++pParse->nMem;
3721 regRowid = ++pParse->nMem;
3722 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3723 }
danielk19771d461462009-04-21 09:02:45 +00003724 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3725
drh8871ef52011-10-07 13:33:10 +00003726 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
3727 ** Then for every term xN, evaluate as the subexpression: xN AND z
3728 ** That way, terms in y that are factored into the disjunction will
3729 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
drh331b67c2012-03-09 22:02:08 +00003730 **
3731 ** Actually, each subexpression is converted to "xN AND w" where w is
3732 ** the "interesting" terms of z - terms that did not originate in the
3733 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3734 ** indices.
drhb3129fa2013-05-09 14:20:11 +00003735 **
3736 ** This optimization also only applies if the (x1 OR x2 OR ...) term
3737 ** is not contained in the ON clause of a LEFT JOIN.
3738 ** See ticket http://www.sqlite.org/src/info/f2369304e4
drh8871ef52011-10-07 13:33:10 +00003739 */
3740 if( pWC->nTerm>1 ){
drh7a484802012-03-16 00:28:11 +00003741 int iTerm;
3742 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3743 Expr *pExpr = pWC->a[iTerm].pExpr;
drh331b67c2012-03-09 22:02:08 +00003744 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drh7a484802012-03-16 00:28:11 +00003745 if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
3746 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
drh331b67c2012-03-09 22:02:08 +00003747 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
3748 pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
3749 }
3750 if( pAndExpr ){
3751 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3752 }
drh8871ef52011-10-07 13:33:10 +00003753 }
3754
danielk19771d461462009-04-21 09:02:45 +00003755 for(ii=0; ii<pOrWc->nTerm; ii++){
3756 WhereTerm *pOrTerm = &pOrWc->a[ii];
drh7a5bcc02013-01-16 17:08:58 +00003757 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
danielk19771d461462009-04-21 09:02:45 +00003758 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
drh8871ef52011-10-07 13:33:10 +00003759 Expr *pOrExpr = pOrTerm->pExpr;
drhb3129fa2013-05-09 14:20:11 +00003760 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
drh8871ef52011-10-07 13:33:10 +00003761 pAndExpr->pLeft = pOrExpr;
3762 pOrExpr = pAndExpr;
3763 }
danielk19771d461462009-04-21 09:02:45 +00003764 /* Loop through table entries that match term pOrTerm. */
drh8871ef52011-10-07 13:33:10 +00003765 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
drh9ef61f42011-10-07 14:40:59 +00003766 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
dan0efb72c2012-08-24 18:44:56 +00003767 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
danbfca6a42012-08-24 10:52:35 +00003768 assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
danielk19771d461462009-04-21 09:02:45 +00003769 if( pSubWInfo ){
drh7ba39a92013-05-30 17:43:19 +00003770 WhereLoop *pSubLoop;
dan17c0bc02010-11-09 17:35:19 +00003771 explainOneScan(
dan4a07e3d2010-11-09 14:48:59 +00003772 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
dan2ce22452010-11-08 19:01:16 +00003773 );
drh70d18342013-06-06 19:16:33 +00003774 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003775 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3776 int r;
3777 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
drha748fdc2012-03-28 01:34:47 +00003778 regRowid, 0);
drh8cff69d2009-11-12 19:59:44 +00003779 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
3780 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
drh336a5302009-04-24 15:46:21 +00003781 }
danielk19771d461462009-04-21 09:02:45 +00003782 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
3783
drhc01a3c12009-12-16 22:10:49 +00003784 /* The pSubWInfo->untestedTerms flag means that this OR term
3785 ** contained one or more AND term from a notReady table. The
3786 ** terms from the notReady table could not be tested and will
3787 ** need to be tested later.
3788 */
3789 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3790
danbfca6a42012-08-24 10:52:35 +00003791 /* If all of the OR-connected terms are optimized using the same
3792 ** index, and the index is opened using the same cursor number
3793 ** by each call to sqlite3WhereBegin() made by this loop, it may
3794 ** be possible to use that index as a covering index.
3795 **
3796 ** If the call to sqlite3WhereBegin() above resulted in a scan that
3797 ** uses an index, and this is either the first OR-connected term
3798 ** processed or the index is the same as that used by all previous
dan0efb72c2012-08-24 18:44:56 +00003799 ** terms, set pCov to the candidate covering index. Otherwise, set
3800 ** pCov to NULL to indicate that no candidate covering index will
3801 ** be available.
danbfca6a42012-08-24 10:52:35 +00003802 */
drh7ba39a92013-05-30 17:43:19 +00003803 pSubLoop = pSubWInfo->a[0].pWLoop;
3804 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
3805 && (pSubLoop->wsFlags & WHERE_TEMP_INDEX)==0
3806 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
danbfca6a42012-08-24 10:52:35 +00003807 ){
drh7ba39a92013-05-30 17:43:19 +00003808 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
drh907717f2013-06-04 18:03:22 +00003809 pCov = pSubLoop->u.btree.pIndex;
danbfca6a42012-08-24 10:52:35 +00003810 }else{
3811 pCov = 0;
3812 }
3813
danielk19771d461462009-04-21 09:02:45 +00003814 /* Finish the loop through table entries that match term pOrTerm. */
3815 sqlite3WhereEnd(pSubWInfo);
3816 }
drhdd5f5a62008-12-23 13:35:23 +00003817 }
3818 }
drhd40e2082012-08-24 23:24:15 +00003819 pLevel->u.pCovidx = pCov;
drh90abfd02012-10-09 21:07:23 +00003820 if( pCov ) pLevel->iIdxCur = iCovCur;
drh331b67c2012-03-09 22:02:08 +00003821 if( pAndExpr ){
3822 pAndExpr->pLeft = 0;
3823 sqlite3ExprDelete(pParse->db, pAndExpr);
3824 }
danielk19771d461462009-04-21 09:02:45 +00003825 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00003826 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
3827 sqlite3VdbeResolveLabel(v, iLoopBody);
3828
drhc01a3c12009-12-16 22:10:49 +00003829 if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
3830 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00003831 }else
drh23d04d52008-12-23 23:56:22 +00003832#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00003833
3834 {
drh7ba39a92013-05-30 17:43:19 +00003835 /* Case 6: There is no usable index. We must do a complete
drh111a6a72008-12-21 03:51:16 +00003836 ** scan of the entire table.
3837 */
drh699b3d42009-02-23 16:52:07 +00003838 static const u8 aStep[] = { OP_Next, OP_Prev };
3839 static const u8 aStart[] = { OP_Rewind, OP_Last };
3840 assert( bRev==0 || bRev==1 );
drh699b3d42009-02-23 16:52:07 +00003841 pLevel->op = aStep[bRev];
drh111a6a72008-12-21 03:51:16 +00003842 pLevel->p1 = iCur;
drh699b3d42009-02-23 16:52:07 +00003843 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh111a6a72008-12-21 03:51:16 +00003844 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3845 }
drh70d18342013-06-06 19:16:33 +00003846 newNotReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
drh111a6a72008-12-21 03:51:16 +00003847
3848 /* Insert code to test every subexpression that can be completely
3849 ** computed using the current set of tables.
drhe9cdcea2010-07-22 22:40:03 +00003850 **
3851 ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
3852 ** the use of indices become tests that are evaluated against each row of
3853 ** the relevant input tables.
drh111a6a72008-12-21 03:51:16 +00003854 */
drh111a6a72008-12-21 03:51:16 +00003855 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3856 Expr *pE;
drhe9cdcea2010-07-22 22:40:03 +00003857 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003858 testcase( pTerm->wtFlags & TERM_CODED );
3859 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0c41d222013-04-22 02:39:10 +00003860 if( (pTerm->prereqAll & newNotReady)!=0 ){
drhc01a3c12009-12-16 22:10:49 +00003861 testcase( pWInfo->untestedTerms==0
3862 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
3863 pWInfo->untestedTerms = 1;
3864 continue;
3865 }
drh111a6a72008-12-21 03:51:16 +00003866 pE = pTerm->pExpr;
3867 assert( pE!=0 );
3868 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
3869 continue;
3870 }
drh111a6a72008-12-21 03:51:16 +00003871 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003872 pTerm->wtFlags |= TERM_CODED;
3873 }
3874
drh0c41d222013-04-22 02:39:10 +00003875 /* Insert code to test for implied constraints based on transitivity
3876 ** of the "==" operator.
3877 **
3878 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
3879 ** and we are coding the t1 loop and the t2 loop has not yet coded,
3880 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
3881 ** the implied "t1.a=123" constraint.
3882 */
3883 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3884 Expr *pE;
3885 WhereTerm *pAlt;
3886 Expr sEq;
3887 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3888 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
3889 if( pTerm->leftCursor!=iCur ) continue;
3890 pE = pTerm->pExpr;
3891 assert( !ExprHasProperty(pE, EP_FromJoin) );
3892 assert( (pTerm->prereqRight & newNotReady)!=0 );
3893 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
3894 if( pAlt==0 ) continue;
drh5c10f3b2013-05-01 17:22:38 +00003895 if( pAlt->wtFlags & (TERM_CODED) ) continue;
drh0c41d222013-04-22 02:39:10 +00003896 VdbeNoopComment((v, "begin transitive constraint"));
3897 sEq = *pAlt->pExpr;
3898 sEq.pLeft = pE->pLeft;
3899 sqlite3ExprIfFalse(pParse, &sEq, addrCont, SQLITE_JUMPIFNULL);
3900 }
3901
drh111a6a72008-12-21 03:51:16 +00003902 /* For a LEFT OUTER JOIN, generate code that will record the fact that
3903 ** at least one row of the right table has matched the left table.
3904 */
3905 if( pLevel->iLeftJoin ){
3906 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
3907 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
3908 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00003909 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00003910 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drhe9cdcea2010-07-22 22:40:03 +00003911 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003912 testcase( pTerm->wtFlags & TERM_CODED );
3913 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0c41d222013-04-22 02:39:10 +00003914 if( (pTerm->prereqAll & newNotReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00003915 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00003916 continue;
3917 }
drh111a6a72008-12-21 03:51:16 +00003918 assert( pTerm->pExpr );
3919 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3920 pTerm->wtFlags |= TERM_CODED;
3921 }
3922 }
danielk19771d461462009-04-21 09:02:45 +00003923 sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh23d04d52008-12-23 23:56:22 +00003924
drh0c41d222013-04-22 02:39:10 +00003925 return newNotReady;
drh111a6a72008-12-21 03:51:16 +00003926}
3927
drhd15cb172013-05-21 19:23:10 +00003928#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00003929/*
3930** Print a WhereLoop object for debugging purposes
3931*/
3932static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
drhb8a8e8a2013-06-10 19:12:39 +00003933 int nb = 1+(pTabList->nSrc+7)/8;
drha18f3d22013-05-08 03:05:41 +00003934 struct SrcList_item *pItem = pTabList->a + p->iTab;
3935 Table *pTab = pItem->pTab;
drhd15cb172013-05-21 19:23:10 +00003936 sqlite3DebugPrintf("%c %2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00003937 p->iTab, nb, p->maskSelf, nb, p->prereq);
3938 sqlite3DebugPrintf(" %8s",
drha18f3d22013-05-08 03:05:41 +00003939 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00003940 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
3941 if( p->u.btree.pIndex ){
drh319f6772013-05-14 15:31:07 +00003942 const char *zName = p->u.btree.pIndex->zName;
drhae70cf12013-05-31 15:18:46 +00003943 if( zName==0 ) zName = "ipk";
drh319f6772013-05-14 15:31:07 +00003944 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
3945 int i = sqlite3Strlen30(zName) - 1;
3946 while( zName[i]!='_' ) i--;
3947 zName += i;
3948 }
3949 sqlite3DebugPrintf(".%-12s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00003950 }else{
3951 sqlite3DebugPrintf("%16s","");
3952 }
drha18f3d22013-05-08 03:05:41 +00003953 }else{
drh5346e952013-05-08 14:14:26 +00003954 char *z;
3955 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00003956 z = sqlite3_mprintf("(%d,\"%s\",%x)",
3957 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003958 }else{
drh3bd26f02013-05-24 14:52:03 +00003959 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003960 }
3961 sqlite3DebugPrintf(" %-15s", z);
3962 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00003963 }
drh4efc9292013-06-06 23:02:03 +00003964 sqlite3DebugPrintf(" fg %05x N %d", p->wsFlags, p->nLTerm);
drhb8a8e8a2013-06-10 19:12:39 +00003965 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
drha18f3d22013-05-08 03:05:41 +00003966}
3967#endif
3968
drhf1b5f5b2013-05-02 00:15:01 +00003969/*
drh4efc9292013-06-06 23:02:03 +00003970** Convert bulk memory into a valid WhereLoop that can be passed
3971** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00003972*/
drh4efc9292013-06-06 23:02:03 +00003973static void whereLoopInit(WhereLoop *p){
3974 p->aLTerm = p->aLTermSpace;
3975 p->nLTerm = 0;
3976 p->nLSlot = ArraySize(p->aLTermSpace);
3977 p->wsFlags = 0;
3978}
3979
3980/*
3981** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
3982*/
3983static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh13e11b42013-06-06 23:44:25 +00003984 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_TEMP_INDEX) ){
3985 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
3986 sqlite3_free(p->u.vtab.idxStr);
3987 p->u.vtab.needFree = 0;
3988 p->u.vtab.idxStr = 0;
3989 }else if( (p->wsFlags & WHERE_TEMP_INDEX)!=0 && p->u.btree.pIndex!=0 ){
3990 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
3991 sqlite3DbFree(db, p->u.btree.pIndex);
3992 p->u.btree.pIndex = 0;
3993 }
drh5346e952013-05-08 14:14:26 +00003994 }
3995}
3996
drh4efc9292013-06-06 23:02:03 +00003997/*
3998** Deallocate internal memory used by a WhereLoop object
3999*/
4000static void whereLoopClear(sqlite3 *db, WhereLoop *p){
4001 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
4002 whereLoopClearUnion(db, p);
4003 whereLoopInit(p);
4004}
4005
4006/*
4007** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
4008*/
4009static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
4010 WhereTerm **paNew;
4011 if( p->nLSlot>=n ) return SQLITE_OK;
4012 n = (n+7)&~7;
4013 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
4014 if( paNew==0 ) return SQLITE_NOMEM;
4015 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
4016 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
4017 p->aLTerm = paNew;
4018 p->nLSlot = n;
4019 return SQLITE_OK;
4020}
4021
4022/*
4023** Transfer content from the second pLoop into the first.
4024*/
4025static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
4026 if( whereLoopResize(db, pTo, pFrom->nLTerm) ) return SQLITE_NOMEM;
4027 whereLoopClearUnion(db, pTo);
drha2014152013-06-07 00:29:23 +00004028 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
4029 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00004030 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
4031 pFrom->u.vtab.needFree = 0;
drh13e11b42013-06-06 23:44:25 +00004032 }else if( (pFrom->wsFlags & WHERE_TEMP_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00004033 pFrom->u.btree.pIndex = 0;
4034 }
4035 return SQLITE_OK;
4036}
4037
drh5346e952013-05-08 14:14:26 +00004038/*
drhf1b5f5b2013-05-02 00:15:01 +00004039** Delete a WhereLoop object
4040*/
4041static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00004042 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00004043 sqlite3DbFree(db, p);
4044}
drh84bfda42005-07-15 13:05:21 +00004045
drh9eff6162006-06-12 21:59:13 +00004046/*
4047** Free a WhereInfo structure
4048*/
drh10fe8402008-10-11 16:47:35 +00004049static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00004050 if( ALWAYS(pWInfo) ){
drh70d18342013-06-06 19:16:33 +00004051 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00004052 while( pWInfo->pLoops ){
4053 WhereLoop *p = pWInfo->pLoops;
4054 pWInfo->pLoops = p->pNextLoop;
4055 whereLoopDelete(db, p);
4056 }
drh633e6d52008-07-28 19:34:53 +00004057 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00004058 }
4059}
4060
drhf1b5f5b2013-05-02 00:15:01 +00004061/*
4062** Insert or replace a WhereLoop entry using the template supplied.
4063**
4064** An existing WhereLoop entry might be overwritten if the new template
4065** is better and has fewer dependencies. Or the template will be ignored
4066** and no insert will occur if an existing WhereLoop is faster and has
4067** fewer dependencies than the template. Otherwise a new WhereLoop is
drhd044d202013-05-31 12:43:55 +00004068** added based on the template.
drh23f98da2013-05-21 15:52:07 +00004069**
4070** If pBuilder->pBest is not NULL then we only care about the very
4071** best template and that template should be stored in pBuilder->pBest.
4072** If pBuilder->pBest is NULL then a list of the best templates are stored
4073** in pBuilder->pWInfo->pLoops.
4074**
4075** When accumulating multiple loops (when pBuilder->pBest is NULL) we
4076** still might overwrite similar loops with the new template if the
4077** template is better. Loops may be overwritten if the following
4078** conditions are met:
4079**
4080** (1) They have the same iTab.
4081** (2) They have the same iSortIdx.
4082** (3) The template has same or fewer dependencies than the current loop
4083** (4) The template has the same or lower cost than the current loop
drhd044d202013-05-31 12:43:55 +00004084** (5) The template uses more terms of the same index but has no additional
4085** dependencies
drhf1b5f5b2013-05-02 00:15:01 +00004086*/
drhcf8fa7a2013-05-10 20:26:22 +00004087static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh4efc9292013-06-06 23:02:03 +00004088 WhereLoop **ppPrev, *p, *pNext = 0;
drhcf8fa7a2013-05-10 20:26:22 +00004089 WhereInfo *pWInfo = pBuilder->pWInfo;
drh70d18342013-06-06 19:16:33 +00004090 sqlite3 *db = pWInfo->pParse->db;
drhcf8fa7a2013-05-10 20:26:22 +00004091
drh23f98da2013-05-21 15:52:07 +00004092 /* If pBuilder->pBest is defined, then only keep track of the single
4093 ** best WhereLoop. pBuilder->pBest->maskSelf==0 indicates that no
4094 ** prior WhereLoops have been evaluated and that the current pTemplate
4095 ** is therefore the first and hence the best and should be retained.
4096 */
drhcf8fa7a2013-05-10 20:26:22 +00004097 if( (p = pBuilder->pBest)!=0 ){
4098 if( p->maskSelf!=0 ){
drhb8a8e8a2013-06-10 19:12:39 +00004099 WhereCost rCost = whereCostAdd(p->rRun,p->rSetup);
4100 WhereCost rTemplate = whereCostAdd(pTemplate->rRun,pTemplate->rSetup);
drh4efc9292013-06-06 23:02:03 +00004101 if( rCost < rTemplate ){
drhae70cf12013-05-31 15:18:46 +00004102 goto whereLoopInsert_noop;
drhcf8fa7a2013-05-10 20:26:22 +00004103 }
drh4efc9292013-06-06 23:02:03 +00004104 if( rCost == rTemplate && p->prereq <= pTemplate->prereq ){
drhae70cf12013-05-31 15:18:46 +00004105 goto whereLoopInsert_noop;
drhcf8fa7a2013-05-10 20:26:22 +00004106 }
4107 }
drhae70cf12013-05-31 15:18:46 +00004108#if WHERETRACE_ENABLED
4109 if( sqlite3WhereTrace & 0x8 ){
drh5822d6f2013-06-10 23:30:09 +00004110 sqlite3DebugPrintf(p->maskSelf==0 ? "ins-init: " : "ins-best: ");
drh70d18342013-06-06 19:16:33 +00004111 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004112 }
4113#endif
drh5822d6f2013-06-10 23:30:09 +00004114 whereLoopXfer(db, p, pTemplate);
drhcf8fa7a2013-05-10 20:26:22 +00004115 return SQLITE_OK;
4116 }
drhf1b5f5b2013-05-02 00:15:01 +00004117
4118 /* Search for an existing WhereLoop to overwrite, or which takes
4119 ** priority over pTemplate.
4120 */
4121 for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
drh23f98da2013-05-21 15:52:07 +00004122 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ) continue;
drhf1b5f5b2013-05-02 00:15:01 +00004123 if( (p->prereq & pTemplate->prereq)==p->prereq
drhf1b5f5b2013-05-02 00:15:01 +00004124 && p->rSetup<=pTemplate->rSetup
4125 && p->rRun<=pTemplate->rRun
4126 ){
drhcd0f4072013-06-05 12:47:59 +00004127 /* p is equal or better than pTemplate */
drh4efc9292013-06-06 23:02:03 +00004128 if( p->nLTerm<pTemplate->nLTerm
drhcd0f4072013-06-05 12:47:59 +00004129 && (p->wsFlags & WHERE_INDEXED)!=0
4130 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
4131 && p->u.btree.pIndex==pTemplate->u.btree.pIndex
4132 && p->prereq==pTemplate->prereq
4133 ){
4134 /* Overwrite an existing WhereLoop with an similar one that uses
4135 ** more terms of the index */
4136 pNext = p->pNextLoop;
drhcd0f4072013-06-05 12:47:59 +00004137 break;
drh8636e9c2013-06-11 01:50:08 +00004138 }else if( p->nOut>pTemplate->nOut
4139 && p->rSetup==pTemplate->rSetup
4140 && p->rRun==pTemplate->rRun
4141 ){
4142 /* Overwrite an existing WhereLoop with the same cost but more
4143 ** outputs */
4144 pNext = p->pNextLoop;
4145 break;
drhcd0f4072013-06-05 12:47:59 +00004146 }else{
4147 /* pTemplate is not helpful.
4148 ** Return without changing or adding anything */
4149 goto whereLoopInsert_noop;
4150 }
drhf1b5f5b2013-05-02 00:15:01 +00004151 }
4152 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
drhf1b5f5b2013-05-02 00:15:01 +00004153 && p->rSetup>=pTemplate->rSetup
4154 && p->rRun>=pTemplate->rRun
4155 ){
4156 /* Overwrite an existing WhereLoop with a better one */
drh43fe25f2013-05-07 23:06:23 +00004157 pNext = p->pNextLoop;
drhf1b5f5b2013-05-02 00:15:01 +00004158 break;
4159 }
4160 }
4161
4162 /* If we reach this point it means that either p[] should be overwritten
4163 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
4164 ** WhereLoop and insert it.
4165 */
drhae70cf12013-05-31 15:18:46 +00004166#if WHERETRACE_ENABLED
4167 if( sqlite3WhereTrace & 0x8 ){
4168 if( p!=0 ){
4169 sqlite3DebugPrintf("ins-del: ");
drh70d18342013-06-06 19:16:33 +00004170 whereLoopPrint(p, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004171 }
4172 sqlite3DebugPrintf("ins-new: ");
drh70d18342013-06-06 19:16:33 +00004173 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004174 }
4175#endif
drhf1b5f5b2013-05-02 00:15:01 +00004176 if( p==0 ){
drh4efc9292013-06-06 23:02:03 +00004177 p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00004178 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00004179 whereLoopInit(p);
drhf1b5f5b2013-05-02 00:15:01 +00004180 }
drh4efc9292013-06-06 23:02:03 +00004181 whereLoopXfer(db, p, pTemplate);
drh43fe25f2013-05-07 23:06:23 +00004182 p->pNextLoop = pNext;
4183 *ppPrev = p;
drh5346e952013-05-08 14:14:26 +00004184 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00004185 Index *pIndex = p->u.btree.pIndex;
4186 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004187 p->u.btree.pIndex = 0;
4188 }
drh5346e952013-05-08 14:14:26 +00004189 }
drhf1b5f5b2013-05-02 00:15:01 +00004190 return SQLITE_OK;
drhae70cf12013-05-31 15:18:46 +00004191
4192 /* Jump here if the insert is a no-op */
4193whereLoopInsert_noop:
4194#if WHERETRACE_ENABLED
4195 if( sqlite3WhereTrace & 0x8 ){
drh5822d6f2013-06-10 23:30:09 +00004196 sqlite3DebugPrintf(pBuilder->pBest ? "ins-skip: " : "ins-noop: ");
drh70d18342013-06-06 19:16:33 +00004197 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004198 }
4199#endif
4200 return SQLITE_OK;
drhf1b5f5b2013-05-02 00:15:01 +00004201}
4202
4203/*
drh5346e952013-05-08 14:14:26 +00004204** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
drh1c8148f2013-05-04 20:25:23 +00004205** Try to match one more.
4206**
4207** If pProbe->tnum==0, that means pIndex is a fake index used for the
4208** INTEGER PRIMARY KEY.
4209*/
drh5346e952013-05-08 14:14:26 +00004210static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00004211 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
4212 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
4213 Index *pProbe, /* An index on pSrc */
drhb8a8e8a2013-06-10 19:12:39 +00004214 WhereCost nInMul /* log(Number of iterations due to IN) */
drh1c8148f2013-05-04 20:25:23 +00004215){
drh70d18342013-06-06 19:16:33 +00004216 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
4217 Parse *pParse = pWInfo->pParse; /* Parsing context */
4218 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00004219 WhereLoop *pNew; /* Template WhereLoop under construction */
4220 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00004221 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00004222 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00004223 Bitmask saved_prereq; /* Original value of pNew->prereq */
4224 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
4225 int saved_nEq; /* Original value of pNew->u.btree.nEq */
4226 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
4227 WhereCost saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00004228 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00004229 int rc = SQLITE_OK; /* Return code */
drhb8a8e8a2013-06-10 19:12:39 +00004230 WhereCost nRowEst; /* Estimated index selectivity */
drh4efc9292013-06-06 23:02:03 +00004231 WhereCost rLogSize; /* Logarithm of table size */
drh6f2bfad2013-06-03 17:35:22 +00004232 WhereTerm *pTop, *pBtm; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00004233
drh1c8148f2013-05-04 20:25:23 +00004234 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00004235 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00004236
drh5346e952013-05-08 14:14:26 +00004237 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh0f133a42013-05-22 17:01:17 +00004238 assert( pNew->u.btree.nEq<=pProbe->nColumn );
drh43fe25f2013-05-07 23:06:23 +00004239 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
4240 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
4241 opMask = WO_LT|WO_LE;
4242 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
4243 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004244 }else{
drh43fe25f2013-05-07 23:06:23 +00004245 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004246 }
drhef866372013-05-22 20:49:02 +00004247 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00004248
drh0f133a42013-05-22 17:01:17 +00004249 if( pNew->u.btree.nEq < pProbe->nColumn ){
4250 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
drhe1e2e9a2013-06-13 15:16:53 +00004251 nRowEst = whereCost(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
drh0f133a42013-05-22 17:01:17 +00004252 }else{
4253 iCol = -1;
drhb8a8e8a2013-06-10 19:12:39 +00004254 nRowEst = 0;
drh0f133a42013-05-22 17:01:17 +00004255 }
drha18f3d22013-05-08 03:05:41 +00004256 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00004257 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00004258 saved_nEq = pNew->u.btree.nEq;
4259 saved_nLTerm = pNew->nLTerm;
4260 saved_wsFlags = pNew->wsFlags;
4261 saved_prereq = pNew->prereq;
4262 saved_nOut = pNew->nOut;
drhb8a8e8a2013-06-10 19:12:39 +00004263 pNew->rSetup = 0;
drhe1e2e9a2013-06-13 15:16:53 +00004264 rLogSize = estLog(whereCost(pProbe->aiRowEst[0]));
drh5346e952013-05-08 14:14:26 +00004265 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
drhb8a8e8a2013-06-10 19:12:39 +00004266 int nIn = 0;
drh79a13bf2013-05-31 20:28:28 +00004267 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drh4efc9292013-06-06 23:02:03 +00004268 pNew->wsFlags = saved_wsFlags;
4269 pNew->u.btree.nEq = saved_nEq;
4270 pNew->nLTerm = saved_nLTerm;
4271 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4272 pNew->aLTerm[pNew->nLTerm++] = pTerm;
4273 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
drhe1e2e9a2013-06-13 15:16:53 +00004274 pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
drha18f3d22013-05-08 03:05:41 +00004275 if( pTerm->eOperator & WO_IN ){
4276 Expr *pExpr = pTerm->pExpr;
4277 pNew->wsFlags |= WHERE_COLUMN_IN;
4278 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhe1e2e9a2013-06-13 15:16:53 +00004279 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
4280 nIn = 46; assert( 46==whereCost(25) );
drha18f3d22013-05-08 03:05:41 +00004281 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
4282 /* "x IN (value, value, ...)" */
drhe1e2e9a2013-06-13 15:16:53 +00004283 nIn = whereCost(pExpr->x.pList->nExpr);
drhf1645f02013-05-07 19:44:38 +00004284 }
drhb8a8e8a2013-06-10 19:12:39 +00004285 pNew->rRun += nIn;
drh5346e952013-05-08 14:14:26 +00004286 pNew->u.btree.nEq++;
drhb8a8e8a2013-06-10 19:12:39 +00004287 pNew->nOut = nRowEst + nInMul + nIn;
drh6fa978d2013-05-30 19:29:19 +00004288 }else if( pTerm->eOperator & (WO_EQ) ){
drh7699d1c2013-06-04 12:42:29 +00004289 assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
drhb8a8e8a2013-06-10 19:12:39 +00004290 || nInMul==0 );
drha18f3d22013-05-08 03:05:41 +00004291 pNew->wsFlags |= WHERE_COLUMN_EQ;
drh7699d1c2013-06-04 12:42:29 +00004292 if( iCol<0
drhb8a8e8a2013-06-10 19:12:39 +00004293 || (pProbe->onError!=OE_None && nInMul==0
drh21f7ff72013-06-03 15:07:23 +00004294 && pNew->u.btree.nEq==pProbe->nColumn-1)
4295 ){
drh7699d1c2013-06-04 12:42:29 +00004296 testcase( pNew->wsFlags & WHERE_COLUMN_IN );
4297 pNew->wsFlags |= WHERE_ONEROW;
drh21f7ff72013-06-03 15:07:23 +00004298 }
drh5346e952013-05-08 14:14:26 +00004299 pNew->u.btree.nEq++;
drhb8a8e8a2013-06-10 19:12:39 +00004300 pNew->nOut = nRowEst + nInMul;
drh6fa978d2013-05-30 19:29:19 +00004301 }else if( pTerm->eOperator & (WO_ISNULL) ){
4302 pNew->wsFlags |= WHERE_COLUMN_NULL;
4303 pNew->u.btree.nEq++;
drhe1e2e9a2013-06-13 15:16:53 +00004304 /* TUNING: IS NULL selects 2 rows */
4305 nIn = 10; assert( 10==whereCost(2) );
drhb8a8e8a2013-06-10 19:12:39 +00004306 pNew->nOut = nRowEst + nInMul + nIn;
drha18f3d22013-05-08 03:05:41 +00004307 }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
4308 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004309 pBtm = pTerm;
4310 pTop = 0;
drha18f3d22013-05-08 03:05:41 +00004311 }else if( pTerm->eOperator & (WO_LT|WO_LE) ){
4312 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004313 pTop = pTerm;
4314 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00004315 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00004316 }
drh6f2bfad2013-06-03 17:35:22 +00004317 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
4318 /* Adjust nOut and rRun for STAT3 range values */
drh4efc9292013-06-06 23:02:03 +00004319 WhereCost rDiv;
drh70d18342013-06-06 19:16:33 +00004320 whereRangeScanEst(pParse, pProbe, pNew->u.btree.nEq,
drh6f2bfad2013-06-03 17:35:22 +00004321 pBtm, pTop, &rDiv);
drh8636e9c2013-06-11 01:50:08 +00004322 pNew->nOut = saved_nOut>rDiv+10 ? saved_nOut - rDiv : 10;
drh6f2bfad2013-06-03 17:35:22 +00004323 }
4324#ifdef SQLITE_ENABLE_STAT3
4325 if( pNew->u.btree.nEq==1 && pProbe->nSample ){
drhb8a8e8a2013-06-10 19:12:39 +00004326 tRowcnt nOut = 0;
drh6f2bfad2013-06-03 17:35:22 +00004327 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
drhb8a8e8a2013-06-10 19:12:39 +00004328 rc = whereEqualScanEst(pParse, pProbe, pTerm->pExpr->pRight, &nOut);
drh6f2bfad2013-06-03 17:35:22 +00004329 }else if( (pTerm->eOperator & WO_IN)
4330 && !ExprHasProperty(pTerm->pExpr, EP_xIsSelect) ){
drhb8a8e8a2013-06-10 19:12:39 +00004331 rc = whereInScanEst(pParse, pProbe, pTerm->pExpr->x.pList, &nOut);
drh6f2bfad2013-06-03 17:35:22 +00004332 }
drhe1e2e9a2013-06-13 15:16:53 +00004333 pNew->nOut = whereCost(nOut);
drh6f2bfad2013-06-03 17:35:22 +00004334 }
4335#endif
drhe217efc2013-06-12 03:48:41 +00004336 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
drheb04de32013-05-10 15:16:30 +00004337 /* Each row involves a step of the index, then a binary search of
4338 ** the main table */
drhe217efc2013-06-12 03:48:41 +00004339 pNew->rRun = whereCostAdd(pNew->rRun, rLogSize>27 ? rLogSize-17 : 10);
drheb04de32013-05-10 15:16:30 +00004340 }
drhe217efc2013-06-12 03:48:41 +00004341 /* Step cost for each output row */
4342 pNew->rRun = whereCostAdd(pNew->rRun, pNew->nOut);
drheb04de32013-05-10 15:16:30 +00004343 /* TBD: Adjust nOut for additional constraints */
drhcf8fa7a2013-05-10 20:26:22 +00004344 rc = whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004345 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
drhbbe8b242013-06-13 15:50:59 +00004346 && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
drh5346e952013-05-08 14:14:26 +00004347 ){
drhb8a8e8a2013-06-10 19:12:39 +00004348 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
drha18f3d22013-05-08 03:05:41 +00004349 }
drh1c8148f2013-05-04 20:25:23 +00004350 }
drh4efc9292013-06-06 23:02:03 +00004351 pNew->prereq = saved_prereq;
4352 pNew->u.btree.nEq = saved_nEq;
4353 pNew->wsFlags = saved_wsFlags;
4354 pNew->nOut = saved_nOut;
4355 pNew->nLTerm = saved_nLTerm;
drh5346e952013-05-08 14:14:26 +00004356 return rc;
drh1c8148f2013-05-04 20:25:23 +00004357}
4358
4359/*
drh23f98da2013-05-21 15:52:07 +00004360** Return True if it is possible that pIndex might be useful in
4361** implementing the ORDER BY clause in pBuilder.
4362**
4363** Return False if pBuilder does not contain an ORDER BY clause or
4364** if there is no way for pIndex to be useful in implementing that
4365** ORDER BY clause.
4366*/
4367static int indexMightHelpWithOrderBy(
4368 WhereLoopBuilder *pBuilder,
4369 Index *pIndex,
4370 int iCursor
4371){
4372 ExprList *pOB;
4373 int iCol;
4374 int ii;
4375
drh53cfbe92013-06-13 17:28:22 +00004376 if( pIndex->bUnordered ) return 0;
drh70d18342013-06-06 19:16:33 +00004377 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00004378 iCol = pIndex->aiColumn[0];
4379 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00004380 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00004381 if( pExpr->op!=TK_COLUMN ) return 0;
4382 if( pExpr->iTable==iCursor ){
4383 if( pExpr->iColumn==iCol ) return 1;
4384 return 0;
4385 }
4386 }
4387 return 0;
4388}
4389
4390/*
drh92a121f2013-06-10 12:15:47 +00004391** Return a bitmask where 1s indicate that the corresponding column of
4392** the table is used by an index. Only the first 63 columns are considered.
4393*/
drhfd5874d2013-06-12 14:52:39 +00004394static Bitmask columnsInIndex(Index *pIdx){
drh92a121f2013-06-10 12:15:47 +00004395 Bitmask m = 0;
4396 int j;
4397 for(j=pIdx->nColumn-1; j>=0; j--){
4398 int x = pIdx->aiColumn[j];
4399 if( x<BMS-1 ) m |= MASKBIT(x);
4400 }
4401 return m;
4402}
4403
4404
4405/*
drh0823c892013-05-11 00:06:23 +00004406** Add all WhereLoop objects a single table of the join were the table
4407** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
4408** a b-tree table, not a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004409*/
drh5346e952013-05-08 14:14:26 +00004410static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00004411 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00004412 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00004413){
drh70d18342013-06-06 19:16:33 +00004414 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00004415 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00004416 Index sPk; /* A fake index object for the primary key */
4417 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
4418 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00004419 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00004420 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00004421 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00004422 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00004423 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00004424 int b; /* A boolean value */
drhb8a8e8a2013-06-10 19:12:39 +00004425 WhereCost rSize; /* number of rows in the table */
4426 WhereCost rLogSize; /* Logarithm of the number of rows in the table */
drh23f98da2013-05-21 15:52:07 +00004427
drh1c8148f2013-05-04 20:25:23 +00004428 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004429 pWInfo = pBuilder->pWInfo;
4430 pTabList = pWInfo->pTabList;
4431 pSrc = pTabList->a + pNew->iTab;
drh0823c892013-05-11 00:06:23 +00004432 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00004433
4434 if( pSrc->pIndex ){
4435 /* An INDEXED BY clause specifies a particular index to use */
4436 pProbe = pSrc->pIndex;
4437 }else{
4438 /* There is no INDEXED BY clause. Create a fake Index object in local
4439 ** variable sPk to represent the rowid primary key index. Make this
4440 ** fake index the first in a chain of Index objects with all of the real
4441 ** indices to follow */
4442 Index *pFirst; /* First of real indices on the table */
4443 memset(&sPk, 0, sizeof(Index));
4444 sPk.nColumn = 1;
4445 sPk.aiColumn = &aiColumnPk;
4446 sPk.aiRowEst = aiRowEstPk;
4447 sPk.onError = OE_Replace;
4448 sPk.pTable = pSrc->pTab;
4449 aiRowEstPk[0] = pSrc->pTab->nRowEst;
4450 aiRowEstPk[1] = 1;
4451 pFirst = pSrc->pTab->pIndex;
4452 if( pSrc->notIndexed==0 ){
4453 /* The real indices of the table are only considered if the
4454 ** NOT INDEXED qualifier is omitted from the FROM clause */
4455 sPk.pNext = pFirst;
4456 }
4457 pProbe = &sPk;
4458 }
drhe1e2e9a2013-06-13 15:16:53 +00004459 rSize = whereCost(pSrc->pTab->nRowEst);
drheb04de32013-05-10 15:16:30 +00004460 rLogSize = estLog(rSize);
4461
4462 /* Automatic indexes */
drhcf8fa7a2013-05-10 20:26:22 +00004463 if( !pBuilder->pBest
drh4fe425a2013-06-12 17:08:06 +00004464 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
4465 && pSrc->pIndex==0
drheb04de32013-05-10 15:16:30 +00004466 && !pSrc->viaCoroutine
4467 && !pSrc->notIndexed
4468 && !pSrc->isCorrelated
4469 ){
4470 /* Generate auto-index WhereLoops */
4471 WhereClause *pWC = pBuilder->pWC;
4472 WhereTerm *pTerm;
4473 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
4474 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00004475 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00004476 if( termCanDriveIndex(pTerm, pSrc, 0) ){
4477 pNew->u.btree.nEq = 1;
drhef866372013-05-22 20:49:02 +00004478 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00004479 pNew->nLTerm = 1;
4480 pNew->aLTerm[0] = pTerm;
drhe1e2e9a2013-06-13 15:16:53 +00004481 /* TUNING: One-time cost for computing the automatic index is
4482 ** approximately 6*N*log2(N) where N is the number of rows in
4483 ** the table being indexed. */
4484 pNew->rSetup = rLogSize + rSize + 26; assert( 26==whereCost(6) );
4485 /* TUNING: Each index lookup yields 10 rows in the table */
4486 pNew->nOut = 33; assert( 33==whereCost(10) );
drhb8a8e8a2013-06-10 19:12:39 +00004487 pNew->rRun = whereCostAdd(rLogSize,pNew->nOut);
drheb04de32013-05-10 15:16:30 +00004488 pNew->wsFlags = WHERE_TEMP_INDEX;
4489 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00004490 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00004491 }
4492 }
4493 }
drh1c8148f2013-05-04 20:25:23 +00004494
4495 /* Loop over all indices
4496 */
drh23f98da2013-05-21 15:52:07 +00004497 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh5346e952013-05-08 14:14:26 +00004498 pNew->u.btree.nEq = 0;
drh4efc9292013-06-06 23:02:03 +00004499 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00004500 pNew->iSortIdx = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004501 pNew->rSetup = 0;
drh23f98da2013-05-21 15:52:07 +00004502 pNew->prereq = mExtra;
4503 pNew->u.btree.pIndex = pProbe;
4504 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh53cfbe92013-06-13 17:28:22 +00004505 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
4506 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
drh43fe25f2013-05-07 23:06:23 +00004507 if( pProbe->tnum<=0 ){
4508 /* Integer primary key index */
4509 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00004510
4511 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00004512 pNew->iSortIdx = b ? iSortIdx : 0;
drh23f98da2013-05-21 15:52:07 +00004513 pNew->nOut = rSize;
drhe1e2e9a2013-06-13 15:16:53 +00004514 /* TUNING: Cost of full table scan is 3*(N + log2(N)).
4515 ** + The extra 3 factor is to encourage the use of indexed lookups
4516 ** over full scans. A smaller constant 2 is used for covering
4517 ** index scans so that a covering index scan will be favored over
4518 ** a table scan. */
4519 pNew->rRun = whereCostAdd(rSize,rLogSize) + 16;
drh23f98da2013-05-21 15:52:07 +00004520 rc = whereLoopInsert(pBuilder, pNew);
4521 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00004522 }else{
drhfd5874d2013-06-12 14:52:39 +00004523 Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
drh6fa978d2013-05-30 19:29:19 +00004524 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
drh1c8148f2013-05-04 20:25:23 +00004525
drh23f98da2013-05-21 15:52:07 +00004526 /* Full scan via index */
drh53cfbe92013-06-13 17:28:22 +00004527 if( b
4528 || ( m==0
4529 && pProbe->bUnordered==0
4530 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
4531 && sqlite3GlobalConfig.bUseCis
4532 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
4533 )
drhe3b7c922013-06-03 19:17:40 +00004534 ){
drh23f98da2013-05-21 15:52:07 +00004535 pNew->iSortIdx = b ? iSortIdx : 0;
4536 pNew->nOut = rSize;
drhe1e2e9a2013-06-13 15:16:53 +00004537 if( m==0 ){
4538 /* TUNING: Cost of a covering index scan is 2*(N + log2(N)).
4539 ** + The extra 2 factor is to encourage the use of indexed lookups
4540 ** over index scans. A table scan uses a factor of 3 so that
4541 ** index scans are favored over table scans.
4542 ** + If this covering index might also help satisfy the ORDER BY
4543 ** clause, then the cost is fudged down slightly so that this
4544 ** index is favored above other indices that have no hope of
4545 ** helping with the ORDER BY. */
4546 pNew->rRun = 10 + whereCostAdd(rSize,rLogSize) - b;
4547 }else{
4548 assert( b!=0 );
4549 /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
4550 ** which we will simplify to just N*log2(N) */
4551 pNew->rRun = rSize + rLogSize;
4552 }
drh23f98da2013-05-21 15:52:07 +00004553 rc = whereLoopInsert(pBuilder, pNew);
4554 if( rc ) break;
4555 }
4556 }
drhb8a8e8a2013-06-10 19:12:39 +00004557 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
drh1c8148f2013-05-04 20:25:23 +00004558
4559 /* If there was an INDEXED BY clause, then only that one index is
4560 ** considered. */
4561 if( pSrc->pIndex ) break;
4562 }
drh5346e952013-05-08 14:14:26 +00004563 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004564}
4565
drh8636e9c2013-06-11 01:50:08 +00004566#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf1b5f5b2013-05-02 00:15:01 +00004567/*
drh0823c892013-05-11 00:06:23 +00004568** Add all WhereLoop objects for a table of the join identified by
4569** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004570*/
drh5346e952013-05-08 14:14:26 +00004571static int whereLoopAddVirtual(
drh1c8148f2013-05-04 20:25:23 +00004572 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00004573 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00004574){
drh70d18342013-06-06 19:16:33 +00004575 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00004576 Parse *pParse; /* The parsing context */
4577 WhereClause *pWC; /* The WHERE clause */
4578 struct SrcList_item *pSrc; /* The FROM clause term to search */
4579 Table *pTab;
4580 sqlite3 *db;
4581 sqlite3_index_info *pIdxInfo;
4582 struct sqlite3_index_constraint *pIdxCons;
4583 struct sqlite3_index_constraint_usage *pUsage;
4584 WhereTerm *pTerm;
4585 int i, j;
4586 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00004587 int nConstraint;
drh5346e952013-05-08 14:14:26 +00004588 int seenIn = 0; /* True if an IN operator is seen */
4589 int seenVar = 0; /* True if a non-constant constraint is seen */
4590 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
4591 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00004592 int rc = SQLITE_OK;
4593
drh70d18342013-06-06 19:16:33 +00004594 pWInfo = pBuilder->pWInfo;
4595 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00004596 db = pParse->db;
4597 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00004598 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004599 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00004600 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00004601 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00004602 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00004603 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00004604 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00004605 pNew->rSetup = 0;
4606 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00004607 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00004608 pNew->u.vtab.needFree = 0;
4609 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00004610 nConstraint = pIdxInfo->nConstraint;
4611 if( whereLoopResize(db, pNew, nConstraint) ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00004612
drh0823c892013-05-11 00:06:23 +00004613 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00004614 if( !seenIn && (iPhase&1)!=0 ){
4615 iPhase++;
4616 if( iPhase>3 ) break;
4617 }
4618 if( !seenVar && iPhase>1 ) break;
4619 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4620 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
4621 j = pIdxCons->iTermOffset;
4622 pTerm = &pWC->a[j];
4623 switch( iPhase ){
4624 case 0: /* Constants without IN operator */
4625 pIdxCons->usable = 0;
4626 if( (pTerm->eOperator & WO_IN)!=0 ){
4627 seenIn = 1;
4628 }else if( pTerm->prereqRight!=0 ){
4629 seenVar = 1;
4630 }else{
4631 pIdxCons->usable = 1;
4632 }
4633 break;
4634 case 1: /* Constants with IN operators */
4635 assert( seenIn );
4636 pIdxCons->usable = (pTerm->prereqRight==0);
4637 break;
4638 case 2: /* Variables without IN */
4639 assert( seenVar );
4640 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
4641 break;
4642 default: /* Variables with IN */
4643 assert( seenVar && seenIn );
4644 pIdxCons->usable = 1;
4645 break;
4646 }
4647 }
4648 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
4649 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4650 pIdxInfo->idxStr = 0;
4651 pIdxInfo->idxNum = 0;
4652 pIdxInfo->needToFreeIdxStr = 0;
4653 pIdxInfo->orderByConsumed = 0;
drh8636e9c2013-06-11 01:50:08 +00004654 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
drh5346e952013-05-08 14:14:26 +00004655 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
4656 if( rc ) goto whereLoopAddVtab_exit;
4657 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4658 pNew->prereq = 0;
drhc718f1c2013-05-08 20:05:58 +00004659 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00004660 assert( pNew->nLSlot>=nConstraint );
4661 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00004662 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00004663 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00004664 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4665 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00004666 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00004667 || j<0
4668 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00004669 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00004670 ){
4671 rc = SQLITE_ERROR;
4672 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
4673 goto whereLoopAddVtab_exit;
4674 }
4675 pTerm = &pWC->a[j];
4676 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00004677 assert( iTerm<pNew->nLSlot );
4678 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00004679 if( iTerm>mxTerm ) mxTerm = iTerm;
drh52986302013-06-03 16:03:16 +00004680 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00004681 if( (pTerm->eOperator & WO_IN)!=0 ){
4682 if( pUsage[i].omit==0 ){
4683 /* Do not attempt to use an IN constraint if the virtual table
4684 ** says that the equivalent EQ constraint cannot be safely omitted.
4685 ** If we do attempt to use such a constraint, some rows might be
4686 ** repeated in the output. */
4687 break;
4688 }
4689 /* A virtual table that is constrained by an IN clause may not
4690 ** consume the ORDER BY clause because (1) the order of IN terms
4691 ** is not necessarily related to the order of output terms and
4692 ** (2) Multiple outputs from a single IN value will not merge
4693 ** together. */
4694 pIdxInfo->orderByConsumed = 0;
4695 }
4696 }
4697 }
drh4efc9292013-06-06 23:02:03 +00004698 if( i>=nConstraint ){
4699 pNew->nLTerm = mxTerm+1;
4700 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00004701 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4702 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4703 pIdxInfo->needToFreeIdxStr = 0;
4704 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh3b1d8082013-06-03 16:56:37 +00004705 pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
4706 && pIdxInfo->orderByConsumed);
drhb8a8e8a2013-06-10 19:12:39 +00004707 pNew->rSetup = 0;
drh8636e9c2013-06-11 01:50:08 +00004708 pNew->rRun = whereCostFromDouble(pIdxInfo->estimatedCost);
drhe1e2e9a2013-06-13 15:16:53 +00004709 /* TUNING: Every virtual table query returns 25 rows */
4710 pNew->nOut = 46; assert( 46==whereCost(25) );
drhcf8fa7a2013-05-10 20:26:22 +00004711 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004712 if( pNew->u.vtab.needFree ){
4713 sqlite3_free(pNew->u.vtab.idxStr);
4714 pNew->u.vtab.needFree = 0;
4715 }
4716 }
4717 }
4718
4719whereLoopAddVtab_exit:
4720 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4721 sqlite3DbFree(db, pIdxInfo);
4722 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004723}
drh8636e9c2013-06-11 01:50:08 +00004724#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhf1b5f5b2013-05-02 00:15:01 +00004725
4726/*
drhcf8fa7a2013-05-10 20:26:22 +00004727** Add WhereLoop entries to handle OR terms. This works for either
4728** btrees or virtual tables.
4729*/
4730static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00004731 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00004732 WhereClause *pWC;
4733 WhereLoop *pNew;
4734 WhereTerm *pTerm, *pWCEnd;
4735 int rc = SQLITE_OK;
4736 int iCur;
4737 WhereClause tempWC;
4738 WhereLoopBuilder sSubBuild;
4739 WhereLoop sBest;
4740 struct SrcList_item *pItem;
4741
drhcf8fa7a2013-05-10 20:26:22 +00004742 pWC = pBuilder->pWC;
drh70d18342013-06-06 19:16:33 +00004743 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
drhcf8fa7a2013-05-10 20:26:22 +00004744 pWCEnd = pWC->a + pWC->nTerm;
4745 pNew = pBuilder->pNew;
drhcf8fa7a2013-05-10 20:26:22 +00004746
4747 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4748 if( (pTerm->eOperator & WO_OR)!=0
4749 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4750 ){
4751 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4752 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4753 WhereTerm *pOrTerm;
drh4efc9292013-06-06 23:02:03 +00004754 WhereCost rTotal = 0;
4755 WhereCost nRow = 0;
drhcf8fa7a2013-05-10 20:26:22 +00004756 Bitmask prereq = mExtra;
drh783dece2013-06-05 17:53:43 +00004757
drh13e11b42013-06-06 23:44:25 +00004758 whereLoopInit(&sBest);
drh70d18342013-06-06 19:16:33 +00004759 pItem = pWInfo->pTabList->a + pNew->iTab;
drh783dece2013-06-05 17:53:43 +00004760 iCur = pItem->iCursor;
4761 sSubBuild = *pBuilder;
4762 sSubBuild.pOrderBy = 0;
4763 sSubBuild.pBest = &sBest;
drhcf8fa7a2013-05-10 20:26:22 +00004764
drh95ed68d2013-06-12 17:55:50 +00004765 for(pOrTerm=pOrWC->a; rc==SQLITE_OK && pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00004766 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004767 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4768 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00004769 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00004770 tempWC.pOuter = pWC;
4771 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00004772 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00004773 tempWC.a = pOrTerm;
4774 sSubBuild.pWC = &tempWC;
4775 }else{
4776 continue;
4777 }
4778 sBest.maskSelf = 0;
drh4efc9292013-06-06 23:02:03 +00004779 sBest.rSetup = 0;
4780 sBest.rRun = 0;
drh8636e9c2013-06-11 01:50:08 +00004781#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcf8fa7a2013-05-10 20:26:22 +00004782 if( IsVirtual(pItem->pTab) ){
4783 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
drh8636e9c2013-06-11 01:50:08 +00004784 }else
4785#endif
4786 {
drhcf8fa7a2013-05-10 20:26:22 +00004787 rc = whereLoopAddBtree(&sSubBuild, mExtra);
4788 }
4789 if( sBest.maskSelf==0 ) break;
drhb8a8e8a2013-06-10 19:12:39 +00004790 assert( sBest.rSetup==0 );
4791 rTotal = whereCostAdd(rTotal, sBest.rRun);
4792 nRow = whereCostAdd(nRow, sBest.nOut);
drhcf8fa7a2013-05-10 20:26:22 +00004793 prereq |= sBest.prereq;
4794 }
drh4efc9292013-06-06 23:02:03 +00004795 assert( pNew->nLSlot>=1 );
drhfd5874d2013-06-12 14:52:39 +00004796 if( sBest.maskSelf ){
4797 pNew->nLTerm = 1;
4798 pNew->aLTerm[0] = pTerm;
4799 pNew->wsFlags = WHERE_MULTI_OR;
4800 pNew->rSetup = 0;
4801 pNew->rRun = rTotal;
4802 pNew->nOut = nRow;
4803 pNew->prereq = prereq;
4804 memset(&pNew->u, 0, sizeof(pNew->u));
4805 rc = whereLoopInsert(pBuilder, pNew);
4806 }
drh13e11b42013-06-06 23:44:25 +00004807 whereLoopClear(pWInfo->pParse->db, &sBest);
drhcf8fa7a2013-05-10 20:26:22 +00004808 }
4809 }
4810 return rc;
4811}
4812
4813/*
drhf1b5f5b2013-05-02 00:15:01 +00004814** Add all WhereLoop objects for all tables
4815*/
drh5346e952013-05-08 14:14:26 +00004816static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00004817 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00004818 Bitmask mExtra = 0;
4819 Bitmask mPrior = 0;
4820 int iTab;
drh70d18342013-06-06 19:16:33 +00004821 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00004822 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00004823 sqlite3 *db = pWInfo->pParse->db;
4824 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00004825 int rc = SQLITE_OK;
drhc63367e2013-06-10 20:46:50 +00004826 u8 priorJoinType = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004827 WhereLoop *pNew;
drhf1b5f5b2013-05-02 00:15:01 +00004828
4829 /* Loop over the tables in the join, from left to right */
drhb8a8e8a2013-06-10 19:12:39 +00004830 pNew = pBuilder->pNew;
drha2014152013-06-07 00:29:23 +00004831 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00004832 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00004833 pNew->iTab = iTab;
drh70d18342013-06-06 19:16:33 +00004834 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
drhc63367e2013-06-10 20:46:50 +00004835 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
drhf1b5f5b2013-05-02 00:15:01 +00004836 mExtra = mPrior;
4837 }
drhc63367e2013-06-10 20:46:50 +00004838 priorJoinType = pItem->jointype;
drhb2a90f02013-05-10 03:30:49 +00004839 if( IsVirtual(pItem->pTab) ){
4840 rc = whereLoopAddVirtual(pBuilder, mExtra);
4841 }else{
4842 rc = whereLoopAddBtree(pBuilder, mExtra);
4843 }
drhb2a90f02013-05-10 03:30:49 +00004844 if( rc==SQLITE_OK ){
4845 rc = whereLoopAddOr(pBuilder, mExtra);
4846 }
drhb2a90f02013-05-10 03:30:49 +00004847 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00004848 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00004849 }
drha2014152013-06-07 00:29:23 +00004850 whereLoopClear(db, pNew);
drh5346e952013-05-08 14:14:26 +00004851 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004852}
4853
drha18f3d22013-05-08 03:05:41 +00004854/*
drh7699d1c2013-06-04 12:42:29 +00004855** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00004856** parameters) to see if it outputs rows in the requested ORDER BY
4857** (or GROUP BY) without requiring a separate source operation. Return:
4858**
4859** 0: ORDER BY is not satisfied. Sorting required
4860** 1: ORDER BY is satisfied. Omit sorting
4861** -1: Unknown at this time
4862**
drh6b7157b2013-05-10 02:00:35 +00004863*/
4864static int wherePathSatisfiesOrderBy(
4865 WhereInfo *pWInfo, /* The WHERE clause */
drh4f402f22013-06-11 18:59:38 +00004866 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
drh6b7157b2013-05-10 02:00:35 +00004867 WherePath *pPath, /* The WherePath to check */
drh4f402f22013-06-11 18:59:38 +00004868 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
4869 u16 nLoop, /* Number of entries in pPath->aLoop[] */
4870 u8 isLastLoop, /* True if pLast is the inner-most loop */
drh319f6772013-05-14 15:31:07 +00004871 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
drh4f402f22013-06-11 18:59:38 +00004872 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00004873){
drh88da6442013-05-27 17:59:37 +00004874 u8 revSet; /* True if rev is known */
4875 u8 rev; /* Composite sort order */
4876 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00004877 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
4878 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
4879 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drh7699d1c2013-06-04 12:42:29 +00004880 u16 nColumn; /* Number of columns in pIndex */
4881 u16 nOrderBy; /* Number terms in the ORDER BY clause */
4882 int iLoop; /* Index of WhereLoop in pPath being processed */
4883 int i, j; /* Loop counters */
4884 int iCur; /* Cursor number for current WhereLoop */
4885 int iColumn; /* A column number within table iCur */
4886 WhereLoop *pLoop; /* Current WhereLoop being processed. */
drh7699d1c2013-06-04 12:42:29 +00004887 WhereTerm *pTerm; /* A single term of the WHERE clause */
4888 Expr *pOBExpr; /* An expression from the ORDER BY clause */
4889 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
4890 Index *pIndex; /* The index associated with pLoop */
4891 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
4892 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
4893 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00004894 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drh7699d1c2013-06-04 12:42:29 +00004895
drh319f6772013-05-14 15:31:07 +00004896
4897 /*
drh7699d1c2013-06-04 12:42:29 +00004898 ** We say the WhereLoop is "one-row" if it generates no more than one
4899 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00004900 ** (a) All index columns match with WHERE_COLUMN_EQ.
4901 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00004902 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
4903 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00004904 **
drhe353ee32013-06-04 23:40:53 +00004905 ** We say the WhereLoop is "order-distinct" if the set of columns from
4906 ** that WhereLoop that are in the ORDER BY clause are different for every
4907 ** row of the WhereLoop. Every one-row WhereLoop is automatically
4908 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
4909 ** is not order-distinct. To be order-distinct is not quite the same as being
4910 ** UNIQUE since a UNIQUE column or index can have multiple rows that
4911 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4912 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4913 **
4914 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4915 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4916 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00004917 */
4918
4919 assert( pOrderBy!=0 );
4920
4921 /* Sortability of virtual tables is determined by the xBestIndex method
4922 ** of the virtual table itself */
4923 if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
drh7699d1c2013-06-04 12:42:29 +00004924 testcase( nLoop>0 ); /* True when outer loops are one-row and match
4925 ** no ORDER BY terms */
drh319f6772013-05-14 15:31:07 +00004926 return pLast->u.vtab.isOrdered;
drh6b7157b2013-05-10 02:00:35 +00004927 }
drh7699d1c2013-06-04 12:42:29 +00004928 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00004929
drh319f6772013-05-14 15:31:07 +00004930 nOrderBy = pOrderBy->nExpr;
drhe353ee32013-06-04 23:40:53 +00004931 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
4932 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00004933 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00004934 orderDistinctMask = 0;
drhe353ee32013-06-04 23:40:53 +00004935 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drh7699d1c2013-06-04 12:42:29 +00004936 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh319f6772013-05-14 15:31:07 +00004937 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh319f6772013-05-14 15:31:07 +00004938 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drh7699d1c2013-06-04 12:42:29 +00004939 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
4940 if( pLoop->wsFlags & WHERE_IPK ){
4941 pIndex = 0;
4942 nColumn = 0;
4943 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00004944 return 0;
drh7699d1c2013-06-04 12:42:29 +00004945 }else{
4946 nColumn = pIndex->nColumn;
drhe353ee32013-06-04 23:40:53 +00004947 isOrderDistinct = pIndex->onError!=OE_None;
drh1b0f0262013-05-30 22:27:09 +00004948 }
drh7699d1c2013-06-04 12:42:29 +00004949
drhe353ee32013-06-04 23:40:53 +00004950 /* For every term of the index that is constrained by == or IS NULL,
drh7699d1c2013-06-04 12:42:29 +00004951 ** mark off corresponding ORDER BY terms wherever they occur
4952 ** in the ORDER BY clause.
4953 */
4954 for(i=0; i<pLoop->u.btree.nEq; i++){
drh4efc9292013-06-06 23:02:03 +00004955 pTerm = pLoop->aLTerm[i];
drh7699d1c2013-06-04 12:42:29 +00004956 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))==0 ) continue;
4957 iColumn = pTerm->u.leftColumn;
4958 for(j=0; j<nOrderBy; j++){
4959 if( MASKBIT(j) & obSat ) continue;
4960 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[j].pExpr);
4961 if( pOBExpr->op!=TK_COLUMN ) continue;
4962 if( pOBExpr->iTable!=iCur ) continue;
4963 if( pOBExpr->iColumn!=iColumn ) continue;
4964 if( iColumn>=0 ){
4965 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[j].pExpr);
4966 if( !pColl ) pColl = db->pDfltColl;
4967 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[i])!=0 ) continue;
4968 }
4969 obSat |= MASKBIT(j);
drhdc3cd4b2013-05-30 23:21:20 +00004970 }
drh7699d1c2013-06-04 12:42:29 +00004971 if( obSat==obDone ) return 1;
drh88da6442013-05-27 17:59:37 +00004972 }
drh7699d1c2013-06-04 12:42:29 +00004973
4974 /* Loop through all columns of the index and deal with the ones
4975 ** that are not constrained by == or IN.
4976 */
4977 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00004978 distinctColumns = 0;
drh7699d1c2013-06-04 12:42:29 +00004979 for(j=0; j<=nColumn; j++){
4980 u8 bOnce; /* True to run the ORDER BY search loop */
4981
drhe353ee32013-06-04 23:40:53 +00004982 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00004983 if( j<pLoop->u.btree.nEq
drh4efc9292013-06-06 23:02:03 +00004984 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
drh7699d1c2013-06-04 12:42:29 +00004985 ){
drhe353ee32013-06-04 23:40:53 +00004986 if( i & WO_ISNULL ) isOrderDistinct = 0;
4987 continue;
drh7699d1c2013-06-04 12:42:29 +00004988 }
4989
drhe353ee32013-06-04 23:40:53 +00004990 /* Get the column number in the table (iColumn) and sort order
4991 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00004992 */
4993 if( j<nColumn ){
4994 /* Normal index columns */
4995 iColumn = pIndex->aiColumn[j];
4996 revIdx = pIndex->aSortOrder[j];
4997 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00004998 }else{
drh7699d1c2013-06-04 12:42:29 +00004999 /* The ROWID column at the end */
5000 iColumn = -1;
5001 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00005002 }
drh7699d1c2013-06-04 12:42:29 +00005003
5004 /* An unconstrained column that might be NULL means that this
5005 ** WhereLoop is not well-ordered
5006 */
drhe353ee32013-06-04 23:40:53 +00005007 if( isOrderDistinct
5008 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00005009 && j>=pLoop->u.btree.nEq
5010 && pIndex->pTable->aCol[iColumn].notNull==0
5011 ){
drhe353ee32013-06-04 23:40:53 +00005012 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00005013 }
5014
5015 /* Find the ORDER BY term that corresponds to the j-th column
5016 ** of the index and and mark that ORDER BY term off
5017 */
5018 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00005019 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00005020 for(i=0; bOnce && i<nOrderBy; i++){
5021 if( MASKBIT(i) & obSat ) continue;
5022 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh4f402f22013-06-11 18:59:38 +00005023 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00005024 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00005025 if( pOBExpr->iTable!=iCur ) continue;
5026 if( pOBExpr->iColumn!=iColumn ) continue;
5027 if( iColumn>=0 ){
5028 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5029 if( !pColl ) pColl = db->pDfltColl;
5030 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
5031 }
drhe353ee32013-06-04 23:40:53 +00005032 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00005033 break;
5034 }
drhe353ee32013-06-04 23:40:53 +00005035 if( isMatch ){
5036 if( iColumn<0 ) distinctColumns = 1;
drh7699d1c2013-06-04 12:42:29 +00005037 obSat |= MASKBIT(i);
5038 if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
drhe353ee32013-06-04 23:40:53 +00005039 /* Make sure the sort order is compatible in an ORDER BY clause.
5040 ** Sort order is irrelevant for a GROUP BY clause. */
drh7699d1c2013-06-04 12:42:29 +00005041 if( revSet ){
5042 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
5043 }else{
5044 rev = revIdx ^ pOrderBy->a[i].sortOrder;
5045 if( rev ) *pRevMask |= MASKBIT(iLoop);
5046 revSet = 1;
5047 }
5048 }
5049 }else{
5050 /* No match found */
drhe353ee32013-06-04 23:40:53 +00005051 if( j==0 || j<nColumn ) isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00005052 break;
5053 }
5054 } /* end Loop over all index columns */
drhe353ee32013-06-04 23:40:53 +00005055 if( distinctColumns ) isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00005056 } /* end-if not one-row */
5057
5058 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00005059 if( isOrderDistinct ){
5060 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005061 for(i=0; i<nOrderBy; i++){
5062 Expr *p;
5063 if( MASKBIT(i) & obSat ) continue;
5064 p = pOrderBy->a[i].pExpr;
drh70d18342013-06-06 19:16:33 +00005065 if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00005066 obSat |= MASKBIT(i);
5067 }
drh0afb4232013-05-31 13:36:32 +00005068 }
drh319f6772013-05-14 15:31:07 +00005069 }
drh319f6772013-05-14 15:31:07 +00005070 }
drh7699d1c2013-06-04 12:42:29 +00005071 if( obSat==obDone ) return 1;
drhe353ee32013-06-04 23:40:53 +00005072 if( !isOrderDistinct ) return 0;
drh7699d1c2013-06-04 12:42:29 +00005073 if( isLastLoop ) return 1;
drh319f6772013-05-14 15:31:07 +00005074 return -1;
drh6b7157b2013-05-10 02:00:35 +00005075}
5076
drhd15cb172013-05-21 19:23:10 +00005077#ifdef WHERETRACE_ENABLED
5078/* For debugging use only: */
5079static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
5080 static char zName[65];
5081 int i;
5082 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
5083 if( pLast ) zName[i++] = pLast->cId;
5084 zName[i] = 0;
5085 return zName;
5086}
5087#endif
5088
drh6b7157b2013-05-10 02:00:35 +00005089
5090/*
drha18f3d22013-05-08 03:05:41 +00005091** Given the list of WhereLoop objects on pWInfo->pLoops, this routine
5092** attempts to find the lowest cost path that visits each WhereLoop
5093** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5094**
5095** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5096** error occurs.
5097*/
drh4efc9292013-06-06 23:02:03 +00005098static int wherePathSolver(WhereInfo *pWInfo, WhereCost nRowEst){
drh783dece2013-06-05 17:53:43 +00005099 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00005100 int nLoop; /* Number of terms in the join */
drhe1e2e9a2013-06-13 15:16:53 +00005101 Parse *pParse; /* Parsing context */
drha18f3d22013-05-08 03:05:41 +00005102 sqlite3 *db; /* The database connection */
5103 int iLoop; /* Loop counter over the terms of the join */
5104 int ii, jj; /* Loop counters */
drh4efc9292013-06-06 23:02:03 +00005105 WhereCost rCost; /* Cost of a path */
5106 WhereCost mxCost; /* Maximum cost of a set of paths */
5107 WhereCost rSortCost; /* Cost to do a sort */
drha18f3d22013-05-08 03:05:41 +00005108 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
5109 WherePath *aFrom; /* All nFrom paths at the previous level */
5110 WherePath *aTo; /* The nTo best paths at the current level */
5111 WherePath *pFrom; /* An element of aFrom[] that we are working on */
5112 WherePath *pTo; /* An element of aTo[] that we are working on */
5113 WhereLoop *pWLoop; /* One of the WhereLoop objects */
5114 WhereLoop **pX; /* Used to divy up the pSpace memory */
5115 char *pSpace; /* Temporary memory used by this routine */
5116
drhe1e2e9a2013-06-13 15:16:53 +00005117 pParse = pWInfo->pParse;
5118 db = pParse->db;
drha18f3d22013-05-08 03:05:41 +00005119 nLoop = pWInfo->nLevel;
drhe1e2e9a2013-06-13 15:16:53 +00005120 /* TUNING: For simple queries, only the best path is tracked.
5121 ** For 2-way joins, the 5 best paths are followed.
5122 ** For joins of 3 or more tables, track the 10 best paths */
drhe9d935a2013-06-05 16:19:59 +00005123 mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00005124 assert( nLoop<=pWInfo->pTabList->nSrc );
drh3b48e8c2013-06-12 20:18:16 +00005125 WHERETRACE(0x002, ("---- begin solver\n"));
drha18f3d22013-05-08 03:05:41 +00005126
5127 /* Allocate and initialize space for aTo and aFrom */
5128 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
5129 pSpace = sqlite3DbMallocRaw(db, ii);
5130 if( pSpace==0 ) return SQLITE_NOMEM;
5131 aTo = (WherePath*)pSpace;
5132 aFrom = aTo+mxChoice;
5133 memset(aFrom, 0, sizeof(aFrom[0]));
5134 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00005135 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00005136 pFrom->aLoop = pX;
5137 }
5138
drhe1e2e9a2013-06-13 15:16:53 +00005139 /* Seed the search with a single WherePath containing zero WhereLoops.
5140 **
5141 ** TUNING: Do not let the number of iterations go above 25. If the cost
5142 ** of computing an automatic index is not paid back within the first 25
5143 ** rows, then do not use the automatic index. */
5144 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==whereCost(25) );
drha18f3d22013-05-08 03:05:41 +00005145 nFrom = 1;
drh6b7157b2013-05-10 02:00:35 +00005146
5147 /* Precompute the cost of sorting the final result set, if the caller
5148 ** to sqlite3WhereBegin() was concerned about sorting */
drhb8a8e8a2013-06-10 19:12:39 +00005149 rSortCost = 0;
5150 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
drh6b7157b2013-05-10 02:00:35 +00005151 aFrom[0].isOrderedValid = 1;
5152 }else{
drhe1e2e9a2013-06-13 15:16:53 +00005153 /* TUNING: Estimated cost of sorting is N*log2(N) where N is the
5154 ** number of output rows. */
drhb8a8e8a2013-06-10 19:12:39 +00005155 rSortCost = nRowEst + estLog(nRowEst);
drh3b48e8c2013-06-12 20:18:16 +00005156 WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
drh6b7157b2013-05-10 02:00:35 +00005157 }
5158
5159 /* Compute successively longer WherePaths using the previous generation
5160 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5161 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00005162 for(iLoop=0; iLoop<nLoop; iLoop++){
5163 nTo = 0;
5164 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
5165 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
5166 Bitmask maskNew;
drh319f6772013-05-14 15:31:07 +00005167 Bitmask revMask = 0;
drh6b7157b2013-05-10 02:00:35 +00005168 u8 isOrderedValid = pFrom->isOrderedValid;
5169 u8 isOrdered = pFrom->isOrdered;
drha18f3d22013-05-08 03:05:41 +00005170 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5171 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00005172 /* At this point, pWLoop is a candidate to be the next loop.
5173 ** Compute its cost */
drhb8a8e8a2013-06-10 19:12:39 +00005174 rCost = whereCostAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
5175 rCost = whereCostAdd(rCost, pFrom->rCost);
drha18f3d22013-05-08 03:05:41 +00005176 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh6b7157b2013-05-10 02:00:35 +00005177 if( !isOrderedValid ){
drh4f402f22013-06-11 18:59:38 +00005178 switch( wherePathSatisfiesOrderBy(pWInfo,
5179 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
5180 iLoop, iLoop==nLoop-1, pWLoop, &revMask) ){
drh6b7157b2013-05-10 02:00:35 +00005181 case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
5182 isOrdered = 1;
5183 isOrderedValid = 1;
5184 break;
5185 case 0: /* No. pFrom+pWLoop will require a separate sort */
5186 isOrdered = 0;
5187 isOrderedValid = 1;
drhb8a8e8a2013-06-10 19:12:39 +00005188 rCost = whereCostAdd(rCost, rSortCost);
drh6b7157b2013-05-10 02:00:35 +00005189 break;
5190 default: /* Cannot tell yet. Try again on the next iteration */
5191 break;
5192 }
drh3a5ba8b2013-06-03 15:34:48 +00005193 }else{
5194 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00005195 }
5196 /* Check to see if pWLoop should be added to the mxChoice best so far */
5197 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
5198 if( pTo->maskLoop==maskNew && pTo->isOrderedValid==isOrderedValid ){
5199 break;
5200 }
5201 }
drha18f3d22013-05-08 03:05:41 +00005202 if( jj>=nTo ){
drhd15cb172013-05-21 19:23:10 +00005203 if( nTo>=mxChoice && rCost>=mxCost ){
drhae70cf12013-05-31 15:18:46 +00005204#ifdef WHERETRACE_ENABLED
5205 if( sqlite3WhereTrace&0x4 ){
drhb8a8e8a2013-06-10 19:12:39 +00005206 sqlite3DebugPrintf("Skip %s cost=%3d order=%c\n",
drhd15cb172013-05-21 19:23:10 +00005207 wherePathName(pFrom, iLoop, pWLoop), rCost,
5208 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5209 }
5210#endif
5211 continue;
5212 }
5213 /* Add a new Path to the aTo[] set */
drha18f3d22013-05-08 03:05:41 +00005214 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00005215 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00005216 jj = nTo++;
5217 }else{
drhd15cb172013-05-21 19:23:10 +00005218 /* New path replaces the prior worst to keep count below mxChoice */
drhc718f1c2013-05-08 20:05:58 +00005219 for(jj=nTo-1; aTo[jj].rCost<mxCost; jj--){ assert(jj>0); }
drha18f3d22013-05-08 03:05:41 +00005220 }
5221 pTo = &aTo[jj];
drhd15cb172013-05-21 19:23:10 +00005222#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005223 if( sqlite3WhereTrace&0x4 ){
drhb8a8e8a2013-06-10 19:12:39 +00005224 sqlite3DebugPrintf("New %s cost=%-3d order=%c\n",
drhd15cb172013-05-21 19:23:10 +00005225 wherePathName(pFrom, iLoop, pWLoop), rCost,
5226 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5227 }
5228#endif
drhf204dac2013-05-08 03:22:07 +00005229 }else{
drhd15cb172013-05-21 19:23:10 +00005230 if( pTo->rCost<=rCost ){
5231#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005232 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005233 sqlite3DebugPrintf(
drhb8a8e8a2013-06-10 19:12:39 +00005234 "Skip %s cost=%-3d order=%c",
drhd15cb172013-05-21 19:23:10 +00005235 wherePathName(pFrom, iLoop, pWLoop), rCost,
5236 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
drhb8a8e8a2013-06-10 19:12:39 +00005237 sqlite3DebugPrintf(" vs %s cost=%-3d order=%c\n",
drhd15cb172013-05-21 19:23:10 +00005238 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
5239 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5240 }
5241#endif
5242 continue;
5243 }
5244 /* A new and better score for a previously created equivalent path */
5245#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005246 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005247 sqlite3DebugPrintf(
drhb8a8e8a2013-06-10 19:12:39 +00005248 "Update %s cost=%-3d order=%c",
drhd15cb172013-05-21 19:23:10 +00005249 wherePathName(pFrom, iLoop, pWLoop), rCost,
5250 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
drhb8a8e8a2013-06-10 19:12:39 +00005251 sqlite3DebugPrintf(" was %s cost=%-3d order=%c\n",
drhd15cb172013-05-21 19:23:10 +00005252 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
5253 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5254 }
5255#endif
drha18f3d22013-05-08 03:05:41 +00005256 }
drh6b7157b2013-05-10 02:00:35 +00005257 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00005258 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00005259 pTo->revLoop = revMask;
drhb8a8e8a2013-06-10 19:12:39 +00005260 pTo->nRow = pFrom->nRow + pWLoop->nOut;
drha18f3d22013-05-08 03:05:41 +00005261 pTo->rCost = rCost;
drh6b7157b2013-05-10 02:00:35 +00005262 pTo->isOrderedValid = isOrderedValid;
5263 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00005264 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5265 pTo->aLoop[iLoop] = pWLoop;
5266 if( nTo>=mxChoice ){
5267 mxCost = aTo[0].rCost;
5268 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
5269 if( pTo->rCost>mxCost ) mxCost = pTo->rCost;
5270 }
5271 }
5272 }
5273 }
5274
drhd15cb172013-05-21 19:23:10 +00005275#ifdef WHERETRACE_ENABLED
5276 if( sqlite3WhereTrace>=2 ){
drha50ef112013-05-22 02:06:59 +00005277 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00005278 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drhb8a8e8a2013-06-10 19:12:39 +00005279 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
drha50ef112013-05-22 02:06:59 +00005280 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00005281 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
drh88da6442013-05-27 17:59:37 +00005282 if( pTo->isOrderedValid && pTo->isOrdered ){
5283 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5284 }else{
5285 sqlite3DebugPrintf("\n");
5286 }
drhf204dac2013-05-08 03:22:07 +00005287 }
5288 }
5289#endif
5290
drh6b7157b2013-05-10 02:00:35 +00005291 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00005292 pFrom = aTo;
5293 aTo = aFrom;
5294 aFrom = pFrom;
5295 nFrom = nTo;
5296 }
5297
drh75b93402013-05-31 20:43:57 +00005298 if( nFrom==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00005299 sqlite3ErrorMsg(pParse, "no query solution");
drh75b93402013-05-31 20:43:57 +00005300 sqlite3DbFree(db, pSpace);
5301 return SQLITE_ERROR;
5302 }
drha18f3d22013-05-08 03:05:41 +00005303
drh6b7157b2013-05-10 02:00:35 +00005304 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00005305 pFrom = aFrom;
5306 for(ii=1; ii<nFrom; ii++){
5307 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5308 }
5309 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00005310 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00005311 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00005312 WhereLevel *pLevel = pWInfo->a + iLoop;
5313 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
drhe217efc2013-06-12 03:48:41 +00005314 pLevel->iFrom = pWLoop->iTab;
drh7ba39a92013-05-30 17:43:19 +00005315 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00005316 }
drh4f402f22013-06-11 18:59:38 +00005317 if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5318 && pWInfo->pDistinct
5319 && nRowEst
5320 ){
5321 Bitmask notUsed;
5322 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinct, pFrom,
5323 WHERE_DISTINCTBY, nLoop-1, 1, pFrom->aLoop[nLoop-1], &notUsed);
5324 if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5325 }
drh6b7157b2013-05-10 02:00:35 +00005326 if( pFrom->isOrdered ){
drh4f402f22013-06-11 18:59:38 +00005327 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
5328 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5329 }else{
5330 pWInfo->bOBSat = 1;
5331 pWInfo->revMask = pFrom->revLoop;
5332 }
drh6b7157b2013-05-10 02:00:35 +00005333 }
drha50ef112013-05-22 02:06:59 +00005334 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00005335
5336 /* Free temporary memory and return success */
5337 sqlite3DbFree(db, pSpace);
5338 return SQLITE_OK;
5339}
drh94a11212004-09-25 13:12:14 +00005340
5341/*
drh60c96cd2013-06-09 17:21:25 +00005342** Most queries use only a single table (they are not joins) and have
5343** simple == constraints against indexed fields. This routine attempts
5344** to plan those simple cases using much less ceremony than the
5345** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5346** times for the common case.
5347**
5348** Return non-zero on success, if this query can be handled by this
5349** no-frills query planner. Return zero if this query needs the
5350** general-purpose query planner.
5351*/
drhb8a8e8a2013-06-10 19:12:39 +00005352static int whereShortCut(WhereLoopBuilder *pBuilder){
drh60c96cd2013-06-09 17:21:25 +00005353 WhereInfo *pWInfo;
5354 struct SrcList_item *pItem;
5355 WhereClause *pWC;
5356 WhereTerm *pTerm;
5357 WhereLoop *pLoop;
5358 int iCur;
drh92a121f2013-06-10 12:15:47 +00005359 int j;
drh60c96cd2013-06-09 17:21:25 +00005360 Table *pTab;
5361 Index *pIdx;
5362
5363 pWInfo = pBuilder->pWInfo;
drh5822d6f2013-06-10 23:30:09 +00005364 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
drh60c96cd2013-06-09 17:21:25 +00005365 assert( pWInfo->pTabList->nSrc>=1 );
5366 pItem = pWInfo->pTabList->a;
5367 pTab = pItem->pTab;
5368 if( IsVirtual(pTab) ) return 0;
5369 if( pItem->zIndex ) return 0;
5370 iCur = pItem->iCursor;
5371 pWC = &pWInfo->sWC;
5372 pLoop = pBuilder->pNew;
drh60c96cd2013-06-09 17:21:25 +00005373 pLoop->wsFlags = 0;
drh3b75ffa2013-06-10 14:56:25 +00005374 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
drh60c96cd2013-06-09 17:21:25 +00005375 if( pTerm ){
5376 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5377 pLoop->aLTerm[0] = pTerm;
5378 pLoop->nLTerm = 1;
5379 pLoop->u.btree.nEq = 1;
drhe1e2e9a2013-06-13 15:16:53 +00005380 /* TUNING: Cost of a rowid lookup is 10 */
5381 pLoop->rRun = 33; /* 33==whereCost(10) */
drh60c96cd2013-06-09 17:21:25 +00005382 }else{
5383 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5384 if( pIdx->onError==OE_None ) continue;
5385 for(j=0; j<pIdx->nColumn; j++){
drh3b75ffa2013-06-10 14:56:25 +00005386 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
drh60c96cd2013-06-09 17:21:25 +00005387 if( pTerm==0 ) break;
5388 whereLoopResize(pWInfo->pParse->db, pLoop, j);
5389 pLoop->aLTerm[j] = pTerm;
5390 }
5391 if( j!=pIdx->nColumn ) continue;
drh92a121f2013-06-10 12:15:47 +00005392 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
drhfd5874d2013-06-12 14:52:39 +00005393 if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
drh92a121f2013-06-10 12:15:47 +00005394 pLoop->wsFlags |= WHERE_IDX_ONLY;
5395 }
drh60c96cd2013-06-09 17:21:25 +00005396 pLoop->nLTerm = j;
5397 pLoop->u.btree.nEq = j;
5398 pLoop->u.btree.pIndex = pIdx;
drhe1e2e9a2013-06-13 15:16:53 +00005399 /* TUNING: Cost of a unique index lookup is 15 */
5400 pLoop->rRun = 39; /* 39==whereCost(15) */
drh60c96cd2013-06-09 17:21:25 +00005401 break;
5402 }
5403 }
drh3b75ffa2013-06-10 14:56:25 +00005404 if( pLoop->wsFlags ){
5405 pLoop->nOut = (WhereCost)1;
5406 pWInfo->a[0].pWLoop = pLoop;
5407 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
5408 pWInfo->a[0].iTabCur = iCur;
5409 pWInfo->nRowOut = 1;
drh4f402f22013-06-11 18:59:38 +00005410 if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
5411 if( pWInfo->pDistinct ) pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
drh3b75ffa2013-06-10 14:56:25 +00005412#ifdef SQLITE_DEBUG
5413 pLoop->cId = '0';
5414#endif
5415 return 1;
5416 }
5417 return 0;
drh60c96cd2013-06-09 17:21:25 +00005418}
5419
5420/*
drhe3184742002-06-19 14:27:05 +00005421** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00005422** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00005423** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00005424** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00005425** in order to complete the WHERE clause processing.
5426**
5427** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00005428**
5429** The basic idea is to do a nested loop, one loop for each table in
5430** the FROM clause of a select. (INSERT and UPDATE statements are the
5431** same as a SELECT with only a single table in the FROM clause.) For
5432** example, if the SQL is this:
5433**
5434** SELECT * FROM t1, t2, t3 WHERE ...;
5435**
5436** Then the code generated is conceptually like the following:
5437**
5438** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005439** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00005440** foreach row3 in t3 do /
5441** ...
5442** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005443** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00005444** end /
5445**
drh29dda4a2005-07-21 18:23:20 +00005446** Note that the loops might not be nested in the order in which they
5447** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00005448** use of indices. Note also that when the IN operator appears in
5449** the WHERE clause, it might result in additional nested loops for
5450** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00005451**
drhc27a1ce2002-06-14 20:58:45 +00005452** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00005453** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5454** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00005455** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00005456**
drhe6f85e72004-12-25 01:03:13 +00005457** The code that sqlite3WhereBegin() generates leaves the cursors named
5458** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00005459** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00005460** data from the various tables of the loop.
5461**
drhc27a1ce2002-06-14 20:58:45 +00005462** If the WHERE clause is empty, the foreach loops must each scan their
5463** entire tables. Thus a three-way join is an O(N^3) operation. But if
5464** the tables have indices and there are terms in the WHERE clause that
5465** refer to those indices, a complete table scan can be avoided and the
5466** code will run much faster. Most of the work of this routine is checking
5467** to see if there are indices that can be used to speed up the loop.
5468**
5469** Terms of the WHERE clause are also used to limit which rows actually
5470** make it to the "..." in the middle of the loop. After each "foreach",
5471** terms of the WHERE clause that use only terms in that loop and outer
5472** loops are evaluated and if false a jump is made around all subsequent
5473** inner loops (or around the "..." if the test occurs within the inner-
5474** most loop)
5475**
5476** OUTER JOINS
5477**
5478** An outer join of tables t1 and t2 is conceptally coded as follows:
5479**
5480** foreach row1 in t1 do
5481** flag = 0
5482** foreach row2 in t2 do
5483** start:
5484** ...
5485** flag = 1
5486** end
drhe3184742002-06-19 14:27:05 +00005487** if flag==0 then
5488** move the row2 cursor to a null row
5489** goto start
5490** fi
drhc27a1ce2002-06-14 20:58:45 +00005491** end
5492**
drhe3184742002-06-19 14:27:05 +00005493** ORDER BY CLAUSE PROCESSING
5494**
drh46ec5b62012-09-24 15:30:54 +00005495** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
drhe3184742002-06-19 14:27:05 +00005496** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00005497** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drh75897232000-05-29 14:26:00 +00005498*/
danielk19774adee202004-05-08 08:23:19 +00005499WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00005500 Parse *pParse, /* The parser context */
5501 SrcList *pTabList, /* A list of all tables to be scanned */
5502 Expr *pWhere, /* The WHERE clause */
drh46ec5b62012-09-24 15:30:54 +00005503 ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
dan38cc40c2011-06-30 20:17:15 +00005504 ExprList *pDistinct, /* The select-list for DISTINCT queries - or NULL */
dan0efb72c2012-08-24 18:44:56 +00005505 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
5506 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00005507){
danielk1977be229652009-03-20 14:18:51 +00005508 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00005509 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00005510 WhereInfo *pWInfo; /* Will become the return value of this function */
5511 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00005512 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00005513 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00005514 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00005515 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drh9cd1c992012-09-25 20:43:35 +00005516 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00005517 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00005518 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00005519
drh56f1b992012-09-25 14:29:39 +00005520
5521 /* Variable initialization */
drh1c8148f2013-05-04 20:25:23 +00005522 memset(&sWLB, 0, sizeof(sWLB));
drh1c8148f2013-05-04 20:25:23 +00005523 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00005524
drh29dda4a2005-07-21 18:23:20 +00005525 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00005526 ** bits in a Bitmask
5527 */
drh67ae0cb2010-04-08 14:38:51 +00005528 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00005529 if( pTabList->nSrc>BMS ){
5530 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00005531 return 0;
5532 }
5533
drhc01a3c12009-12-16 22:10:49 +00005534 /* This function normally generates a nested loop for all tables in
5535 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
5536 ** only generate code for the first table in pTabList and assume that
5537 ** any cursors associated with subsequent tables are uninitialized.
5538 */
5539 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
5540
drh75897232000-05-29 14:26:00 +00005541 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00005542 ** return value. A single allocation is used to store the WhereInfo
5543 ** struct, the contents of WhereInfo.a[], the WhereClause structure
5544 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5545 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5546 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00005547 */
drh17435752007-08-16 04:30:38 +00005548 db = pParse->db;
drhc01a3c12009-12-16 22:10:49 +00005549 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00005550 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00005551 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00005552 sqlite3DbFree(db, pWInfo);
5553 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00005554 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00005555 }
drhc01a3c12009-12-16 22:10:49 +00005556 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00005557 pWInfo->pParse = pParse;
5558 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00005559 pWInfo->pOrderBy = pOrderBy;
5560 pWInfo->pDistinct = pDistinct;
danielk19774adee202004-05-08 08:23:19 +00005561 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00005562 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00005563 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00005564 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00005565 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00005566 sWLB.pWC = &pWInfo->sWC;
drh60c96cd2013-06-09 17:21:25 +00005567 sWLB.pNew = (WhereLoop*)&pWInfo->a[nTabList];
5568 whereLoopInit(sWLB.pNew);
drhb8a8e8a2013-06-10 19:12:39 +00005569#ifdef SQLITE_DEBUG
5570 sWLB.pNew->cId = '*';
5571#endif
drh08192d52002-04-30 19:20:28 +00005572
drha9b1b912011-07-08 13:07:02 +00005573 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
5574 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
drh7e5418e2012-09-27 15:05:54 +00005575 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
drha9b1b912011-07-08 13:07:02 +00005576
drh111a6a72008-12-21 03:51:16 +00005577 /* Split the WHERE clause into separate subexpressions where each
5578 ** subexpression is separated by an AND operator.
5579 */
5580 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00005581 whereClauseInit(&pWInfo->sWC, pWInfo);
drh111a6a72008-12-21 03:51:16 +00005582 sqlite3ExprCodeConstants(pParse, pWhere);
drh70d18342013-06-06 19:16:33 +00005583 whereSplit(&pWInfo->sWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
drh111a6a72008-12-21 03:51:16 +00005584
drh08192d52002-04-30 19:20:28 +00005585 /* Special case: a WHERE clause that is constant. Evaluate the
5586 ** expression and either jump over all of the code or fall thru.
5587 */
drhc01a3c12009-12-16 22:10:49 +00005588 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
drh35573352008-01-08 23:54:25 +00005589 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
drhdf199a22002-06-14 22:38:41 +00005590 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00005591 }
drh75897232000-05-29 14:26:00 +00005592
drh4fe425a2013-06-12 17:08:06 +00005593 /* Special case: No FROM clause
5594 */
5595 if( nTabList==0 ){
5596 if( pOrderBy ) pWInfo->bOBSat = 1;
5597 if( pDistinct ) pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5598 }
5599
drh42165be2008-03-26 14:56:34 +00005600 /* Assign a bit from the bitmask to every term in the FROM clause.
5601 **
5602 ** When assigning bitmask values to FROM clause cursors, it must be
5603 ** the case that if X is the bitmask for the N-th FROM clause term then
5604 ** the bitmask for all FROM clause terms to the left of the N-th term
5605 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
5606 ** its Expr.iRightJoinTable value to find the bitmask of the right table
5607 ** of the join. Subtracting one from the right table bitmask gives a
5608 ** bitmask for all tables to the left of the join. Knowing the bitmask
5609 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00005610 **
drhc01a3c12009-12-16 22:10:49 +00005611 ** Note that bitmasks are created for all pTabList->nSrc tables in
5612 ** pTabList, not just the first nTabList tables. nTabList is normally
5613 ** equal to pTabList->nSrc but might be shortened to 1 if the
5614 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00005615 */
drh9cd1c992012-09-25 20:43:35 +00005616 for(ii=0; ii<pTabList->nSrc; ii++){
5617 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005618 }
5619#ifndef NDEBUG
5620 {
5621 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00005622 for(ii=0; ii<pTabList->nSrc; ii++){
5623 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005624 assert( (m-1)==toTheLeft );
5625 toTheLeft |= m;
5626 }
5627 }
5628#endif
5629
drh29dda4a2005-07-21 18:23:20 +00005630 /* Analyze all of the subexpressions. Note that exprAnalyze() might
5631 ** add new virtual terms onto the end of the WHERE clause. We do not
5632 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00005633 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00005634 */
drh70d18342013-06-06 19:16:33 +00005635 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drh17435752007-08-16 04:30:38 +00005636 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00005637 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00005638 }
drh75897232000-05-29 14:26:00 +00005639
drh4f402f22013-06-11 18:59:38 +00005640 /* If the ORDER BY (or GROUP BY) clause contains references to general
5641 ** expressions, then we won't be able to satisfy it using indices, so
5642 ** go ahead and disable it now.
5643 */
drhe217efc2013-06-12 03:48:41 +00005644 if( pOrderBy && pDistinct ){
drh4f402f22013-06-11 18:59:38 +00005645 for(ii=0; ii<pOrderBy->nExpr; ii++){
5646 Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
5647 if( pExpr->op!=TK_COLUMN ){
5648 pWInfo->pOrderBy = pOrderBy = 0;
5649 break;
drhe217efc2013-06-12 03:48:41 +00005650 }else if( pExpr->iColumn<0 ){
5651 break;
drh4f402f22013-06-11 18:59:38 +00005652 }
5653 }
5654 }
5655
dan38cc40c2011-06-30 20:17:15 +00005656 /* Check if the DISTINCT qualifier, if there is one, is redundant.
5657 ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
5658 ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
5659 */
drh4f402f22013-06-11 18:59:38 +00005660 if( pDistinct ){
5661 if( isDistinctRedundant(pParse,pTabList,&pWInfo->sWC,pDistinct) ){
5662 pDistinct = 0;
5663 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5664 }else if( pOrderBy==0 ){
5665 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
5666 pWInfo->pOrderBy = pDistinct;
5667 }
dan38cc40c2011-06-30 20:17:15 +00005668 }
5669
drhf1b5f5b2013-05-02 00:15:01 +00005670 /* Construct the WhereLoop objects */
drh3b48e8c2013-06-12 20:18:16 +00005671 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
drhb8a8e8a2013-06-10 19:12:39 +00005672 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
drh60c96cd2013-06-09 17:21:25 +00005673 rc = whereLoopAddAll(&sWLB);
5674 if( rc ) goto whereBeginError;
5675
5676 /* Display all of the WhereLoop objects if wheretrace is enabled */
drhd15cb172013-05-21 19:23:10 +00005677#ifdef WHERETRACE_ENABLED
drh60c96cd2013-06-09 17:21:25 +00005678 if( sqlite3WhereTrace ){
5679 WhereLoop *p;
5680 int i = 0;
5681 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5682 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
5683 for(p=pWInfo->pLoops; p; p=p->pNextLoop){
5684 p->cId = zLabel[(i++)%sizeof(zLabel)];
5685 whereLoopPrint(p, pTabList);
5686 }
5687 }
5688#endif
5689
drh4f402f22013-06-11 18:59:38 +00005690 wherePathSolver(pWInfo, 0);
drh60c96cd2013-06-09 17:21:25 +00005691 if( db->mallocFailed ) goto whereBeginError;
5692 if( pWInfo->pOrderBy ){
5693 wherePathSolver(pWInfo, pWInfo->nRowOut);
5694 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00005695 }
5696 }
drh60c96cd2013-06-09 17:21:25 +00005697 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00005698 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00005699 }
drh75b93402013-05-31 20:43:57 +00005700 if( pParse->nErr || db->mallocFailed ){
5701 goto whereBeginError;
5702 }
drhd15cb172013-05-21 19:23:10 +00005703#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00005704 if( sqlite3WhereTrace ){
5705 int ii;
drh4f402f22013-06-11 18:59:38 +00005706 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
5707 if( pWInfo->bOBSat ){
5708 sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00005709 }
drh4f402f22013-06-11 18:59:38 +00005710 switch( pWInfo->eDistinct ){
5711 case WHERE_DISTINCT_UNIQUE: {
5712 sqlite3DebugPrintf(" DISTINCT=unique");
5713 break;
5714 }
5715 case WHERE_DISTINCT_ORDERED: {
5716 sqlite3DebugPrintf(" DISTINCT=ordered");
5717 break;
5718 }
5719 case WHERE_DISTINCT_UNORDERED: {
5720 sqlite3DebugPrintf(" DISTINCT=unordered");
5721 break;
5722 }
5723 }
5724 sqlite3DebugPrintf("\n");
drha18f3d22013-05-08 03:05:41 +00005725 for(ii=0; ii<nTabList; ii++){
5726 whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
drhf1b5f5b2013-05-02 00:15:01 +00005727 }
5728 }
5729#endif
drh3b48e8c2013-06-12 20:18:16 +00005730 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
drh8e23daf2013-06-11 13:30:04 +00005731 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
drhf1b5f5b2013-05-02 00:15:01 +00005732
drh08c88eb2008-04-10 13:33:18 +00005733 /* If the caller is an UPDATE or DELETE statement that is requesting
5734 ** to use a one-pass algorithm, determine if this is appropriate.
5735 ** The one-pass algorithm only works if the WHERE clause constraints
5736 ** the statement to update a single row.
5737 */
drh165be382008-12-05 02:36:33 +00005738 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh3b48e8c2013-06-12 20:18:16 +00005739 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
5740 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00005741 pWInfo->okOnePass = 1;
drh3b48e8c2013-06-12 20:18:16 +00005742 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
drh08c88eb2008-04-10 13:33:18 +00005743 }
drheb04de32013-05-10 15:16:30 +00005744
drh9012bcb2004-12-19 00:11:35 +00005745 /* Open all tables in the pTabList and any indices selected for
5746 ** searching those tables.
5747 */
5748 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
drh8b307fb2010-04-06 15:57:05 +00005749 notReady = ~(Bitmask)0;
drh4efc9292013-06-06 23:02:03 +00005750 pWInfo->nRowOut = (WhereCost)1;
drh9cd1c992012-09-25 20:43:35 +00005751 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00005752 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00005753 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00005754 struct SrcList_item *pTabItem;
drh7ba39a92013-05-30 17:43:19 +00005755 WhereLoop *pLoop;
drh9012bcb2004-12-19 00:11:35 +00005756
drh29dda4a2005-07-21 18:23:20 +00005757 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005758 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00005759 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00005760 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00005761 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00005762 /* Do nothing */
5763 }else
drh9eff6162006-06-12 21:59:13 +00005764#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00005765 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00005766 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00005767 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00005768 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00005769 }else if( IsVirtual(pTab) ){
5770 /* noop */
drh9eff6162006-06-12 21:59:13 +00005771 }else
5772#endif
drh7ba39a92013-05-30 17:43:19 +00005773 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00005774 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drh08c88eb2008-04-10 13:33:18 +00005775 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
5776 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drh67ae0cb2010-04-08 14:38:51 +00005777 testcase( pTab->nCol==BMS-1 );
5778 testcase( pTab->nCol==BMS );
danielk197723432972008-11-17 16:42:00 +00005779 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
danielk19779792eef2006-01-13 15:58:43 +00005780 Bitmask b = pTabItem->colUsed;
5781 int n = 0;
drh74161702006-02-24 02:53:49 +00005782 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00005783 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
5784 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00005785 assert( n<=pTab->nCol );
5786 }
danielk1977c00da102006-01-07 13:21:04 +00005787 }else{
5788 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00005789 }
drhc6339082010-04-07 16:54:58 +00005790#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh7ba39a92013-05-30 17:43:19 +00005791 if( (pLoop->wsFlags & WHERE_TEMP_INDEX)!=0 ){
drh70d18342013-06-06 19:16:33 +00005792 constructAutomaticIndex(pParse, &pWInfo->sWC, pTabItem, notReady, pLevel);
drhc6339082010-04-07 16:54:58 +00005793 }else
5794#endif
drh7e47cb82013-05-31 17:55:27 +00005795 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00005796 Index *pIx = pLoop->u.btree.pIndex;
danielk1977b3bf5562006-01-10 17:58:23 +00005797 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
drhae70cf12013-05-31 15:18:46 +00005798 /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
5799 int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
danielk1977da184232006-01-05 11:34:32 +00005800 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00005801 assert( iIndexCur>=0 );
5802 sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00005803 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00005804 VdbeComment((v, "%s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00005805 }
danielk1977da184232006-01-05 11:34:32 +00005806 sqlite3CodeVerifySchema(pParse, iDb);
drh70d18342013-06-06 19:16:33 +00005807 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00005808 }
5809 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00005810 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00005811
drh29dda4a2005-07-21 18:23:20 +00005812 /* Generate the code to do the search. Each iteration of the for
5813 ** loop below generates code for a single nested loop of the VM
5814 ** program.
drh75897232000-05-29 14:26:00 +00005815 */
drhfe05af82005-07-21 03:14:59 +00005816 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00005817 for(ii=0; ii<nTabList; ii++){
5818 pLevel = &pWInfo->a[ii];
5819 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
drh70d18342013-06-06 19:16:33 +00005820 notReady = codeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00005821 pWInfo->iContinue = pLevel->addrCont;
drh75897232000-05-29 14:26:00 +00005822 }
drh7ec764a2005-07-21 03:48:20 +00005823
drh6fa978d2013-05-30 19:29:19 +00005824 /* Done. */
drh75897232000-05-29 14:26:00 +00005825 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00005826
5827 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00005828whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00005829 if( pWInfo ){
5830 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5831 whereInfoFree(db, pWInfo);
5832 }
drhe23399f2005-07-22 00:31:39 +00005833 return 0;
drh75897232000-05-29 14:26:00 +00005834}
5835
5836/*
drhc27a1ce2002-06-14 20:58:45 +00005837** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00005838** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00005839*/
danielk19774adee202004-05-08 08:23:19 +00005840void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00005841 Parse *pParse = pWInfo->pParse;
5842 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00005843 int i;
drh6b563442001-11-07 16:48:26 +00005844 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00005845 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00005846 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00005847 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00005848
drh9012bcb2004-12-19 00:11:35 +00005849 /* Generate loop termination code.
5850 */
drhceea3322009-04-23 13:22:42 +00005851 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00005852 for(i=pWInfo->nLevel-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00005853 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00005854 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00005855 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00005856 if( pLevel->op!=OP_Noop ){
drh66a51672008-01-03 00:01:23 +00005857 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
drhd1d38482008-10-07 23:46:38 +00005858 sqlite3VdbeChangeP5(v, pLevel->p5);
drh19a775c2000-06-05 18:54:46 +00005859 }
drh7ba39a92013-05-30 17:43:19 +00005860 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00005861 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00005862 int j;
drhb3190c12008-12-08 21:37:14 +00005863 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00005864 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00005865 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00005866 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drhb3190c12008-12-08 21:37:14 +00005867 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00005868 }
drh111a6a72008-12-21 03:51:16 +00005869 sqlite3DbFree(db, pLevel->u.in.aInLoop);
drhd99f7062002-06-08 23:25:08 +00005870 }
drhb3190c12008-12-08 21:37:14 +00005871 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhad2d8302002-05-24 20:31:36 +00005872 if( pLevel->iLeftJoin ){
5873 int addr;
drh3c84ddf2008-01-09 02:15:38 +00005874 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
drh7ba39a92013-05-30 17:43:19 +00005875 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
5876 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
5877 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00005878 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
5879 }
drh76f4cfb2013-05-31 18:20:52 +00005880 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00005881 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00005882 }
drh336a5302009-04-24 15:46:21 +00005883 if( pLevel->op==OP_Return ){
5884 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
5885 }else{
5886 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
5887 }
drhd654be82005-09-20 17:42:23 +00005888 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00005889 }
drh19a775c2000-06-05 18:54:46 +00005890 }
drh9012bcb2004-12-19 00:11:35 +00005891
5892 /* The "break" point is here, just past the end of the outer loop.
5893 ** Set it.
5894 */
danielk19774adee202004-05-08 08:23:19 +00005895 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00005896
drh29dda4a2005-07-21 18:23:20 +00005897 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00005898 */
drhc01a3c12009-12-16 22:10:49 +00005899 assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
5900 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
danbfca6a42012-08-24 10:52:35 +00005901 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00005902 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005903 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00005904 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00005905 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00005906 if( (pTab->tabFlags & TF_Ephemeral)==0
5907 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00005908 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00005909 ){
drh7ba39a92013-05-30 17:43:19 +00005910 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00005911 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00005912 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
5913 }
drh7ba39a92013-05-30 17:43:19 +00005914 if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_TEMP_INDEX))==0 ){
drh6df2acd2008-12-28 16:55:25 +00005915 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
5916 }
drh9012bcb2004-12-19 00:11:35 +00005917 }
5918
danielk197721de2e72007-11-29 17:43:27 +00005919 /* If this scan uses an index, make code substitutions to read data
5920 ** from the index in preference to the table. Sometimes, this means
5921 ** the table need never be read from. This is a performance boost,
5922 ** as the vdbe level waits until the table is read before actually
5923 ** seeking the table cursor to the record corresponding to the current
5924 ** position in the index.
drh9012bcb2004-12-19 00:11:35 +00005925 **
5926 ** Calls to the code generator in between sqlite3WhereBegin and
5927 ** sqlite3WhereEnd will have created code that references the table
5928 ** directly. This loop scans all that code looking for opcodes
5929 ** that reference the table and converts them into opcodes that
5930 ** reference the index.
5931 */
drh7ba39a92013-05-30 17:43:19 +00005932 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
5933 pIdx = pLoop->u.btree.pIndex;
5934 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00005935 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00005936 }
drh7ba39a92013-05-30 17:43:19 +00005937 if( pIdx && !db->mallocFailed ){
danielk1977f0113002006-01-24 12:09:17 +00005938 int k, j, last;
drh9012bcb2004-12-19 00:11:35 +00005939 VdbeOp *pOp;
drh9012bcb2004-12-19 00:11:35 +00005940
drh9012bcb2004-12-19 00:11:35 +00005941 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
5942 last = sqlite3VdbeCurrentAddr(v);
danielk1977f0113002006-01-24 12:09:17 +00005943 for(k=pWInfo->iTop; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00005944 if( pOp->p1!=pLevel->iTabCur ) continue;
5945 if( pOp->opcode==OP_Column ){
drh9012bcb2004-12-19 00:11:35 +00005946 for(j=0; j<pIdx->nColumn; j++){
5947 if( pOp->p2==pIdx->aiColumn[j] ){
5948 pOp->p2 = j;
danielk197721de2e72007-11-29 17:43:27 +00005949 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00005950 break;
5951 }
5952 }
drh7ba39a92013-05-30 17:43:19 +00005953 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
drhf0863fe2005-06-12 21:35:51 +00005954 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00005955 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00005956 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00005957 }
5958 }
drh6b563442001-11-07 16:48:26 +00005959 }
drh19a775c2000-06-05 18:54:46 +00005960 }
drh9012bcb2004-12-19 00:11:35 +00005961
5962 /* Final cleanup
5963 */
drhf12cde52010-04-08 17:28:00 +00005964 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5965 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00005966 return;
5967}