blob: 9f65d551a345096ca3b495caa300f8ccb9af8286 [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;
drhaa32e3c2013-07-16 21:31:23 +000048typedef struct WhereOrCost WhereOrCost;
49typedef struct WhereOrSet WhereOrSet;
drhc63367e2013-06-10 20:46:50 +000050
51/*
52** Cost X is tracked as 10*log2(X) stored in a 16-bit integer. The
drh3b48e8c2013-06-12 20:18:16 +000053** maximum cost for ordinary tables is 64*(2**63) which becomes 6900.
54** (Virtual tables can return a larger cost, but let's assume they do not.)
55** So all costs can be stored in a 16-bit unsigned integer without risk
56** of overflow.
57**
58** Costs are estimates, so don't go to the computational trouble to compute
59** 10*log2(X) exactly. Instead, a close estimate is used. Any value of
60** X<=1 is stored as 0. X=2 is 10. X=3 is 16. X=1000 is 99. etc.
61**
drhe1e2e9a2013-06-13 15:16:53 +000062** The tool/wherecosttest.c source file implements a command-line program
63** that will convert between WhereCost to integers and do addition and
64** multiplication on WhereCost values. That command-line program is a
65** useful utility to have around when working with this module.
drhc63367e2013-06-10 20:46:50 +000066*/
67typedef unsigned short int WhereCost;
drhf1b5f5b2013-05-02 00:15:01 +000068
69/*
drhf0030762013-06-14 13:27:01 +000070** This object contains information needed to implement a single nested
drh3b48e8c2013-06-12 20:18:16 +000071** loop in WHERE clause.
drh6f328482013-06-05 23:39:34 +000072**
drh3b48e8c2013-06-12 20:18:16 +000073** Contrast this object with WhereLoop. This object describes the
74** implementation of the loop. WhereLoop describes the algorithm.
75** This object contains a pointer to the WhereLoop algorithm as one of
76** its elements.
77**
78** The WhereInfo object contains a single instance of this object for
79** each term in the FROM clause (which is to say, for each of the
80** nested loops as implemented). The order of WhereLevel objects determines
81** the loop nested order, with WhereInfo.a[0] being the outer loop and
82** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
drh6f328482013-06-05 23:39:34 +000083*/
84struct WhereLevel {
85 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
86 int iTabCur; /* The VDBE cursor used to access the table */
87 int iIdxCur; /* The VDBE cursor used to access pIdx */
88 int addrBrk; /* Jump here to break out of the loop */
89 int addrNxt; /* Jump here to start the next IN combination */
90 int addrCont; /* Jump here to continue with the next loop cycle */
91 int addrFirst; /* First instruction of interior of the loop */
drhe217efc2013-06-12 03:48:41 +000092 u8 iFrom; /* Which entry in the FROM clause */
drh6f328482013-06-05 23:39:34 +000093 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
94 int p1, p2; /* Operands of the opcode used to ends the loop */
drh37ca0482013-06-12 17:17:45 +000095 union { /* Information that depends on pWLoop->wsFlags */
drh6f328482013-06-05 23:39:34 +000096 struct {
97 int nIn; /* Number of entries in aInLoop[] */
98 struct InLoop {
99 int iCur; /* The VDBE cursor used by this IN operator */
100 int addrInTop; /* Top of the IN loop */
101 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
102 } *aInLoop; /* Information about each nested IN operator */
drh37ca0482013-06-12 17:17:45 +0000103 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
drh6f328482013-06-05 23:39:34 +0000104 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
105 } u;
106 struct WhereLoop *pWLoop; /* The selected WhereLoop object */
107};
108
109/*
drh3b48e8c2013-06-12 20:18:16 +0000110** Each instance of this object represents an algorithm for evaluating one
111** term of a join. Every term of the FROM clause will have at least
112** one corresponding WhereLoop object (unless INDEXED BY constraints
113** prevent a query solution - which is an error) and many terms of the
114** FROM clause will have multiple WhereLoop objects, each describing a
115** potential way of implementing that FROM-clause term, together with
116** dependencies and cost estimates for using the chosen algorithm.
117**
118** Query planning consists of building up a collection of these WhereLoop
119** objects, then computing a particular sequence of WhereLoop objects, with
120** one WhereLoop object per FROM clause term, that satisfy all dependencies
121** and that minimize the overall cost.
drhf1b5f5b2013-05-02 00:15:01 +0000122*/
123struct WhereLoop {
124 Bitmask prereq; /* Bitmask of other loops that must run first */
drha18f3d22013-05-08 03:05:41 +0000125 Bitmask maskSelf; /* Bitmask identifying table iTab */
drhd15cb172013-05-21 19:23:10 +0000126#ifdef SQLITE_DEBUG
127 char cId; /* Symbolic ID of this loop for debugging use */
128#endif
drh7ba39a92013-05-30 17:43:19 +0000129 u8 iTab; /* Position in FROM clause of table for this loop */
drh23f98da2013-05-21 15:52:07 +0000130 u8 iSortIdx; /* Sorting index number. 0==None */
drh4efc9292013-06-06 23:02:03 +0000131 WhereCost rSetup; /* One-time setup cost (ex: create transient index) */
132 WhereCost rRun; /* Cost of running each loop */
133 WhereCost nOut; /* Estimated number of output rows */
drh5346e952013-05-08 14:14:26 +0000134 union {
135 struct { /* Information for internal btree tables */
136 int nEq; /* Number of equality constraints */
137 Index *pIndex; /* Index used, or NULL */
138 } btree;
drh6b7157b2013-05-10 02:00:35 +0000139 struct { /* Information for virtual tables */
drh5346e952013-05-08 14:14:26 +0000140 int idxNum; /* Index number */
drh6b7157b2013-05-10 02:00:35 +0000141 u8 needFree; /* True if sqlite3_free(idxStr) is needed */
142 u8 isOrdered; /* True if satisfies ORDER BY */
drh3bd26f02013-05-24 14:52:03 +0000143 u16 omitMask; /* Terms that may be omitted */
drh5346e952013-05-08 14:14:26 +0000144 char *idxStr; /* Index identifier string */
145 } vtab;
146 } u;
drha2014152013-06-07 00:29:23 +0000147 u32 wsFlags; /* WHERE_* flags describing the plan */
148 u16 nLTerm; /* Number of entries in aLTerm[] */
149 /**** whereLoopXfer() copies fields above ***********************/
150# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
151 u16 nLSlot; /* Number of slots allocated for aLTerm[] */
drh4efc9292013-06-06 23:02:03 +0000152 WhereTerm **aLTerm; /* WhereTerms used */
drhf1b5f5b2013-05-02 00:15:01 +0000153 WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
drh4efc9292013-06-06 23:02:03 +0000154 WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
drhf1b5f5b2013-05-02 00:15:01 +0000155};
156
drhaa32e3c2013-07-16 21:31:23 +0000157/* This object holds the prerequisites and the cost of running a
158** subquery on one operand of an OR operator in the WHERE clause.
159** See WhereOrSet for additional information
160*/
161struct WhereOrCost {
162 Bitmask prereq; /* Prerequisites */
163 WhereCost rRun; /* Cost of running this subquery */
164 WhereCost nOut; /* Number of outputs for this subquery */
165};
166
167/* The WhereOrSet object holds a set of possible WhereOrCosts that
168** correspond to the subquery(s) of OR-clause processing. At most
169** favorable N_OR_COST elements are retained.
170*/
171#define N_OR_COST 3
172struct WhereOrSet {
173 u16 n; /* Number of valid a[] entries */
174 WhereOrCost a[N_OR_COST]; /* Set of best costs */
175};
176
177
drh4efc9292013-06-06 23:02:03 +0000178/* Forward declaration of methods */
179static int whereLoopResize(sqlite3*, WhereLoop*, int);
180
drhf1b5f5b2013-05-02 00:15:01 +0000181/*
182** Each instance of this object holds a sequence of WhereLoop objects
drh3b48e8c2013-06-12 20:18:16 +0000183** that implement some or all of a query plan.
184**
dan51576f42013-07-02 10:06:15 +0000185** Think of each WhereLoop object as a node in a graph with arcs
drh3b48e8c2013-06-12 20:18:16 +0000186** showing dependences and costs for travelling between nodes. (That is
187** not a completely accurate description because WhereLoop costs are a
188** vector, not a scalar, and because dependences are many-to-one, not
189** one-to-one as are graph nodes. But it is a useful visualization aid.)
190** Then a WherePath object is a path through the graph that visits some
191** or all of the WhereLoop objects once.
192**
193** The "solver" works by creating the N best WherePath objects of length
194** 1. Then using those as a basis to compute the N best WherePath objects
195** of length 2. And so forth until the length of WherePaths equals the
196** number of nodes in the FROM clause. The best (lowest cost) WherePath
197** at the end is the choosen query plan.
drhf1b5f5b2013-05-02 00:15:01 +0000198*/
199struct WherePath {
200 Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
drh319f6772013-05-14 15:31:07 +0000201 Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
drh4efc9292013-06-06 23:02:03 +0000202 WhereCost nRow; /* Estimated number of rows generated by this path */
203 WhereCost rCost; /* Total cost of this path */
drh6b7157b2013-05-10 02:00:35 +0000204 u8 isOrdered; /* True if this path satisfies ORDER BY */
205 u8 isOrderedValid; /* True if the isOrdered field is valid */
drha18f3d22013-05-08 03:05:41 +0000206 WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
drhf1b5f5b2013-05-02 00:15:01 +0000207};
drh0aa74ed2005-07-16 13:33:20 +0000208
209/*
drh75897232000-05-29 14:26:00 +0000210** The query generator uses an array of instances of this structure to
211** help it analyze the subexpressions of the WHERE clause. Each WHERE
drh61495262009-04-22 15:32:59 +0000212** clause subexpression is separated from the others by AND operators,
213** usually, or sometimes subexpressions separated by OR.
drh51669862004-12-18 18:40:26 +0000214**
drh0fcef5e2005-07-19 17:38:22 +0000215** All WhereTerms are collected into a single WhereClause structure.
216** The following identity holds:
drh51669862004-12-18 18:40:26 +0000217**
drh0fcef5e2005-07-19 17:38:22 +0000218** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
drh51669862004-12-18 18:40:26 +0000219**
drh0fcef5e2005-07-19 17:38:22 +0000220** When a term is of the form:
221**
222** X <op> <expr>
223**
224** where X is a column name and <op> is one of certain operators,
drh700a2262008-12-17 19:22:15 +0000225** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
226** cursor number and column number for X. WhereTerm.eOperator records
drh51147ba2005-07-23 22:59:55 +0000227** the <op> using a bitmask encoding defined by WO_xxx below. The
228** use of a bitmask encoding for the operator allows us to search
229** quickly for terms that match any of several different operators.
drh0fcef5e2005-07-19 17:38:22 +0000230**
drh700a2262008-12-17 19:22:15 +0000231** A WhereTerm might also be two or more subterms connected by OR:
232**
233** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
234**
235** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
236** and the WhereTerm.u.pOrInfo field points to auxiliary information that
237** is collected about the
238**
239** If a term in the WHERE clause does not match either of the two previous
240** categories, then eOperator==0. The WhereTerm.pExpr field is still set
241** to the original subexpression content and wtFlags is set up appropriately
242** but no other fields in the WhereTerm object are meaningful.
243**
244** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
drh111a6a72008-12-21 03:51:16 +0000245** but they do so indirectly. A single WhereMaskSet structure translates
drh51669862004-12-18 18:40:26 +0000246** cursor number into bits and the translated bit is stored in the prereq
247** fields. The translation is used in order to maximize the number of
248** bits that will fit in a Bitmask. The VDBE cursor numbers might be
249** spread out over the non-negative integers. For example, the cursor
drh111a6a72008-12-21 03:51:16 +0000250** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
drh51669862004-12-18 18:40:26 +0000251** translates these sparse cursor numbers into consecutive integers
252** beginning with 0 in order to make the best possible use of the available
253** bits in the Bitmask. So, in the example above, the cursor numbers
254** would be mapped into integers 0 through 7.
drh6a1e0712008-12-05 15:24:15 +0000255**
256** The number of terms in a join is limited by the number of bits
257** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
258** is only able to process joins with 64 or fewer tables.
drh75897232000-05-29 14:26:00 +0000259*/
drh0aa74ed2005-07-16 13:33:20 +0000260struct WhereTerm {
drh165be382008-12-05 02:36:33 +0000261 Expr *pExpr; /* Pointer to the subexpression that is this term */
drhec1724e2008-12-09 01:32:03 +0000262 int iParent; /* Disable pWC->a[iParent] when this term disabled */
263 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
drh700a2262008-12-17 19:22:15 +0000264 union {
265 int leftColumn; /* Column number of X in "X <op> <expr>" */
drh7a5bcc02013-01-16 17:08:58 +0000266 WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
267 WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
drh700a2262008-12-17 19:22:15 +0000268 } u;
drhb52076c2006-01-23 13:22:09 +0000269 u16 eOperator; /* A WO_xx value describing <op> */
drh165be382008-12-05 02:36:33 +0000270 u8 wtFlags; /* TERM_xxx bit flags. See below */
drh45b1ee42005-08-02 17:48:22 +0000271 u8 nChild; /* Number of children that must disable us */
drh0fcef5e2005-07-19 17:38:22 +0000272 WhereClause *pWC; /* The clause this term is part of */
drh165be382008-12-05 02:36:33 +0000273 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
274 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
drh75897232000-05-29 14:26:00 +0000275};
276
277/*
drh165be382008-12-05 02:36:33 +0000278** Allowed values of WhereTerm.wtFlags
drh0aa74ed2005-07-16 13:33:20 +0000279*/
drh633e6d52008-07-28 19:34:53 +0000280#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
drh6c30be82005-07-29 15:10:17 +0000281#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
282#define TERM_CODED 0x04 /* This term is already coded */
drh45b1ee42005-08-02 17:48:22 +0000283#define TERM_COPIED 0x08 /* Has a child */
drh700a2262008-12-17 19:22:15 +0000284#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
285#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
286#define TERM_OR_OK 0x40 /* Used during OR-clause processing */
drhfaacf172011-08-12 01:51:45 +0000287#ifdef SQLITE_ENABLE_STAT3
drh59b61882011-02-11 02:43:14 +0000288# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
289#else
drhd3ed7342011-09-21 00:09:41 +0000290# define TERM_VNULL 0x00 /* Disabled if not using stat3 */
drh59b61882011-02-11 02:43:14 +0000291#endif
drh0aa74ed2005-07-16 13:33:20 +0000292
293/*
drh1c8148f2013-05-04 20:25:23 +0000294** An instance of the WhereScan object is used as an iterator for locating
295** terms in the WHERE clause that are useful to the query planner.
296*/
297struct WhereScan {
drh1c8148f2013-05-04 20:25:23 +0000298 WhereClause *pOrigWC; /* Original, innermost WhereClause */
299 WhereClause *pWC; /* WhereClause currently being scanned */
drh7ba39a92013-05-30 17:43:19 +0000300 char *zCollName; /* Required collating sequence, if not NULL */
drh1c8148f2013-05-04 20:25:23 +0000301 char idxaff; /* Must match this affinity, if zCollName!=NULL */
302 unsigned char nEquiv; /* Number of entries in aEquiv[] */
303 unsigned char iEquiv; /* Next unused slot in aEquiv[] */
304 u32 opMask; /* Acceptable operators */
305 int k; /* Resume scanning at this->pWC->a[this->k] */
306 int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
307};
308
309/*
drh0aa74ed2005-07-16 13:33:20 +0000310** An instance of the following structure holds all information about a
311** WHERE clause. Mostly this is a container for one or more WhereTerms.
drh8871ef52011-10-07 13:33:10 +0000312**
313** Explanation of pOuter: For a WHERE clause of the form
314**
315** a AND ((b AND c) OR (d AND e)) AND f
316**
317** There are separate WhereClause objects for the whole clause and for
318** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
319** subclauses points to the WhereClause object for the whole clause.
drh0aa74ed2005-07-16 13:33:20 +0000320*/
drh0aa74ed2005-07-16 13:33:20 +0000321struct WhereClause {
drh70d18342013-06-06 19:16:33 +0000322 WhereInfo *pWInfo; /* WHERE clause processing context */
drh8871ef52011-10-07 13:33:10 +0000323 WhereClause *pOuter; /* Outer conjunction */
drh29435252008-12-28 18:35:08 +0000324 u8 op; /* Split operator. TK_AND or TK_OR */
drh0aa74ed2005-07-16 13:33:20 +0000325 int nTerm; /* Number of terms */
326 int nSlot; /* Number of entries in a[] */
drh51147ba2005-07-23 22:59:55 +0000327 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
drh50d654d2009-06-03 01:24:54 +0000328#if defined(SQLITE_SMALL_STACK)
329 WhereTerm aStatic[1]; /* Initial static space for a[] */
330#else
331 WhereTerm aStatic[8]; /* Initial static space for a[] */
332#endif
drhe23399f2005-07-22 00:31:39 +0000333};
334
335/*
drh700a2262008-12-17 19:22:15 +0000336** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
337** a dynamically allocated instance of the following structure.
338*/
339struct WhereOrInfo {
drh111a6a72008-12-21 03:51:16 +0000340 WhereClause wc; /* Decomposition into subterms */
drh1a58fe02008-12-20 02:06:13 +0000341 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
drh700a2262008-12-17 19:22:15 +0000342};
343
344/*
345** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
346** a dynamically allocated instance of the following structure.
347*/
348struct WhereAndInfo {
drh29435252008-12-28 18:35:08 +0000349 WhereClause wc; /* The subexpression broken out */
drh700a2262008-12-17 19:22:15 +0000350};
351
352/*
drh6a3ea0e2003-05-02 14:32:12 +0000353** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000354** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000355**
356** The VDBE cursor numbers are small integers contained in
357** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
358** clause, the cursor numbers might not begin with 0 and they might
359** contain gaps in the numbering sequence. But we want to make maximum
360** use of the bits in our bitmasks. This structure provides a mapping
361** from the sparse cursor numbers into consecutive integers beginning
362** with 0.
363**
drh111a6a72008-12-21 03:51:16 +0000364** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
drh51669862004-12-18 18:40:26 +0000365** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
366**
367** For example, if the WHERE clause expression used these VDBE
drh111a6a72008-12-21 03:51:16 +0000368** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
drh51669862004-12-18 18:40:26 +0000369** would map those cursor numbers into bits 0 through 5.
370**
371** Note that the mapping is not necessarily ordered. In the example
372** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
373** 57->5, 73->4. Or one of 719 other combinations might be used. It
374** does not really matter. What is important is that sparse cursor
375** numbers all get mapped into bit numbers that begin with 0 and contain
376** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000377*/
drh111a6a72008-12-21 03:51:16 +0000378struct WhereMaskSet {
drh1398ad32005-01-19 23:24:50 +0000379 int n; /* Number of assigned cursor values */
danielk197723432972008-11-17 16:42:00 +0000380 int ix[BMS]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000381};
382
drh111a6a72008-12-21 03:51:16 +0000383/*
drh3b48e8c2013-06-12 20:18:16 +0000384** This object is a convenience wrapper holding all information needed
385** to construct WhereLoop objects for a particular query.
drh1c8148f2013-05-04 20:25:23 +0000386*/
387struct WhereLoopBuilder {
388 WhereInfo *pWInfo; /* Information about this WHERE */
drh1c8148f2013-05-04 20:25:23 +0000389 WhereClause *pWC; /* WHERE clause terms */
drh1c8148f2013-05-04 20:25:23 +0000390 ExprList *pOrderBy; /* ORDER BY clause */
391 WhereLoop *pNew; /* Template WhereLoop */
drhaa32e3c2013-07-16 21:31:23 +0000392 WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
drh1c8148f2013-05-04 20:25:23 +0000393};
394
395/*
drh70d18342013-06-06 19:16:33 +0000396** The WHERE clause processing routine has two halves. The
397** first part does the start of the WHERE loop and the second
398** half does the tail of the WHERE loop. An instance of
399** this structure is returned by the first half and passed
400** into the second half to give some continuity.
drh3b48e8c2013-06-12 20:18:16 +0000401**
402** An instance of this object holds the complete state of the query
403** planner.
drh70d18342013-06-06 19:16:33 +0000404*/
405struct WhereInfo {
406 Parse *pParse; /* Parsing and code generating context */
407 SrcList *pTabList; /* List of tables in the join */
408 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
drh6457a352013-06-21 00:35:37 +0000409 ExprList *pResultSet; /* Result set. DISTINCT operates on these */
drh4f402f22013-06-11 18:59:38 +0000410 WhereLoop *pLoops; /* List of all WhereLoop objects */
drh70d18342013-06-06 19:16:33 +0000411 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
drh4f402f22013-06-11 18:59:38 +0000412 WhereCost nRowOut; /* Estimated number of output rows */
drh70d18342013-06-06 19:16:33 +0000413 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
drh4f402f22013-06-11 18:59:38 +0000414 u8 bOBSat; /* ORDER BY satisfied by indices */
drh70d18342013-06-06 19:16:33 +0000415 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
416 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
417 u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
drhfd636c72013-06-21 02:05:06 +0000418 u8 nLevel; /* Number of nested loop */
drh70d18342013-06-06 19:16:33 +0000419 int iTop; /* The very beginning of the WHERE loop */
420 int iContinue; /* Jump here to continue with next record */
421 int iBreak; /* Jump here to break out of the loop */
drh4f402f22013-06-11 18:59:38 +0000422 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
drh70d18342013-06-06 19:16:33 +0000423 WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
424 WhereClause sWC; /* Decomposition of the WHERE clause */
drh70d18342013-06-06 19:16:33 +0000425 WhereLevel a[1]; /* Information about each nest loop in WHERE */
426};
427
428/*
drh3b48e8c2013-06-12 20:18:16 +0000429** Bitmasks for the operators on WhereTerm objects. These are all
430** operators that are of interest to the query planner. An
drh51147ba2005-07-23 22:59:55 +0000431** OR-ed combination of these values can be used when searching for
drh3b48e8c2013-06-12 20:18:16 +0000432** particular WhereTerms within a WhereClause.
drh51147ba2005-07-23 22:59:55 +0000433*/
drh165be382008-12-05 02:36:33 +0000434#define WO_IN 0x001
435#define WO_EQ 0x002
drh51147ba2005-07-23 22:59:55 +0000436#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
437#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
438#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
439#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
drh165be382008-12-05 02:36:33 +0000440#define WO_MATCH 0x040
441#define WO_ISNULL 0x080
drh700a2262008-12-17 19:22:15 +0000442#define WO_OR 0x100 /* Two or more OR-connected terms */
443#define WO_AND 0x200 /* Two or more AND-connected terms */
drh7a5bcc02013-01-16 17:08:58 +0000444#define WO_EQUIV 0x400 /* Of the form A==B, both columns */
drh534230c2011-01-22 00:10:45 +0000445#define WO_NOOP 0x800 /* This term does not restrict search space */
drh51147ba2005-07-23 22:59:55 +0000446
drhec1724e2008-12-09 01:32:03 +0000447#define WO_ALL 0xfff /* Mask of all possible WO_* values */
drh1a58fe02008-12-20 02:06:13 +0000448#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
drhec1724e2008-12-09 01:32:03 +0000449
drh51147ba2005-07-23 22:59:55 +0000450/*
drh3b48e8c2013-06-12 20:18:16 +0000451** These are definitions of bits in the WhereLoop.wsFlags field.
452** The particular combination of bits in each WhereLoop help to
453** determine the algorithm that WhereLoop represents.
drh51147ba2005-07-23 22:59:55 +0000454*/
drhbe4fe3a2013-07-01 10:38:35 +0000455#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
drh6fa978d2013-05-30 19:29:19 +0000456#define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
457#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
458#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
drhef71c1f2013-06-04 12:58:02 +0000459#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
drh6fa978d2013-05-30 19:29:19 +0000460#define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
461#define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
462#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
463#define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
464#define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
465#define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
466#define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
467#define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
drh7699d1c2013-06-04 12:42:29 +0000468#define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
drh6fa978d2013-05-30 19:29:19 +0000469#define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
drh986b3872013-06-28 21:12:20 +0000470#define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
drh51147ba2005-07-23 22:59:55 +0000471
drhc63367e2013-06-10 20:46:50 +0000472
473/* Convert a WhereCost value (10 times log2(X)) into its integer value X.
drh3b48e8c2013-06-12 20:18:16 +0000474** A rough approximation is used. The value returned is not exact.
drhc63367e2013-06-10 20:46:50 +0000475*/
476static u64 whereCostToInt(WhereCost x){
477 u64 n;
drh12ffbc72013-06-13 14:51:53 +0000478 if( x<10 ) return 1;
drhc63367e2013-06-10 20:46:50 +0000479 n = x%10;
480 x /= 10;
481 if( n>=5 ) n -= 2;
482 else if( n>=1 ) n -= 1;
483 if( x>=3 ) return (n+8)<<(x-3);
484 return (n+8)>>(3-x);
485}
486
drh51147ba2005-07-23 22:59:55 +0000487/*
drh6f328482013-06-05 23:39:34 +0000488** Return the estimated number of output rows from a WHERE clause
489*/
drhc63367e2013-06-10 20:46:50 +0000490u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
491 return whereCostToInt(pWInfo->nRowOut);
drh6f328482013-06-05 23:39:34 +0000492}
493
494/*
495** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
496** WHERE clause returns outputs for DISTINCT processing.
497*/
498int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
499 return pWInfo->eDistinct;
500}
501
502/*
503** Return TRUE if the WHERE clause returns rows in ORDER BY order.
504** Return FALSE if the output needs to be sorted.
505*/
506int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
drh4f402f22013-06-11 18:59:38 +0000507 return pWInfo->bOBSat!=0;
drh6f328482013-06-05 23:39:34 +0000508}
509
510/*
511** Return the VDBE address or label to jump to in order to continue
512** immediately with the next row of a WHERE clause.
513*/
514int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
515 return pWInfo->iContinue;
516}
517
518/*
519** Return the VDBE address or label to jump to in order to break
520** out of a WHERE loop.
521*/
522int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
523 return pWInfo->iBreak;
524}
525
526/*
527** Return TRUE if an UPDATE or DELETE statement can operate directly on
528** the rowids returned by a WHERE clause. Return FALSE if doing an
529** UPDATE or DELETE might change subsequent WHERE clause results.
530*/
531int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
532 return pWInfo->okOnePass;
533}
534
535/*
drhaa32e3c2013-07-16 21:31:23 +0000536** Move the content of pSrc into pDest
537*/
538static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
539 pDest->n = pSrc->n;
540 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
541}
542
543/*
544** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
545**
546** The new entry might overwrite an existing entry, or it might be
547** appended, or it might be discarded. Do whatever is the right thing
548** so that pSet keeps the N_OR_COST best entries seen so far.
549*/
550static int whereOrInsert(
551 WhereOrSet *pSet, /* The WhereOrSet to be updated */
552 Bitmask prereq, /* Prerequisites of the new entry */
553 WhereCost rRun, /* Run-cost of the new entry */
554 WhereCost nOut /* Number of outputs for the new entry */
555){
556 u16 i;
557 WhereOrCost *p;
558 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
559 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
560 goto whereOrInsert_done;
561 }
562 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
563 return 0;
564 }
565 }
566 if( pSet->n<N_OR_COST ){
567 p = &pSet->a[pSet->n++];
568 p->nOut = nOut;
569 }else{
570 p = pSet->a;
571 for(i=1; i<pSet->n; i++){
572 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
573 }
574 if( p->rRun<=rRun ) return 0;
575 }
576whereOrInsert_done:
577 p->prereq = prereq;
578 p->rRun = rRun;
579 if( p->nOut>nOut ) p->nOut = nOut;
580 return 1;
581}
582
583/*
drh0aa74ed2005-07-16 13:33:20 +0000584** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000585*/
drh7b4fc6a2007-02-06 13:26:32 +0000586static void whereClauseInit(
587 WhereClause *pWC, /* The WhereClause to be initialized */
drh70d18342013-06-06 19:16:33 +0000588 WhereInfo *pWInfo /* The WHERE processing context */
drh7b4fc6a2007-02-06 13:26:32 +0000589){
drh70d18342013-06-06 19:16:33 +0000590 pWC->pWInfo = pWInfo;
drh8871ef52011-10-07 13:33:10 +0000591 pWC->pOuter = 0;
drh0aa74ed2005-07-16 13:33:20 +0000592 pWC->nTerm = 0;
drhcad651e2007-04-20 12:22:01 +0000593 pWC->nSlot = ArraySize(pWC->aStatic);
drh0aa74ed2005-07-16 13:33:20 +0000594 pWC->a = pWC->aStatic;
595}
596
drh700a2262008-12-17 19:22:15 +0000597/* Forward reference */
598static void whereClauseClear(WhereClause*);
599
600/*
601** Deallocate all memory associated with a WhereOrInfo object.
602*/
603static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000604 whereClauseClear(&p->wc);
605 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000606}
607
608/*
609** Deallocate all memory associated with a WhereAndInfo object.
610*/
611static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000612 whereClauseClear(&p->wc);
613 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000614}
615
drh0aa74ed2005-07-16 13:33:20 +0000616/*
617** Deallocate a WhereClause structure. The WhereClause structure
618** itself is not freed. This routine is the inverse of whereClauseInit().
619*/
620static void whereClauseClear(WhereClause *pWC){
621 int i;
622 WhereTerm *a;
drh70d18342013-06-06 19:16:33 +0000623 sqlite3 *db = pWC->pWInfo->pParse->db;
drh0aa74ed2005-07-16 13:33:20 +0000624 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
drh165be382008-12-05 02:36:33 +0000625 if( a->wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000626 sqlite3ExprDelete(db, a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000627 }
drh700a2262008-12-17 19:22:15 +0000628 if( a->wtFlags & TERM_ORINFO ){
629 whereOrInfoDelete(db, a->u.pOrInfo);
630 }else if( a->wtFlags & TERM_ANDINFO ){
631 whereAndInfoDelete(db, a->u.pAndInfo);
632 }
drh0aa74ed2005-07-16 13:33:20 +0000633 }
634 if( pWC->a!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000635 sqlite3DbFree(db, pWC->a);
drh0aa74ed2005-07-16 13:33:20 +0000636 }
637}
638
639/*
drh6a1e0712008-12-05 15:24:15 +0000640** Add a single new WhereTerm entry to the WhereClause object pWC.
641** The new WhereTerm object is constructed from Expr p and with wtFlags.
642** The index in pWC->a[] of the new WhereTerm is returned on success.
643** 0 is returned if the new WhereTerm could not be added due to a memory
644** allocation error. The memory allocation failure will be recorded in
645** the db->mallocFailed flag so that higher-level functions can detect it.
646**
647** This routine will increase the size of the pWC->a[] array as necessary.
drh9eb20282005-08-24 03:52:18 +0000648**
drh165be382008-12-05 02:36:33 +0000649** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
drh6a1e0712008-12-05 15:24:15 +0000650** for freeing the expression p is assumed by the WhereClause object pWC.
651** This is true even if this routine fails to allocate a new WhereTerm.
drhb63a53d2007-03-31 01:34:44 +0000652**
drh9eb20282005-08-24 03:52:18 +0000653** WARNING: This routine might reallocate the space used to store
drh909626d2008-05-30 14:58:37 +0000654** WhereTerms. All pointers to WhereTerms should be invalidated after
drh9eb20282005-08-24 03:52:18 +0000655** calling this routine. Such pointers may be reinitialized by referencing
656** the pWC->a[] array.
drh0aa74ed2005-07-16 13:33:20 +0000657*/
drhec1724e2008-12-09 01:32:03 +0000658static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
drh0aa74ed2005-07-16 13:33:20 +0000659 WhereTerm *pTerm;
drh9eb20282005-08-24 03:52:18 +0000660 int idx;
drhe9cdcea2010-07-22 22:40:03 +0000661 testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
drh0aa74ed2005-07-16 13:33:20 +0000662 if( pWC->nTerm>=pWC->nSlot ){
663 WhereTerm *pOld = pWC->a;
drh70d18342013-06-06 19:16:33 +0000664 sqlite3 *db = pWC->pWInfo->pParse->db;
drh633e6d52008-07-28 19:34:53 +0000665 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
drhb63a53d2007-03-31 01:34:44 +0000666 if( pWC->a==0 ){
drh165be382008-12-05 02:36:33 +0000667 if( wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000668 sqlite3ExprDelete(db, p);
drhb63a53d2007-03-31 01:34:44 +0000669 }
drhf998b732007-11-26 13:36:00 +0000670 pWC->a = pOld;
drhb63a53d2007-03-31 01:34:44 +0000671 return 0;
672 }
drh0aa74ed2005-07-16 13:33:20 +0000673 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
674 if( pOld!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000675 sqlite3DbFree(db, pOld);
drh0aa74ed2005-07-16 13:33:20 +0000676 }
drh6a1e0712008-12-05 15:24:15 +0000677 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
drh0aa74ed2005-07-16 13:33:20 +0000678 }
drh6a1e0712008-12-05 15:24:15 +0000679 pTerm = &pWC->a[idx = pWC->nTerm++];
drh7ee751d2012-12-19 15:53:51 +0000680 pTerm->pExpr = sqlite3ExprSkipCollate(p);
drh165be382008-12-05 02:36:33 +0000681 pTerm->wtFlags = wtFlags;
drh0fcef5e2005-07-19 17:38:22 +0000682 pTerm->pWC = pWC;
drh45b1ee42005-08-02 17:48:22 +0000683 pTerm->iParent = -1;
drh9eb20282005-08-24 03:52:18 +0000684 return idx;
drh0aa74ed2005-07-16 13:33:20 +0000685}
drh75897232000-05-29 14:26:00 +0000686
687/*
drh51669862004-12-18 18:40:26 +0000688** This routine identifies subexpressions in the WHERE clause where
drhb6fb62d2005-09-20 08:47:20 +0000689** each subexpression is separated by the AND operator or some other
drh6c30be82005-07-29 15:10:17 +0000690** operator specified in the op parameter. The WhereClause structure
691** is filled with pointers to subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000692**
drh51669862004-12-18 18:40:26 +0000693** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
694** \________/ \_______________/ \________________/
695** slot[0] slot[1] slot[2]
696**
697** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000698** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000699**
drh51147ba2005-07-23 22:59:55 +0000700** In the previous sentence and in the diagram, "slot[]" refers to
drh902b9ee2008-12-05 17:17:07 +0000701** the WhereClause.a[] array. The slot[] array grows as needed to contain
drh51147ba2005-07-23 22:59:55 +0000702** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000703*/
drh74f91d42013-06-19 18:01:44 +0000704static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
705 pWC->op = op;
drh0aa74ed2005-07-16 13:33:20 +0000706 if( pExpr==0 ) return;
drh6c30be82005-07-29 15:10:17 +0000707 if( pExpr->op!=op ){
drh0aa74ed2005-07-16 13:33:20 +0000708 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000709 }else{
drh6c30be82005-07-29 15:10:17 +0000710 whereSplit(pWC, pExpr->pLeft, op);
711 whereSplit(pWC, pExpr->pRight, op);
drh75897232000-05-29 14:26:00 +0000712 }
drh75897232000-05-29 14:26:00 +0000713}
714
715/*
drh3b48e8c2013-06-12 20:18:16 +0000716** Initialize a WhereMaskSet object
drh6a3ea0e2003-05-02 14:32:12 +0000717*/
drhfd5874d2013-06-12 14:52:39 +0000718#define initMaskSet(P) (P)->n=0
drh6a3ea0e2003-05-02 14:32:12 +0000719
720/*
drh1398ad32005-01-19 23:24:50 +0000721** Return the bitmask for the given cursor number. Return 0 if
722** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000723*/
drh111a6a72008-12-21 03:51:16 +0000724static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000725 int i;
drhfcd71b62011-04-05 22:08:24 +0000726 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
drh6a3ea0e2003-05-02 14:32:12 +0000727 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000728 if( pMaskSet->ix[i]==iCursor ){
drh7699d1c2013-06-04 12:42:29 +0000729 return MASKBIT(i);
drh51669862004-12-18 18:40:26 +0000730 }
drh6a3ea0e2003-05-02 14:32:12 +0000731 }
drh6a3ea0e2003-05-02 14:32:12 +0000732 return 0;
733}
734
735/*
drh1398ad32005-01-19 23:24:50 +0000736** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000737**
738** There is one cursor per table in the FROM clause. The number of
739** tables in the FROM clause is limited by a test early in the
drhb6fb62d2005-09-20 08:47:20 +0000740** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
drh0fcef5e2005-07-19 17:38:22 +0000741** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000742*/
drh111a6a72008-12-21 03:51:16 +0000743static void createMask(WhereMaskSet *pMaskSet, int iCursor){
drhcad651e2007-04-20 12:22:01 +0000744 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
drh0fcef5e2005-07-19 17:38:22 +0000745 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000746}
747
748/*
drh3b48e8c2013-06-12 20:18:16 +0000749** These routine walk (recursively) an expression tree and generates
drh75897232000-05-29 14:26:00 +0000750** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000751** tree.
drh75897232000-05-29 14:26:00 +0000752*/
drh111a6a72008-12-21 03:51:16 +0000753static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
754static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
755static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
drh51669862004-12-18 18:40:26 +0000756 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000757 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000758 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000759 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000760 return mask;
drh75897232000-05-29 14:26:00 +0000761 }
danielk1977b3bce662005-01-29 08:32:43 +0000762 mask = exprTableUsage(pMaskSet, p->pRight);
763 mask |= exprTableUsage(pMaskSet, p->pLeft);
danielk19776ab3a2e2009-02-19 14:39:25 +0000764 if( ExprHasProperty(p, EP_xIsSelect) ){
765 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
766 }else{
767 mask |= exprListTableUsage(pMaskSet, p->x.pList);
768 }
danielk1977b3bce662005-01-29 08:32:43 +0000769 return mask;
770}
drh111a6a72008-12-21 03:51:16 +0000771static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
danielk1977b3bce662005-01-29 08:32:43 +0000772 int i;
773 Bitmask mask = 0;
774 if( pList ){
775 for(i=0; i<pList->nExpr; i++){
776 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000777 }
778 }
drh75897232000-05-29 14:26:00 +0000779 return mask;
780}
drh111a6a72008-12-21 03:51:16 +0000781static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
drha430ae82007-09-12 15:41:01 +0000782 Bitmask mask = 0;
783 while( pS ){
drha464c232011-09-16 19:04:03 +0000784 SrcList *pSrc = pS->pSrc;
drha430ae82007-09-12 15:41:01 +0000785 mask |= exprListTableUsage(pMaskSet, pS->pEList);
drhf5b11382005-09-17 13:07:13 +0000786 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
787 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
788 mask |= exprTableUsage(pMaskSet, pS->pWhere);
789 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drha464c232011-09-16 19:04:03 +0000790 if( ALWAYS(pSrc!=0) ){
drh88501772011-09-16 17:43:06 +0000791 int i;
792 for(i=0; i<pSrc->nSrc; i++){
793 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
794 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
795 }
796 }
drha430ae82007-09-12 15:41:01 +0000797 pS = pS->pPrior;
drhf5b11382005-09-17 13:07:13 +0000798 }
799 return mask;
800}
drh75897232000-05-29 14:26:00 +0000801
802/*
drh487ab3c2001-11-08 00:45:21 +0000803** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000804** allowed for an indexable WHERE clause term. The allowed operators are
drh3b48e8c2013-06-12 20:18:16 +0000805** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
drhe9cdcea2010-07-22 22:40:03 +0000806**
807** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
808** of one of the following forms: column = expression column > expression
809** column >= expression column < expression column <= expression
810** expression = column expression > column expression >= column
811** expression < column expression <= column column IN
812** (expression-list) column IN (subquery) column IS NULL
drh487ab3c2001-11-08 00:45:21 +0000813*/
814static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000815 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
816 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
817 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
818 assert( TK_GE==TK_EQ+4 );
drh50b39962006-10-28 00:28:09 +0000819 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
drh487ab3c2001-11-08 00:45:21 +0000820}
821
822/*
drh902b9ee2008-12-05 17:17:07 +0000823** Swap two objects of type TYPE.
drh193bd772004-07-20 18:23:14 +0000824*/
825#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
826
827/*
drh909626d2008-05-30 14:58:37 +0000828** Commute a comparison operator. Expressions of the form "X op Y"
drh0fcef5e2005-07-19 17:38:22 +0000829** are converted into "Y op X".
danielk1977eb5453d2007-07-30 14:40:48 +0000830**
mistachkin48864df2013-03-21 21:20:32 +0000831** If left/right precedence rules come into play when determining the
drh3b48e8c2013-06-12 20:18:16 +0000832** collating sequence, then COLLATE operators are adjusted to ensure
833** that the collating sequence does not change. For example:
834** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
danielk1977eb5453d2007-07-30 14:40:48 +0000835** the left hand side of a comparison overrides any collation sequence
drhae80dde2012-12-06 21:16:43 +0000836** attached to the right. For the same reason the EP_Collate flag
danielk1977eb5453d2007-07-30 14:40:48 +0000837** is not commuted.
drh193bd772004-07-20 18:23:14 +0000838*/
drh7d10d5a2008-08-20 16:35:10 +0000839static void exprCommute(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000840 u16 expRight = (pExpr->pRight->flags & EP_Collate);
841 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
drhfe05af82005-07-21 03:14:59 +0000842 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drhae80dde2012-12-06 21:16:43 +0000843 if( expRight==expLeft ){
844 /* Either X and Y both have COLLATE operator or neither do */
845 if( expRight ){
846 /* Both X and Y have COLLATE operators. Make sure X is always
847 ** used by clearing the EP_Collate flag from Y. */
848 pExpr->pRight->flags &= ~EP_Collate;
849 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
850 /* Neither X nor Y have COLLATE operators, but X has a non-default
851 ** collating sequence. So add the EP_Collate marker on X to cause
852 ** it to be searched first. */
853 pExpr->pLeft->flags |= EP_Collate;
854 }
855 }
drh0fcef5e2005-07-19 17:38:22 +0000856 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
857 if( pExpr->op>=TK_GT ){
858 assert( TK_LT==TK_GT+2 );
859 assert( TK_GE==TK_LE+2 );
860 assert( TK_GT>TK_EQ );
861 assert( TK_GT<TK_LE );
862 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
863 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000864 }
drh193bd772004-07-20 18:23:14 +0000865}
866
867/*
drhfe05af82005-07-21 03:14:59 +0000868** Translate from TK_xx operator to WO_xx bitmask.
869*/
drhec1724e2008-12-09 01:32:03 +0000870static u16 operatorMask(int op){
871 u16 c;
drhfe05af82005-07-21 03:14:59 +0000872 assert( allowedOp(op) );
873 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000874 c = WO_IN;
drh50b39962006-10-28 00:28:09 +0000875 }else if( op==TK_ISNULL ){
876 c = WO_ISNULL;
drhfe05af82005-07-21 03:14:59 +0000877 }else{
drhec1724e2008-12-09 01:32:03 +0000878 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
879 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000880 }
drh50b39962006-10-28 00:28:09 +0000881 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000882 assert( op!=TK_IN || c==WO_IN );
883 assert( op!=TK_EQ || c==WO_EQ );
884 assert( op!=TK_LT || c==WO_LT );
885 assert( op!=TK_LE || c==WO_LE );
886 assert( op!=TK_GT || c==WO_GT );
887 assert( op!=TK_GE || c==WO_GE );
888 return c;
drhfe05af82005-07-21 03:14:59 +0000889}
890
891/*
drh1c8148f2013-05-04 20:25:23 +0000892** Advance to the next WhereTerm that matches according to the criteria
893** established when the pScan object was initialized by whereScanInit().
894** Return NULL if there are no more matching WhereTerms.
895*/
danb2cfc142013-07-05 11:10:54 +0000896static WhereTerm *whereScanNext(WhereScan *pScan){
drh1c8148f2013-05-04 20:25:23 +0000897 int iCur; /* The cursor on the LHS of the term */
898 int iColumn; /* The column on the LHS of the term. -1 for IPK */
899 Expr *pX; /* An expression being tested */
900 WhereClause *pWC; /* Shorthand for pScan->pWC */
901 WhereTerm *pTerm; /* The term being tested */
drh43b85ef2013-06-10 12:34:45 +0000902 int k = pScan->k; /* Where to start scanning */
drh1c8148f2013-05-04 20:25:23 +0000903
904 while( pScan->iEquiv<=pScan->nEquiv ){
905 iCur = pScan->aEquiv[pScan->iEquiv-2];
906 iColumn = pScan->aEquiv[pScan->iEquiv-1];
907 while( (pWC = pScan->pWC)!=0 ){
drh43b85ef2013-06-10 12:34:45 +0000908 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
drh1c8148f2013-05-04 20:25:23 +0000909 if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
910 if( (pTerm->eOperator & WO_EQUIV)!=0
911 && pScan->nEquiv<ArraySize(pScan->aEquiv)
912 ){
913 int j;
914 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
915 assert( pX->op==TK_COLUMN );
916 for(j=0; j<pScan->nEquiv; j+=2){
917 if( pScan->aEquiv[j]==pX->iTable
918 && pScan->aEquiv[j+1]==pX->iColumn ){
919 break;
920 }
921 }
922 if( j==pScan->nEquiv ){
923 pScan->aEquiv[j] = pX->iTable;
924 pScan->aEquiv[j+1] = pX->iColumn;
925 pScan->nEquiv += 2;
926 }
927 }
928 if( (pTerm->eOperator & pScan->opMask)!=0 ){
929 /* Verify the affinity and collating sequence match */
930 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
931 CollSeq *pColl;
drh70d18342013-06-06 19:16:33 +0000932 Parse *pParse = pWC->pWInfo->pParse;
drh1c8148f2013-05-04 20:25:23 +0000933 pX = pTerm->pExpr;
934 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
935 continue;
936 }
937 assert(pX->pLeft);
drh70d18342013-06-06 19:16:33 +0000938 pColl = sqlite3BinaryCompareCollSeq(pParse,
drh1c8148f2013-05-04 20:25:23 +0000939 pX->pLeft, pX->pRight);
drh70d18342013-06-06 19:16:33 +0000940 if( pColl==0 ) pColl = pParse->db->pDfltColl;
drh1c8148f2013-05-04 20:25:23 +0000941 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
942 continue;
943 }
944 }
drha184fb82013-05-08 04:22:59 +0000945 if( (pTerm->eOperator & WO_EQ)!=0
946 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
947 && pX->iTable==pScan->aEquiv[0]
948 && pX->iColumn==pScan->aEquiv[1]
949 ){
950 continue;
951 }
drh43b85ef2013-06-10 12:34:45 +0000952 pScan->k = k+1;
drh1c8148f2013-05-04 20:25:23 +0000953 return pTerm;
954 }
955 }
956 }
drhad01d892013-06-19 13:59:49 +0000957 pScan->pWC = pScan->pWC->pOuter;
drh43b85ef2013-06-10 12:34:45 +0000958 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000959 }
960 pScan->pWC = pScan->pOrigWC;
drh43b85ef2013-06-10 12:34:45 +0000961 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000962 pScan->iEquiv += 2;
963 }
drh1c8148f2013-05-04 20:25:23 +0000964 return 0;
965}
966
967/*
968** Initialize a WHERE clause scanner object. Return a pointer to the
969** first match. Return NULL if there are no matches.
970**
971** The scanner will be searching the WHERE clause pWC. It will look
972** for terms of the form "X <op> <expr>" where X is column iColumn of table
973** iCur. The <op> must be one of the operators described by opMask.
974**
drh3b48e8c2013-06-12 20:18:16 +0000975** If the search is for X and the WHERE clause contains terms of the
976** form X=Y then this routine might also return terms of the form
977** "Y <op> <expr>". The number of levels of transitivity is limited,
978** but is enough to handle most commonly occurring SQL statements.
979**
drh1c8148f2013-05-04 20:25:23 +0000980** If X is not the INTEGER PRIMARY KEY then X must be compatible with
981** index pIdx.
982*/
danb2cfc142013-07-05 11:10:54 +0000983static WhereTerm *whereScanInit(
drh1c8148f2013-05-04 20:25:23 +0000984 WhereScan *pScan, /* The WhereScan object being initialized */
985 WhereClause *pWC, /* The WHERE clause to be scanned */
986 int iCur, /* Cursor to scan for */
987 int iColumn, /* Column to scan for */
988 u32 opMask, /* Operator(s) to scan for */
989 Index *pIdx /* Must be compatible with this index */
990){
991 int j;
992
drhe9d935a2013-06-05 16:19:59 +0000993 /* memset(pScan, 0, sizeof(*pScan)); */
drh1c8148f2013-05-04 20:25:23 +0000994 pScan->pOrigWC = pWC;
995 pScan->pWC = pWC;
996 if( pIdx && iColumn>=0 ){
997 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
998 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
999 if( NEVER(j>=pIdx->nColumn) ) return 0;
1000 }
1001 pScan->zCollName = pIdx->azColl[j];
drhe9d935a2013-06-05 16:19:59 +00001002 }else{
1003 pScan->idxaff = 0;
1004 pScan->zCollName = 0;
drh1c8148f2013-05-04 20:25:23 +00001005 }
1006 pScan->opMask = opMask;
drhe9d935a2013-06-05 16:19:59 +00001007 pScan->k = 0;
drh1c8148f2013-05-04 20:25:23 +00001008 pScan->aEquiv[0] = iCur;
1009 pScan->aEquiv[1] = iColumn;
1010 pScan->nEquiv = 2;
1011 pScan->iEquiv = 2;
1012 return whereScanNext(pScan);
1013}
1014
1015/*
drhfe05af82005-07-21 03:14:59 +00001016** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
1017** where X is a reference to the iColumn of table iCur and <op> is one of
1018** the WO_xx operator codes specified by the op parameter.
1019** Return a pointer to the term. Return 0 if not found.
drh58eb1c02013-01-17 00:08:42 +00001020**
1021** The term returned might by Y=<expr> if there is another constraint in
1022** the WHERE clause that specifies that X=Y. Any such constraints will be
1023** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
1024** aEquiv[] array holds X and all its equivalents, with each SQL variable
1025** taking up two slots in aEquiv[]. The first slot is for the cursor number
1026** and the second is for the column number. There are 22 slots in aEquiv[]
1027** so that means we can look for X plus up to 10 other equivalent values.
1028** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
1029** and ... and A9=A10 and A10=<expr>.
1030**
1031** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
1032** then try for the one with no dependencies on <expr> - in other words where
1033** <expr> is a constant expression of some kind. Only return entries of
1034** the form "X <op> Y" where Y is a column in another table if no terms of
drh459f63e2013-03-06 01:55:27 +00001035** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
1036** exist, try to return a term that does not use WO_EQUIV.
drhfe05af82005-07-21 03:14:59 +00001037*/
1038static WhereTerm *findTerm(
1039 WhereClause *pWC, /* The WHERE clause to be searched */
1040 int iCur, /* Cursor number of LHS */
1041 int iColumn, /* Column number of LHS */
1042 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +00001043 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +00001044 Index *pIdx /* Must be compatible with this index, if not NULL */
1045){
drh1c8148f2013-05-04 20:25:23 +00001046 WhereTerm *pResult = 0;
1047 WhereTerm *p;
1048 WhereScan scan;
drh7a5bcc02013-01-16 17:08:58 +00001049
drh1c8148f2013-05-04 20:25:23 +00001050 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
1051 while( p ){
1052 if( (p->prereqRight & notReady)==0 ){
1053 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
1054 return p;
drhfe05af82005-07-21 03:14:59 +00001055 }
drh1c8148f2013-05-04 20:25:23 +00001056 if( pResult==0 ) pResult = p;
drhfe05af82005-07-21 03:14:59 +00001057 }
drh1c8148f2013-05-04 20:25:23 +00001058 p = whereScanNext(&scan);
drhfe05af82005-07-21 03:14:59 +00001059 }
drh7a5bcc02013-01-16 17:08:58 +00001060 return pResult;
drhfe05af82005-07-21 03:14:59 +00001061}
1062
drh6c30be82005-07-29 15:10:17 +00001063/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +00001064static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +00001065
1066/*
1067** Call exprAnalyze on all terms in a WHERE clause.
drh6c30be82005-07-29 15:10:17 +00001068*/
1069static void exprAnalyzeAll(
1070 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +00001071 WhereClause *pWC /* the WHERE clause to be analyzed */
1072){
drh6c30be82005-07-29 15:10:17 +00001073 int i;
drh9eb20282005-08-24 03:52:18 +00001074 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +00001075 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +00001076 }
1077}
1078
drhd2687b72005-08-12 22:56:09 +00001079#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1080/*
1081** Check to see if the given expression is a LIKE or GLOB operator that
1082** can be optimized using inequality constraints. Return TRUE if it is
1083** so and false if not.
1084**
1085** In order for the operator to be optimizible, the RHS must be a string
1086** literal that does not begin with a wildcard.
1087*/
1088static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +00001089 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +00001090 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +00001091 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +00001092 int *pisComplete, /* True if the only wildcard is % in the last character */
1093 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +00001094){
dan937d0de2009-10-15 18:35:38 +00001095 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +00001096 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
1097 ExprList *pList; /* List of operands to the LIKE operator */
1098 int c; /* One character in z[] */
1099 int cnt; /* Number of non-wildcard prefix characters */
1100 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +00001101 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +00001102 sqlite3_value *pVal = 0;
1103 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +00001104
drh9f504ea2008-02-23 21:55:39 +00001105 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +00001106 return 0;
1107 }
drh9f504ea2008-02-23 21:55:39 +00001108#ifdef SQLITE_EBCDIC
1109 if( *pnoCase ) return 0;
1110#endif
danielk19776ab3a2e2009-02-19 14:39:25 +00001111 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +00001112 pLeft = pList->a[1].pExpr;
danc68939e2012-03-29 14:29:07 +00001113 if( pLeft->op!=TK_COLUMN
1114 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
1115 || IsVirtual(pLeft->pTab)
1116 ){
drhd91ca492009-10-22 20:50:36 +00001117 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
1118 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +00001119 return 0;
1120 }
drhd91ca492009-10-22 20:50:36 +00001121 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +00001122
1123 pRight = pList->a[0].pExpr;
1124 op = pRight->op;
1125 if( op==TK_REGISTER ){
1126 op = pRight->op2;
1127 }
1128 if( op==TK_VARIABLE ){
1129 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +00001130 int iCol = pRight->iColumn;
1131 pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
dan937d0de2009-10-15 18:35:38 +00001132 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
1133 z = (char *)sqlite3_value_text(pVal);
1134 }
drhf9b22ca2011-10-21 16:47:31 +00001135 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +00001136 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
1137 }else if( op==TK_STRING ){
1138 z = pRight->u.zToken;
1139 }
1140 if( z ){
shane85095702009-06-15 16:27:08 +00001141 cnt = 0;
drhb7916a72009-05-27 10:31:29 +00001142 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +00001143 cnt++;
1144 }
drh93ee23c2010-07-22 12:33:57 +00001145 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +00001146 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +00001147 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +00001148 pPrefix = sqlite3Expr(db, TK_STRING, z);
1149 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
1150 *ppPrefix = pPrefix;
1151 if( op==TK_VARIABLE ){
1152 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +00001153 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +00001154 if( *pisComplete && pRight->u.zToken[1] ){
1155 /* If the rhs of the LIKE expression is a variable, and the current
1156 ** value of the variable means there is no need to invoke the LIKE
1157 ** function, then no OP_Variable will be added to the program.
1158 ** This causes problems for the sqlite3_bind_parameter_name()
drhbec451f2009-10-17 13:13:02 +00001159 ** API. To workaround them, add a dummy OP_Variable here.
1160 */
1161 int r1 = sqlite3GetTempReg(pParse);
1162 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +00001163 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +00001164 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +00001165 }
1166 }
1167 }else{
1168 z = 0;
shane85095702009-06-15 16:27:08 +00001169 }
drhf998b732007-11-26 13:36:00 +00001170 }
dan937d0de2009-10-15 18:35:38 +00001171
1172 sqlite3ValueFree(pVal);
1173 return (z!=0);
drhd2687b72005-08-12 22:56:09 +00001174}
1175#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1176
drhedb193b2006-06-27 13:20:21 +00001177
1178#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +00001179/*
drh7f375902006-06-13 17:38:59 +00001180** Check to see if the given expression is of the form
1181**
1182** column MATCH expr
1183**
1184** If it is then return TRUE. If not, return FALSE.
1185*/
1186static int isMatchOfColumn(
1187 Expr *pExpr /* Test this expression */
1188){
1189 ExprList *pList;
1190
1191 if( pExpr->op!=TK_FUNCTION ){
1192 return 0;
1193 }
drh33e619f2009-05-28 01:00:55 +00001194 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +00001195 return 0;
1196 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001197 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +00001198 if( pList->nExpr!=2 ){
1199 return 0;
1200 }
1201 if( pList->a[1].pExpr->op != TK_COLUMN ){
1202 return 0;
1203 }
1204 return 1;
1205}
drhedb193b2006-06-27 13:20:21 +00001206#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +00001207
1208/*
drh54a167d2005-11-26 14:08:07 +00001209** If the pBase expression originated in the ON or USING clause of
1210** a join, then transfer the appropriate markings over to derived.
1211*/
1212static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
1213 pDerived->flags |= pBase->flags & EP_FromJoin;
1214 pDerived->iRightJoinTable = pBase->iRightJoinTable;
1215}
1216
drh3e355802007-02-23 23:13:33 +00001217#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1218/*
drh1a58fe02008-12-20 02:06:13 +00001219** Analyze a term that consists of two or more OR-connected
1220** subterms. So in:
drh3e355802007-02-23 23:13:33 +00001221**
drh1a58fe02008-12-20 02:06:13 +00001222** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
1223** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +00001224**
drh1a58fe02008-12-20 02:06:13 +00001225** This routine analyzes terms such as the middle term in the above example.
1226** A WhereOrTerm object is computed and attached to the term under
1227** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +00001228**
drh1a58fe02008-12-20 02:06:13 +00001229** WhereTerm.wtFlags |= TERM_ORINFO
1230** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +00001231**
drh1a58fe02008-12-20 02:06:13 +00001232** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +00001233** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +00001234** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +00001235**
drh1a58fe02008-12-20 02:06:13 +00001236** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
1237** (B) x=expr1 OR expr2=x OR x=expr3
1238** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
1239** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
1240** (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 +00001241**
drh1a58fe02008-12-20 02:06:13 +00001242** CASE 1:
1243**
drhc3e552f2013-02-08 16:04:19 +00001244** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +00001245** a single table T (as shown in example B above) then create a new virtual
1246** term that is an equivalent IN expression. In other words, if the term
1247** being analyzed is:
1248**
1249** x = expr1 OR expr2 = x OR x = expr3
1250**
1251** then create a new virtual term like this:
1252**
1253** x IN (expr1,expr2,expr3)
1254**
1255** CASE 2:
1256**
1257** If all subterms are indexable by a single table T, then set
1258**
1259** WhereTerm.eOperator = WO_OR
1260** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
1261**
1262** A subterm is "indexable" if it is of the form
1263** "T.C <op> <expr>" where C is any column of table T and
1264** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
1265** A subterm is also indexable if it is an AND of two or more
1266** subsubterms at least one of which is indexable. Indexable AND
1267** subterms have their eOperator set to WO_AND and they have
1268** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
1269**
1270** From another point of view, "indexable" means that the subterm could
1271** potentially be used with an index if an appropriate index exists.
1272** This analysis does not consider whether or not the index exists; that
1273** is something the bestIndex() routine will determine. This analysis
1274** only looks at whether subterms appropriate for indexing exist.
1275**
1276** All examples A through E above all satisfy case 2. But if a term
1277** also statisfies case 1 (such as B) we know that the optimizer will
1278** always prefer case 1, so in that case we pretend that case 2 is not
1279** satisfied.
1280**
1281** It might be the case that multiple tables are indexable. For example,
1282** (E) above is indexable on tables P, Q, and R.
1283**
1284** Terms that satisfy case 2 are candidates for lookup by using
1285** separate indices to find rowids for each subterm and composing
1286** the union of all rowids using a RowSet object. This is similar
1287** to "bitmap indices" in other database engines.
1288**
1289** OTHERWISE:
1290**
1291** If neither case 1 nor case 2 apply, then leave the eOperator set to
1292** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +00001293*/
drh1a58fe02008-12-20 02:06:13 +00001294static void exprAnalyzeOrTerm(
1295 SrcList *pSrc, /* the FROM clause */
1296 WhereClause *pWC, /* the complete WHERE clause */
1297 int idxTerm /* Index of the OR-term to be analyzed */
1298){
drh70d18342013-06-06 19:16:33 +00001299 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
1300 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +00001301 sqlite3 *db = pParse->db; /* Database connection */
1302 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
1303 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +00001304 int i; /* Loop counters */
1305 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
1306 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
1307 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
1308 Bitmask chngToIN; /* Tables that might satisfy case 1 */
1309 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +00001310
drh1a58fe02008-12-20 02:06:13 +00001311 /*
1312 ** Break the OR clause into its separate subterms. The subterms are
1313 ** stored in a WhereClause structure containing within the WhereOrInfo
1314 ** object that is attached to the original OR clause term.
1315 */
1316 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
1317 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +00001318 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +00001319 if( pOrInfo==0 ) return;
1320 pTerm->wtFlags |= TERM_ORINFO;
1321 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +00001322 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +00001323 whereSplit(pOrWc, pExpr, TK_OR);
1324 exprAnalyzeAll(pSrc, pOrWc);
1325 if( db->mallocFailed ) return;
1326 assert( pOrWc->nTerm>=2 );
1327
1328 /*
1329 ** Compute the set of tables that might satisfy cases 1 or 2.
1330 */
danielk1977e672c8e2009-05-22 15:43:26 +00001331 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +00001332 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +00001333 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
1334 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +00001335 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +00001336 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +00001337 chngToIN = 0;
drh29435252008-12-28 18:35:08 +00001338 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
1339 if( pAndInfo ){
1340 WhereClause *pAndWC;
1341 WhereTerm *pAndTerm;
1342 int j;
1343 Bitmask b = 0;
1344 pOrTerm->u.pAndInfo = pAndInfo;
1345 pOrTerm->wtFlags |= TERM_ANDINFO;
1346 pOrTerm->eOperator = WO_AND;
1347 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +00001348 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +00001349 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
1350 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +00001351 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +00001352 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +00001353 if( !db->mallocFailed ){
1354 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
1355 assert( pAndTerm->pExpr );
1356 if( allowedOp(pAndTerm->pExpr->op) ){
drh70d18342013-06-06 19:16:33 +00001357 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +00001358 }
drh29435252008-12-28 18:35:08 +00001359 }
1360 }
1361 indexable &= b;
1362 }
drh1a58fe02008-12-20 02:06:13 +00001363 }else if( pOrTerm->wtFlags & TERM_COPIED ){
1364 /* Skip this term for now. We revisit it when we process the
1365 ** corresponding TERM_VIRTUAL term */
1366 }else{
1367 Bitmask b;
drh70d18342013-06-06 19:16:33 +00001368 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001369 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
1370 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh70d18342013-06-06 19:16:33 +00001371 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001372 }
1373 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +00001374 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +00001375 chngToIN = 0;
1376 }else{
1377 chngToIN &= b;
1378 }
1379 }
drh3e355802007-02-23 23:13:33 +00001380 }
drh1a58fe02008-12-20 02:06:13 +00001381
1382 /*
1383 ** Record the set of tables that satisfy case 2. The set might be
drh111a6a72008-12-21 03:51:16 +00001384 ** empty.
drh1a58fe02008-12-20 02:06:13 +00001385 */
1386 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +00001387 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +00001388
1389 /*
1390 ** chngToIN holds a set of tables that *might* satisfy case 1. But
1391 ** we have to do some additional checking to see if case 1 really
1392 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +00001393 **
1394 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
1395 ** that there is no possibility of transforming the OR clause into an
1396 ** IN operator because one or more terms in the OR clause contain
1397 ** something other than == on a column in the single table. The 1-bit
1398 ** case means that every term of the OR clause is of the form
1399 ** "table.column=expr" for some single table. The one bit that is set
1400 ** will correspond to the common table. We still need to check to make
1401 ** sure the same column is used on all terms. The 2-bit case is when
1402 ** the all terms are of the form "table1.column=table2.column". It
1403 ** might be possible to form an IN operator with either table1.column
1404 ** or table2.column as the LHS if either is common to every term of
1405 ** the OR clause.
1406 **
1407 ** Note that terms of the form "table.column1=table.column2" (the
1408 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +00001409 */
1410 if( chngToIN ){
1411 int okToChngToIN = 0; /* True if the conversion to IN is valid */
1412 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +00001413 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +00001414 int j = 0; /* Loop counter */
1415
1416 /* Search for a table and column that appears on one side or the
1417 ** other of the == operator in every subterm. That table and column
1418 ** will be recorded in iCursor and iColumn. There might not be any
1419 ** such table and column. Set okToChngToIN if an appropriate table
1420 ** and column is found but leave okToChngToIN false if not found.
1421 */
1422 for(j=0; j<2 && !okToChngToIN; j++){
1423 pOrTerm = pOrWc->a;
1424 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001425 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001426 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +00001427 if( pOrTerm->leftCursor==iCursor ){
1428 /* This is the 2-bit case and we are on the second iteration and
1429 ** current term is from the first iteration. So skip this term. */
1430 assert( j==1 );
1431 continue;
1432 }
drh70d18342013-06-06 19:16:33 +00001433 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +00001434 /* This term must be of the form t1.a==t2.b where t2 is in the
1435 ** chngToIN set but t1 is not. This term will be either preceeded
1436 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
1437 ** and use its inversion. */
1438 testcase( pOrTerm->wtFlags & TERM_COPIED );
1439 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
1440 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
1441 continue;
1442 }
drh1a58fe02008-12-20 02:06:13 +00001443 iColumn = pOrTerm->u.leftColumn;
1444 iCursor = pOrTerm->leftCursor;
1445 break;
1446 }
1447 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +00001448 /* No candidate table+column was found. This can only occur
1449 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +00001450 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +00001451 assert( IsPowerOfTwo(chngToIN) );
drh70d18342013-06-06 19:16:33 +00001452 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +00001453 break;
1454 }
drh4e8be3b2009-06-08 17:11:08 +00001455 testcase( j==1 );
1456
1457 /* We have found a candidate table and column. Check to see if that
1458 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001459 okToChngToIN = 1;
1460 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001461 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001462 if( pOrTerm->leftCursor!=iCursor ){
1463 pOrTerm->wtFlags &= ~TERM_OR_OK;
1464 }else if( pOrTerm->u.leftColumn!=iColumn ){
1465 okToChngToIN = 0;
1466 }else{
1467 int affLeft, affRight;
1468 /* If the right-hand side is also a column, then the affinities
1469 ** of both right and left sides must be such that no type
1470 ** conversions are required on the right. (Ticket #2249)
1471 */
1472 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1473 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1474 if( affRight!=0 && affRight!=affLeft ){
1475 okToChngToIN = 0;
1476 }else{
1477 pOrTerm->wtFlags |= TERM_OR_OK;
1478 }
1479 }
1480 }
1481 }
1482
1483 /* At this point, okToChngToIN is true if original pTerm satisfies
1484 ** case 1. In that case, construct a new virtual term that is
1485 ** pTerm converted into an IN operator.
drhe9cdcea2010-07-22 22:40:03 +00001486 **
1487 ** EV: R-00211-15100
drh1a58fe02008-12-20 02:06:13 +00001488 */
1489 if( okToChngToIN ){
1490 Expr *pDup; /* A transient duplicate expression */
1491 ExprList *pList = 0; /* The RHS of the IN operator */
1492 Expr *pLeft = 0; /* The LHS of the IN operator */
1493 Expr *pNew; /* The complete IN operator */
1494
1495 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1496 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001497 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001498 assert( pOrTerm->leftCursor==iCursor );
1499 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001500 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001501 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001502 pLeft = pOrTerm->pExpr->pLeft;
1503 }
1504 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001505 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001506 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001507 if( pNew ){
1508 int idxNew;
1509 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001510 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1511 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001512 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1513 testcase( idxNew==0 );
1514 exprAnalyze(pSrc, pWC, idxNew);
1515 pTerm = &pWC->a[idxTerm];
1516 pWC->a[idxNew].iParent = idxTerm;
1517 pTerm->nChild = 1;
1518 }else{
1519 sqlite3ExprListDelete(db, pList);
1520 }
drh534230c2011-01-22 00:10:45 +00001521 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
drh1a58fe02008-12-20 02:06:13 +00001522 }
drh3e355802007-02-23 23:13:33 +00001523 }
drh3e355802007-02-23 23:13:33 +00001524}
1525#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001526
drh7a5bcc02013-01-16 17:08:58 +00001527/*
drh0aa74ed2005-07-16 13:33:20 +00001528** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001529** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001530** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001531** structure.
drh51147ba2005-07-23 22:59:55 +00001532**
1533** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001534** to the standard form of "X <op> <expr>".
1535**
1536** If the expression is of the form "X <op> Y" where both X and Y are
1537** columns, then the original expression is unchanged and a new virtual
1538** term of the form "Y <op> X" is added to the WHERE clause and
1539** analyzed separately. The original term is marked with TERM_COPIED
1540** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1541** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1542** is a commuted copy of a prior term.) The original term has nChild=1
1543** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001544*/
drh0fcef5e2005-07-19 17:38:22 +00001545static void exprAnalyze(
1546 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001547 WhereClause *pWC, /* the WHERE clause */
1548 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001549){
drh70d18342013-06-06 19:16:33 +00001550 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001551 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001552 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001553 Expr *pExpr; /* The expression to be analyzed */
1554 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1555 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001556 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001557 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1558 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1559 int noCase = 0; /* LIKE/GLOB distinguishes case */
drh1a58fe02008-12-20 02:06:13 +00001560 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001561 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001562 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001563
drhf998b732007-11-26 13:36:00 +00001564 if( db->mallocFailed ){
1565 return;
1566 }
1567 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001568 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001569 pExpr = pTerm->pExpr;
1570 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001571 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001572 op = pExpr->op;
1573 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001574 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001575 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1576 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1577 }else{
1578 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1579 }
drh50b39962006-10-28 00:28:09 +00001580 }else if( op==TK_ISNULL ){
1581 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001582 }else{
1583 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1584 }
drh22d6a532005-09-19 21:05:48 +00001585 prereqAll = exprTableUsage(pMaskSet, pExpr);
1586 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001587 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1588 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001589 extraRight = x-1; /* ON clause terms may not be used with an index
1590 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001591 }
1592 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001593 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001594 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001595 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001596 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001597 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1598 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001599 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001600 if( pLeft->op==TK_COLUMN ){
1601 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001602 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001603 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001604 }
drh0fcef5e2005-07-19 17:38:22 +00001605 if( pRight && pRight->op==TK_COLUMN ){
1606 WhereTerm *pNew;
1607 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001608 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001609 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001610 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001611 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001612 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001613 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001614 return;
1615 }
drh9eb20282005-08-24 03:52:18 +00001616 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1617 if( idxNew==0 ) return;
1618 pNew = &pWC->a[idxNew];
1619 pNew->iParent = idxTerm;
1620 pTerm = &pWC->a[idxTerm];
drh45b1ee42005-08-02 17:48:22 +00001621 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001622 pTerm->wtFlags |= TERM_COPIED;
drheb5bc922013-01-17 16:43:33 +00001623 if( pExpr->op==TK_EQ
1624 && !ExprHasProperty(pExpr, EP_FromJoin)
1625 && OptimizationEnabled(db, SQLITE_Transitive)
1626 ){
drh7a5bcc02013-01-16 17:08:58 +00001627 pTerm->eOperator |= WO_EQUIV;
1628 eExtraOp = WO_EQUIV;
1629 }
drh0fcef5e2005-07-19 17:38:22 +00001630 }else{
1631 pDup = pExpr;
1632 pNew = pTerm;
1633 }
drh7d10d5a2008-08-20 16:35:10 +00001634 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001635 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001636 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001637 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001638 testcase( (prereqLeft | extraRight) != prereqLeft );
1639 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001640 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001641 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001642 }
1643 }
drhed378002005-07-28 23:12:08 +00001644
drhd2687b72005-08-12 22:56:09 +00001645#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001646 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001647 ** that define the range that the BETWEEN implements. For example:
1648 **
1649 ** a BETWEEN b AND c
1650 **
1651 ** is converted into:
1652 **
1653 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1654 **
1655 ** The two new terms are added onto the end of the WhereClause object.
1656 ** The new terms are "dynamic" and are children of the original BETWEEN
1657 ** term. That means that if the BETWEEN term is coded, the children are
1658 ** skipped. Or, if the children are satisfied by an index, the original
1659 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001660 */
drh29435252008-12-28 18:35:08 +00001661 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001662 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001663 int i;
1664 static const u8 ops[] = {TK_GE, TK_LE};
1665 assert( pList!=0 );
1666 assert( pList->nExpr==2 );
1667 for(i=0; i<2; i++){
1668 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001669 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001670 pNewExpr = sqlite3PExpr(pParse, ops[i],
1671 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001672 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drh9eb20282005-08-24 03:52:18 +00001673 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001674 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001675 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001676 pTerm = &pWC->a[idxTerm];
1677 pWC->a[idxNew].iParent = idxTerm;
drhed378002005-07-28 23:12:08 +00001678 }
drh45b1ee42005-08-02 17:48:22 +00001679 pTerm->nChild = 2;
drhed378002005-07-28 23:12:08 +00001680 }
drhd2687b72005-08-12 22:56:09 +00001681#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001682
danielk19771576cd92006-01-14 08:02:28 +00001683#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001684 /* Analyze a term that is composed of two or more subterms connected by
1685 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001686 */
1687 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001688 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001689 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001690 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001691 }
drhd2687b72005-08-12 22:56:09 +00001692#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1693
1694#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1695 /* Add constraints to reduce the search space on a LIKE or GLOB
1696 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001697 **
1698 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1699 **
1700 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
1701 **
1702 ** The last character of the prefix "abc" is incremented to form the
shane7bc71e52008-05-28 18:01:44 +00001703 ** termination condition "abd".
drhd2687b72005-08-12 22:56:09 +00001704 */
dan937d0de2009-10-15 18:35:38 +00001705 if( pWC->op==TK_AND
1706 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1707 ){
drh1d452e12009-11-01 19:26:59 +00001708 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1709 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1710 Expr *pNewExpr1;
1711 Expr *pNewExpr2;
1712 int idxNew1;
1713 int idxNew2;
drhae80dde2012-12-06 21:16:43 +00001714 Token sCollSeqName; /* Name of collating sequence */
drh9eb20282005-08-24 03:52:18 +00001715
danielk19776ab3a2e2009-02-19 14:39:25 +00001716 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001717 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drhf998b732007-11-26 13:36:00 +00001718 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001719 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001720 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001721 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001722 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001723 /* The point is to increment the last character before the first
1724 ** wildcard. But if we increment '@', that will push it into the
1725 ** alphabetic range where case conversions will mess up the
1726 ** inequality. To avoid this, make sure to also run the full
1727 ** LIKE on all candidate expressions by clearing the isComplete flag
1728 */
drhe9cdcea2010-07-22 22:40:03 +00001729 if( c=='A'-1 ) isComplete = 0; /* EV: R-64339-08207 */
1730
drh254993e2009-06-08 19:44:36 +00001731
drh02a50b72008-05-26 18:33:40 +00001732 c = sqlite3UpperToLower[c];
1733 }
drh9f504ea2008-02-23 21:55:39 +00001734 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001735 }
drhae80dde2012-12-06 21:16:43 +00001736 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1737 sCollSeqName.n = 6;
1738 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001739 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
drh0a8a4062012-12-07 18:38:16 +00001740 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001741 pStr1, 0);
drh9eb20282005-08-24 03:52:18 +00001742 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001743 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001744 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001745 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001746 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
drh0a8a4062012-12-07 18:38:16 +00001747 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001748 pStr2, 0);
drh9eb20282005-08-24 03:52:18 +00001749 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001750 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001751 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001752 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001753 if( isComplete ){
drh9eb20282005-08-24 03:52:18 +00001754 pWC->a[idxNew1].iParent = idxTerm;
1755 pWC->a[idxNew2].iParent = idxTerm;
drhd2687b72005-08-12 22:56:09 +00001756 pTerm->nChild = 2;
1757 }
1758 }
1759#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001760
1761#ifndef SQLITE_OMIT_VIRTUALTABLE
1762 /* Add a WO_MATCH auxiliary term to the constraint set if the
1763 ** current expression is of the form: column MATCH expr.
1764 ** This information is used by the xBestIndex methods of
1765 ** virtual tables. The native query optimizer does not attempt
1766 ** to do anything with MATCH functions.
1767 */
1768 if( isMatchOfColumn(pExpr) ){
1769 int idxNew;
1770 Expr *pRight, *pLeft;
1771 WhereTerm *pNewTerm;
1772 Bitmask prereqColumn, prereqExpr;
1773
danielk19776ab3a2e2009-02-19 14:39:25 +00001774 pRight = pExpr->x.pList->a[0].pExpr;
1775 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001776 prereqExpr = exprTableUsage(pMaskSet, pRight);
1777 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1778 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001779 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001780 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1781 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001782 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001783 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001784 pNewTerm = &pWC->a[idxNew];
1785 pNewTerm->prereqRight = prereqExpr;
1786 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001787 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001788 pNewTerm->eOperator = WO_MATCH;
1789 pNewTerm->iParent = idxTerm;
drhd2ca60d2006-06-27 02:36:58 +00001790 pTerm = &pWC->a[idxTerm];
drh7f375902006-06-13 17:38:59 +00001791 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001792 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001793 pNewTerm->prereqAll = pTerm->prereqAll;
1794 }
1795 }
1796#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001797
drhfaacf172011-08-12 01:51:45 +00001798#ifdef SQLITE_ENABLE_STAT3
drhd3ed7342011-09-21 00:09:41 +00001799 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001800 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1801 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1802 ** virtual term of that form.
1803 **
1804 ** Note that the virtual term must be tagged with TERM_VNULL. This
1805 ** TERM_VNULL tag will suppress the not-null check at the beginning
1806 ** of the loop. Without the TERM_VNULL flag, the not-null check at
1807 ** the start of the loop will prevent any results from being returned.
1808 */
drhea6dc442011-04-08 21:35:26 +00001809 if( pExpr->op==TK_NOTNULL
1810 && pExpr->pLeft->op==TK_COLUMN
1811 && pExpr->pLeft->iColumn>=0
drh40aa9362013-06-28 17:29:25 +00001812 && OptimizationEnabled(db, SQLITE_Stat3)
drhea6dc442011-04-08 21:35:26 +00001813 ){
drh534230c2011-01-22 00:10:45 +00001814 Expr *pNewExpr;
1815 Expr *pLeft = pExpr->pLeft;
1816 int idxNew;
1817 WhereTerm *pNewTerm;
1818
1819 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1820 sqlite3ExprDup(db, pLeft, 0),
1821 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1822
1823 idxNew = whereClauseInsert(pWC, pNewExpr,
1824 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001825 if( idxNew ){
1826 pNewTerm = &pWC->a[idxNew];
1827 pNewTerm->prereqRight = 0;
1828 pNewTerm->leftCursor = pLeft->iTable;
1829 pNewTerm->u.leftColumn = pLeft->iColumn;
1830 pNewTerm->eOperator = WO_GT;
1831 pNewTerm->iParent = idxTerm;
1832 pTerm = &pWC->a[idxTerm];
1833 pTerm->nChild = 1;
1834 pTerm->wtFlags |= TERM_COPIED;
1835 pNewTerm->prereqAll = pTerm->prereqAll;
1836 }
drh534230c2011-01-22 00:10:45 +00001837 }
drhfaacf172011-08-12 01:51:45 +00001838#endif /* SQLITE_ENABLE_STAT */
drh534230c2011-01-22 00:10:45 +00001839
drhdafc0ce2008-04-17 19:14:02 +00001840 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1841 ** an index for tables to the left of the join.
1842 */
1843 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001844}
1845
drh7b4fc6a2007-02-06 13:26:32 +00001846/*
drh3b48e8c2013-06-12 20:18:16 +00001847** This function searches pList for a entry that matches the iCol-th column
1848** of index pIdx.
dan6f343962011-07-01 18:26:40 +00001849**
1850** If such an expression is found, its index in pList->a[] is returned. If
1851** no expression is found, -1 is returned.
1852*/
1853static int findIndexCol(
1854 Parse *pParse, /* Parse context */
1855 ExprList *pList, /* Expression list to search */
1856 int iBase, /* Cursor for table associated with pIdx */
1857 Index *pIdx, /* Index to match column of */
1858 int iCol /* Column of index to match */
1859){
1860 int i;
1861 const char *zColl = pIdx->azColl[iCol];
1862
1863 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001864 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001865 if( p->op==TK_COLUMN
1866 && p->iColumn==pIdx->aiColumn[iCol]
1867 && p->iTable==iBase
1868 ){
drh580c8c12012-12-08 03:34:04 +00001869 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001870 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001871 return i;
1872 }
1873 }
1874 }
1875
1876 return -1;
1877}
1878
1879/*
dan6f343962011-07-01 18:26:40 +00001880** Return true if the DISTINCT expression-list passed as the third argument
drh4f402f22013-06-11 18:59:38 +00001881** is redundant.
1882**
drh3b48e8c2013-06-12 20:18:16 +00001883** A DISTINCT list is redundant if the database contains some subset of
drh4f402f22013-06-11 18:59:38 +00001884** columns that are unique and non-null.
dan6f343962011-07-01 18:26:40 +00001885*/
1886static int isDistinctRedundant(
drh4f402f22013-06-11 18:59:38 +00001887 Parse *pParse, /* Parsing context */
1888 SrcList *pTabList, /* The FROM clause */
1889 WhereClause *pWC, /* The WHERE clause */
1890 ExprList *pDistinct /* The result set that needs to be DISTINCT */
dan6f343962011-07-01 18:26:40 +00001891){
1892 Table *pTab;
1893 Index *pIdx;
1894 int i;
1895 int iBase;
1896
1897 /* If there is more than one table or sub-select in the FROM clause of
1898 ** this query, then it will not be possible to show that the DISTINCT
1899 ** clause is redundant. */
1900 if( pTabList->nSrc!=1 ) return 0;
1901 iBase = pTabList->a[0].iCursor;
1902 pTab = pTabList->a[0].pTab;
1903
dan94e08d92011-07-02 06:44:05 +00001904 /* If any of the expressions is an IPK column on table iBase, then return
1905 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1906 ** current SELECT is a correlated sub-query.
1907 */
dan6f343962011-07-01 18:26:40 +00001908 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001909 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001910 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001911 }
1912
1913 /* Loop through all indices on the table, checking each to see if it makes
1914 ** the DISTINCT qualifier redundant. It does so if:
1915 **
1916 ** 1. The index is itself UNIQUE, and
1917 **
1918 ** 2. All of the columns in the index are either part of the pDistinct
1919 ** list, or else the WHERE clause contains a term of the form "col=X",
1920 ** where X is a constant value. The collation sequences of the
1921 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001922 **
1923 ** 3. All of those index columns for which the WHERE clause does not
1924 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001925 */
1926 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1927 if( pIdx->onError==OE_None ) continue;
1928 for(i=0; i<pIdx->nColumn; i++){
1929 int iCol = pIdx->aiColumn[i];
dan6a36f432012-04-20 16:59:24 +00001930 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1931 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
1932 if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
1933 break;
1934 }
dan6f343962011-07-01 18:26:40 +00001935 }
1936 }
1937 if( i==pIdx->nColumn ){
1938 /* This index implies that the DISTINCT qualifier is redundant. */
1939 return 1;
1940 }
1941 }
1942
1943 return 0;
1944}
drh0fcef5e2005-07-19 17:38:22 +00001945
drhb8a8e8a2013-06-10 19:12:39 +00001946/*
drh3b48e8c2013-06-12 20:18:16 +00001947** The (an approximate) sum of two WhereCosts. This computation is
1948** not a simple "+" operator because WhereCost is stored as a logarithmic
1949** value.
1950**
drhb8a8e8a2013-06-10 19:12:39 +00001951*/
1952static WhereCost whereCostAdd(WhereCost a, WhereCost b){
1953 static const unsigned char x[] = {
1954 10, 10, /* 0,1 */
1955 9, 9, /* 2,3 */
1956 8, 8, /* 4,5 */
1957 7, 7, 7, /* 6,7,8 */
1958 6, 6, 6, /* 9,10,11 */
1959 5, 5, 5, /* 12-14 */
1960 4, 4, 4, 4, /* 15-18 */
1961 3, 3, 3, 3, 3, 3, /* 19-24 */
1962 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
1963 };
1964 if( a>=b ){
1965 if( a>b+49 ) return a;
1966 if( a>b+31 ) return a+1;
1967 return a+x[a-b];
1968 }else{
1969 if( b>a+49 ) return b;
1970 if( b>a+31 ) return b+1;
1971 return b+x[b-a];
1972 }
1973}
1974
1975/*
drh3b48e8c2013-06-12 20:18:16 +00001976** Convert an integer into a WhereCost. In other words, compute a
1977** good approximatation for 10*log2(x).
drhb8a8e8a2013-06-10 19:12:39 +00001978*/
drhe1e2e9a2013-06-13 15:16:53 +00001979static WhereCost whereCost(tRowcnt x){
drhb8a8e8a2013-06-10 19:12:39 +00001980 static WhereCost a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1981 WhereCost y = 40;
1982 if( x<8 ){
1983 if( x<2 ) return 0;
1984 while( x<8 ){ y -= 10; x <<= 1; }
1985 }else{
1986 while( x>255 ){ y += 40; x >>= 4; }
1987 while( x>15 ){ y += 10; x >>= 1; }
1988 }
1989 return a[x&7] + y - 10;
1990}
1991
drh8636e9c2013-06-11 01:50:08 +00001992#ifndef SQLITE_OMIT_VIRTUALTABLE
1993/*
1994** Convert a double (as received from xBestIndex of a virtual table)
drh3b48e8c2013-06-12 20:18:16 +00001995** into a WhereCost. In other words, compute an approximation for
1996** 10*log2(x).
drh8636e9c2013-06-11 01:50:08 +00001997*/
1998static WhereCost whereCostFromDouble(double x){
1999 u64 a;
2000 WhereCost e;
2001 assert( sizeof(x)==8 && sizeof(a)==8 );
2002 if( x<=1 ) return 0;
drhe1e2e9a2013-06-13 15:16:53 +00002003 if( x<=2000000000 ) return whereCost((tRowcnt)x);
drh8636e9c2013-06-11 01:50:08 +00002004 memcpy(&a, &x, 8);
2005 e = (a>>52) - 1022;
2006 return e*10;
2007}
2008#endif /* SQLITE_OMIT_VIRTUALTABLE */
2009
drh75897232000-05-29 14:26:00 +00002010/*
drh3b48e8c2013-06-12 20:18:16 +00002011** Estimate the logarithm of the input value to base 2.
drh28c4cf42005-07-27 20:41:43 +00002012*/
drh4efc9292013-06-06 23:02:03 +00002013static WhereCost estLog(WhereCost N){
drhe1e2e9a2013-06-13 15:16:53 +00002014 WhereCost x = whereCost(N);
drh4fe425a2013-06-12 17:08:06 +00002015 return x>33 ? x - 33 : 0;
drh28c4cf42005-07-27 20:41:43 +00002016}
2017
drh6d209d82006-06-27 01:54:26 +00002018/*
2019** Two routines for printing the content of an sqlite3_index_info
2020** structure. Used for testing and debugging only. If neither
2021** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
2022** are no-ops.
2023*/
drhd15cb172013-05-21 19:23:10 +00002024#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00002025static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
2026 int i;
mlcreech3a00f902008-03-04 17:45:01 +00002027 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00002028 for(i=0; i<p->nConstraint; i++){
2029 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
2030 i,
2031 p->aConstraint[i].iColumn,
2032 p->aConstraint[i].iTermOffset,
2033 p->aConstraint[i].op,
2034 p->aConstraint[i].usable);
2035 }
2036 for(i=0; i<p->nOrderBy; i++){
2037 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
2038 i,
2039 p->aOrderBy[i].iColumn,
2040 p->aOrderBy[i].desc);
2041 }
2042}
2043static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
2044 int i;
mlcreech3a00f902008-03-04 17:45:01 +00002045 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00002046 for(i=0; i<p->nConstraint; i++){
2047 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
2048 i,
2049 p->aConstraintUsage[i].argvIndex,
2050 p->aConstraintUsage[i].omit);
2051 }
2052 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
2053 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
2054 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
2055 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
2056}
2057#else
2058#define TRACE_IDX_INPUTS(A)
2059#define TRACE_IDX_OUTPUTS(A)
2060#endif
2061
drhc6339082010-04-07 16:54:58 +00002062#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00002063/*
drh4139c992010-04-07 14:59:45 +00002064** Return TRUE if the WHERE clause term pTerm is of a form where it
2065** could be used with an index to access pSrc, assuming an appropriate
2066** index existed.
2067*/
2068static int termCanDriveIndex(
2069 WhereTerm *pTerm, /* WHERE clause term to check */
2070 struct SrcList_item *pSrc, /* Table we are trying to access */
2071 Bitmask notReady /* Tables in outer loops of the join */
2072){
2073 char aff;
2074 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drh7a5bcc02013-01-16 17:08:58 +00002075 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00002076 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00002077 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00002078 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
2079 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
2080 return 1;
2081}
drhc6339082010-04-07 16:54:58 +00002082#endif
drh4139c992010-04-07 14:59:45 +00002083
drhc6339082010-04-07 16:54:58 +00002084
2085#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00002086/*
drhc6339082010-04-07 16:54:58 +00002087** Generate code to construct the Index object for an automatic index
2088** and to set up the WhereLevel object pLevel so that the code generator
2089** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00002090*/
drhc6339082010-04-07 16:54:58 +00002091static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00002092 Parse *pParse, /* The parsing context */
2093 WhereClause *pWC, /* The WHERE clause */
2094 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
2095 Bitmask notReady, /* Mask of cursors that are not available */
2096 WhereLevel *pLevel /* Write new index here */
2097){
2098 int nColumn; /* Number of columns in the constructed index */
2099 WhereTerm *pTerm; /* A single term of the WHERE clause */
2100 WhereTerm *pWCEnd; /* End of pWC->a[] */
2101 int nByte; /* Byte of memory needed for pIdx */
2102 Index *pIdx; /* Object describing the transient index */
2103 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00002104 int addrInit; /* Address of the initialization bypass jump */
2105 Table *pTable; /* The table being indexed */
2106 KeyInfo *pKeyinfo; /* Key information for the index */
2107 int addrTop; /* Top of the index fill loop */
2108 int regRecord; /* Register holding an index record */
2109 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00002110 int i; /* Loop counter */
2111 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00002112 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00002113 WhereLoop *pLoop; /* The Loop object */
drh4139c992010-04-07 14:59:45 +00002114 Bitmask idxCols; /* Bitmap of columns used for indexing */
2115 Bitmask extraCols; /* Bitmap of additional columns */
drh8d56e202013-06-28 23:55:45 +00002116 u8 sentWarning = 0; /* True if a warnning has been issued */
drh8b307fb2010-04-06 15:57:05 +00002117
2118 /* Generate code to skip over the creation and initialization of the
2119 ** transient index on 2nd and subsequent iterations of the loop. */
2120 v = pParse->pVdbe;
2121 assert( v!=0 );
dan1d8cb212011-12-09 13:24:16 +00002122 addrInit = sqlite3CodeOnce(pParse);
drh8b307fb2010-04-06 15:57:05 +00002123
drh4139c992010-04-07 14:59:45 +00002124 /* Count the number of columns that will be added to the index
2125 ** and used to match WHERE clause constraints */
drh8b307fb2010-04-06 15:57:05 +00002126 nColumn = 0;
drh424aab82010-04-06 18:28:20 +00002127 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00002128 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00002129 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00002130 idxCols = 0;
drh81186b42013-06-18 01:52:41 +00002131 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00002132 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
2133 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00002134 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00002135 testcase( iCol==BMS );
2136 testcase( iCol==BMS-1 );
drh8d56e202013-06-28 23:55:45 +00002137 if( !sentWarning ){
2138 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
2139 "automatic index on %s(%s)", pTable->zName,
2140 pTable->aCol[iCol].zName);
2141 sentWarning = 1;
2142 }
drh0013e722010-04-08 00:40:15 +00002143 if( (idxCols & cMask)==0 ){
drh4efc9292013-06-06 23:02:03 +00002144 if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
2145 pLoop->aLTerm[nColumn++] = pTerm;
drh0013e722010-04-08 00:40:15 +00002146 idxCols |= cMask;
2147 }
drh8b307fb2010-04-06 15:57:05 +00002148 }
2149 }
2150 assert( nColumn>0 );
drh4efc9292013-06-06 23:02:03 +00002151 pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
drh53b52f72013-05-31 11:57:39 +00002152 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
drh986b3872013-06-28 21:12:20 +00002153 | WHERE_AUTO_INDEX;
drh4139c992010-04-07 14:59:45 +00002154
2155 /* Count the number of additional columns needed to create a
2156 ** covering index. A "covering index" is an index that contains all
2157 ** columns that are needed by the query. With a covering index, the
2158 ** original table never needs to be accessed. Automatic indices must
2159 ** be a covering index because the index will not be updated if the
2160 ** original table changes and the index and table cannot both be used
2161 ** if they go out of sync.
2162 */
drh7699d1c2013-06-04 12:42:29 +00002163 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drh4139c992010-04-07 14:59:45 +00002164 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
drh52ff8ea2010-04-08 14:15:56 +00002165 testcase( pTable->nCol==BMS-1 );
2166 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00002167 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00002168 if( extraCols & MASKBIT(i) ) nColumn++;
drh4139c992010-04-07 14:59:45 +00002169 }
drh7699d1c2013-06-04 12:42:29 +00002170 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00002171 nColumn += pTable->nCol - BMS + 1;
2172 }
drh7ba39a92013-05-30 17:43:19 +00002173 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
drh8b307fb2010-04-06 15:57:05 +00002174
2175 /* Construct the Index object to describe this index */
2176 nByte = sizeof(Index);
2177 nByte += nColumn*sizeof(int); /* Index.aiColumn */
2178 nByte += nColumn*sizeof(char*); /* Index.azColl */
2179 nByte += nColumn; /* Index.aSortOrder */
2180 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
2181 if( pIdx==0 ) return;
drh7ba39a92013-05-30 17:43:19 +00002182 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00002183 pIdx->azColl = (char**)&pIdx[1];
2184 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
2185 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
2186 pIdx->zName = "auto-index";
2187 pIdx->nColumn = nColumn;
drh424aab82010-04-06 18:28:20 +00002188 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00002189 n = 0;
drh0013e722010-04-08 00:40:15 +00002190 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00002191 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00002192 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00002193 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00002194 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh7963b0e2013-06-17 21:37:40 +00002195 testcase( iCol==BMS-1 );
2196 testcase( iCol==BMS );
drh0013e722010-04-08 00:40:15 +00002197 if( (idxCols & cMask)==0 ){
2198 Expr *pX = pTerm->pExpr;
2199 idxCols |= cMask;
2200 pIdx->aiColumn[n] = pTerm->u.leftColumn;
2201 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh6f2e6c02011-02-17 13:33:15 +00002202 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00002203 n++;
2204 }
drh8b307fb2010-04-06 15:57:05 +00002205 }
2206 }
drh7ba39a92013-05-30 17:43:19 +00002207 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00002208
drhc6339082010-04-07 16:54:58 +00002209 /* Add additional columns needed to make the automatic index into
2210 ** a covering index */
drh4139c992010-04-07 14:59:45 +00002211 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00002212 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00002213 pIdx->aiColumn[n] = i;
2214 pIdx->azColl[n] = "BINARY";
2215 n++;
2216 }
2217 }
drh7699d1c2013-06-04 12:42:29 +00002218 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00002219 for(i=BMS-1; i<pTable->nCol; i++){
2220 pIdx->aiColumn[n] = i;
2221 pIdx->azColl[n] = "BINARY";
2222 n++;
2223 }
2224 }
2225 assert( n==nColumn );
drh8b307fb2010-04-06 15:57:05 +00002226
drhc6339082010-04-07 16:54:58 +00002227 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00002228 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
2229 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00002230 pLevel->iIdxCur = pParse->nTab++;
drha21a64d2010-04-06 22:33:55 +00002231 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
drh8b307fb2010-04-06 15:57:05 +00002232 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
drha21a64d2010-04-06 22:33:55 +00002233 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00002234
drhc6339082010-04-07 16:54:58 +00002235 /* Fill the automatic index with content */
drh8b307fb2010-04-06 15:57:05 +00002236 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
2237 regRecord = sqlite3GetTempReg(pParse);
2238 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
2239 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
2240 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2241 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
drha21a64d2010-04-06 22:33:55 +00002242 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00002243 sqlite3VdbeJumpHere(v, addrTop);
2244 sqlite3ReleaseTempReg(pParse, regRecord);
2245
2246 /* Jump here when skipping the initialization */
2247 sqlite3VdbeJumpHere(v, addrInit);
2248}
drhc6339082010-04-07 16:54:58 +00002249#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00002250
drh9eff6162006-06-12 21:59:13 +00002251#ifndef SQLITE_OMIT_VIRTUALTABLE
2252/*
danielk19771d461462009-04-21 09:02:45 +00002253** Allocate and populate an sqlite3_index_info structure. It is the
2254** responsibility of the caller to eventually release the structure
2255** by passing the pointer returned by this function to sqlite3_free().
2256*/
drh5346e952013-05-08 14:14:26 +00002257static sqlite3_index_info *allocateIndexInfo(
2258 Parse *pParse,
2259 WhereClause *pWC,
2260 struct SrcList_item *pSrc,
2261 ExprList *pOrderBy
2262){
danielk19771d461462009-04-21 09:02:45 +00002263 int i, j;
2264 int nTerm;
2265 struct sqlite3_index_constraint *pIdxCons;
2266 struct sqlite3_index_orderby *pIdxOrderBy;
2267 struct sqlite3_index_constraint_usage *pUsage;
2268 WhereTerm *pTerm;
2269 int nOrderBy;
2270 sqlite3_index_info *pIdxInfo;
2271
danielk19771d461462009-04-21 09:02:45 +00002272 /* Count the number of possible WHERE clause constraints referring
2273 ** to this virtual table */
2274 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
2275 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00002276 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2277 testcase( pTerm->eOperator & WO_IN );
2278 testcase( pTerm->eOperator & WO_ISNULL );
drh281bbe22012-10-16 23:17:14 +00002279 if( pTerm->eOperator & (WO_ISNULL) ) continue;
drhb4256992011-08-02 01:57:39 +00002280 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00002281 nTerm++;
2282 }
2283
2284 /* If the ORDER BY clause contains only columns in the current
2285 ** virtual table then allocate space for the aOrderBy part of
2286 ** the sqlite3_index_info structure.
2287 */
2288 nOrderBy = 0;
2289 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00002290 int n = pOrderBy->nExpr;
2291 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00002292 Expr *pExpr = pOrderBy->a[i].pExpr;
2293 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
2294 }
drh56f1b992012-09-25 14:29:39 +00002295 if( i==n){
2296 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00002297 }
2298 }
2299
2300 /* Allocate the sqlite3_index_info structure
2301 */
2302 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
2303 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
2304 + sizeof(*pIdxOrderBy)*nOrderBy );
2305 if( pIdxInfo==0 ){
2306 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00002307 return 0;
2308 }
2309
2310 /* Initialize the structure. The sqlite3_index_info structure contains
2311 ** many fields that are declared "const" to prevent xBestIndex from
2312 ** changing them. We have to do some funky casting in order to
2313 ** initialize those fields.
2314 */
2315 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
2316 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
2317 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
2318 *(int*)&pIdxInfo->nConstraint = nTerm;
2319 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
2320 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
2321 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
2322 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
2323 pUsage;
2324
2325 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00002326 u8 op;
danielk19771d461462009-04-21 09:02:45 +00002327 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00002328 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2329 testcase( pTerm->eOperator & WO_IN );
2330 testcase( pTerm->eOperator & WO_ISNULL );
drh281bbe22012-10-16 23:17:14 +00002331 if( pTerm->eOperator & (WO_ISNULL) ) continue;
drhb4256992011-08-02 01:57:39 +00002332 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00002333 pIdxCons[j].iColumn = pTerm->u.leftColumn;
2334 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00002335 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00002336 if( op==WO_IN ) op = WO_EQ;
2337 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00002338 /* The direct assignment in the previous line is possible only because
2339 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
2340 ** following asserts verify this fact. */
2341 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
2342 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
2343 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
2344 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
2345 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
2346 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00002347 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00002348 j++;
2349 }
2350 for(i=0; i<nOrderBy; i++){
2351 Expr *pExpr = pOrderBy->a[i].pExpr;
2352 pIdxOrderBy[i].iColumn = pExpr->iColumn;
2353 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
2354 }
2355
2356 return pIdxInfo;
2357}
2358
2359/*
2360** The table object reference passed as the second argument to this function
2361** must represent a virtual table. This function invokes the xBestIndex()
drh3b48e8c2013-06-12 20:18:16 +00002362** method of the virtual table with the sqlite3_index_info object that
2363** comes in as the 3rd argument to this function.
danielk19771d461462009-04-21 09:02:45 +00002364**
2365** If an error occurs, pParse is populated with an error message and a
2366** non-zero value is returned. Otherwise, 0 is returned and the output
2367** part of the sqlite3_index_info structure is left populated.
2368**
2369** Whether or not an error is returned, it is the responsibility of the
2370** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
2371** that this is required.
2372*/
2373static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00002374 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00002375 int i;
2376 int rc;
2377
danielk19771d461462009-04-21 09:02:45 +00002378 TRACE_IDX_INPUTS(p);
2379 rc = pVtab->pModule->xBestIndex(pVtab, p);
2380 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00002381
2382 if( rc!=SQLITE_OK ){
2383 if( rc==SQLITE_NOMEM ){
2384 pParse->db->mallocFailed = 1;
2385 }else if( !pVtab->zErrMsg ){
2386 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
2387 }else{
2388 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
2389 }
2390 }
drhb9755982010-07-24 16:34:37 +00002391 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00002392 pVtab->zErrMsg = 0;
2393
2394 for(i=0; i<p->nConstraint; i++){
2395 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
2396 sqlite3ErrorMsg(pParse,
2397 "table %s: xBestIndex returned an invalid plan", pTab->zName);
2398 }
2399 }
2400
2401 return pParse->nErr;
2402}
drh7ba39a92013-05-30 17:43:19 +00002403#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00002404
2405
drhfaacf172011-08-12 01:51:45 +00002406#ifdef SQLITE_ENABLE_STAT3
drh28c4cf42005-07-27 20:41:43 +00002407/*
drhfaacf172011-08-12 01:51:45 +00002408** Estimate the location of a particular key among all keys in an
2409** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00002410**
drhfaacf172011-08-12 01:51:45 +00002411** aStat[0] Est. number of rows less than pVal
2412** aStat[1] Est. number of rows equal to pVal
dan02fa4692009-08-17 17:06:58 +00002413**
drhfaacf172011-08-12 01:51:45 +00002414** Return SQLITE_OK on success.
dan02fa4692009-08-17 17:06:58 +00002415*/
drhfaacf172011-08-12 01:51:45 +00002416static int whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00002417 Parse *pParse, /* Database connection */
2418 Index *pIdx, /* Index to consider domain of */
2419 sqlite3_value *pVal, /* Value to consider */
drhfaacf172011-08-12 01:51:45 +00002420 int roundUp, /* Round up if true. Round down if false */
2421 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00002422){
drhfaacf172011-08-12 01:51:45 +00002423 tRowcnt n;
2424 IndexSample *aSample;
2425 int i, eType;
2426 int isEq = 0;
drh4e50c5e2011-08-13 19:35:19 +00002427 i64 v;
drhb8a8e8a2013-06-10 19:12:39 +00002428 double r, rS;
dan02fa4692009-08-17 17:06:58 +00002429
drhfaacf172011-08-12 01:51:45 +00002430 assert( roundUp==0 || roundUp==1 );
drh5c624862011-09-22 18:46:34 +00002431 assert( pIdx->nSample>0 );
drhfaacf172011-08-12 01:51:45 +00002432 if( pVal==0 ) return SQLITE_ERROR;
2433 n = pIdx->aiRowEst[0];
2434 aSample = pIdx->aSample;
drhfaacf172011-08-12 01:51:45 +00002435 eType = sqlite3_value_type(pVal);
2436
2437 if( eType==SQLITE_INTEGER ){
drh4e50c5e2011-08-13 19:35:19 +00002438 v = sqlite3_value_int64(pVal);
2439 r = (i64)v;
drhfaacf172011-08-12 01:51:45 +00002440 for(i=0; i<pIdx->nSample; i++){
2441 if( aSample[i].eType==SQLITE_NULL ) continue;
2442 if( aSample[i].eType>=SQLITE_TEXT ) break;
drh4e50c5e2011-08-13 19:35:19 +00002443 if( aSample[i].eType==SQLITE_INTEGER ){
2444 if( aSample[i].u.i>=v ){
2445 isEq = aSample[i].u.i==v;
2446 break;
2447 }
2448 }else{
2449 assert( aSample[i].eType==SQLITE_FLOAT );
2450 if( aSample[i].u.r>=r ){
2451 isEq = aSample[i].u.r==r;
2452 break;
2453 }
dan02fa4692009-08-17 17:06:58 +00002454 }
drhfaacf172011-08-12 01:51:45 +00002455 }
2456 }else if( eType==SQLITE_FLOAT ){
drh4e50c5e2011-08-13 19:35:19 +00002457 r = sqlite3_value_double(pVal);
drhfaacf172011-08-12 01:51:45 +00002458 for(i=0; i<pIdx->nSample; i++){
2459 if( aSample[i].eType==SQLITE_NULL ) continue;
2460 if( aSample[i].eType>=SQLITE_TEXT ) break;
drh4e50c5e2011-08-13 19:35:19 +00002461 if( aSample[i].eType==SQLITE_FLOAT ){
2462 rS = aSample[i].u.r;
2463 }else{
2464 rS = aSample[i].u.i;
2465 }
2466 if( rS>=r ){
2467 isEq = rS==r;
drhfaacf172011-08-12 01:51:45 +00002468 break;
drh9b3eb0a2011-01-21 14:37:04 +00002469 }
drhfaacf172011-08-12 01:51:45 +00002470 }
2471 }else if( eType==SQLITE_NULL ){
2472 i = 0;
drh5c624862011-09-22 18:46:34 +00002473 if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
drhfaacf172011-08-12 01:51:45 +00002474 }else{
2475 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
2476 for(i=0; i<pIdx->nSample; i++){
2477 if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
2478 break;
2479 }
2480 }
2481 if( i<pIdx->nSample ){
dan02fa4692009-08-17 17:06:58 +00002482 sqlite3 *db = pParse->db;
2483 CollSeq *pColl;
2484 const u8 *z;
dan02fa4692009-08-17 17:06:58 +00002485 if( eType==SQLITE_BLOB ){
2486 z = (const u8 *)sqlite3_value_blob(pVal);
2487 pColl = db->pDfltColl;
dane275dc32009-08-18 16:24:58 +00002488 assert( pColl->enc==SQLITE_UTF8 );
dan02fa4692009-08-17 17:06:58 +00002489 }else{
drh79e72a52012-10-05 14:43:40 +00002490 pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
drh472eae82013-06-20 17:32:28 +00002491 /* If the collating sequence was unavailable, we should have failed
2492 ** long ago and never reached this point. But we'll check just to
2493 ** be doubly sure. */
2494 if( NEVER(pColl==0) ) return SQLITE_ERROR;
dan02fa4692009-08-17 17:06:58 +00002495 z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
dane275dc32009-08-18 16:24:58 +00002496 if( !z ){
2497 return SQLITE_NOMEM;
2498 }
dan02fa4692009-08-17 17:06:58 +00002499 assert( z && pColl && pColl->xCmp );
2500 }
2501 n = sqlite3ValueBytes(pVal, pColl->enc);
drhfaacf172011-08-12 01:51:45 +00002502
2503 for(; i<pIdx->nSample; i++){
drhe847d322011-01-20 02:56:37 +00002504 int c;
dan02fa4692009-08-17 17:06:58 +00002505 int eSampletype = aSample[i].eType;
drhfaacf172011-08-12 01:51:45 +00002506 if( eSampletype<eType ) continue;
2507 if( eSampletype!=eType ) break;
dane83c4f32009-09-21 16:34:24 +00002508#ifndef SQLITE_OMIT_UTF16
2509 if( pColl->enc!=SQLITE_UTF8 ){
dane275dc32009-08-18 16:24:58 +00002510 int nSample;
2511 char *zSample = sqlite3Utf8to16(
dan02fa4692009-08-17 17:06:58 +00002512 db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
2513 );
dane275dc32009-08-18 16:24:58 +00002514 if( !zSample ){
2515 assert( db->mallocFailed );
2516 return SQLITE_NOMEM;
2517 }
drhe847d322011-01-20 02:56:37 +00002518 c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
dane275dc32009-08-18 16:24:58 +00002519 sqlite3DbFree(db, zSample);
dane83c4f32009-09-21 16:34:24 +00002520 }else
2521#endif
2522 {
drhe847d322011-01-20 02:56:37 +00002523 c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
dan02fa4692009-08-17 17:06:58 +00002524 }
drhfaacf172011-08-12 01:51:45 +00002525 if( c>=0 ){
2526 if( c==0 ) isEq = 1;
2527 break;
2528 }
dan02fa4692009-08-17 17:06:58 +00002529 }
2530 }
drhfaacf172011-08-12 01:51:45 +00002531 }
dan02fa4692009-08-17 17:06:58 +00002532
drhfaacf172011-08-12 01:51:45 +00002533 /* At this point, aSample[i] is the first sample that is greater than
2534 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
2535 ** than pVal. If aSample[i]==pVal, then isEq==1.
2536 */
2537 if( isEq ){
2538 assert( i<pIdx->nSample );
2539 aStat[0] = aSample[i].nLt;
2540 aStat[1] = aSample[i].nEq;
2541 }else{
2542 tRowcnt iLower, iUpper, iGap;
2543 if( i==0 ){
2544 iLower = 0;
2545 iUpper = aSample[0].nLt;
drhfaacf172011-08-12 01:51:45 +00002546 }else{
drh4e50c5e2011-08-13 19:35:19 +00002547 iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
drhfaacf172011-08-12 01:51:45 +00002548 iLower = aSample[i-1].nEq + aSample[i-1].nLt;
drhfaacf172011-08-12 01:51:45 +00002549 }
drh4e50c5e2011-08-13 19:35:19 +00002550 aStat[1] = pIdx->avgEq;
drhfaacf172011-08-12 01:51:45 +00002551 if( iLower>=iUpper ){
2552 iGap = 0;
2553 }else{
2554 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00002555 }
2556 if( roundUp ){
2557 iGap = (iGap*2)/3;
2558 }else{
2559 iGap = iGap/3;
2560 }
2561 aStat[0] = iLower + iGap;
dan02fa4692009-08-17 17:06:58 +00002562 }
2563 return SQLITE_OK;
2564}
drhfaacf172011-08-12 01:51:45 +00002565#endif /* SQLITE_ENABLE_STAT3 */
dan02fa4692009-08-17 17:06:58 +00002566
2567/*
dan937d0de2009-10-15 18:35:38 +00002568** If expression pExpr represents a literal value, set *pp to point to
2569** an sqlite3_value structure containing the same value, with affinity
2570** aff applied to it, before returning. It is the responsibility of the
2571** caller to eventually release this structure by passing it to
2572** sqlite3ValueFree().
2573**
2574** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
2575** is an SQL variable that currently has a non-NULL value bound to it,
2576** create an sqlite3_value structure containing this value, again with
2577** affinity aff applied to it, instead.
2578**
2579** If neither of the above apply, set *pp to NULL.
2580**
2581** If an error occurs, return an error code. Otherwise, SQLITE_OK.
2582*/
drhfaacf172011-08-12 01:51:45 +00002583#ifdef SQLITE_ENABLE_STAT3
dan937d0de2009-10-15 18:35:38 +00002584static int valueFromExpr(
2585 Parse *pParse,
2586 Expr *pExpr,
2587 u8 aff,
2588 sqlite3_value **pp
2589){
drh4278d532010-12-16 19:52:52 +00002590 if( pExpr->op==TK_VARIABLE
2591 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
2592 ){
dan937d0de2009-10-15 18:35:38 +00002593 int iVar = pExpr->iColumn;
drhf9b22ca2011-10-21 16:47:31 +00002594 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
dan937d0de2009-10-15 18:35:38 +00002595 *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
2596 return SQLITE_OK;
2597 }
2598 return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
2599}
danf7b0b0a2009-10-19 15:52:32 +00002600#endif
dan937d0de2009-10-15 18:35:38 +00002601
2602/*
dan02fa4692009-08-17 17:06:58 +00002603** This function is used to estimate the number of rows that will be visited
2604** by scanning an index for a range of values. The range may have an upper
2605** bound, a lower bound, or both. The WHERE clause terms that set the upper
2606** and lower bounds are represented by pLower and pUpper respectively. For
2607** example, assuming that index p is on t1(a):
2608**
2609** ... FROM t1 WHERE a > ? AND a < ? ...
2610** |_____| |_____|
2611** | |
2612** pLower pUpper
2613**
drh98cdf622009-08-20 18:14:42 +00002614** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00002615** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00002616**
2617** The nEq parameter is passed the index of the index column subject to the
2618** range constraint. Or, equivalently, the number of equality constraints
2619** optimized by the proposed index scan. For example, assuming index p is
2620** on t1(a, b), and the SQL query is:
2621**
2622** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2623**
2624** then nEq should be passed the value 1 (as the range restricted column,
2625** b, is the second left-most column of the index). Or, if the query is:
2626**
2627** ... FROM t1 WHERE a > ? AND a < ? ...
2628**
2629** then nEq should be passed 0.
2630**
drhfaacf172011-08-12 01:51:45 +00002631** The returned value is an integer divisor to reduce the estimated
2632** search space. A return value of 1 means that range constraints are
2633** no help at all. A return value of 2 means range constraints are
2634** expected to reduce the search space by half. And so forth...
drh98cdf622009-08-20 18:14:42 +00002635**
drhfaacf172011-08-12 01:51:45 +00002636** In the absence of sqlite_stat3 ANALYZE data, each range inequality
2637** reduces the search space by a factor of 4. Hence a single constraint (x>?)
2638** results in a return of 4 and a range constraint (x>? AND x<?) results
2639** in a return of 16.
dan02fa4692009-08-17 17:06:58 +00002640*/
2641static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002642 Parse *pParse, /* Parsing & code generating context */
2643 Index *p, /* The index containing the range-compared column; "x" */
2644 int nEq, /* index into p->aCol[] of the range-compared column */
2645 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2646 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
drh4efc9292013-06-06 23:02:03 +00002647 WhereCost *pRangeDiv /* OUT: Reduce search space by this divisor */
dan02fa4692009-08-17 17:06:58 +00002648){
dan69188d92009-08-19 08:18:32 +00002649 int rc = SQLITE_OK;
2650
drhfaacf172011-08-12 01:51:45 +00002651#ifdef SQLITE_ENABLE_STAT3
dan02fa4692009-08-17 17:06:58 +00002652
drh40aa9362013-06-28 17:29:25 +00002653 if( nEq==0 && p->nSample && OptimizationEnabled(pParse->db, SQLITE_Stat3) ){
drhfaacf172011-08-12 01:51:45 +00002654 sqlite3_value *pRangeVal;
2655 tRowcnt iLower = 0;
2656 tRowcnt iUpper = p->aiRowEst[0];
2657 tRowcnt a[2];
dan937d0de2009-10-15 18:35:38 +00002658 u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
drh98cdf622009-08-20 18:14:42 +00002659
dan02fa4692009-08-17 17:06:58 +00002660 if( pLower ){
2661 Expr *pExpr = pLower->pExpr->pRight;
drhfaacf172011-08-12 01:51:45 +00002662 rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
drh7a5bcc02013-01-16 17:08:58 +00002663 assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
drhfaacf172011-08-12 01:51:45 +00002664 if( rc==SQLITE_OK
2665 && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
2666 ){
2667 iLower = a[0];
drh7a5bcc02013-01-16 17:08:58 +00002668 if( (pLower->eOperator & WO_GT)!=0 ) iLower += a[1];
drhfaacf172011-08-12 01:51:45 +00002669 }
2670 sqlite3ValueFree(pRangeVal);
dan02fa4692009-08-17 17:06:58 +00002671 }
drh98cdf622009-08-20 18:14:42 +00002672 if( rc==SQLITE_OK && pUpper ){
dan02fa4692009-08-17 17:06:58 +00002673 Expr *pExpr = pUpper->pExpr->pRight;
drhfaacf172011-08-12 01:51:45 +00002674 rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
drh7a5bcc02013-01-16 17:08:58 +00002675 assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
drhfaacf172011-08-12 01:51:45 +00002676 if( rc==SQLITE_OK
2677 && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
2678 ){
2679 iUpper = a[0];
drh7a5bcc02013-01-16 17:08:58 +00002680 if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
dan02fa4692009-08-17 17:06:58 +00002681 }
drhfaacf172011-08-12 01:51:45 +00002682 sqlite3ValueFree(pRangeVal);
dan02fa4692009-08-17 17:06:58 +00002683 }
drhfaacf172011-08-12 01:51:45 +00002684 if( rc==SQLITE_OK ){
drhe1e2e9a2013-06-13 15:16:53 +00002685 WhereCost iBase = whereCost(p->aiRowEst[0]);
drhb8a8e8a2013-06-10 19:12:39 +00002686 if( iUpper>iLower ){
drhe1e2e9a2013-06-13 15:16:53 +00002687 iBase -= whereCost(iUpper - iLower);
drhfaacf172011-08-12 01:51:45 +00002688 }
drhb8a8e8a2013-06-10 19:12:39 +00002689 *pRangeDiv = iBase;
drh3b48e8c2013-06-12 20:18:16 +00002690 WHERETRACE(0x100, ("range scan regions: %u..%u div=%d\n",
2691 (u32)iLower, (u32)iUpper, *pRangeDiv));
drhfaacf172011-08-12 01:51:45 +00002692 return SQLITE_OK;
drh98cdf622009-08-20 18:14:42 +00002693 }
dan02fa4692009-08-17 17:06:58 +00002694 }
drh3f022182009-09-09 16:10:50 +00002695#else
2696 UNUSED_PARAMETER(pParse);
2697 UNUSED_PARAMETER(p);
2698 UNUSED_PARAMETER(nEq);
dan69188d92009-08-19 08:18:32 +00002699#endif
dan02fa4692009-08-17 17:06:58 +00002700 assert( pLower || pUpper );
drhb8a8e8a2013-06-10 19:12:39 +00002701 *pRangeDiv = 0;
drhe1e2e9a2013-06-13 15:16:53 +00002702 /* TUNING: Each inequality constraint reduces the search space 4-fold.
2703 ** A BETWEEN operator, therefore, reduces the search space 16-fold */
drhb8a8e8a2013-06-10 19:12:39 +00002704 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00002705 *pRangeDiv += 20; assert( 20==whereCost(4) );
drhb8a8e8a2013-06-10 19:12:39 +00002706 }
2707 if( pUpper ){
drhe1e2e9a2013-06-13 15:16:53 +00002708 *pRangeDiv += 20; assert( 20==whereCost(4) );
drhb8a8e8a2013-06-10 19:12:39 +00002709 }
dan02fa4692009-08-17 17:06:58 +00002710 return rc;
2711}
2712
drhfaacf172011-08-12 01:51:45 +00002713#ifdef SQLITE_ENABLE_STAT3
drh82759752011-01-20 16:52:09 +00002714/*
2715** Estimate the number of rows that will be returned based on
2716** an equality constraint x=VALUE and where that VALUE occurs in
2717** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002718** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002719** for that index. When pExpr==NULL that means the constraint is
2720** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002721**
drh0c50fa02011-01-21 16:27:18 +00002722** Write the estimated row count into *pnRow and return SQLITE_OK.
2723** If unable to make an estimate, leave *pnRow unchanged and return
2724** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002725**
2726** This routine can fail if it is unable to load a collating sequence
2727** required for string comparison, or if unable to allocate memory
2728** for a UTF conversion required for comparison. The error is stored
2729** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002730*/
drh041e09f2011-04-07 19:56:21 +00002731static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002732 Parse *pParse, /* Parsing & code generating context */
2733 Index *p, /* The index whose left-most column is pTerm */
drh0c50fa02011-01-21 16:27:18 +00002734 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drhb8a8e8a2013-06-10 19:12:39 +00002735 tRowcnt *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002736){
2737 sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
drh82759752011-01-20 16:52:09 +00002738 u8 aff; /* Column affinity */
2739 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002740 tRowcnt a[2]; /* Statistics */
drh82759752011-01-20 16:52:09 +00002741
2742 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002743 assert( p->nSample>0 );
drh82759752011-01-20 16:52:09 +00002744 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
drh1f9c7662011-03-17 01:34:26 +00002745 if( pExpr ){
2746 rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
2747 if( rc ) goto whereEqualScanEst_cancel;
2748 }else{
2749 pRhs = sqlite3ValueNew(pParse->db);
2750 }
drh0c50fa02011-01-21 16:27:18 +00002751 if( pRhs==0 ) return SQLITE_NOTFOUND;
drhfaacf172011-08-12 01:51:45 +00002752 rc = whereKeyStats(pParse, p, pRhs, 0, a);
2753 if( rc==SQLITE_OK ){
drh3b48e8c2013-06-12 20:18:16 +00002754 WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
drhfaacf172011-08-12 01:51:45 +00002755 *pnRow = a[1];
drh82759752011-01-20 16:52:09 +00002756 }
drh0c50fa02011-01-21 16:27:18 +00002757whereEqualScanEst_cancel:
drh82759752011-01-20 16:52:09 +00002758 sqlite3ValueFree(pRhs);
drh0c50fa02011-01-21 16:27:18 +00002759 return rc;
2760}
drhfaacf172011-08-12 01:51:45 +00002761#endif /* defined(SQLITE_ENABLE_STAT3) */
drh0c50fa02011-01-21 16:27:18 +00002762
drhfaacf172011-08-12 01:51:45 +00002763#ifdef SQLITE_ENABLE_STAT3
drh0c50fa02011-01-21 16:27:18 +00002764/*
2765** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002766** an IN constraint where the right-hand side of the IN operator
2767** is a list of values. Example:
2768**
2769** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002770**
2771** Write the estimated row count into *pnRow and return SQLITE_OK.
2772** If unable to make an estimate, leave *pnRow unchanged and return
2773** non-zero.
2774**
2775** This routine can fail if it is unable to load a collating sequence
2776** required for string comparison, or if unable to allocate memory
2777** for a UTF conversion required for comparison. The error is stored
2778** in the pParse structure.
2779*/
drh041e09f2011-04-07 19:56:21 +00002780static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002781 Parse *pParse, /* Parsing & code generating context */
2782 Index *p, /* The index whose left-most column is pTerm */
2783 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drhb8a8e8a2013-06-10 19:12:39 +00002784 tRowcnt *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002785){
drhb8a8e8a2013-06-10 19:12:39 +00002786 int rc = SQLITE_OK; /* Subfunction return code */
2787 tRowcnt nEst; /* Number of rows for a single term */
2788 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2789 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002790
2791 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002792 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2793 nEst = p->aiRowEst[0];
2794 rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
2795 nRowEst += nEst;
drh0c50fa02011-01-21 16:27:18 +00002796 }
2797 if( rc==SQLITE_OK ){
drh0c50fa02011-01-21 16:27:18 +00002798 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
2799 *pnRow = nRowEst;
drh3b48e8c2013-06-12 20:18:16 +00002800 WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
drh0c50fa02011-01-21 16:27:18 +00002801 }
drh0c50fa02011-01-21 16:27:18 +00002802 return rc;
drh82759752011-01-20 16:52:09 +00002803}
drhfaacf172011-08-12 01:51:45 +00002804#endif /* defined(SQLITE_ENABLE_STAT3) */
drh82759752011-01-20 16:52:09 +00002805
drh46c35f92012-09-26 23:17:01 +00002806/*
drh2ffb1182004-07-19 19:14:01 +00002807** Disable a term in the WHERE clause. Except, do not disable the term
2808** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2809** or USING clause of that join.
2810**
2811** Consider the term t2.z='ok' in the following queries:
2812**
2813** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2814** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2815** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2816**
drh23bf66d2004-12-14 03:34:34 +00002817** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002818** in the ON clause. The term is disabled in (3) because it is not part
2819** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2820**
drhe9cdcea2010-07-22 22:40:03 +00002821** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
2822** completely satisfied by indices.
2823**
drh2ffb1182004-07-19 19:14:01 +00002824** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002825** of the join. Disabling is an optimization. When terms are satisfied
2826** by indices, we disable them to prevent redundant tests in the inner
2827** loop. We would get the correct results if nothing were ever disabled,
2828** but joins might run a little slower. The trick is to disable as much
2829** as we can without disabling too much. If we disabled in (1), we'd get
2830** the wrong answer. See ticket #813.
drh2ffb1182004-07-19 19:14:01 +00002831*/
drh0fcef5e2005-07-19 17:38:22 +00002832static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
2833 if( pTerm
drhbe837bd2010-04-30 21:03:24 +00002834 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002835 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
2836 ){
drh165be382008-12-05 02:36:33 +00002837 pTerm->wtFlags |= TERM_CODED;
drh45b1ee42005-08-02 17:48:22 +00002838 if( pTerm->iParent>=0 ){
2839 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
2840 if( (--pOther->nChild)==0 ){
drhed378002005-07-28 23:12:08 +00002841 disableTerm(pLevel, pOther);
2842 }
drh0fcef5e2005-07-19 17:38:22 +00002843 }
drh2ffb1182004-07-19 19:14:01 +00002844 }
2845}
2846
2847/*
dan69f8bb92009-08-13 19:21:16 +00002848** Code an OP_Affinity opcode to apply the column affinity string zAff
2849** to the n registers starting at base.
2850**
drh039fc322009-11-17 18:31:47 +00002851** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2852** beginning and end of zAff are ignored. If all entries in zAff are
2853** SQLITE_AFF_NONE, then no code gets generated.
2854**
2855** This routine makes its own copy of zAff so that the caller is free
2856** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002857*/
dan69f8bb92009-08-13 19:21:16 +00002858static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2859 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002860 if( zAff==0 ){
2861 assert( pParse->db->mallocFailed );
2862 return;
2863 }
dan69f8bb92009-08-13 19:21:16 +00002864 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002865
2866 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2867 ** and end of the affinity string.
2868 */
2869 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2870 n--;
2871 base++;
2872 zAff++;
2873 }
2874 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2875 n--;
2876 }
2877
2878 /* Code the OP_Affinity opcode if there is anything left to do. */
2879 if( n>0 ){
2880 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2881 sqlite3VdbeChangeP4(v, -1, zAff, n);
2882 sqlite3ExprCacheAffinityChange(pParse, base, n);
2883 }
drh94a11212004-09-25 13:12:14 +00002884}
2885
drhe8b97272005-07-19 22:22:12 +00002886
2887/*
drh51147ba2005-07-23 22:59:55 +00002888** Generate code for a single equality term of the WHERE clause. An equality
2889** term can be either X=expr or X IN (...). pTerm is the term to be
2890** coded.
2891**
drh1db639c2008-01-17 02:36:28 +00002892** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002893**
2894** For a constraint of the form X=expr, the expression is evaluated and its
2895** result is left on the stack. For constraints of the form X IN (...)
2896** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002897*/
drh678ccce2008-03-31 18:19:54 +00002898static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002899 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002900 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh0fe456b2013-03-12 18:34:50 +00002901 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
2902 int iEq, /* Index of the equality term within this level */
drh7ba39a92013-05-30 17:43:19 +00002903 int bRev, /* True for reverse-order IN operations */
drh678ccce2008-03-31 18:19:54 +00002904 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002905){
drh0fcef5e2005-07-19 17:38:22 +00002906 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002907 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002908 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002909
danielk19772d605492008-10-01 08:43:03 +00002910 assert( iTarget>0 );
drh50b39962006-10-28 00:28:09 +00002911 if( pX->op==TK_EQ ){
drh678ccce2008-03-31 18:19:54 +00002912 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002913 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002914 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002915 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002916#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002917 }else{
danielk19779a96b662007-11-29 17:05:18 +00002918 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002919 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002920 struct InLoop *pIn;
drh7ba39a92013-05-30 17:43:19 +00002921 WhereLoop *pLoop = pLevel->pWLoop;
danielk1977b3bce662005-01-29 08:32:43 +00002922
drh7ba39a92013-05-30 17:43:19 +00002923 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
2924 && pLoop->u.btree.pIndex!=0
2925 && pLoop->u.btree.pIndex->aSortOrder[iEq]
drhd3832162013-03-12 18:49:25 +00002926 ){
drh725e1ae2013-03-12 23:58:42 +00002927 testcase( iEq==0 );
drh725e1ae2013-03-12 23:58:42 +00002928 testcase( bRev );
drh1ccce442013-03-12 20:38:51 +00002929 bRev = !bRev;
drh0fe456b2013-03-12 18:34:50 +00002930 }
drh50b39962006-10-28 00:28:09 +00002931 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002932 iReg = iTarget;
danielk19770cdc0222008-06-26 18:04:03 +00002933 eType = sqlite3FindInIndex(pParse, pX, 0);
drh725e1ae2013-03-12 23:58:42 +00002934 if( eType==IN_INDEX_INDEX_DESC ){
2935 testcase( bRev );
2936 bRev = !bRev;
2937 }
danielk1977b3bce662005-01-29 08:32:43 +00002938 iTab = pX->iTable;
drh2d96b932013-02-08 18:48:23 +00002939 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
drh6fa978d2013-05-30 19:29:19 +00002940 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
2941 pLoop->wsFlags |= WHERE_IN_ABLE;
drh111a6a72008-12-21 03:51:16 +00002942 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002943 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00002944 }
drh111a6a72008-12-21 03:51:16 +00002945 pLevel->u.in.nIn++;
2946 pLevel->u.in.aInLoop =
2947 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2948 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2949 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00002950 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00002951 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00002952 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00002953 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00002954 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00002955 }else{
drhb3190c12008-12-08 21:37:14 +00002956 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00002957 }
drh2d96b932013-02-08 18:48:23 +00002958 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
drh1db639c2008-01-17 02:36:28 +00002959 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
drha6110402005-07-28 20:51:19 +00002960 }else{
drh111a6a72008-12-21 03:51:16 +00002961 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00002962 }
danielk1977b3bce662005-01-29 08:32:43 +00002963#endif
drh94a11212004-09-25 13:12:14 +00002964 }
drh0fcef5e2005-07-19 17:38:22 +00002965 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00002966 return iReg;
drh94a11212004-09-25 13:12:14 +00002967}
2968
drh51147ba2005-07-23 22:59:55 +00002969/*
2970** Generate code that will evaluate all == and IN constraints for an
drh039fc322009-11-17 18:31:47 +00002971** index.
drh51147ba2005-07-23 22:59:55 +00002972**
2973** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2974** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
2975** The index has as many as three equality constraints, but in this
2976** example, the third "c" value is an inequality. So only two
2977** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00002978** a==5 and b IN (1,2,3). The current values for a and b will be stored
2979** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00002980**
2981** In the example above nEq==2. But this subroutine works for any value
2982** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00002983** The only thing it does is allocate the pLevel->iMem memory cell and
2984** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00002985**
drh700a2262008-12-17 19:22:15 +00002986** This routine always allocates at least one memory cell and returns
2987** the index of that memory cell. The code that
2988** calls this routine will use that memory cell to store the termination
drh51147ba2005-07-23 22:59:55 +00002989** key value of the loop. If one or more IN operators appear, then
2990** this routine allocates an additional nEq memory cells for internal
2991** use.
dan69f8bb92009-08-13 19:21:16 +00002992**
2993** Before returning, *pzAff is set to point to a buffer containing a
2994** copy of the column affinity string of the index allocated using
2995** sqlite3DbMalloc(). Except, entries in the copy of the string associated
2996** with equality constraints that use NONE affinity are set to
2997** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
2998**
2999** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
3000** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
3001**
3002** In the example above, the index on t1(a) has TEXT affinity. But since
3003** the right hand side of the equality constraint (t2.b) has NONE affinity,
3004** no conversion should be attempted before using a t2.b value as part of
3005** a key to search the index. Hence the first byte in the returned affinity
3006** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00003007*/
drh1db639c2008-01-17 02:36:28 +00003008static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00003009 Parse *pParse, /* Parsing context */
3010 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
drh7ba39a92013-05-30 17:43:19 +00003011 int bRev, /* Reverse the order of IN operators */
dan69f8bb92009-08-13 19:21:16 +00003012 int nExtraReg, /* Number of extra registers to allocate */
3013 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00003014){
drh7ba39a92013-05-30 17:43:19 +00003015 int nEq; /* The number of == or IN constraints to code */
drh111a6a72008-12-21 03:51:16 +00003016 Vdbe *v = pParse->pVdbe; /* The vm under construction */
3017 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00003018 WhereTerm *pTerm; /* A single constraint term */
drh7ba39a92013-05-30 17:43:19 +00003019 WhereLoop *pLoop; /* The WhereLoop object */
drh51147ba2005-07-23 22:59:55 +00003020 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00003021 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00003022 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00003023 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00003024
drh111a6a72008-12-21 03:51:16 +00003025 /* This module is only called on query plans that use an index. */
drh7ba39a92013-05-30 17:43:19 +00003026 pLoop = pLevel->pWLoop;
3027 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
3028 nEq = pLoop->u.btree.nEq;
3029 pIdx = pLoop->u.btree.pIndex;
3030 assert( pIdx!=0 );
drh111a6a72008-12-21 03:51:16 +00003031
drh51147ba2005-07-23 22:59:55 +00003032 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00003033 */
drh700a2262008-12-17 19:22:15 +00003034 regBase = pParse->nMem + 1;
drh7ba39a92013-05-30 17:43:19 +00003035 nReg = pLoop->u.btree.nEq + nExtraReg;
drh6df2acd2008-12-28 16:55:25 +00003036 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00003037
dan69f8bb92009-08-13 19:21:16 +00003038 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
3039 if( !zAff ){
3040 pParse->db->mallocFailed = 1;
3041 }
3042
drh51147ba2005-07-23 22:59:55 +00003043 /* Evaluate the equality constraints
3044 */
drhc49de5d2007-01-19 01:06:01 +00003045 assert( pIdx->nColumn>=nEq );
3046 for(j=0; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00003047 int r1;
drh4efc9292013-06-06 23:02:03 +00003048 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00003049 assert( pTerm!=0 );
drhbe837bd2010-04-30 21:03:24 +00003050 /* The following true for indices with redundant columns.
3051 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
3052 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drhe9cdcea2010-07-22 22:40:03 +00003053 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh7ba39a92013-05-30 17:43:19 +00003054 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
drh678ccce2008-03-31 18:19:54 +00003055 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00003056 if( nReg==1 ){
3057 sqlite3ReleaseTempReg(pParse, regBase);
3058 regBase = r1;
3059 }else{
3060 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
3061 }
drh678ccce2008-03-31 18:19:54 +00003062 }
drh981642f2008-04-19 14:40:43 +00003063 testcase( pTerm->eOperator & WO_ISNULL );
3064 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00003065 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00003066 Expr *pRight = pTerm->pExpr->pRight;
drh2f2855b2009-11-18 01:25:26 +00003067 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
drh039fc322009-11-17 18:31:47 +00003068 if( zAff ){
3069 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
3070 zAff[j] = SQLITE_AFF_NONE;
3071 }
3072 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
3073 zAff[j] = SQLITE_AFF_NONE;
3074 }
dan69f8bb92009-08-13 19:21:16 +00003075 }
drh51147ba2005-07-23 22:59:55 +00003076 }
3077 }
dan69f8bb92009-08-13 19:21:16 +00003078 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00003079 return regBase;
drh51147ba2005-07-23 22:59:55 +00003080}
3081
dan2ce22452010-11-08 19:01:16 +00003082#ifndef SQLITE_OMIT_EXPLAIN
dan17c0bc02010-11-09 17:35:19 +00003083/*
drh69174c42010-11-12 15:35:59 +00003084** This routine is a helper for explainIndexRange() below
3085**
3086** pStr holds the text of an expression that we are building up one term
3087** at a time. This routine adds a new term to the end of the expression.
3088** Terms are separated by AND so add the "AND" text for second and subsequent
3089** terms only.
3090*/
3091static void explainAppendTerm(
3092 StrAccum *pStr, /* The text expression being built */
3093 int iTerm, /* Index of this term. First is zero */
3094 const char *zColumn, /* Name of the column */
3095 const char *zOp /* Name of the operator */
3096){
3097 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
3098 sqlite3StrAccumAppend(pStr, zColumn, -1);
3099 sqlite3StrAccumAppend(pStr, zOp, 1);
3100 sqlite3StrAccumAppend(pStr, "?", 1);
3101}
3102
3103/*
dan17c0bc02010-11-09 17:35:19 +00003104** Argument pLevel describes a strategy for scanning table pTab. This
3105** function returns a pointer to a string buffer containing a description
3106** of the subset of table rows scanned by the strategy in the form of an
3107** SQL expression. Or, if all rows are scanned, NULL is returned.
3108**
3109** For example, if the query:
3110**
3111** SELECT * FROM t1 WHERE a=1 AND b>2;
3112**
3113** is run and there is an index on (a, b), then this function returns a
3114** string similar to:
3115**
3116** "a=? AND b>?"
3117**
3118** The returned pointer points to memory obtained from sqlite3DbMalloc().
3119** It is the responsibility of the caller to free the buffer when it is
3120** no longer required.
3121*/
drhef866372013-05-22 20:49:02 +00003122static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
3123 Index *pIndex = pLoop->u.btree.pIndex;
3124 int nEq = pLoop->u.btree.nEq;
drh69174c42010-11-12 15:35:59 +00003125 int i, j;
3126 Column *aCol = pTab->aCol;
3127 int *aiColumn = pIndex->aiColumn;
3128 StrAccum txt;
dan2ce22452010-11-08 19:01:16 +00003129
drhef866372013-05-22 20:49:02 +00003130 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
drh69174c42010-11-12 15:35:59 +00003131 return 0;
3132 }
3133 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
drh03b6df12010-11-15 16:29:30 +00003134 txt.db = db;
drh69174c42010-11-12 15:35:59 +00003135 sqlite3StrAccumAppend(&txt, " (", 2);
dan2ce22452010-11-08 19:01:16 +00003136 for(i=0; i<nEq; i++){
drh69174c42010-11-12 15:35:59 +00003137 explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
dan2ce22452010-11-08 19:01:16 +00003138 }
3139
drh69174c42010-11-12 15:35:59 +00003140 j = i;
drhef866372013-05-22 20:49:02 +00003141 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
dan0c733f62011-11-16 15:27:09 +00003142 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
3143 explainAppendTerm(&txt, i++, z, ">");
dan2ce22452010-11-08 19:01:16 +00003144 }
drhef866372013-05-22 20:49:02 +00003145 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
dan0c733f62011-11-16 15:27:09 +00003146 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
3147 explainAppendTerm(&txt, i, z, "<");
dan2ce22452010-11-08 19:01:16 +00003148 }
drh69174c42010-11-12 15:35:59 +00003149 sqlite3StrAccumAppend(&txt, ")", 1);
3150 return sqlite3StrAccumFinish(&txt);
dan2ce22452010-11-08 19:01:16 +00003151}
3152
dan17c0bc02010-11-09 17:35:19 +00003153/*
3154** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
3155** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
3156** record is added to the output to describe the table scan strategy in
3157** pLevel.
3158*/
3159static void explainOneScan(
dan2ce22452010-11-08 19:01:16 +00003160 Parse *pParse, /* Parse context */
3161 SrcList *pTabList, /* Table list this loop refers to */
3162 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
3163 int iLevel, /* Value for "level" column of output */
dan4a07e3d2010-11-09 14:48:59 +00003164 int iFrom, /* Value for "from" column of output */
3165 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
dan2ce22452010-11-08 19:01:16 +00003166){
3167 if( pParse->explain==2 ){
dan2ce22452010-11-08 19:01:16 +00003168 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
dan17c0bc02010-11-09 17:35:19 +00003169 Vdbe *v = pParse->pVdbe; /* VM being constructed */
3170 sqlite3 *db = pParse->db; /* Database handle */
3171 char *zMsg; /* Text to add to EQP output */
dan4a07e3d2010-11-09 14:48:59 +00003172 int iId = pParse->iSelectId; /* Select id (left-most output column) */
dan4bc39fa2010-11-13 16:42:27 +00003173 int isSearch; /* True for a SEARCH. False for SCAN. */
drhef866372013-05-22 20:49:02 +00003174 WhereLoop *pLoop; /* The controlling WhereLoop object */
3175 u32 flags; /* Flags that describe this loop */
dan2ce22452010-11-08 19:01:16 +00003176
drhef866372013-05-22 20:49:02 +00003177 pLoop = pLevel->pWLoop;
3178 flags = pLoop->wsFlags;
dan4a07e3d2010-11-09 14:48:59 +00003179 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
dan2ce22452010-11-08 19:01:16 +00003180
drhef866372013-05-22 20:49:02 +00003181 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
3182 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
3183 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
dan4bc39fa2010-11-13 16:42:27 +00003184
3185 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
dan4a07e3d2010-11-09 14:48:59 +00003186 if( pItem->pSelect ){
dan4bc39fa2010-11-13 16:42:27 +00003187 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
dan4a07e3d2010-11-09 14:48:59 +00003188 }else{
dan4bc39fa2010-11-13 16:42:27 +00003189 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
dan4a07e3d2010-11-09 14:48:59 +00003190 }
3191
dan2ce22452010-11-08 19:01:16 +00003192 if( pItem->zAlias ){
3193 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
3194 }
drhef866372013-05-22 20:49:02 +00003195 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
drh7963b0e2013-06-17 21:37:40 +00003196 && ALWAYS(pLoop->u.btree.pIndex!=0)
drhef866372013-05-22 20:49:02 +00003197 ){
3198 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
drh986b3872013-06-28 21:12:20 +00003199 zMsg = sqlite3MAppendf(db, zMsg,
3200 ((flags & WHERE_AUTO_INDEX) ?
3201 "%s USING AUTOMATIC %sINDEX%.0s%s" :
3202 "%s USING %sINDEX %s%s"),
3203 zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
3204 pLoop->u.btree.pIndex->zName, zWhere);
dan2ce22452010-11-08 19:01:16 +00003205 sqlite3DbFree(db, zWhere);
drhef71c1f2013-06-04 12:58:02 +00003206 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
dan4bc39fa2010-11-13 16:42:27 +00003207 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
dan2ce22452010-11-08 19:01:16 +00003208
drh8e23daf2013-06-11 13:30:04 +00003209 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
dan2ce22452010-11-08 19:01:16 +00003210 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
drh04098e62010-11-15 21:50:19 +00003211 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
dan2ce22452010-11-08 19:01:16 +00003212 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
3213 }else if( flags&WHERE_BTM_LIMIT ){
3214 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
drh7963b0e2013-06-17 21:37:40 +00003215 }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
dan2ce22452010-11-08 19:01:16 +00003216 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
3217 }
3218 }
3219#ifndef SQLITE_OMIT_VIRTUALTABLE
3220 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
dan2ce22452010-11-08 19:01:16 +00003221 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
drhef866372013-05-22 20:49:02 +00003222 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
dan2ce22452010-11-08 19:01:16 +00003223 }
3224#endif
drhb8a8e8a2013-06-10 19:12:39 +00003225 zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
dan4a07e3d2010-11-09 14:48:59 +00003226 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
dan2ce22452010-11-08 19:01:16 +00003227 }
3228}
3229#else
dan17c0bc02010-11-09 17:35:19 +00003230# define explainOneScan(u,v,w,x,y,z)
dan2ce22452010-11-08 19:01:16 +00003231#endif /* SQLITE_OMIT_EXPLAIN */
3232
3233
drh111a6a72008-12-21 03:51:16 +00003234/*
3235** Generate code for the start of the iLevel-th loop in the WHERE clause
3236** implementation described by pWInfo.
3237*/
3238static Bitmask codeOneLoopStart(
3239 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
3240 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh7a484802012-03-16 00:28:11 +00003241 Bitmask notReady /* Which tables are currently available */
drh111a6a72008-12-21 03:51:16 +00003242){
3243 int j, k; /* Loop counters */
3244 int iCur; /* The VDBE cursor for the table */
3245 int addrNxt; /* Where to jump to continue with the next IN case */
3246 int omitTable; /* True if we use the index only */
3247 int bRev; /* True if we need to scan in reverse order */
3248 WhereLevel *pLevel; /* The where level to be coded */
drh7ba39a92013-05-30 17:43:19 +00003249 WhereLoop *pLoop; /* The WhereLoop object being coded */
drh111a6a72008-12-21 03:51:16 +00003250 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
3251 WhereTerm *pTerm; /* A WHERE clause term */
3252 Parse *pParse; /* Parsing context */
drh6b36e822013-07-30 15:10:32 +00003253 sqlite3 *db; /* Database connection */
drh111a6a72008-12-21 03:51:16 +00003254 Vdbe *v; /* The prepared stmt under constructions */
3255 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00003256 int addrBrk; /* Jump here to break out of the loop */
3257 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00003258 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
3259 int iReleaseReg = 0; /* Temp register to free before returning */
drh0c41d222013-04-22 02:39:10 +00003260 Bitmask newNotReady; /* Return value */
drh111a6a72008-12-21 03:51:16 +00003261
3262 pParse = pWInfo->pParse;
3263 v = pParse->pVdbe;
drh70d18342013-06-06 19:16:33 +00003264 pWC = &pWInfo->sWC;
drh6b36e822013-07-30 15:10:32 +00003265 db = pParse->db;
drh111a6a72008-12-21 03:51:16 +00003266 pLevel = &pWInfo->a[iLevel];
drh7ba39a92013-05-30 17:43:19 +00003267 pLoop = pLevel->pWLoop;
drh111a6a72008-12-21 03:51:16 +00003268 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
3269 iCur = pTabItem->iCursor;
drh7ba39a92013-05-30 17:43:19 +00003270 bRev = (pWInfo->revMask>>iLevel)&1;
3271 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drh70d18342013-06-06 19:16:33 +00003272 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
drh0c41d222013-04-22 02:39:10 +00003273 VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
drh111a6a72008-12-21 03:51:16 +00003274
3275 /* Create labels for the "break" and "continue" instructions
3276 ** for the current loop. Jump to addrBrk to break out of a loop.
3277 ** Jump to cont to go immediately to the next iteration of the
3278 ** loop.
3279 **
3280 ** When there is an IN operator, we also have a "addrNxt" label that
3281 ** means to continue with the next IN value combination. When
3282 ** there are no IN operators in the constraints, the "addrNxt" label
3283 ** is the same as "addrBrk".
3284 */
3285 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
3286 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
3287
3288 /* If this is the right table of a LEFT OUTER JOIN, allocate and
3289 ** initialize a memory cell that records if this table matches any
3290 ** row of the left table of the join.
3291 */
3292 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
3293 pLevel->iLeftJoin = ++pParse->nMem;
3294 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
3295 VdbeComment((v, "init LEFT JOIN no-match flag"));
3296 }
3297
drh21172c42012-10-30 00:29:07 +00003298 /* Special case of a FROM clause subquery implemented as a co-routine */
3299 if( pTabItem->viaCoroutine ){
3300 int regYield = pTabItem->regReturn;
3301 sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
3302 pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
3303 VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
3304 sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
3305 pLevel->op = OP_Goto;
3306 }else
3307
drh111a6a72008-12-21 03:51:16 +00003308#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00003309 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
3310 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
drh111a6a72008-12-21 03:51:16 +00003311 ** to access the data.
3312 */
3313 int iReg; /* P3 Value for OP_VFilter */
drh281bbe22012-10-16 23:17:14 +00003314 int addrNotFound;
drh4efc9292013-06-06 23:02:03 +00003315 int nConstraint = pLoop->nLTerm;
drh111a6a72008-12-21 03:51:16 +00003316
drha62bb8d2009-11-23 21:23:45 +00003317 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00003318 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh281bbe22012-10-16 23:17:14 +00003319 addrNotFound = pLevel->addrBrk;
drh111a6a72008-12-21 03:51:16 +00003320 for(j=0; j<nConstraint; j++){
drhe2250172013-05-31 18:13:50 +00003321 int iTarget = iReg+j+2;
drh4efc9292013-06-06 23:02:03 +00003322 pTerm = pLoop->aLTerm[j];
drh95ed68d2013-06-12 17:55:50 +00003323 if( pTerm==0 ) continue;
drh7ba39a92013-05-30 17:43:19 +00003324 if( pTerm->eOperator & WO_IN ){
3325 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
3326 addrNotFound = pLevel->addrNxt;
3327 }else{
3328 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
3329 }
3330 }
3331 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
drh7e47cb82013-05-31 17:55:27 +00003332 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
drh7ba39a92013-05-30 17:43:19 +00003333 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
3334 pLoop->u.vtab.idxStr,
3335 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
3336 pLoop->u.vtab.needFree = 0;
3337 for(j=0; j<nConstraint && j<16; j++){
3338 if( (pLoop->u.vtab.omitMask>>j)&1 ){
drh4efc9292013-06-06 23:02:03 +00003339 disableTerm(pLevel, pLoop->aLTerm[j]);
drh111a6a72008-12-21 03:51:16 +00003340 }
3341 }
3342 pLevel->op = OP_VNext;
3343 pLevel->p1 = iCur;
3344 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00003345 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drha62bb8d2009-11-23 21:23:45 +00003346 sqlite3ExprCachePop(pParse, 1);
drh111a6a72008-12-21 03:51:16 +00003347 }else
3348#endif /* SQLITE_OMIT_VIRTUALTABLE */
3349
drh7ba39a92013-05-30 17:43:19 +00003350 if( (pLoop->wsFlags & WHERE_IPK)!=0
3351 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
3352 ){
3353 /* Case 2: We can directly reference a single row using an
drh111a6a72008-12-21 03:51:16 +00003354 ** equality comparison against the ROWID field. Or
3355 ** we reference multiple rows using a "rowid IN (...)"
3356 ** construct.
3357 */
drh7ba39a92013-05-30 17:43:19 +00003358 assert( pLoop->u.btree.nEq==1 );
danielk19771d461462009-04-21 09:02:45 +00003359 iReleaseReg = sqlite3GetTempReg(pParse);
drh4efc9292013-06-06 23:02:03 +00003360 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003361 assert( pTerm!=0 );
3362 assert( pTerm->pExpr!=0 );
drh111a6a72008-12-21 03:51:16 +00003363 assert( omitTable==0 );
drhe9cdcea2010-07-22 22:40:03 +00003364 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh7ba39a92013-05-30 17:43:19 +00003365 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00003366 addrNxt = pLevel->addrNxt;
danielk19771d461462009-04-21 09:02:45 +00003367 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
3368 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drh459f63e2013-03-06 01:55:27 +00003369 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
drhceea3322009-04-23 13:22:42 +00003370 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00003371 VdbeComment((v, "pk"));
3372 pLevel->op = OP_Noop;
drh7ba39a92013-05-30 17:43:19 +00003373 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
3374 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
3375 ){
3376 /* Case 3: We have an inequality comparison against the ROWID field.
drh111a6a72008-12-21 03:51:16 +00003377 */
3378 int testOp = OP_Noop;
3379 int start;
3380 int memEndValue = 0;
3381 WhereTerm *pStart, *pEnd;
3382
3383 assert( omitTable==0 );
drh7ba39a92013-05-30 17:43:19 +00003384 j = 0;
3385 pStart = pEnd = 0;
drh4efc9292013-06-06 23:02:03 +00003386 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
3387 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
drh81186b42013-06-18 01:52:41 +00003388 assert( pStart!=0 || pEnd!=0 );
drh111a6a72008-12-21 03:51:16 +00003389 if( bRev ){
3390 pTerm = pStart;
3391 pStart = pEnd;
3392 pEnd = pTerm;
3393 }
3394 if( pStart ){
3395 Expr *pX; /* The expression that defines the start bound */
3396 int r1, rTemp; /* Registers for holding the start boundary */
3397
3398 /* The following constant maps TK_xx codes into corresponding
3399 ** seek opcodes. It depends on a particular ordering of TK_xx
3400 */
3401 const u8 aMoveOp[] = {
3402 /* TK_GT */ OP_SeekGt,
3403 /* TK_LE */ OP_SeekLe,
3404 /* TK_LT */ OP_SeekLt,
3405 /* TK_GE */ OP_SeekGe
3406 };
3407 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
3408 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
3409 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
3410
drhb5246e52013-07-08 21:12:57 +00003411 assert( (pStart->wtFlags & TERM_VNULL)==0 );
drhe9cdcea2010-07-22 22:40:03 +00003412 testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003413 pX = pStart->pExpr;
3414 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003415 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
drh111a6a72008-12-21 03:51:16 +00003416 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
3417 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
3418 VdbeComment((v, "pk"));
3419 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
3420 sqlite3ReleaseTempReg(pParse, rTemp);
3421 disableTerm(pLevel, pStart);
3422 }else{
3423 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
3424 }
3425 if( pEnd ){
3426 Expr *pX;
3427 pX = pEnd->pExpr;
3428 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003429 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
3430 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
drhe9cdcea2010-07-22 22:40:03 +00003431 testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003432 memEndValue = ++pParse->nMem;
3433 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
3434 if( pX->op==TK_LT || pX->op==TK_GT ){
3435 testOp = bRev ? OP_Le : OP_Ge;
3436 }else{
3437 testOp = bRev ? OP_Lt : OP_Gt;
3438 }
3439 disableTerm(pLevel, pEnd);
3440 }
3441 start = sqlite3VdbeCurrentAddr(v);
3442 pLevel->op = bRev ? OP_Prev : OP_Next;
3443 pLevel->p1 = iCur;
3444 pLevel->p2 = start;
drh81186b42013-06-18 01:52:41 +00003445 assert( pLevel->p5==0 );
danielk19771d461462009-04-21 09:02:45 +00003446 if( testOp!=OP_Noop ){
3447 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3448 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003449 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003450 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
3451 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003452 }
drh1b0f0262013-05-30 22:27:09 +00003453 }else if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00003454 /* Case 4: A scan using an index.
drh111a6a72008-12-21 03:51:16 +00003455 **
3456 ** The WHERE clause may contain zero or more equality
3457 ** terms ("==" or "IN" operators) that refer to the N
3458 ** left-most columns of the index. It may also contain
3459 ** inequality constraints (>, <, >= or <=) on the indexed
3460 ** column that immediately follows the N equalities. Only
3461 ** the right-most column can be an inequality - the rest must
3462 ** use the "==" and "IN" operators. For example, if the
3463 ** index is on (x,y,z), then the following clauses are all
3464 ** optimized:
3465 **
3466 ** x=5
3467 ** x=5 AND y=10
3468 ** x=5 AND y<10
3469 ** x=5 AND y>5 AND y<10
3470 ** x=5 AND y=5 AND z<=10
3471 **
3472 ** The z<10 term of the following cannot be used, only
3473 ** the x=5 term:
3474 **
3475 ** x=5 AND z<10
3476 **
3477 ** N may be zero if there are inequality constraints.
3478 ** If there are no inequality constraints, then N is at
3479 ** least one.
3480 **
3481 ** This case is also used when there are no WHERE clause
3482 ** constraints but an index is selected anyway, in order
3483 ** to force the output order to conform to an ORDER BY.
3484 */
drh3bb9b932010-08-06 02:10:00 +00003485 static const u8 aStartOp[] = {
drh111a6a72008-12-21 03:51:16 +00003486 0,
3487 0,
3488 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
3489 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
3490 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
3491 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
3492 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
3493 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
3494 };
drh3bb9b932010-08-06 02:10:00 +00003495 static const u8 aEndOp[] = {
drh111a6a72008-12-21 03:51:16 +00003496 OP_Noop, /* 0: (!end_constraints) */
3497 OP_IdxGE, /* 1: (end_constraints && !bRev) */
3498 OP_IdxLT /* 2: (end_constraints && bRev) */
3499 };
drh7ba39a92013-05-30 17:43:19 +00003500 int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
3501 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
drh111a6a72008-12-21 03:51:16 +00003502 int regBase; /* Base register holding constraint values */
3503 int r1; /* Temp register */
3504 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
3505 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
3506 int startEq; /* True if range start uses ==, >= or <= */
3507 int endEq; /* True if range end uses ==, >= or <= */
3508 int start_constraints; /* Start of range is constrained */
3509 int nConstraint; /* Number of constraint terms */
drh3bb9b932010-08-06 02:10:00 +00003510 Index *pIdx; /* The index we will be using */
3511 int iIdxCur; /* The VDBE cursor for the index */
3512 int nExtraReg = 0; /* Number of extra registers needed */
3513 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00003514 char *zStartAff; /* Affinity for start of range constraint */
3515 char *zEndAff; /* Affinity for end of range constraint */
drh111a6a72008-12-21 03:51:16 +00003516
drh7ba39a92013-05-30 17:43:19 +00003517 pIdx = pLoop->u.btree.pIndex;
drh111a6a72008-12-21 03:51:16 +00003518 iIdxCur = pLevel->iIdxCur;
drh111a6a72008-12-21 03:51:16 +00003519
drh111a6a72008-12-21 03:51:16 +00003520 /* If this loop satisfies a sort order (pOrderBy) request that
3521 ** was passed to this function to implement a "SELECT min(x) ..."
3522 ** query, then the caller will only allow the loop to run for
3523 ** a single iteration. This means that the first row returned
3524 ** should not have a NULL value stored in 'x'. If column 'x' is
3525 ** the first one after the nEq equality constraints in the index,
3526 ** this requires some special handling.
3527 */
drh70d18342013-06-06 19:16:33 +00003528 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
drh4f402f22013-06-11 18:59:38 +00003529 && (pWInfo->bOBSat!=0)
drh111a6a72008-12-21 03:51:16 +00003530 && (pIdx->nColumn>nEq)
3531 ){
3532 /* assert( pOrderBy->nExpr==1 ); */
3533 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
3534 isMinQuery = 1;
drh6df2acd2008-12-28 16:55:25 +00003535 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003536 }
3537
3538 /* Find any inequality constraint terms for the start and end
3539 ** of the range.
3540 */
drh7ba39a92013-05-30 17:43:19 +00003541 j = nEq;
3542 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003543 pRangeStart = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003544 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003545 }
drh7ba39a92013-05-30 17:43:19 +00003546 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003547 pRangeEnd = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003548 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003549 }
3550
drh6df2acd2008-12-28 16:55:25 +00003551 /* Generate code to evaluate all constraint terms using == or IN
3552 ** and store the values of those terms in an array of registers
3553 ** starting at regBase.
3554 */
drh613ba1e2013-06-15 15:11:45 +00003555 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
drh6b36e822013-07-30 15:10:32 +00003556 zEndAff = sqlite3DbStrDup(db, zStartAff);
drh6df2acd2008-12-28 16:55:25 +00003557 addrNxt = pLevel->addrNxt;
3558
drh111a6a72008-12-21 03:51:16 +00003559 /* If we are doing a reverse order scan on an ascending index, or
3560 ** a forward order scan on a descending index, interchange the
3561 ** start and end terms (pRangeStart and pRangeEnd).
3562 */
dan0c733f62011-11-16 15:27:09 +00003563 if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3564 || (bRev && pIdx->nColumn==nEq)
3565 ){
drh111a6a72008-12-21 03:51:16 +00003566 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
3567 }
3568
drh7963b0e2013-06-17 21:37:40 +00003569 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
3570 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
3571 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
3572 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
drh111a6a72008-12-21 03:51:16 +00003573 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3574 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3575 start_constraints = pRangeStart || nEq>0;
3576
3577 /* Seek the index cursor to the start of the range. */
3578 nConstraint = nEq;
3579 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003580 Expr *pRight = pRangeStart->pExpr->pRight;
3581 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003582 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
3583 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3584 }
dan6ac43392010-06-09 15:47:11 +00003585 if( zStartAff ){
3586 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003587 /* Since the comparison is to be performed with no conversions
3588 ** applied to the operands, set the affinity to apply to pRight to
3589 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003590 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003591 }
dan6ac43392010-06-09 15:47:11 +00003592 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3593 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003594 }
3595 }
drh111a6a72008-12-21 03:51:16 +00003596 nConstraint++;
drhe9cdcea2010-07-22 22:40:03 +00003597 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003598 }else if( isMinQuery ){
3599 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3600 nConstraint++;
3601 startEq = 0;
3602 start_constraints = 1;
3603 }
dan6ac43392010-06-09 15:47:11 +00003604 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003605 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3606 assert( op!=0 );
3607 testcase( op==OP_Rewind );
3608 testcase( op==OP_Last );
3609 testcase( op==OP_SeekGt );
3610 testcase( op==OP_SeekGe );
3611 testcase( op==OP_SeekLe );
3612 testcase( op==OP_SeekLt );
drh8cff69d2009-11-12 19:59:44 +00003613 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh111a6a72008-12-21 03:51:16 +00003614
3615 /* Load the value for the inequality constraint at the end of the
3616 ** range (if any).
3617 */
3618 nConstraint = nEq;
3619 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003620 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003621 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003622 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003623 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
3624 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3625 }
dan6ac43392010-06-09 15:47:11 +00003626 if( zEndAff ){
3627 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003628 /* Since the comparison is to be performed with no conversions
3629 ** applied to the operands, set the affinity to apply to pRight to
3630 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003631 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003632 }
dan6ac43392010-06-09 15:47:11 +00003633 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
3634 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003635 }
3636 }
dan6ac43392010-06-09 15:47:11 +00003637 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003638 nConstraint++;
drhe9cdcea2010-07-22 22:40:03 +00003639 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003640 }
drh6b36e822013-07-30 15:10:32 +00003641 sqlite3DbFree(db, zStartAff);
3642 sqlite3DbFree(db, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003643
3644 /* Top of the loop body */
3645 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3646
3647 /* Check if the index cursor is past the end of the range. */
3648 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
3649 testcase( op==OP_Noop );
3650 testcase( op==OP_IdxGE );
3651 testcase( op==OP_IdxLT );
drh6df2acd2008-12-28 16:55:25 +00003652 if( op!=OP_Noop ){
drh8cff69d2009-11-12 19:59:44 +00003653 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh6df2acd2008-12-28 16:55:25 +00003654 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
3655 }
drh111a6a72008-12-21 03:51:16 +00003656
3657 /* If there are inequality constraints, check that the value
3658 ** of the table column that the inequality contrains is not NULL.
3659 ** If it is, jump to the next iteration of the loop.
3660 */
3661 r1 = sqlite3GetTempReg(pParse);
drh37ca0482013-06-12 17:17:45 +00003662 testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
3663 testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
drh7ba39a92013-05-30 17:43:19 +00003664 if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
drh111a6a72008-12-21 03:51:16 +00003665 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
3666 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
3667 }
danielk19771d461462009-04-21 09:02:45 +00003668 sqlite3ReleaseTempReg(pParse, r1);
drh111a6a72008-12-21 03:51:16 +00003669
3670 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003671 disableTerm(pLevel, pRangeStart);
3672 disableTerm(pLevel, pRangeEnd);
danielk19771d461462009-04-21 09:02:45 +00003673 if( !omitTable ){
3674 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3675 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003676 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003677 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drh111a6a72008-12-21 03:51:16 +00003678 }
drh111a6a72008-12-21 03:51:16 +00003679
3680 /* Record the instruction used to terminate the loop. Disable
3681 ** WHERE clause terms made redundant by the index range scan.
3682 */
drh7699d1c2013-06-04 12:42:29 +00003683 if( pLoop->wsFlags & WHERE_ONEROW ){
drh95e037b2011-03-09 21:02:31 +00003684 pLevel->op = OP_Noop;
3685 }else if( bRev ){
3686 pLevel->op = OP_Prev;
3687 }else{
3688 pLevel->op = OP_Next;
3689 }
drh111a6a72008-12-21 03:51:16 +00003690 pLevel->p1 = iIdxCur;
drh53cfbe92013-06-13 17:28:22 +00003691 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
drh3f4d1d12012-09-15 18:45:54 +00003692 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3693 }else{
3694 assert( pLevel->p5==0 );
3695 }
drhdd5f5a62008-12-23 13:35:23 +00003696 }else
3697
drh23d04d52008-12-23 23:56:22 +00003698#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drh7ba39a92013-05-30 17:43:19 +00003699 if( pLoop->wsFlags & WHERE_MULTI_OR ){
3700 /* Case 5: Two or more separately indexed terms connected by OR
drh111a6a72008-12-21 03:51:16 +00003701 **
3702 ** Example:
3703 **
3704 ** CREATE TABLE t1(a,b,c,d);
3705 ** CREATE INDEX i1 ON t1(a);
3706 ** CREATE INDEX i2 ON t1(b);
3707 ** CREATE INDEX i3 ON t1(c);
3708 **
3709 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3710 **
3711 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003712 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003713 **
drh1b26c7c2009-04-22 02:15:47 +00003714 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003715 **
danielk19771d461462009-04-21 09:02:45 +00003716 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003717 ** RowSetTest are such that the rowid of the current row is inserted
3718 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003719 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003720 **
danielk19771d461462009-04-21 09:02:45 +00003721 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003722 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003723 ** Gosub 2 A
3724 ** sqlite3WhereEnd()
3725 **
3726 ** Following the above, code to terminate the loop. Label A, the target
3727 ** of the Gosub above, jumps to the instruction right after the Goto.
3728 **
drh1b26c7c2009-04-22 02:15:47 +00003729 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003730 ** Goto B # The loop is finished.
3731 **
3732 ** A: <loop body> # Return data, whatever.
3733 **
3734 ** Return 2 # Jump back to the Gosub
3735 **
3736 ** B: <after the loop>
3737 **
drh111a6a72008-12-21 03:51:16 +00003738 */
drh111a6a72008-12-21 03:51:16 +00003739 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
drhc01a3c12009-12-16 22:10:49 +00003740 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
dan0efb72c2012-08-24 18:44:56 +00003741 Index *pCov = 0; /* Potential covering index (or NULL) */
3742 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
danielk19771d461462009-04-21 09:02:45 +00003743
3744 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003745 int regRowset = 0; /* Register for RowSet object */
3746 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003747 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3748 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003749 int untestedTerms = 0; /* Some terms not completely tested */
drh8871ef52011-10-07 13:33:10 +00003750 int ii; /* Loop counter */
3751 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
drh111a6a72008-12-21 03:51:16 +00003752
drh4efc9292013-06-06 23:02:03 +00003753 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003754 assert( pTerm!=0 );
drh7a5bcc02013-01-16 17:08:58 +00003755 assert( pTerm->eOperator & WO_OR );
drh111a6a72008-12-21 03:51:16 +00003756 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3757 pOrWc = &pTerm->u.pOrInfo->wc;
drhc01a3c12009-12-16 22:10:49 +00003758 pLevel->op = OP_Return;
3759 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003760
danbfca6a42012-08-24 10:52:35 +00003761 /* Set up a new SrcList in pOrTab containing the table being scanned
drhc01a3c12009-12-16 22:10:49 +00003762 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3763 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3764 */
3765 if( pWInfo->nLevel>1 ){
3766 int nNotReady; /* The number of notReady tables */
3767 struct SrcList_item *origSrc; /* Original list of tables */
3768 nNotReady = pWInfo->nLevel - iLevel - 1;
drh6b36e822013-07-30 15:10:32 +00003769 pOrTab = sqlite3StackAllocRaw(db,
drhc01a3c12009-12-16 22:10:49 +00003770 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3771 if( pOrTab==0 ) return notReady;
drhad01d892013-06-19 13:59:49 +00003772 pOrTab->nAlloc = (u8)(nNotReady + 1);
shaneh46aae3c2009-12-31 19:06:23 +00003773 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003774 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3775 origSrc = pWInfo->pTabList->a;
3776 for(k=1; k<=nNotReady; k++){
3777 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3778 }
3779 }else{
3780 pOrTab = pWInfo->pTabList;
3781 }
danielk19771d461462009-04-21 09:02:45 +00003782
drh1b26c7c2009-04-22 02:15:47 +00003783 /* Initialize the rowset register to contain NULL. An SQL NULL is
3784 ** equivalent to an empty rowset.
danielk19771d461462009-04-21 09:02:45 +00003785 **
3786 ** Also initialize regReturn to contain the address of the instruction
3787 ** immediately following the OP_Return at the bottom of the loop. This
3788 ** is required in a few obscure LEFT JOIN cases where control jumps
3789 ** over the top of the loop into the body of it. In this case the
3790 ** correct response for the end-of-loop code (the OP_Return) is to
3791 ** fall through to the next instruction, just as an OP_Next does if
3792 ** called on an uninitialized cursor.
3793 */
drh70d18342013-06-06 19:16:33 +00003794 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003795 regRowset = ++pParse->nMem;
3796 regRowid = ++pParse->nMem;
3797 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3798 }
danielk19771d461462009-04-21 09:02:45 +00003799 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3800
drh8871ef52011-10-07 13:33:10 +00003801 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
3802 ** Then for every term xN, evaluate as the subexpression: xN AND z
3803 ** That way, terms in y that are factored into the disjunction will
3804 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
drh331b67c2012-03-09 22:02:08 +00003805 **
3806 ** Actually, each subexpression is converted to "xN AND w" where w is
3807 ** the "interesting" terms of z - terms that did not originate in the
3808 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3809 ** indices.
drhb3129fa2013-05-09 14:20:11 +00003810 **
3811 ** This optimization also only applies if the (x1 OR x2 OR ...) term
3812 ** is not contained in the ON clause of a LEFT JOIN.
3813 ** See ticket http://www.sqlite.org/src/info/f2369304e4
drh8871ef52011-10-07 13:33:10 +00003814 */
3815 if( pWC->nTerm>1 ){
drh7a484802012-03-16 00:28:11 +00003816 int iTerm;
3817 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3818 Expr *pExpr = pWC->a[iTerm].pExpr;
drhaa32e3c2013-07-16 21:31:23 +00003819 if( &pWC->a[iTerm] == pTerm ) continue;
drh331b67c2012-03-09 22:02:08 +00003820 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drhaa32e3c2013-07-16 21:31:23 +00003821 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue;
drh7a484802012-03-16 00:28:11 +00003822 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
drh6b36e822013-07-30 15:10:32 +00003823 pExpr = sqlite3ExprDup(db, pExpr, 0);
3824 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
drh331b67c2012-03-09 22:02:08 +00003825 }
3826 if( pAndExpr ){
3827 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3828 }
drh8871ef52011-10-07 13:33:10 +00003829 }
3830
danielk19771d461462009-04-21 09:02:45 +00003831 for(ii=0; ii<pOrWc->nTerm; ii++){
3832 WhereTerm *pOrTerm = &pOrWc->a[ii];
drh7a5bcc02013-01-16 17:08:58 +00003833 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
danielk19771d461462009-04-21 09:02:45 +00003834 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
drh8871ef52011-10-07 13:33:10 +00003835 Expr *pOrExpr = pOrTerm->pExpr;
drhb3129fa2013-05-09 14:20:11 +00003836 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
drh8871ef52011-10-07 13:33:10 +00003837 pAndExpr->pLeft = pOrExpr;
3838 pOrExpr = pAndExpr;
3839 }
danielk19771d461462009-04-21 09:02:45 +00003840 /* Loop through table entries that match term pOrTerm. */
drh8871ef52011-10-07 13:33:10 +00003841 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
drh9ef61f42011-10-07 14:40:59 +00003842 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
dan0efb72c2012-08-24 18:44:56 +00003843 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
drh6b36e822013-07-30 15:10:32 +00003844 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
danielk19771d461462009-04-21 09:02:45 +00003845 if( pSubWInfo ){
drh7ba39a92013-05-30 17:43:19 +00003846 WhereLoop *pSubLoop;
dan17c0bc02010-11-09 17:35:19 +00003847 explainOneScan(
dan4a07e3d2010-11-09 14:48:59 +00003848 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
dan2ce22452010-11-08 19:01:16 +00003849 );
drh70d18342013-06-06 19:16:33 +00003850 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003851 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3852 int r;
3853 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
drha748fdc2012-03-28 01:34:47 +00003854 regRowid, 0);
drh8cff69d2009-11-12 19:59:44 +00003855 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
3856 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
drh336a5302009-04-24 15:46:21 +00003857 }
danielk19771d461462009-04-21 09:02:45 +00003858 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
3859
drhc01a3c12009-12-16 22:10:49 +00003860 /* The pSubWInfo->untestedTerms flag means that this OR term
3861 ** contained one or more AND term from a notReady table. The
3862 ** terms from the notReady table could not be tested and will
3863 ** need to be tested later.
3864 */
3865 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3866
danbfca6a42012-08-24 10:52:35 +00003867 /* If all of the OR-connected terms are optimized using the same
3868 ** index, and the index is opened using the same cursor number
3869 ** by each call to sqlite3WhereBegin() made by this loop, it may
3870 ** be possible to use that index as a covering index.
3871 **
3872 ** If the call to sqlite3WhereBegin() above resulted in a scan that
3873 ** uses an index, and this is either the first OR-connected term
3874 ** processed or the index is the same as that used by all previous
dan0efb72c2012-08-24 18:44:56 +00003875 ** terms, set pCov to the candidate covering index. Otherwise, set
3876 ** pCov to NULL to indicate that no candidate covering index will
3877 ** be available.
danbfca6a42012-08-24 10:52:35 +00003878 */
drh7ba39a92013-05-30 17:43:19 +00003879 pSubLoop = pSubWInfo->a[0].pWLoop;
drh986b3872013-06-28 21:12:20 +00003880 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drh7ba39a92013-05-30 17:43:19 +00003881 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
drh7ba39a92013-05-30 17:43:19 +00003882 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
danbfca6a42012-08-24 10:52:35 +00003883 ){
drh7ba39a92013-05-30 17:43:19 +00003884 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
drh907717f2013-06-04 18:03:22 +00003885 pCov = pSubLoop->u.btree.pIndex;
danbfca6a42012-08-24 10:52:35 +00003886 }else{
3887 pCov = 0;
3888 }
3889
danielk19771d461462009-04-21 09:02:45 +00003890 /* Finish the loop through table entries that match term pOrTerm. */
3891 sqlite3WhereEnd(pSubWInfo);
3892 }
drhdd5f5a62008-12-23 13:35:23 +00003893 }
3894 }
drhd40e2082012-08-24 23:24:15 +00003895 pLevel->u.pCovidx = pCov;
drh90abfd02012-10-09 21:07:23 +00003896 if( pCov ) pLevel->iIdxCur = iCovCur;
drh331b67c2012-03-09 22:02:08 +00003897 if( pAndExpr ){
3898 pAndExpr->pLeft = 0;
drh6b36e822013-07-30 15:10:32 +00003899 sqlite3ExprDelete(db, pAndExpr);
drh331b67c2012-03-09 22:02:08 +00003900 }
danielk19771d461462009-04-21 09:02:45 +00003901 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00003902 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
3903 sqlite3VdbeResolveLabel(v, iLoopBody);
3904
drh6b36e822013-07-30 15:10:32 +00003905 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
drhc01a3c12009-12-16 22:10:49 +00003906 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00003907 }else
drh23d04d52008-12-23 23:56:22 +00003908#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00003909
3910 {
drh7ba39a92013-05-30 17:43:19 +00003911 /* Case 6: There is no usable index. We must do a complete
drh111a6a72008-12-21 03:51:16 +00003912 ** scan of the entire table.
3913 */
drh699b3d42009-02-23 16:52:07 +00003914 static const u8 aStep[] = { OP_Next, OP_Prev };
3915 static const u8 aStart[] = { OP_Rewind, OP_Last };
3916 assert( bRev==0 || bRev==1 );
drh699b3d42009-02-23 16:52:07 +00003917 pLevel->op = aStep[bRev];
drh111a6a72008-12-21 03:51:16 +00003918 pLevel->p1 = iCur;
drh699b3d42009-02-23 16:52:07 +00003919 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh111a6a72008-12-21 03:51:16 +00003920 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3921 }
drh70d18342013-06-06 19:16:33 +00003922 newNotReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
drh111a6a72008-12-21 03:51:16 +00003923
3924 /* Insert code to test every subexpression that can be completely
3925 ** computed using the current set of tables.
drhe9cdcea2010-07-22 22:40:03 +00003926 **
3927 ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
3928 ** the use of indices become tests that are evaluated against each row of
3929 ** the relevant input tables.
drh111a6a72008-12-21 03:51:16 +00003930 */
drh111a6a72008-12-21 03:51:16 +00003931 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3932 Expr *pE;
drhe9cdcea2010-07-22 22:40:03 +00003933 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003934 testcase( pTerm->wtFlags & TERM_CODED );
3935 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0c41d222013-04-22 02:39:10 +00003936 if( (pTerm->prereqAll & newNotReady)!=0 ){
drhc01a3c12009-12-16 22:10:49 +00003937 testcase( pWInfo->untestedTerms==0
3938 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
3939 pWInfo->untestedTerms = 1;
3940 continue;
3941 }
drh111a6a72008-12-21 03:51:16 +00003942 pE = pTerm->pExpr;
3943 assert( pE!=0 );
3944 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
3945 continue;
3946 }
drh111a6a72008-12-21 03:51:16 +00003947 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003948 pTerm->wtFlags |= TERM_CODED;
3949 }
3950
drh0c41d222013-04-22 02:39:10 +00003951 /* Insert code to test for implied constraints based on transitivity
3952 ** of the "==" operator.
3953 **
3954 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
3955 ** and we are coding the t1 loop and the t2 loop has not yet coded,
3956 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
3957 ** the implied "t1.a=123" constraint.
3958 */
3959 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
drh6b36e822013-07-30 15:10:32 +00003960 Expr *pE, *pEAlt;
drh0c41d222013-04-22 02:39:10 +00003961 WhereTerm *pAlt;
drh0c41d222013-04-22 02:39:10 +00003962 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3963 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
3964 if( pTerm->leftCursor!=iCur ) continue;
drhcdc2e432013-07-01 17:27:19 +00003965 if( pLevel->iLeftJoin ) continue;
drh0c41d222013-04-22 02:39:10 +00003966 pE = pTerm->pExpr;
3967 assert( !ExprHasProperty(pE, EP_FromJoin) );
3968 assert( (pTerm->prereqRight & newNotReady)!=0 );
3969 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
3970 if( pAlt==0 ) continue;
drh5c10f3b2013-05-01 17:22:38 +00003971 if( pAlt->wtFlags & (TERM_CODED) ) continue;
drh7963b0e2013-06-17 21:37:40 +00003972 testcase( pAlt->eOperator & WO_EQ );
3973 testcase( pAlt->eOperator & WO_IN );
drh0c41d222013-04-22 02:39:10 +00003974 VdbeNoopComment((v, "begin transitive constraint"));
drh6b36e822013-07-30 15:10:32 +00003975 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
3976 if( pEAlt ){
3977 *pEAlt = *pAlt->pExpr;
3978 pEAlt->pLeft = pE->pLeft;
3979 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
3980 sqlite3StackFree(db, pEAlt);
3981 }
drh0c41d222013-04-22 02:39:10 +00003982 }
3983
drh111a6a72008-12-21 03:51:16 +00003984 /* For a LEFT OUTER JOIN, generate code that will record the fact that
3985 ** at least one row of the right table has matched the left table.
3986 */
3987 if( pLevel->iLeftJoin ){
3988 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
3989 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
3990 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00003991 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00003992 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drhe9cdcea2010-07-22 22:40:03 +00003993 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003994 testcase( pTerm->wtFlags & TERM_CODED );
3995 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0c41d222013-04-22 02:39:10 +00003996 if( (pTerm->prereqAll & newNotReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00003997 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00003998 continue;
3999 }
drh111a6a72008-12-21 03:51:16 +00004000 assert( pTerm->pExpr );
4001 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
4002 pTerm->wtFlags |= TERM_CODED;
4003 }
4004 }
danielk19771d461462009-04-21 09:02:45 +00004005 sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh23d04d52008-12-23 23:56:22 +00004006
drh0c41d222013-04-22 02:39:10 +00004007 return newNotReady;
drh111a6a72008-12-21 03:51:16 +00004008}
4009
drhd15cb172013-05-21 19:23:10 +00004010#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00004011/*
4012** Print a WhereLoop object for debugging purposes
4013*/
4014static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
drhb8a8e8a2013-06-10 19:12:39 +00004015 int nb = 1+(pTabList->nSrc+7)/8;
drha18f3d22013-05-08 03:05:41 +00004016 struct SrcList_item *pItem = pTabList->a + p->iTab;
4017 Table *pTab = pItem->pTab;
drh6457a352013-06-21 00:35:37 +00004018 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00004019 p->iTab, nb, p->maskSelf, nb, p->prereq);
drh6457a352013-06-21 00:35:37 +00004020 sqlite3DebugPrintf(" %12s",
drha18f3d22013-05-08 03:05:41 +00004021 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00004022 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
4023 if( p->u.btree.pIndex ){
drh319f6772013-05-14 15:31:07 +00004024 const char *zName = p->u.btree.pIndex->zName;
drhae70cf12013-05-31 15:18:46 +00004025 if( zName==0 ) zName = "ipk";
drh319f6772013-05-14 15:31:07 +00004026 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
4027 int i = sqlite3Strlen30(zName) - 1;
4028 while( zName[i]!='_' ) i--;
4029 zName += i;
4030 }
drh6457a352013-06-21 00:35:37 +00004031 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00004032 }else{
drh6457a352013-06-21 00:35:37 +00004033 sqlite3DebugPrintf("%20s","");
drh5346e952013-05-08 14:14:26 +00004034 }
drha18f3d22013-05-08 03:05:41 +00004035 }else{
drh5346e952013-05-08 14:14:26 +00004036 char *z;
4037 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00004038 z = sqlite3_mprintf("(%d,\"%s\",%x)",
4039 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00004040 }else{
drh3bd26f02013-05-24 14:52:03 +00004041 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00004042 }
drh6457a352013-06-21 00:35:37 +00004043 sqlite3DebugPrintf(" %-19s", z);
drh5346e952013-05-08 14:14:26 +00004044 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00004045 }
drh6457a352013-06-21 00:35:37 +00004046 sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
drhb8a8e8a2013-06-10 19:12:39 +00004047 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
drha18f3d22013-05-08 03:05:41 +00004048}
4049#endif
4050
drhf1b5f5b2013-05-02 00:15:01 +00004051/*
drh4efc9292013-06-06 23:02:03 +00004052** Convert bulk memory into a valid WhereLoop that can be passed
4053** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00004054*/
drh4efc9292013-06-06 23:02:03 +00004055static void whereLoopInit(WhereLoop *p){
4056 p->aLTerm = p->aLTermSpace;
4057 p->nLTerm = 0;
4058 p->nLSlot = ArraySize(p->aLTermSpace);
4059 p->wsFlags = 0;
4060}
4061
4062/*
4063** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
4064*/
4065static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh986b3872013-06-28 21:12:20 +00004066 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
drh13e11b42013-06-06 23:44:25 +00004067 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
4068 sqlite3_free(p->u.vtab.idxStr);
4069 p->u.vtab.needFree = 0;
4070 p->u.vtab.idxStr = 0;
drh986b3872013-06-28 21:12:20 +00004071 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
drh13e11b42013-06-06 23:44:25 +00004072 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
4073 sqlite3DbFree(db, p->u.btree.pIndex);
4074 p->u.btree.pIndex = 0;
4075 }
drh5346e952013-05-08 14:14:26 +00004076 }
4077}
4078
drh4efc9292013-06-06 23:02:03 +00004079/*
4080** Deallocate internal memory used by a WhereLoop object
4081*/
4082static void whereLoopClear(sqlite3 *db, WhereLoop *p){
4083 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
4084 whereLoopClearUnion(db, p);
4085 whereLoopInit(p);
4086}
4087
4088/*
4089** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
4090*/
4091static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
4092 WhereTerm **paNew;
4093 if( p->nLSlot>=n ) return SQLITE_OK;
4094 n = (n+7)&~7;
4095 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
4096 if( paNew==0 ) return SQLITE_NOMEM;
4097 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
4098 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
4099 p->aLTerm = paNew;
4100 p->nLSlot = n;
4101 return SQLITE_OK;
4102}
4103
4104/*
4105** Transfer content from the second pLoop into the first.
4106*/
4107static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
4108 if( whereLoopResize(db, pTo, pFrom->nLTerm) ) return SQLITE_NOMEM;
4109 whereLoopClearUnion(db, pTo);
drha2014152013-06-07 00:29:23 +00004110 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
4111 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00004112 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
4113 pFrom->u.vtab.needFree = 0;
drh986b3872013-06-28 21:12:20 +00004114 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00004115 pFrom->u.btree.pIndex = 0;
4116 }
4117 return SQLITE_OK;
4118}
4119
drh5346e952013-05-08 14:14:26 +00004120/*
drhf1b5f5b2013-05-02 00:15:01 +00004121** Delete a WhereLoop object
4122*/
4123static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00004124 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00004125 sqlite3DbFree(db, p);
4126}
drh84bfda42005-07-15 13:05:21 +00004127
drh9eff6162006-06-12 21:59:13 +00004128/*
4129** Free a WhereInfo structure
4130*/
drh10fe8402008-10-11 16:47:35 +00004131static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00004132 if( ALWAYS(pWInfo) ){
drh70d18342013-06-06 19:16:33 +00004133 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00004134 while( pWInfo->pLoops ){
4135 WhereLoop *p = pWInfo->pLoops;
4136 pWInfo->pLoops = p->pNextLoop;
4137 whereLoopDelete(db, p);
4138 }
drh633e6d52008-07-28 19:34:53 +00004139 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00004140 }
4141}
4142
drhf1b5f5b2013-05-02 00:15:01 +00004143/*
4144** Insert or replace a WhereLoop entry using the template supplied.
4145**
4146** An existing WhereLoop entry might be overwritten if the new template
4147** is better and has fewer dependencies. Or the template will be ignored
4148** and no insert will occur if an existing WhereLoop is faster and has
4149** fewer dependencies than the template. Otherwise a new WhereLoop is
drhd044d202013-05-31 12:43:55 +00004150** added based on the template.
drh23f98da2013-05-21 15:52:07 +00004151**
drhaa32e3c2013-07-16 21:31:23 +00004152** If pBuilder->pOrSet is not NULL then we only care about only the
4153** prerequisites and rRun and nOut costs of the N best loops. That
4154** information is gathered in the pBuilder->pOrSet object. This special
4155** processing mode is used only for OR clause processing.
drh23f98da2013-05-21 15:52:07 +00004156**
drhaa32e3c2013-07-16 21:31:23 +00004157** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
drh23f98da2013-05-21 15:52:07 +00004158** still might overwrite similar loops with the new template if the
4159** template is better. Loops may be overwritten if the following
4160** conditions are met:
4161**
4162** (1) They have the same iTab.
4163** (2) They have the same iSortIdx.
4164** (3) The template has same or fewer dependencies than the current loop
4165** (4) The template has the same or lower cost than the current loop
drhd044d202013-05-31 12:43:55 +00004166** (5) The template uses more terms of the same index but has no additional
4167** dependencies
drhf1b5f5b2013-05-02 00:15:01 +00004168*/
drhcf8fa7a2013-05-10 20:26:22 +00004169static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh4efc9292013-06-06 23:02:03 +00004170 WhereLoop **ppPrev, *p, *pNext = 0;
drhcf8fa7a2013-05-10 20:26:22 +00004171 WhereInfo *pWInfo = pBuilder->pWInfo;
drh70d18342013-06-06 19:16:33 +00004172 sqlite3 *db = pWInfo->pParse->db;
drhcf8fa7a2013-05-10 20:26:22 +00004173
drhaa32e3c2013-07-16 21:31:23 +00004174 /* If pBuilder->pOrSet is defined, then only keep track of the costs
4175 ** and prereqs.
drh23f98da2013-05-21 15:52:07 +00004176 */
drhaa32e3c2013-07-16 21:31:23 +00004177 if( pBuilder->pOrSet!=0 ){
4178#if WHERETRACE_ENABLED
4179 u16 n = pBuilder->pOrSet->n;
4180 int x =
4181#endif
4182 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
4183 pTemplate->nOut);
drhae70cf12013-05-31 15:18:46 +00004184#if WHERETRACE_ENABLED
4185 if( sqlite3WhereTrace & 0x8 ){
drhaa32e3c2013-07-16 21:31:23 +00004186 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
drh70d18342013-06-06 19:16:33 +00004187 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004188 }
4189#endif
drhcf8fa7a2013-05-10 20:26:22 +00004190 return SQLITE_OK;
4191 }
drhf1b5f5b2013-05-02 00:15:01 +00004192
4193 /* Search for an existing WhereLoop to overwrite, or which takes
4194 ** priority over pTemplate.
4195 */
4196 for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
drhdbb80232013-06-19 12:34:13 +00004197 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
4198 /* If either the iTab or iSortIdx values for two WhereLoop are different
4199 ** then those WhereLoops need to be considered separately. Neither is
4200 ** a candidate to replace the other. */
4201 continue;
4202 }
4203 /* In the current implementation, the rSetup value is either zero
4204 ** or the cost of building an automatic index (NlogN) and the NlogN
4205 ** is the same for compatible WhereLoops. */
4206 assert( p->rSetup==0 || pTemplate->rSetup==0
4207 || p->rSetup==pTemplate->rSetup );
4208
4209 /* whereLoopAddBtree() always generates and inserts the automatic index
4210 ** case first. Hence compatible candidate WhereLoops never have a larger
4211 ** rSetup. Call this SETUP-INVARIANT */
4212 assert( p->rSetup>=pTemplate->rSetup );
4213
drhf1b5f5b2013-05-02 00:15:01 +00004214 if( (p->prereq & pTemplate->prereq)==p->prereq
drhf1b5f5b2013-05-02 00:15:01 +00004215 && p->rSetup<=pTemplate->rSetup
4216 && p->rRun<=pTemplate->rRun
4217 ){
drh4a5acf82013-06-18 20:06:23 +00004218 /* This branch taken when p is equal or better than pTemplate in
4219 ** all of (1) dependences (2) setup-cost, and (3) run-cost. */
drhdbb80232013-06-19 12:34:13 +00004220 assert( p->rSetup==pTemplate->rSetup );
drh4efc9292013-06-06 23:02:03 +00004221 if( p->nLTerm<pTemplate->nLTerm
drhcd0f4072013-06-05 12:47:59 +00004222 && (p->wsFlags & WHERE_INDEXED)!=0
4223 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
4224 && p->u.btree.pIndex==pTemplate->u.btree.pIndex
4225 && p->prereq==pTemplate->prereq
4226 ){
4227 /* Overwrite an existing WhereLoop with an similar one that uses
4228 ** more terms of the index */
4229 pNext = p->pNextLoop;
drhcd0f4072013-06-05 12:47:59 +00004230 break;
4231 }else{
4232 /* pTemplate is not helpful.
4233 ** Return without changing or adding anything */
4234 goto whereLoopInsert_noop;
4235 }
drhf1b5f5b2013-05-02 00:15:01 +00004236 }
4237 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
drhf1b5f5b2013-05-02 00:15:01 +00004238 && p->rRun>=pTemplate->rRun
drhdbb80232013-06-19 12:34:13 +00004239 && ALWAYS(p->rSetup>=pTemplate->rSetup) /* See SETUP-INVARIANT above */
drhf1b5f5b2013-05-02 00:15:01 +00004240 ){
drh4a5acf82013-06-18 20:06:23 +00004241 /* Overwrite an existing WhereLoop with a better one: one that is
4242 ** better at one of (1) dependences, (2) setup-cost, or (3) run-cost
4243 ** and is no worse in any of those categories. */
drh43fe25f2013-05-07 23:06:23 +00004244 pNext = p->pNextLoop;
drhf1b5f5b2013-05-02 00:15:01 +00004245 break;
4246 }
4247 }
4248
4249 /* If we reach this point it means that either p[] should be overwritten
4250 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
4251 ** WhereLoop and insert it.
4252 */
drhae70cf12013-05-31 15:18:46 +00004253#if WHERETRACE_ENABLED
4254 if( sqlite3WhereTrace & 0x8 ){
4255 if( p!=0 ){
4256 sqlite3DebugPrintf("ins-del: ");
drh70d18342013-06-06 19:16:33 +00004257 whereLoopPrint(p, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004258 }
4259 sqlite3DebugPrintf("ins-new: ");
drh70d18342013-06-06 19:16:33 +00004260 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004261 }
4262#endif
drhf1b5f5b2013-05-02 00:15:01 +00004263 if( p==0 ){
drh4efc9292013-06-06 23:02:03 +00004264 p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00004265 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00004266 whereLoopInit(p);
drhf1b5f5b2013-05-02 00:15:01 +00004267 }
drh4efc9292013-06-06 23:02:03 +00004268 whereLoopXfer(db, p, pTemplate);
drh43fe25f2013-05-07 23:06:23 +00004269 p->pNextLoop = pNext;
4270 *ppPrev = p;
drh5346e952013-05-08 14:14:26 +00004271 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00004272 Index *pIndex = p->u.btree.pIndex;
4273 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004274 p->u.btree.pIndex = 0;
4275 }
drh5346e952013-05-08 14:14:26 +00004276 }
drhf1b5f5b2013-05-02 00:15:01 +00004277 return SQLITE_OK;
drhae70cf12013-05-31 15:18:46 +00004278
4279 /* Jump here if the insert is a no-op */
4280whereLoopInsert_noop:
4281#if WHERETRACE_ENABLED
4282 if( sqlite3WhereTrace & 0x8 ){
drhaa32e3c2013-07-16 21:31:23 +00004283 sqlite3DebugPrintf("ins-noop: ");
drh70d18342013-06-06 19:16:33 +00004284 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004285 }
4286#endif
4287 return SQLITE_OK;
drhf1b5f5b2013-05-02 00:15:01 +00004288}
4289
4290/*
drh5346e952013-05-08 14:14:26 +00004291** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
drh1c8148f2013-05-04 20:25:23 +00004292** Try to match one more.
4293**
4294** If pProbe->tnum==0, that means pIndex is a fake index used for the
4295** INTEGER PRIMARY KEY.
4296*/
drh5346e952013-05-08 14:14:26 +00004297static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00004298 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
4299 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
4300 Index *pProbe, /* An index on pSrc */
drhb8a8e8a2013-06-10 19:12:39 +00004301 WhereCost nInMul /* log(Number of iterations due to IN) */
drh1c8148f2013-05-04 20:25:23 +00004302){
drh70d18342013-06-06 19:16:33 +00004303 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
4304 Parse *pParse = pWInfo->pParse; /* Parsing context */
4305 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00004306 WhereLoop *pNew; /* Template WhereLoop under construction */
4307 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00004308 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00004309 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00004310 Bitmask saved_prereq; /* Original value of pNew->prereq */
4311 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
4312 int saved_nEq; /* Original value of pNew->u.btree.nEq */
4313 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
4314 WhereCost saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00004315 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00004316 int rc = SQLITE_OK; /* Return code */
drhb8a8e8a2013-06-10 19:12:39 +00004317 WhereCost nRowEst; /* Estimated index selectivity */
drh4efc9292013-06-06 23:02:03 +00004318 WhereCost rLogSize; /* Logarithm of table size */
drhc7f0d222013-06-19 03:27:12 +00004319 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00004320
drh1c8148f2013-05-04 20:25:23 +00004321 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00004322 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00004323
drh5346e952013-05-08 14:14:26 +00004324 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh43fe25f2013-05-07 23:06:23 +00004325 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
4326 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
4327 opMask = WO_LT|WO_LE;
4328 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
4329 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004330 }else{
drh43fe25f2013-05-07 23:06:23 +00004331 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004332 }
drhef866372013-05-22 20:49:02 +00004333 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00004334
drh7963b0e2013-06-17 21:37:40 +00004335 assert( pNew->u.btree.nEq<=pProbe->nColumn );
drh0f133a42013-05-22 17:01:17 +00004336 if( pNew->u.btree.nEq < pProbe->nColumn ){
4337 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
drhe1e2e9a2013-06-13 15:16:53 +00004338 nRowEst = whereCost(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
drhc7f0d222013-06-19 03:27:12 +00004339 if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
drh0f133a42013-05-22 17:01:17 +00004340 }else{
4341 iCol = -1;
drhb8a8e8a2013-06-10 19:12:39 +00004342 nRowEst = 0;
drh0f133a42013-05-22 17:01:17 +00004343 }
drha18f3d22013-05-08 03:05:41 +00004344 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00004345 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00004346 saved_nEq = pNew->u.btree.nEq;
4347 saved_nLTerm = pNew->nLTerm;
4348 saved_wsFlags = pNew->wsFlags;
4349 saved_prereq = pNew->prereq;
4350 saved_nOut = pNew->nOut;
drhb8a8e8a2013-06-10 19:12:39 +00004351 pNew->rSetup = 0;
drhe1e2e9a2013-06-13 15:16:53 +00004352 rLogSize = estLog(whereCost(pProbe->aiRowEst[0]));
drh5346e952013-05-08 14:14:26 +00004353 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
drhb8a8e8a2013-06-10 19:12:39 +00004354 int nIn = 0;
drh79a13bf2013-05-31 20:28:28 +00004355 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drhb5246e52013-07-08 21:12:57 +00004356#ifdef SQLITE_ENABLE_STAT3
4357 if( (pTerm->wtFlags & TERM_VNULL)!=0 && pSrc->pTab->aCol[iCol].notNull ){
4358 continue; /* skip IS NOT NULL constraints on a NOT NULL column */
4359 }
4360#endif
drh4efc9292013-06-06 23:02:03 +00004361 pNew->wsFlags = saved_wsFlags;
4362 pNew->u.btree.nEq = saved_nEq;
4363 pNew->nLTerm = saved_nLTerm;
4364 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4365 pNew->aLTerm[pNew->nLTerm++] = pTerm;
4366 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
drhe1e2e9a2013-06-13 15:16:53 +00004367 pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
drha18f3d22013-05-08 03:05:41 +00004368 if( pTerm->eOperator & WO_IN ){
4369 Expr *pExpr = pTerm->pExpr;
4370 pNew->wsFlags |= WHERE_COLUMN_IN;
4371 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhe1e2e9a2013-06-13 15:16:53 +00004372 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
4373 nIn = 46; assert( 46==whereCost(25) );
drha18f3d22013-05-08 03:05:41 +00004374 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
4375 /* "x IN (value, value, ...)" */
drhe1e2e9a2013-06-13 15:16:53 +00004376 nIn = whereCost(pExpr->x.pList->nExpr);
drhf1645f02013-05-07 19:44:38 +00004377 }
drhb8a8e8a2013-06-10 19:12:39 +00004378 pNew->rRun += nIn;
drh5346e952013-05-08 14:14:26 +00004379 pNew->u.btree.nEq++;
drhb8a8e8a2013-06-10 19:12:39 +00004380 pNew->nOut = nRowEst + nInMul + nIn;
drh6fa978d2013-05-30 19:29:19 +00004381 }else if( pTerm->eOperator & (WO_EQ) ){
drh7699d1c2013-06-04 12:42:29 +00004382 assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
drhb8a8e8a2013-06-10 19:12:39 +00004383 || nInMul==0 );
drha18f3d22013-05-08 03:05:41 +00004384 pNew->wsFlags |= WHERE_COLUMN_EQ;
drh7699d1c2013-06-04 12:42:29 +00004385 if( iCol<0
drhb8a8e8a2013-06-10 19:12:39 +00004386 || (pProbe->onError!=OE_None && nInMul==0
drh21f7ff72013-06-03 15:07:23 +00004387 && pNew->u.btree.nEq==pProbe->nColumn-1)
4388 ){
drh4a5acf82013-06-18 20:06:23 +00004389 assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
drh7699d1c2013-06-04 12:42:29 +00004390 pNew->wsFlags |= WHERE_ONEROW;
drh21f7ff72013-06-03 15:07:23 +00004391 }
drh5346e952013-05-08 14:14:26 +00004392 pNew->u.btree.nEq++;
drhb8a8e8a2013-06-10 19:12:39 +00004393 pNew->nOut = nRowEst + nInMul;
drh6fa978d2013-05-30 19:29:19 +00004394 }else if( pTerm->eOperator & (WO_ISNULL) ){
4395 pNew->wsFlags |= WHERE_COLUMN_NULL;
4396 pNew->u.btree.nEq++;
drhe1e2e9a2013-06-13 15:16:53 +00004397 /* TUNING: IS NULL selects 2 rows */
4398 nIn = 10; assert( 10==whereCost(2) );
drhb8a8e8a2013-06-10 19:12:39 +00004399 pNew->nOut = nRowEst + nInMul + nIn;
drha18f3d22013-05-08 03:05:41 +00004400 }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
drh7963b0e2013-06-17 21:37:40 +00004401 testcase( pTerm->eOperator & WO_GT );
4402 testcase( pTerm->eOperator & WO_GE );
drha18f3d22013-05-08 03:05:41 +00004403 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004404 pBtm = pTerm;
4405 pTop = 0;
drh7963b0e2013-06-17 21:37:40 +00004406 }else{
4407 assert( pTerm->eOperator & (WO_LT|WO_LE) );
4408 testcase( pTerm->eOperator & WO_LT );
4409 testcase( pTerm->eOperator & WO_LE );
drha18f3d22013-05-08 03:05:41 +00004410 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004411 pTop = pTerm;
4412 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00004413 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00004414 }
drh6f2bfad2013-06-03 17:35:22 +00004415 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
4416 /* Adjust nOut and rRun for STAT3 range values */
drh4efc9292013-06-06 23:02:03 +00004417 WhereCost rDiv;
drh70d18342013-06-06 19:16:33 +00004418 whereRangeScanEst(pParse, pProbe, pNew->u.btree.nEq,
drh6f2bfad2013-06-03 17:35:22 +00004419 pBtm, pTop, &rDiv);
drh8636e9c2013-06-11 01:50:08 +00004420 pNew->nOut = saved_nOut>rDiv+10 ? saved_nOut - rDiv : 10;
drh6f2bfad2013-06-03 17:35:22 +00004421 }
4422#ifdef SQLITE_ENABLE_STAT3
drh40aa9362013-06-28 17:29:25 +00004423 if( pNew->u.btree.nEq==1 && pProbe->nSample
4424 && OptimizationEnabled(db, SQLITE_Stat3) ){
drhb8a8e8a2013-06-10 19:12:39 +00004425 tRowcnt nOut = 0;
drh6f2bfad2013-06-03 17:35:22 +00004426 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
drh93ec45d2013-06-17 18:20:48 +00004427 testcase( pTerm->eOperator & WO_EQ );
4428 testcase( pTerm->eOperator & WO_ISNULL );
drhb8a8e8a2013-06-10 19:12:39 +00004429 rc = whereEqualScanEst(pParse, pProbe, pTerm->pExpr->pRight, &nOut);
drh6f2bfad2013-06-03 17:35:22 +00004430 }else if( (pTerm->eOperator & WO_IN)
4431 && !ExprHasProperty(pTerm->pExpr, EP_xIsSelect) ){
drhb8a8e8a2013-06-10 19:12:39 +00004432 rc = whereInScanEst(pParse, pProbe, pTerm->pExpr->x.pList, &nOut);
drh6f2bfad2013-06-03 17:35:22 +00004433 }
drhad01d892013-06-19 13:59:49 +00004434 if( rc==SQLITE_OK ) pNew->nOut = whereCost(nOut);
drh6f2bfad2013-06-03 17:35:22 +00004435 }
4436#endif
drhe217efc2013-06-12 03:48:41 +00004437 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
drheb04de32013-05-10 15:16:30 +00004438 /* Each row involves a step of the index, then a binary search of
4439 ** the main table */
drhe217efc2013-06-12 03:48:41 +00004440 pNew->rRun = whereCostAdd(pNew->rRun, rLogSize>27 ? rLogSize-17 : 10);
drheb04de32013-05-10 15:16:30 +00004441 }
drhe217efc2013-06-12 03:48:41 +00004442 /* Step cost for each output row */
4443 pNew->rRun = whereCostAdd(pNew->rRun, pNew->nOut);
drheb04de32013-05-10 15:16:30 +00004444 /* TBD: Adjust nOut for additional constraints */
drhcf8fa7a2013-05-10 20:26:22 +00004445 rc = whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004446 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
drhbbe8b242013-06-13 15:50:59 +00004447 && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
drh5346e952013-05-08 14:14:26 +00004448 ){
drhb8a8e8a2013-06-10 19:12:39 +00004449 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
drha18f3d22013-05-08 03:05:41 +00004450 }
drh1c8148f2013-05-04 20:25:23 +00004451 }
drh4efc9292013-06-06 23:02:03 +00004452 pNew->prereq = saved_prereq;
4453 pNew->u.btree.nEq = saved_nEq;
4454 pNew->wsFlags = saved_wsFlags;
4455 pNew->nOut = saved_nOut;
4456 pNew->nLTerm = saved_nLTerm;
drh5346e952013-05-08 14:14:26 +00004457 return rc;
drh1c8148f2013-05-04 20:25:23 +00004458}
4459
4460/*
drh23f98da2013-05-21 15:52:07 +00004461** Return True if it is possible that pIndex might be useful in
4462** implementing the ORDER BY clause in pBuilder.
4463**
4464** Return False if pBuilder does not contain an ORDER BY clause or
4465** if there is no way for pIndex to be useful in implementing that
4466** ORDER BY clause.
4467*/
4468static int indexMightHelpWithOrderBy(
4469 WhereLoopBuilder *pBuilder,
4470 Index *pIndex,
4471 int iCursor
4472){
4473 ExprList *pOB;
drh6d381472013-06-13 17:58:08 +00004474 int ii, jj;
drh23f98da2013-05-21 15:52:07 +00004475
drh53cfbe92013-06-13 17:28:22 +00004476 if( pIndex->bUnordered ) return 0;
drh70d18342013-06-06 19:16:33 +00004477 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00004478 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00004479 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00004480 if( pExpr->op!=TK_COLUMN ) return 0;
4481 if( pExpr->iTable==iCursor ){
drh6d381472013-06-13 17:58:08 +00004482 for(jj=0; jj<pIndex->nColumn; jj++){
4483 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
4484 }
drh23f98da2013-05-21 15:52:07 +00004485 }
4486 }
4487 return 0;
4488}
4489
4490/*
drh92a121f2013-06-10 12:15:47 +00004491** Return a bitmask where 1s indicate that the corresponding column of
4492** the table is used by an index. Only the first 63 columns are considered.
4493*/
drhfd5874d2013-06-12 14:52:39 +00004494static Bitmask columnsInIndex(Index *pIdx){
drh92a121f2013-06-10 12:15:47 +00004495 Bitmask m = 0;
4496 int j;
4497 for(j=pIdx->nColumn-1; j>=0; j--){
4498 int x = pIdx->aiColumn[j];
drh7963b0e2013-06-17 21:37:40 +00004499 testcase( x==BMS-1 );
4500 testcase( x==BMS-2 );
drh92a121f2013-06-10 12:15:47 +00004501 if( x<BMS-1 ) m |= MASKBIT(x);
4502 }
4503 return m;
4504}
4505
4506
4507/*
dan51576f42013-07-02 10:06:15 +00004508** Add all WhereLoop objects for a single table of the join where the table
drh0823c892013-05-11 00:06:23 +00004509** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
4510** a b-tree table, not a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004511*/
drh5346e952013-05-08 14:14:26 +00004512static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00004513 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00004514 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00004515){
drh70d18342013-06-06 19:16:33 +00004516 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00004517 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00004518 Index sPk; /* A fake index object for the primary key */
4519 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
4520 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00004521 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00004522 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00004523 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00004524 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00004525 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00004526 int b; /* A boolean value */
drhb8a8e8a2013-06-10 19:12:39 +00004527 WhereCost rSize; /* number of rows in the table */
4528 WhereCost rLogSize; /* Logarithm of the number of rows in the table */
drh23f98da2013-05-21 15:52:07 +00004529
drh1c8148f2013-05-04 20:25:23 +00004530 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004531 pWInfo = pBuilder->pWInfo;
4532 pTabList = pWInfo->pTabList;
4533 pSrc = pTabList->a + pNew->iTab;
drh0823c892013-05-11 00:06:23 +00004534 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00004535
4536 if( pSrc->pIndex ){
4537 /* An INDEXED BY clause specifies a particular index to use */
4538 pProbe = pSrc->pIndex;
4539 }else{
4540 /* There is no INDEXED BY clause. Create a fake Index object in local
4541 ** variable sPk to represent the rowid primary key index. Make this
4542 ** fake index the first in a chain of Index objects with all of the real
4543 ** indices to follow */
4544 Index *pFirst; /* First of real indices on the table */
4545 memset(&sPk, 0, sizeof(Index));
4546 sPk.nColumn = 1;
4547 sPk.aiColumn = &aiColumnPk;
4548 sPk.aiRowEst = aiRowEstPk;
4549 sPk.onError = OE_Replace;
4550 sPk.pTable = pSrc->pTab;
4551 aiRowEstPk[0] = pSrc->pTab->nRowEst;
4552 aiRowEstPk[1] = 1;
4553 pFirst = pSrc->pTab->pIndex;
4554 if( pSrc->notIndexed==0 ){
4555 /* The real indices of the table are only considered if the
4556 ** NOT INDEXED qualifier is omitted from the FROM clause */
4557 sPk.pNext = pFirst;
4558 }
4559 pProbe = &sPk;
4560 }
drhe1e2e9a2013-06-13 15:16:53 +00004561 rSize = whereCost(pSrc->pTab->nRowEst);
drheb04de32013-05-10 15:16:30 +00004562 rLogSize = estLog(rSize);
4563
4564 /* Automatic indexes */
drhaa32e3c2013-07-16 21:31:23 +00004565 if( !pBuilder->pOrSet
drh4fe425a2013-06-12 17:08:06 +00004566 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
4567 && pSrc->pIndex==0
drheb04de32013-05-10 15:16:30 +00004568 && !pSrc->viaCoroutine
4569 && !pSrc->notIndexed
4570 && !pSrc->isCorrelated
4571 ){
4572 /* Generate auto-index WhereLoops */
4573 WhereClause *pWC = pBuilder->pWC;
4574 WhereTerm *pTerm;
4575 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
4576 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00004577 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00004578 if( termCanDriveIndex(pTerm, pSrc, 0) ){
4579 pNew->u.btree.nEq = 1;
drhef866372013-05-22 20:49:02 +00004580 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00004581 pNew->nLTerm = 1;
4582 pNew->aLTerm[0] = pTerm;
drhe1e2e9a2013-06-13 15:16:53 +00004583 /* TUNING: One-time cost for computing the automatic index is
drh986b3872013-06-28 21:12:20 +00004584 ** approximately 7*N*log2(N) where N is the number of rows in
drhe1e2e9a2013-06-13 15:16:53 +00004585 ** the table being indexed. */
drh986b3872013-06-28 21:12:20 +00004586 pNew->rSetup = rLogSize + rSize + 28; assert( 28==whereCost(7) );
4587 /* TUNING: Each index lookup yields 20 rows in the table. This
4588 ** is more than the usual guess of 10 rows, since we have no way
4589 ** of knowning how selective the index will ultimately be. It would
4590 ** not be unreasonable to make this value much larger. */
4591 pNew->nOut = 43; assert( 43==whereCost(20) );
drhb8a8e8a2013-06-10 19:12:39 +00004592 pNew->rRun = whereCostAdd(rLogSize,pNew->nOut);
drh986b3872013-06-28 21:12:20 +00004593 pNew->wsFlags = WHERE_AUTO_INDEX;
drheb04de32013-05-10 15:16:30 +00004594 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00004595 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00004596 }
4597 }
4598 }
drh1c8148f2013-05-04 20:25:23 +00004599
4600 /* Loop over all indices
4601 */
drh23f98da2013-05-21 15:52:07 +00004602 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh5346e952013-05-08 14:14:26 +00004603 pNew->u.btree.nEq = 0;
drh4efc9292013-06-06 23:02:03 +00004604 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00004605 pNew->iSortIdx = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004606 pNew->rSetup = 0;
drh23f98da2013-05-21 15:52:07 +00004607 pNew->prereq = mExtra;
drh74f91d42013-06-19 18:01:44 +00004608 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004609 pNew->u.btree.pIndex = pProbe;
4610 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh53cfbe92013-06-13 17:28:22 +00004611 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
4612 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
drh43fe25f2013-05-07 23:06:23 +00004613 if( pProbe->tnum<=0 ){
4614 /* Integer primary key index */
4615 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00004616
4617 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00004618 pNew->iSortIdx = b ? iSortIdx : 0;
drhe1e2e9a2013-06-13 15:16:53 +00004619 /* TUNING: Cost of full table scan is 3*(N + log2(N)).
4620 ** + The extra 3 factor is to encourage the use of indexed lookups
4621 ** over full scans. A smaller constant 2 is used for covering
4622 ** index scans so that a covering index scan will be favored over
4623 ** a table scan. */
4624 pNew->rRun = whereCostAdd(rSize,rLogSize) + 16;
drh23f98da2013-05-21 15:52:07 +00004625 rc = whereLoopInsert(pBuilder, pNew);
4626 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00004627 }else{
drhfd5874d2013-06-12 14:52:39 +00004628 Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
drh6fa978d2013-05-30 19:29:19 +00004629 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
drh1c8148f2013-05-04 20:25:23 +00004630
drh23f98da2013-05-21 15:52:07 +00004631 /* Full scan via index */
drh53cfbe92013-06-13 17:28:22 +00004632 if( b
4633 || ( m==0
4634 && pProbe->bUnordered==0
4635 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
4636 && sqlite3GlobalConfig.bUseCis
4637 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
4638 )
drhe3b7c922013-06-03 19:17:40 +00004639 ){
drh23f98da2013-05-21 15:52:07 +00004640 pNew->iSortIdx = b ? iSortIdx : 0;
drhe1e2e9a2013-06-13 15:16:53 +00004641 if( m==0 ){
4642 /* TUNING: Cost of a covering index scan is 2*(N + log2(N)).
4643 ** + The extra 2 factor is to encourage the use of indexed lookups
4644 ** over index scans. A table scan uses a factor of 3 so that
4645 ** index scans are favored over table scans.
4646 ** + If this covering index might also help satisfy the ORDER BY
4647 ** clause, then the cost is fudged down slightly so that this
4648 ** index is favored above other indices that have no hope of
4649 ** helping with the ORDER BY. */
4650 pNew->rRun = 10 + whereCostAdd(rSize,rLogSize) - b;
4651 }else{
4652 assert( b!=0 );
4653 /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
4654 ** which we will simplify to just N*log2(N) */
4655 pNew->rRun = rSize + rLogSize;
4656 }
drh23f98da2013-05-21 15:52:07 +00004657 rc = whereLoopInsert(pBuilder, pNew);
4658 if( rc ) break;
4659 }
4660 }
drhb8a8e8a2013-06-10 19:12:39 +00004661 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
drh1c8148f2013-05-04 20:25:23 +00004662
4663 /* If there was an INDEXED BY clause, then only that one index is
4664 ** considered. */
4665 if( pSrc->pIndex ) break;
4666 }
drh5346e952013-05-08 14:14:26 +00004667 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004668}
4669
drh8636e9c2013-06-11 01:50:08 +00004670#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf1b5f5b2013-05-02 00:15:01 +00004671/*
drh0823c892013-05-11 00:06:23 +00004672** Add all WhereLoop objects for a table of the join identified by
4673** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004674*/
drh5346e952013-05-08 14:14:26 +00004675static int whereLoopAddVirtual(
drh613ba1e2013-06-15 15:11:45 +00004676 WhereLoopBuilder *pBuilder /* WHERE clause information */
drhf1b5f5b2013-05-02 00:15:01 +00004677){
drh70d18342013-06-06 19:16:33 +00004678 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00004679 Parse *pParse; /* The parsing context */
4680 WhereClause *pWC; /* The WHERE clause */
4681 struct SrcList_item *pSrc; /* The FROM clause term to search */
4682 Table *pTab;
4683 sqlite3 *db;
4684 sqlite3_index_info *pIdxInfo;
4685 struct sqlite3_index_constraint *pIdxCons;
4686 struct sqlite3_index_constraint_usage *pUsage;
4687 WhereTerm *pTerm;
4688 int i, j;
4689 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00004690 int nConstraint;
drh5346e952013-05-08 14:14:26 +00004691 int seenIn = 0; /* True if an IN operator is seen */
4692 int seenVar = 0; /* True if a non-constant constraint is seen */
4693 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
4694 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00004695 int rc = SQLITE_OK;
4696
drh70d18342013-06-06 19:16:33 +00004697 pWInfo = pBuilder->pWInfo;
4698 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00004699 db = pParse->db;
4700 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00004701 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004702 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00004703 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00004704 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00004705 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00004706 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00004707 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00004708 pNew->rSetup = 0;
4709 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00004710 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00004711 pNew->u.vtab.needFree = 0;
4712 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00004713 nConstraint = pIdxInfo->nConstraint;
drh7963b0e2013-06-17 21:37:40 +00004714 if( whereLoopResize(db, pNew, nConstraint) ){
4715 sqlite3DbFree(db, pIdxInfo);
4716 return SQLITE_NOMEM;
4717 }
drh5346e952013-05-08 14:14:26 +00004718
drh0823c892013-05-11 00:06:23 +00004719 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00004720 if( !seenIn && (iPhase&1)!=0 ){
4721 iPhase++;
4722 if( iPhase>3 ) break;
4723 }
4724 if( !seenVar && iPhase>1 ) break;
4725 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4726 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
4727 j = pIdxCons->iTermOffset;
4728 pTerm = &pWC->a[j];
4729 switch( iPhase ){
4730 case 0: /* Constants without IN operator */
4731 pIdxCons->usable = 0;
4732 if( (pTerm->eOperator & WO_IN)!=0 ){
4733 seenIn = 1;
drh7963b0e2013-06-17 21:37:40 +00004734 }
4735 if( pTerm->prereqRight!=0 ){
drh5346e952013-05-08 14:14:26 +00004736 seenVar = 1;
drh7963b0e2013-06-17 21:37:40 +00004737 }else if( (pTerm->eOperator & WO_IN)==0 ){
drh5346e952013-05-08 14:14:26 +00004738 pIdxCons->usable = 1;
4739 }
4740 break;
4741 case 1: /* Constants with IN operators */
4742 assert( seenIn );
4743 pIdxCons->usable = (pTerm->prereqRight==0);
4744 break;
4745 case 2: /* Variables without IN */
4746 assert( seenVar );
4747 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
4748 break;
4749 default: /* Variables with IN */
4750 assert( seenVar && seenIn );
4751 pIdxCons->usable = 1;
4752 break;
4753 }
4754 }
4755 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
4756 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4757 pIdxInfo->idxStr = 0;
4758 pIdxInfo->idxNum = 0;
4759 pIdxInfo->needToFreeIdxStr = 0;
4760 pIdxInfo->orderByConsumed = 0;
drh8636e9c2013-06-11 01:50:08 +00004761 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
drh5346e952013-05-08 14:14:26 +00004762 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
4763 if( rc ) goto whereLoopAddVtab_exit;
4764 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4765 pNew->prereq = 0;
drhc718f1c2013-05-08 20:05:58 +00004766 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00004767 assert( pNew->nLSlot>=nConstraint );
4768 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00004769 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00004770 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00004771 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4772 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00004773 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00004774 || j<0
4775 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00004776 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00004777 ){
4778 rc = SQLITE_ERROR;
4779 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
4780 goto whereLoopAddVtab_exit;
4781 }
drh7963b0e2013-06-17 21:37:40 +00004782 testcase( iTerm==nConstraint-1 );
4783 testcase( j==0 );
4784 testcase( j==pWC->nTerm-1 );
drh5346e952013-05-08 14:14:26 +00004785 pTerm = &pWC->a[j];
4786 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00004787 assert( iTerm<pNew->nLSlot );
4788 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00004789 if( iTerm>mxTerm ) mxTerm = iTerm;
drh7963b0e2013-06-17 21:37:40 +00004790 testcase( iTerm==15 );
4791 testcase( iTerm==16 );
drh52986302013-06-03 16:03:16 +00004792 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00004793 if( (pTerm->eOperator & WO_IN)!=0 ){
4794 if( pUsage[i].omit==0 ){
4795 /* Do not attempt to use an IN constraint if the virtual table
4796 ** says that the equivalent EQ constraint cannot be safely omitted.
4797 ** If we do attempt to use such a constraint, some rows might be
4798 ** repeated in the output. */
4799 break;
4800 }
4801 /* A virtual table that is constrained by an IN clause may not
4802 ** consume the ORDER BY clause because (1) the order of IN terms
4803 ** is not necessarily related to the order of output terms and
4804 ** (2) Multiple outputs from a single IN value will not merge
4805 ** together. */
4806 pIdxInfo->orderByConsumed = 0;
4807 }
4808 }
4809 }
drh4efc9292013-06-06 23:02:03 +00004810 if( i>=nConstraint ){
4811 pNew->nLTerm = mxTerm+1;
4812 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00004813 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4814 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4815 pIdxInfo->needToFreeIdxStr = 0;
4816 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh3b1d8082013-06-03 16:56:37 +00004817 pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
4818 && pIdxInfo->orderByConsumed);
drhb8a8e8a2013-06-10 19:12:39 +00004819 pNew->rSetup = 0;
drh8636e9c2013-06-11 01:50:08 +00004820 pNew->rRun = whereCostFromDouble(pIdxInfo->estimatedCost);
drhe1e2e9a2013-06-13 15:16:53 +00004821 /* TUNING: Every virtual table query returns 25 rows */
4822 pNew->nOut = 46; assert( 46==whereCost(25) );
drhcf8fa7a2013-05-10 20:26:22 +00004823 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004824 if( pNew->u.vtab.needFree ){
4825 sqlite3_free(pNew->u.vtab.idxStr);
4826 pNew->u.vtab.needFree = 0;
4827 }
4828 }
4829 }
4830
4831whereLoopAddVtab_exit:
4832 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4833 sqlite3DbFree(db, pIdxInfo);
4834 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004835}
drh8636e9c2013-06-11 01:50:08 +00004836#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhf1b5f5b2013-05-02 00:15:01 +00004837
4838/*
drhcf8fa7a2013-05-10 20:26:22 +00004839** Add WhereLoop entries to handle OR terms. This works for either
4840** btrees or virtual tables.
4841*/
4842static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00004843 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00004844 WhereClause *pWC;
4845 WhereLoop *pNew;
4846 WhereTerm *pTerm, *pWCEnd;
4847 int rc = SQLITE_OK;
4848 int iCur;
4849 WhereClause tempWC;
4850 WhereLoopBuilder sSubBuild;
drhaa32e3c2013-07-16 21:31:23 +00004851 WhereOrSet sSum, sCur, sPrev;
drhcf8fa7a2013-05-10 20:26:22 +00004852 struct SrcList_item *pItem;
4853
drhcf8fa7a2013-05-10 20:26:22 +00004854 pWC = pBuilder->pWC;
drh70d18342013-06-06 19:16:33 +00004855 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
drhcf8fa7a2013-05-10 20:26:22 +00004856 pWCEnd = pWC->a + pWC->nTerm;
4857 pNew = pBuilder->pNew;
drhcf8fa7a2013-05-10 20:26:22 +00004858
4859 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4860 if( (pTerm->eOperator & WO_OR)!=0
4861 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4862 ){
4863 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4864 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4865 WhereTerm *pOrTerm;
drhaa32e3c2013-07-16 21:31:23 +00004866 int once = 1;
4867 int i, j;
drh783dece2013-06-05 17:53:43 +00004868
drh70d18342013-06-06 19:16:33 +00004869 pItem = pWInfo->pTabList->a + pNew->iTab;
drh783dece2013-06-05 17:53:43 +00004870 iCur = pItem->iCursor;
4871 sSubBuild = *pBuilder;
4872 sSubBuild.pOrderBy = 0;
drhaa32e3c2013-07-16 21:31:23 +00004873 sSubBuild.pOrSet = &sCur;
drhcf8fa7a2013-05-10 20:26:22 +00004874
drhc7f0d222013-06-19 03:27:12 +00004875 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00004876 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004877 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4878 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00004879 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00004880 tempWC.pOuter = pWC;
4881 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00004882 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00004883 tempWC.a = pOrTerm;
4884 sSubBuild.pWC = &tempWC;
4885 }else{
4886 continue;
4887 }
drhaa32e3c2013-07-16 21:31:23 +00004888 sCur.n = 0;
drh8636e9c2013-06-11 01:50:08 +00004889#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcf8fa7a2013-05-10 20:26:22 +00004890 if( IsVirtual(pItem->pTab) ){
drh613ba1e2013-06-15 15:11:45 +00004891 rc = whereLoopAddVirtual(&sSubBuild);
drhaa32e3c2013-07-16 21:31:23 +00004892 for(i=0; i<sCur.n; i++) sCur.a[i].prereq |= mExtra;
drh8636e9c2013-06-11 01:50:08 +00004893 }else
4894#endif
4895 {
drhcf8fa7a2013-05-10 20:26:22 +00004896 rc = whereLoopAddBtree(&sSubBuild, mExtra);
4897 }
drhaa32e3c2013-07-16 21:31:23 +00004898 assert( rc==SQLITE_OK || sCur.n==0 );
4899 if( sCur.n==0 ){
4900 sSum.n = 0;
4901 break;
4902 }else if( once ){
4903 whereOrMove(&sSum, &sCur);
4904 once = 0;
4905 }else{
4906 whereOrMove(&sPrev, &sSum);
4907 sSum.n = 0;
4908 for(i=0; i<sPrev.n; i++){
4909 for(j=0; j<sCur.n; j++){
4910 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
4911 whereCostAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4912 whereCostAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
4913 }
4914 }
4915 }
drhcf8fa7a2013-05-10 20:26:22 +00004916 }
drhaa32e3c2013-07-16 21:31:23 +00004917 pNew->nLTerm = 1;
4918 pNew->aLTerm[0] = pTerm;
4919 pNew->wsFlags = WHERE_MULTI_OR;
4920 pNew->rSetup = 0;
4921 pNew->iSortIdx = 0;
4922 memset(&pNew->u, 0, sizeof(pNew->u));
4923 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
drh74f91d42013-06-19 18:01:44 +00004924 /* TUNING: Multiple by 3.5 for the secondary table lookup */
drhaa32e3c2013-07-16 21:31:23 +00004925 pNew->rRun = sSum.a[i].rRun + 18;
4926 pNew->nOut = sSum.a[i].nOut;
4927 pNew->prereq = sSum.a[i].prereq;
drhfd5874d2013-06-12 14:52:39 +00004928 rc = whereLoopInsert(pBuilder, pNew);
4929 }
drhcf8fa7a2013-05-10 20:26:22 +00004930 }
4931 }
4932 return rc;
4933}
4934
4935/*
drhf1b5f5b2013-05-02 00:15:01 +00004936** Add all WhereLoop objects for all tables
4937*/
drh5346e952013-05-08 14:14:26 +00004938static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00004939 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00004940 Bitmask mExtra = 0;
4941 Bitmask mPrior = 0;
4942 int iTab;
drh70d18342013-06-06 19:16:33 +00004943 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00004944 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00004945 sqlite3 *db = pWInfo->pParse->db;
4946 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00004947 int rc = SQLITE_OK;
drhc63367e2013-06-10 20:46:50 +00004948 u8 priorJoinType = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004949 WhereLoop *pNew;
drhf1b5f5b2013-05-02 00:15:01 +00004950
4951 /* Loop over the tables in the join, from left to right */
drhb8a8e8a2013-06-10 19:12:39 +00004952 pNew = pBuilder->pNew;
drha2014152013-06-07 00:29:23 +00004953 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00004954 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00004955 pNew->iTab = iTab;
drh70d18342013-06-06 19:16:33 +00004956 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
drhc63367e2013-06-10 20:46:50 +00004957 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
drhf1b5f5b2013-05-02 00:15:01 +00004958 mExtra = mPrior;
4959 }
drhc63367e2013-06-10 20:46:50 +00004960 priorJoinType = pItem->jointype;
drhb2a90f02013-05-10 03:30:49 +00004961 if( IsVirtual(pItem->pTab) ){
drh613ba1e2013-06-15 15:11:45 +00004962 rc = whereLoopAddVirtual(pBuilder);
drhb2a90f02013-05-10 03:30:49 +00004963 }else{
4964 rc = whereLoopAddBtree(pBuilder, mExtra);
4965 }
drhb2a90f02013-05-10 03:30:49 +00004966 if( rc==SQLITE_OK ){
4967 rc = whereLoopAddOr(pBuilder, mExtra);
4968 }
drhb2a90f02013-05-10 03:30:49 +00004969 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00004970 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00004971 }
drha2014152013-06-07 00:29:23 +00004972 whereLoopClear(db, pNew);
drh5346e952013-05-08 14:14:26 +00004973 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004974}
4975
drha18f3d22013-05-08 03:05:41 +00004976/*
drh7699d1c2013-06-04 12:42:29 +00004977** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00004978** parameters) to see if it outputs rows in the requested ORDER BY
drh94433422013-07-01 11:05:50 +00004979** (or GROUP BY) without requiring a separate sort operation. Return:
drh319f6772013-05-14 15:31:07 +00004980**
4981** 0: ORDER BY is not satisfied. Sorting required
4982** 1: ORDER BY is satisfied. Omit sorting
4983** -1: Unknown at this time
4984**
drh94433422013-07-01 11:05:50 +00004985** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4986** strict. With GROUP BY and DISTINCT the only requirement is that
4987** equivalent rows appear immediately adjacent to one another. GROUP BY
4988** and DISTINT do not require rows to appear in any particular order as long
4989** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
4990** the pOrderBy terms can be matched in any order. With ORDER BY, the
4991** pOrderBy terms must be matched in strict left-to-right order.
drh6b7157b2013-05-10 02:00:35 +00004992*/
4993static int wherePathSatisfiesOrderBy(
4994 WhereInfo *pWInfo, /* The WHERE clause */
drh4f402f22013-06-11 18:59:38 +00004995 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
drh6b7157b2013-05-10 02:00:35 +00004996 WherePath *pPath, /* The WherePath to check */
drh4f402f22013-06-11 18:59:38 +00004997 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
4998 u16 nLoop, /* Number of entries in pPath->aLoop[] */
drh319f6772013-05-14 15:31:07 +00004999 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
drh4f402f22013-06-11 18:59:38 +00005000 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00005001){
drh88da6442013-05-27 17:59:37 +00005002 u8 revSet; /* True if rev is known */
5003 u8 rev; /* Composite sort order */
5004 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00005005 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
5006 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
5007 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drh7699d1c2013-06-04 12:42:29 +00005008 u16 nColumn; /* Number of columns in pIndex */
5009 u16 nOrderBy; /* Number terms in the ORDER BY clause */
5010 int iLoop; /* Index of WhereLoop in pPath being processed */
5011 int i, j; /* Loop counters */
5012 int iCur; /* Cursor number for current WhereLoop */
5013 int iColumn; /* A column number within table iCur */
drhe8ae5832013-06-19 13:32:46 +00005014 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
drh7699d1c2013-06-04 12:42:29 +00005015 WhereTerm *pTerm; /* A single term of the WHERE clause */
5016 Expr *pOBExpr; /* An expression from the ORDER BY clause */
5017 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
5018 Index *pIndex; /* The index associated with pLoop */
5019 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
5020 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
5021 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00005022 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drhb8916be2013-06-14 02:51:48 +00005023 Bitmask ready; /* Mask of inner loops */
drh319f6772013-05-14 15:31:07 +00005024
5025 /*
drh7699d1c2013-06-04 12:42:29 +00005026 ** We say the WhereLoop is "one-row" if it generates no more than one
5027 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00005028 ** (a) All index columns match with WHERE_COLUMN_EQ.
5029 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00005030 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
5031 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00005032 **
drhe353ee32013-06-04 23:40:53 +00005033 ** We say the WhereLoop is "order-distinct" if the set of columns from
5034 ** that WhereLoop that are in the ORDER BY clause are different for every
5035 ** row of the WhereLoop. Every one-row WhereLoop is automatically
5036 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
5037 ** is not order-distinct. To be order-distinct is not quite the same as being
5038 ** UNIQUE since a UNIQUE column or index can have multiple rows that
5039 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
5040 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
5041 **
5042 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
5043 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
5044 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00005045 */
5046
5047 assert( pOrderBy!=0 );
5048
5049 /* Sortability of virtual tables is determined by the xBestIndex method
5050 ** of the virtual table itself */
5051 if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
drh7699d1c2013-06-04 12:42:29 +00005052 testcase( nLoop>0 ); /* True when outer loops are one-row and match
5053 ** no ORDER BY terms */
drh319f6772013-05-14 15:31:07 +00005054 return pLast->u.vtab.isOrdered;
drh6b7157b2013-05-10 02:00:35 +00005055 }
drh7699d1c2013-06-04 12:42:29 +00005056 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00005057
drh319f6772013-05-14 15:31:07 +00005058 nOrderBy = pOrderBy->nExpr;
drh7963b0e2013-06-17 21:37:40 +00005059 testcase( nOrderBy==BMS-1 );
drhe353ee32013-06-04 23:40:53 +00005060 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
5061 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00005062 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00005063 orderDistinctMask = 0;
drhb8916be2013-06-14 02:51:48 +00005064 ready = 0;
drhe353ee32013-06-04 23:40:53 +00005065 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drhb8916be2013-06-14 02:51:48 +00005066 if( iLoop>0 ) ready |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005067 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh319f6772013-05-14 15:31:07 +00005068 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh319f6772013-05-14 15:31:07 +00005069 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drhb8916be2013-06-14 02:51:48 +00005070
5071 /* Mark off any ORDER BY term X that is a column in the table of
5072 ** the current loop for which there is term in the WHERE
5073 ** clause of the form X IS NULL or X=? that reference only outer
5074 ** loops.
5075 */
5076 for(i=0; i<nOrderBy; i++){
5077 if( MASKBIT(i) & obSat ) continue;
5078 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
5079 if( pOBExpr->op!=TK_COLUMN ) continue;
5080 if( pOBExpr->iTable!=iCur ) continue;
5081 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
5082 ~ready, WO_EQ|WO_ISNULL, 0);
5083 if( pTerm==0 ) continue;
drh7963b0e2013-06-17 21:37:40 +00005084 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
drhb8916be2013-06-14 02:51:48 +00005085 const char *z1, *z2;
5086 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5087 if( !pColl ) pColl = db->pDfltColl;
5088 z1 = pColl->zName;
5089 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
5090 if( !pColl ) pColl = db->pDfltColl;
5091 z2 = pColl->zName;
5092 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
5093 }
5094 obSat |= MASKBIT(i);
5095 }
5096
drh7699d1c2013-06-04 12:42:29 +00005097 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
5098 if( pLoop->wsFlags & WHERE_IPK ){
5099 pIndex = 0;
5100 nColumn = 0;
5101 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00005102 return 0;
drh7699d1c2013-06-04 12:42:29 +00005103 }else{
5104 nColumn = pIndex->nColumn;
drhe353ee32013-06-04 23:40:53 +00005105 isOrderDistinct = pIndex->onError!=OE_None;
drh1b0f0262013-05-30 22:27:09 +00005106 }
drh7699d1c2013-06-04 12:42:29 +00005107
drh7699d1c2013-06-04 12:42:29 +00005108 /* Loop through all columns of the index and deal with the ones
5109 ** that are not constrained by == or IN.
5110 */
5111 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00005112 distinctColumns = 0;
drh7699d1c2013-06-04 12:42:29 +00005113 for(j=0; j<=nColumn; j++){
5114 u8 bOnce; /* True to run the ORDER BY search loop */
5115
drhe353ee32013-06-04 23:40:53 +00005116 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00005117 if( j<pLoop->u.btree.nEq
drh4efc9292013-06-06 23:02:03 +00005118 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
drh7699d1c2013-06-04 12:42:29 +00005119 ){
drh7963b0e2013-06-17 21:37:40 +00005120 if( i & WO_ISNULL ){
5121 testcase( isOrderDistinct );
5122 isOrderDistinct = 0;
5123 }
drhe353ee32013-06-04 23:40:53 +00005124 continue;
drh7699d1c2013-06-04 12:42:29 +00005125 }
5126
drhe353ee32013-06-04 23:40:53 +00005127 /* Get the column number in the table (iColumn) and sort order
5128 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00005129 */
5130 if( j<nColumn ){
5131 /* Normal index columns */
5132 iColumn = pIndex->aiColumn[j];
5133 revIdx = pIndex->aSortOrder[j];
5134 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00005135 }else{
drh7699d1c2013-06-04 12:42:29 +00005136 /* The ROWID column at the end */
drh7963b0e2013-06-17 21:37:40 +00005137 assert( j==nColumn );
drh7699d1c2013-06-04 12:42:29 +00005138 iColumn = -1;
5139 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00005140 }
drh7699d1c2013-06-04 12:42:29 +00005141
5142 /* An unconstrained column that might be NULL means that this
5143 ** WhereLoop is not well-ordered
5144 */
drhe353ee32013-06-04 23:40:53 +00005145 if( isOrderDistinct
5146 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00005147 && j>=pLoop->u.btree.nEq
5148 && pIndex->pTable->aCol[iColumn].notNull==0
5149 ){
drhe353ee32013-06-04 23:40:53 +00005150 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00005151 }
5152
5153 /* Find the ORDER BY term that corresponds to the j-th column
5154 ** of the index and and mark that ORDER BY term off
5155 */
5156 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00005157 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00005158 for(i=0; bOnce && i<nOrderBy; i++){
5159 if( MASKBIT(i) & obSat ) continue;
5160 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh93ec45d2013-06-17 18:20:48 +00005161 testcase( wctrlFlags & WHERE_GROUPBY );
5162 testcase( wctrlFlags & WHERE_DISTINCTBY );
drh4f402f22013-06-11 18:59:38 +00005163 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00005164 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00005165 if( pOBExpr->iTable!=iCur ) continue;
5166 if( pOBExpr->iColumn!=iColumn ) continue;
5167 if( iColumn>=0 ){
5168 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5169 if( !pColl ) pColl = db->pDfltColl;
5170 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
5171 }
drhe353ee32013-06-04 23:40:53 +00005172 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00005173 break;
5174 }
drhe353ee32013-06-04 23:40:53 +00005175 if( isMatch ){
drh7963b0e2013-06-17 21:37:40 +00005176 if( iColumn<0 ){
5177 testcase( distinctColumns==0 );
5178 distinctColumns = 1;
5179 }
drh7699d1c2013-06-04 12:42:29 +00005180 obSat |= MASKBIT(i);
5181 if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
drhe353ee32013-06-04 23:40:53 +00005182 /* Make sure the sort order is compatible in an ORDER BY clause.
5183 ** Sort order is irrelevant for a GROUP BY clause. */
drh7699d1c2013-06-04 12:42:29 +00005184 if( revSet ){
5185 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
5186 }else{
5187 rev = revIdx ^ pOrderBy->a[i].sortOrder;
5188 if( rev ) *pRevMask |= MASKBIT(iLoop);
5189 revSet = 1;
5190 }
5191 }
5192 }else{
5193 /* No match found */
drh7963b0e2013-06-17 21:37:40 +00005194 if( j==0 || j<nColumn ){
5195 testcase( isOrderDistinct!=0 );
5196 isOrderDistinct = 0;
5197 }
drh7699d1c2013-06-04 12:42:29 +00005198 break;
5199 }
5200 } /* end Loop over all index columns */
drh81186b42013-06-18 01:52:41 +00005201 if( distinctColumns ){
5202 testcase( isOrderDistinct==0 );
5203 isOrderDistinct = 1;
5204 }
drh7699d1c2013-06-04 12:42:29 +00005205 } /* end-if not one-row */
5206
5207 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00005208 if( isOrderDistinct ){
5209 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005210 for(i=0; i<nOrderBy; i++){
5211 Expr *p;
5212 if( MASKBIT(i) & obSat ) continue;
5213 p = pOrderBy->a[i].pExpr;
drh70d18342013-06-06 19:16:33 +00005214 if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00005215 obSat |= MASKBIT(i);
5216 }
drh0afb4232013-05-31 13:36:32 +00005217 }
drh319f6772013-05-14 15:31:07 +00005218 }
drhb8916be2013-06-14 02:51:48 +00005219 } /* End the loop over all WhereLoops from outer-most down to inner-most */
drh7699d1c2013-06-04 12:42:29 +00005220 if( obSat==obDone ) return 1;
drhe353ee32013-06-04 23:40:53 +00005221 if( !isOrderDistinct ) return 0;
drh319f6772013-05-14 15:31:07 +00005222 return -1;
drh6b7157b2013-05-10 02:00:35 +00005223}
5224
drhd15cb172013-05-21 19:23:10 +00005225#ifdef WHERETRACE_ENABLED
5226/* For debugging use only: */
5227static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
5228 static char zName[65];
5229 int i;
5230 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
5231 if( pLast ) zName[i++] = pLast->cId;
5232 zName[i] = 0;
5233 return zName;
5234}
5235#endif
5236
drh6b7157b2013-05-10 02:00:35 +00005237
5238/*
dan51576f42013-07-02 10:06:15 +00005239** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
drha18f3d22013-05-08 03:05:41 +00005240** attempts to find the lowest cost path that visits each WhereLoop
5241** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5242**
drhc7f0d222013-06-19 03:27:12 +00005243** Assume that the total number of output rows that will need to be sorted
5244** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
5245** costs if nRowEst==0.
5246**
drha18f3d22013-05-08 03:05:41 +00005247** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5248** error occurs.
5249*/
drh4efc9292013-06-06 23:02:03 +00005250static int wherePathSolver(WhereInfo *pWInfo, WhereCost nRowEst){
drh783dece2013-06-05 17:53:43 +00005251 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00005252 int nLoop; /* Number of terms in the join */
drhe1e2e9a2013-06-13 15:16:53 +00005253 Parse *pParse; /* Parsing context */
drha18f3d22013-05-08 03:05:41 +00005254 sqlite3 *db; /* The database connection */
5255 int iLoop; /* Loop counter over the terms of the join */
5256 int ii, jj; /* Loop counters */
drh4efc9292013-06-06 23:02:03 +00005257 WhereCost rCost; /* Cost of a path */
drhc7f0d222013-06-19 03:27:12 +00005258 WhereCost mxCost = 0; /* Maximum cost of a set of paths */
drh4efc9292013-06-06 23:02:03 +00005259 WhereCost rSortCost; /* Cost to do a sort */
drha18f3d22013-05-08 03:05:41 +00005260 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
5261 WherePath *aFrom; /* All nFrom paths at the previous level */
5262 WherePath *aTo; /* The nTo best paths at the current level */
5263 WherePath *pFrom; /* An element of aFrom[] that we are working on */
5264 WherePath *pTo; /* An element of aTo[] that we are working on */
5265 WhereLoop *pWLoop; /* One of the WhereLoop objects */
5266 WhereLoop **pX; /* Used to divy up the pSpace memory */
5267 char *pSpace; /* Temporary memory used by this routine */
5268
drhe1e2e9a2013-06-13 15:16:53 +00005269 pParse = pWInfo->pParse;
5270 db = pParse->db;
drha18f3d22013-05-08 03:05:41 +00005271 nLoop = pWInfo->nLevel;
drhe1e2e9a2013-06-13 15:16:53 +00005272 /* TUNING: For simple queries, only the best path is tracked.
5273 ** For 2-way joins, the 5 best paths are followed.
5274 ** For joins of 3 or more tables, track the 10 best paths */
drhe9d935a2013-06-05 16:19:59 +00005275 mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00005276 assert( nLoop<=pWInfo->pTabList->nSrc );
drh3b48e8c2013-06-12 20:18:16 +00005277 WHERETRACE(0x002, ("---- begin solver\n"));
drha18f3d22013-05-08 03:05:41 +00005278
5279 /* Allocate and initialize space for aTo and aFrom */
5280 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
5281 pSpace = sqlite3DbMallocRaw(db, ii);
5282 if( pSpace==0 ) return SQLITE_NOMEM;
5283 aTo = (WherePath*)pSpace;
5284 aFrom = aTo+mxChoice;
5285 memset(aFrom, 0, sizeof(aFrom[0]));
5286 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00005287 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00005288 pFrom->aLoop = pX;
5289 }
5290
drhe1e2e9a2013-06-13 15:16:53 +00005291 /* Seed the search with a single WherePath containing zero WhereLoops.
5292 **
5293 ** TUNING: Do not let the number of iterations go above 25. If the cost
5294 ** of computing an automatic index is not paid back within the first 25
5295 ** rows, then do not use the automatic index. */
5296 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==whereCost(25) );
drha18f3d22013-05-08 03:05:41 +00005297 nFrom = 1;
drh6b7157b2013-05-10 02:00:35 +00005298
5299 /* Precompute the cost of sorting the final result set, if the caller
5300 ** to sqlite3WhereBegin() was concerned about sorting */
drhb8a8e8a2013-06-10 19:12:39 +00005301 rSortCost = 0;
5302 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
drh6b7157b2013-05-10 02:00:35 +00005303 aFrom[0].isOrderedValid = 1;
5304 }else{
drhe1e2e9a2013-06-13 15:16:53 +00005305 /* TUNING: Estimated cost of sorting is N*log2(N) where N is the
5306 ** number of output rows. */
drhb8a8e8a2013-06-10 19:12:39 +00005307 rSortCost = nRowEst + estLog(nRowEst);
drh3b48e8c2013-06-12 20:18:16 +00005308 WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
drh6b7157b2013-05-10 02:00:35 +00005309 }
5310
5311 /* Compute successively longer WherePaths using the previous generation
5312 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5313 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00005314 for(iLoop=0; iLoop<nLoop; iLoop++){
5315 nTo = 0;
5316 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
5317 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
5318 Bitmask maskNew;
drh319f6772013-05-14 15:31:07 +00005319 Bitmask revMask = 0;
drh6b7157b2013-05-10 02:00:35 +00005320 u8 isOrderedValid = pFrom->isOrderedValid;
5321 u8 isOrdered = pFrom->isOrdered;
drha18f3d22013-05-08 03:05:41 +00005322 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5323 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00005324 /* At this point, pWLoop is a candidate to be the next loop.
5325 ** Compute its cost */
drhb8a8e8a2013-06-10 19:12:39 +00005326 rCost = whereCostAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
5327 rCost = whereCostAdd(rCost, pFrom->rCost);
drha18f3d22013-05-08 03:05:41 +00005328 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh6b7157b2013-05-10 02:00:35 +00005329 if( !isOrderedValid ){
drh4f402f22013-06-11 18:59:38 +00005330 switch( wherePathSatisfiesOrderBy(pWInfo,
5331 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
drh93ec45d2013-06-17 18:20:48 +00005332 iLoop, pWLoop, &revMask) ){
drh6b7157b2013-05-10 02:00:35 +00005333 case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
5334 isOrdered = 1;
5335 isOrderedValid = 1;
5336 break;
5337 case 0: /* No. pFrom+pWLoop will require a separate sort */
5338 isOrdered = 0;
5339 isOrderedValid = 1;
drhb8a8e8a2013-06-10 19:12:39 +00005340 rCost = whereCostAdd(rCost, rSortCost);
drh6b7157b2013-05-10 02:00:35 +00005341 break;
5342 default: /* Cannot tell yet. Try again on the next iteration */
5343 break;
5344 }
drh3a5ba8b2013-06-03 15:34:48 +00005345 }else{
5346 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00005347 }
5348 /* Check to see if pWLoop should be added to the mxChoice best so far */
5349 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
5350 if( pTo->maskLoop==maskNew && pTo->isOrderedValid==isOrderedValid ){
drh7963b0e2013-06-17 21:37:40 +00005351 testcase( jj==nTo-1 );
drh6b7157b2013-05-10 02:00:35 +00005352 break;
5353 }
5354 }
drha18f3d22013-05-08 03:05:41 +00005355 if( jj>=nTo ){
drhd15cb172013-05-21 19:23:10 +00005356 if( nTo>=mxChoice && rCost>=mxCost ){
drhae70cf12013-05-31 15:18:46 +00005357#ifdef WHERETRACE_ENABLED
5358 if( sqlite3WhereTrace&0x4 ){
drhb8a8e8a2013-06-10 19:12:39 +00005359 sqlite3DebugPrintf("Skip %s cost=%3d order=%c\n",
drhd15cb172013-05-21 19:23:10 +00005360 wherePathName(pFrom, iLoop, pWLoop), rCost,
5361 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5362 }
5363#endif
5364 continue;
5365 }
5366 /* Add a new Path to the aTo[] set */
drha18f3d22013-05-08 03:05:41 +00005367 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00005368 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00005369 jj = nTo++;
5370 }else{
drhd15cb172013-05-21 19:23:10 +00005371 /* New path replaces the prior worst to keep count below mxChoice */
drhc718f1c2013-05-08 20:05:58 +00005372 for(jj=nTo-1; aTo[jj].rCost<mxCost; jj--){ assert(jj>0); }
drha18f3d22013-05-08 03:05:41 +00005373 }
5374 pTo = &aTo[jj];
drhd15cb172013-05-21 19:23:10 +00005375#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005376 if( sqlite3WhereTrace&0x4 ){
drhb8a8e8a2013-06-10 19:12:39 +00005377 sqlite3DebugPrintf("New %s cost=%-3d order=%c\n",
drhd15cb172013-05-21 19:23:10 +00005378 wherePathName(pFrom, iLoop, pWLoop), rCost,
5379 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5380 }
5381#endif
drhf204dac2013-05-08 03:22:07 +00005382 }else{
drhd15cb172013-05-21 19:23:10 +00005383 if( pTo->rCost<=rCost ){
5384#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005385 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005386 sqlite3DebugPrintf(
drhb8a8e8a2013-06-10 19:12:39 +00005387 "Skip %s cost=%-3d order=%c",
drhd15cb172013-05-21 19:23:10 +00005388 wherePathName(pFrom, iLoop, pWLoop), rCost,
5389 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
drhb8a8e8a2013-06-10 19:12:39 +00005390 sqlite3DebugPrintf(" vs %s cost=%-3d order=%c\n",
drhd15cb172013-05-21 19:23:10 +00005391 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
5392 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5393 }
5394#endif
drh7963b0e2013-06-17 21:37:40 +00005395 testcase( pTo->rCost==rCost );
drhd15cb172013-05-21 19:23:10 +00005396 continue;
5397 }
drh7963b0e2013-06-17 21:37:40 +00005398 testcase( pTo->rCost==rCost+1 );
drhd15cb172013-05-21 19:23:10 +00005399 /* A new and better score for a previously created equivalent path */
5400#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005401 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005402 sqlite3DebugPrintf(
drhb8a8e8a2013-06-10 19:12:39 +00005403 "Update %s cost=%-3d order=%c",
drhd15cb172013-05-21 19:23:10 +00005404 wherePathName(pFrom, iLoop, pWLoop), rCost,
5405 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
drhb8a8e8a2013-06-10 19:12:39 +00005406 sqlite3DebugPrintf(" was %s cost=%-3d order=%c\n",
drhd15cb172013-05-21 19:23:10 +00005407 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
5408 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5409 }
5410#endif
drha18f3d22013-05-08 03:05:41 +00005411 }
drh6b7157b2013-05-10 02:00:35 +00005412 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00005413 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00005414 pTo->revLoop = revMask;
drhb8a8e8a2013-06-10 19:12:39 +00005415 pTo->nRow = pFrom->nRow + pWLoop->nOut;
drha18f3d22013-05-08 03:05:41 +00005416 pTo->rCost = rCost;
drh6b7157b2013-05-10 02:00:35 +00005417 pTo->isOrderedValid = isOrderedValid;
5418 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00005419 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5420 pTo->aLoop[iLoop] = pWLoop;
5421 if( nTo>=mxChoice ){
5422 mxCost = aTo[0].rCost;
5423 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
5424 if( pTo->rCost>mxCost ) mxCost = pTo->rCost;
5425 }
5426 }
5427 }
5428 }
5429
drhd15cb172013-05-21 19:23:10 +00005430#ifdef WHERETRACE_ENABLED
5431 if( sqlite3WhereTrace>=2 ){
drha50ef112013-05-22 02:06:59 +00005432 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00005433 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drhb8a8e8a2013-06-10 19:12:39 +00005434 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
drha50ef112013-05-22 02:06:59 +00005435 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00005436 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
drh88da6442013-05-27 17:59:37 +00005437 if( pTo->isOrderedValid && pTo->isOrdered ){
5438 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5439 }else{
5440 sqlite3DebugPrintf("\n");
5441 }
drhf204dac2013-05-08 03:22:07 +00005442 }
5443 }
5444#endif
5445
drh6b7157b2013-05-10 02:00:35 +00005446 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00005447 pFrom = aTo;
5448 aTo = aFrom;
5449 aFrom = pFrom;
5450 nFrom = nTo;
5451 }
5452
drh75b93402013-05-31 20:43:57 +00005453 if( nFrom==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00005454 sqlite3ErrorMsg(pParse, "no query solution");
drh75b93402013-05-31 20:43:57 +00005455 sqlite3DbFree(db, pSpace);
5456 return SQLITE_ERROR;
5457 }
drha18f3d22013-05-08 03:05:41 +00005458
drh6b7157b2013-05-10 02:00:35 +00005459 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00005460 pFrom = aFrom;
drh93ec45d2013-06-17 18:20:48 +00005461 assert( nFrom==1 );
5462#if 0 /* The following is needed if nFrom is ever more than 1 */
drha18f3d22013-05-08 03:05:41 +00005463 for(ii=1; ii<nFrom; ii++){
5464 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5465 }
drh93ec45d2013-06-17 18:20:48 +00005466#endif
drha18f3d22013-05-08 03:05:41 +00005467 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00005468 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00005469 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00005470 WhereLevel *pLevel = pWInfo->a + iLoop;
5471 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
drhe217efc2013-06-12 03:48:41 +00005472 pLevel->iFrom = pWLoop->iTab;
drh7ba39a92013-05-30 17:43:19 +00005473 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00005474 }
drhfd636c72013-06-21 02:05:06 +00005475 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5476 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5477 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
drh4f402f22013-06-11 18:59:38 +00005478 && nRowEst
5479 ){
5480 Bitmask notUsed;
drh6457a352013-06-21 00:35:37 +00005481 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
drh93ec45d2013-06-17 18:20:48 +00005482 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
drh4f402f22013-06-11 18:59:38 +00005483 if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5484 }
drh6b7157b2013-05-10 02:00:35 +00005485 if( pFrom->isOrdered ){
drh4f402f22013-06-11 18:59:38 +00005486 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
5487 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5488 }else{
5489 pWInfo->bOBSat = 1;
5490 pWInfo->revMask = pFrom->revLoop;
5491 }
drh6b7157b2013-05-10 02:00:35 +00005492 }
drha50ef112013-05-22 02:06:59 +00005493 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00005494
5495 /* Free temporary memory and return success */
5496 sqlite3DbFree(db, pSpace);
5497 return SQLITE_OK;
5498}
drh94a11212004-09-25 13:12:14 +00005499
5500/*
drh60c96cd2013-06-09 17:21:25 +00005501** Most queries use only a single table (they are not joins) and have
5502** simple == constraints against indexed fields. This routine attempts
5503** to plan those simple cases using much less ceremony than the
5504** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5505** times for the common case.
5506**
5507** Return non-zero on success, if this query can be handled by this
5508** no-frills query planner. Return zero if this query needs the
5509** general-purpose query planner.
5510*/
drhb8a8e8a2013-06-10 19:12:39 +00005511static int whereShortCut(WhereLoopBuilder *pBuilder){
drh60c96cd2013-06-09 17:21:25 +00005512 WhereInfo *pWInfo;
5513 struct SrcList_item *pItem;
5514 WhereClause *pWC;
5515 WhereTerm *pTerm;
5516 WhereLoop *pLoop;
5517 int iCur;
drh92a121f2013-06-10 12:15:47 +00005518 int j;
drh60c96cd2013-06-09 17:21:25 +00005519 Table *pTab;
5520 Index *pIdx;
5521
5522 pWInfo = pBuilder->pWInfo;
drh5822d6f2013-06-10 23:30:09 +00005523 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
drh60c96cd2013-06-09 17:21:25 +00005524 assert( pWInfo->pTabList->nSrc>=1 );
5525 pItem = pWInfo->pTabList->a;
5526 pTab = pItem->pTab;
5527 if( IsVirtual(pTab) ) return 0;
5528 if( pItem->zIndex ) return 0;
5529 iCur = pItem->iCursor;
5530 pWC = &pWInfo->sWC;
5531 pLoop = pBuilder->pNew;
drh60c96cd2013-06-09 17:21:25 +00005532 pLoop->wsFlags = 0;
drh3b75ffa2013-06-10 14:56:25 +00005533 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
drh60c96cd2013-06-09 17:21:25 +00005534 if( pTerm ){
5535 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5536 pLoop->aLTerm[0] = pTerm;
5537 pLoop->nLTerm = 1;
5538 pLoop->u.btree.nEq = 1;
drhe1e2e9a2013-06-13 15:16:53 +00005539 /* TUNING: Cost of a rowid lookup is 10 */
5540 pLoop->rRun = 33; /* 33==whereCost(10) */
drh60c96cd2013-06-09 17:21:25 +00005541 }else{
5542 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5543 if( pIdx->onError==OE_None ) continue;
5544 for(j=0; j<pIdx->nColumn; j++){
drh3b75ffa2013-06-10 14:56:25 +00005545 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
drh60c96cd2013-06-09 17:21:25 +00005546 if( pTerm==0 ) break;
5547 whereLoopResize(pWInfo->pParse->db, pLoop, j);
5548 pLoop->aLTerm[j] = pTerm;
5549 }
5550 if( j!=pIdx->nColumn ) continue;
drh92a121f2013-06-10 12:15:47 +00005551 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
drhfd5874d2013-06-12 14:52:39 +00005552 if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
drh92a121f2013-06-10 12:15:47 +00005553 pLoop->wsFlags |= WHERE_IDX_ONLY;
5554 }
drh60c96cd2013-06-09 17:21:25 +00005555 pLoop->nLTerm = j;
5556 pLoop->u.btree.nEq = j;
5557 pLoop->u.btree.pIndex = pIdx;
drhe1e2e9a2013-06-13 15:16:53 +00005558 /* TUNING: Cost of a unique index lookup is 15 */
5559 pLoop->rRun = 39; /* 39==whereCost(15) */
drh60c96cd2013-06-09 17:21:25 +00005560 break;
5561 }
5562 }
drh3b75ffa2013-06-10 14:56:25 +00005563 if( pLoop->wsFlags ){
5564 pLoop->nOut = (WhereCost)1;
5565 pWInfo->a[0].pWLoop = pLoop;
5566 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
5567 pWInfo->a[0].iTabCur = iCur;
5568 pWInfo->nRowOut = 1;
drh4f402f22013-06-11 18:59:38 +00005569 if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
drh6457a352013-06-21 00:35:37 +00005570 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5571 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5572 }
drh3b75ffa2013-06-10 14:56:25 +00005573#ifdef SQLITE_DEBUG
5574 pLoop->cId = '0';
5575#endif
5576 return 1;
5577 }
5578 return 0;
drh60c96cd2013-06-09 17:21:25 +00005579}
5580
5581/*
drhe3184742002-06-19 14:27:05 +00005582** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00005583** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00005584** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00005585** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00005586** in order to complete the WHERE clause processing.
5587**
5588** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00005589**
5590** The basic idea is to do a nested loop, one loop for each table in
5591** the FROM clause of a select. (INSERT and UPDATE statements are the
5592** same as a SELECT with only a single table in the FROM clause.) For
5593** example, if the SQL is this:
5594**
5595** SELECT * FROM t1, t2, t3 WHERE ...;
5596**
5597** Then the code generated is conceptually like the following:
5598**
5599** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005600** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00005601** foreach row3 in t3 do /
5602** ...
5603** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005604** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00005605** end /
5606**
drh29dda4a2005-07-21 18:23:20 +00005607** Note that the loops might not be nested in the order in which they
5608** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00005609** use of indices. Note also that when the IN operator appears in
5610** the WHERE clause, it might result in additional nested loops for
5611** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00005612**
drhc27a1ce2002-06-14 20:58:45 +00005613** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00005614** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5615** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00005616** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00005617**
drhe6f85e72004-12-25 01:03:13 +00005618** The code that sqlite3WhereBegin() generates leaves the cursors named
5619** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00005620** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00005621** data from the various tables of the loop.
5622**
drhc27a1ce2002-06-14 20:58:45 +00005623** If the WHERE clause is empty, the foreach loops must each scan their
5624** entire tables. Thus a three-way join is an O(N^3) operation. But if
5625** the tables have indices and there are terms in the WHERE clause that
5626** refer to those indices, a complete table scan can be avoided and the
5627** code will run much faster. Most of the work of this routine is checking
5628** to see if there are indices that can be used to speed up the loop.
5629**
5630** Terms of the WHERE clause are also used to limit which rows actually
5631** make it to the "..." in the middle of the loop. After each "foreach",
5632** terms of the WHERE clause that use only terms in that loop and outer
5633** loops are evaluated and if false a jump is made around all subsequent
5634** inner loops (or around the "..." if the test occurs within the inner-
5635** most loop)
5636**
5637** OUTER JOINS
5638**
5639** An outer join of tables t1 and t2 is conceptally coded as follows:
5640**
5641** foreach row1 in t1 do
5642** flag = 0
5643** foreach row2 in t2 do
5644** start:
5645** ...
5646** flag = 1
5647** end
drhe3184742002-06-19 14:27:05 +00005648** if flag==0 then
5649** move the row2 cursor to a null row
5650** goto start
5651** fi
drhc27a1ce2002-06-14 20:58:45 +00005652** end
5653**
drhe3184742002-06-19 14:27:05 +00005654** ORDER BY CLAUSE PROCESSING
5655**
drh94433422013-07-01 11:05:50 +00005656** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
5657** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
drhe3184742002-06-19 14:27:05 +00005658** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00005659** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drh75897232000-05-29 14:26:00 +00005660*/
danielk19774adee202004-05-08 08:23:19 +00005661WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00005662 Parse *pParse, /* The parser context */
drh6457a352013-06-21 00:35:37 +00005663 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
danielk1977ed326d72004-11-16 15:50:19 +00005664 Expr *pWhere, /* The WHERE clause */
drh46ec5b62012-09-24 15:30:54 +00005665 ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
drh6457a352013-06-21 00:35:37 +00005666 ExprList *pResultSet, /* Result set of the query */
dan0efb72c2012-08-24 18:44:56 +00005667 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
5668 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00005669){
danielk1977be229652009-03-20 14:18:51 +00005670 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00005671 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00005672 WhereInfo *pWInfo; /* Will become the return value of this function */
5673 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00005674 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00005675 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00005676 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00005677 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drhfd636c72013-06-21 02:05:06 +00005678 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
drh9cd1c992012-09-25 20:43:35 +00005679 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00005680 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00005681 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00005682
drh56f1b992012-09-25 14:29:39 +00005683
5684 /* Variable initialization */
drhfd636c72013-06-21 02:05:06 +00005685 db = pParse->db;
drh1c8148f2013-05-04 20:25:23 +00005686 memset(&sWLB, 0, sizeof(sWLB));
drh1c8148f2013-05-04 20:25:23 +00005687 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00005688
drhfd636c72013-06-21 02:05:06 +00005689 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
5690 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
5691 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
5692 wctrlFlags &= ~WHERE_WANT_DISTINCT;
5693 }
5694
drh29dda4a2005-07-21 18:23:20 +00005695 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00005696 ** bits in a Bitmask
5697 */
drh67ae0cb2010-04-08 14:38:51 +00005698 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00005699 if( pTabList->nSrc>BMS ){
5700 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00005701 return 0;
5702 }
5703
drhc01a3c12009-12-16 22:10:49 +00005704 /* This function normally generates a nested loop for all tables in
5705 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
5706 ** only generate code for the first table in pTabList and assume that
5707 ** any cursors associated with subsequent tables are uninitialized.
5708 */
5709 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
5710
drh75897232000-05-29 14:26:00 +00005711 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00005712 ** return value. A single allocation is used to store the WhereInfo
5713 ** struct, the contents of WhereInfo.a[], the WhereClause structure
5714 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5715 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5716 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00005717 */
drhc01a3c12009-12-16 22:10:49 +00005718 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00005719 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00005720 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00005721 sqlite3DbFree(db, pWInfo);
5722 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00005723 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00005724 }
drhc01a3c12009-12-16 22:10:49 +00005725 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00005726 pWInfo->pParse = pParse;
5727 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00005728 pWInfo->pOrderBy = pOrderBy;
drh6457a352013-06-21 00:35:37 +00005729 pWInfo->pResultSet = pResultSet;
danielk19774adee202004-05-08 08:23:19 +00005730 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00005731 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00005732 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00005733 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00005734 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00005735 sWLB.pWC = &pWInfo->sWC;
drh1ac87e12013-07-18 14:50:56 +00005736 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
5737 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
drh60c96cd2013-06-09 17:21:25 +00005738 whereLoopInit(sWLB.pNew);
drhb8a8e8a2013-06-10 19:12:39 +00005739#ifdef SQLITE_DEBUG
5740 sWLB.pNew->cId = '*';
5741#endif
drh08192d52002-04-30 19:20:28 +00005742
drh111a6a72008-12-21 03:51:16 +00005743 /* Split the WHERE clause into separate subexpressions where each
5744 ** subexpression is separated by an AND operator.
5745 */
5746 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00005747 whereClauseInit(&pWInfo->sWC, pWInfo);
drh111a6a72008-12-21 03:51:16 +00005748 sqlite3ExprCodeConstants(pParse, pWhere);
drh70d18342013-06-06 19:16:33 +00005749 whereSplit(&pWInfo->sWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
drh5e128b22013-07-09 03:04:32 +00005750 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
drh111a6a72008-12-21 03:51:16 +00005751
drh08192d52002-04-30 19:20:28 +00005752 /* Special case: a WHERE clause that is constant. Evaluate the
5753 ** expression and either jump over all of the code or fall thru.
5754 */
drhc01a3c12009-12-16 22:10:49 +00005755 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
drh35573352008-01-08 23:54:25 +00005756 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
drhdf199a22002-06-14 22:38:41 +00005757 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00005758 }
drh75897232000-05-29 14:26:00 +00005759
drh4fe425a2013-06-12 17:08:06 +00005760 /* Special case: No FROM clause
5761 */
5762 if( nTabList==0 ){
5763 if( pOrderBy ) pWInfo->bOBSat = 1;
drh6457a352013-06-21 00:35:37 +00005764 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5765 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5766 }
drh4fe425a2013-06-12 17:08:06 +00005767 }
5768
drh42165be2008-03-26 14:56:34 +00005769 /* Assign a bit from the bitmask to every term in the FROM clause.
5770 **
5771 ** When assigning bitmask values to FROM clause cursors, it must be
5772 ** the case that if X is the bitmask for the N-th FROM clause term then
5773 ** the bitmask for all FROM clause terms to the left of the N-th term
5774 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
5775 ** its Expr.iRightJoinTable value to find the bitmask of the right table
5776 ** of the join. Subtracting one from the right table bitmask gives a
5777 ** bitmask for all tables to the left of the join. Knowing the bitmask
5778 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00005779 **
drhc01a3c12009-12-16 22:10:49 +00005780 ** Note that bitmasks are created for all pTabList->nSrc tables in
5781 ** pTabList, not just the first nTabList tables. nTabList is normally
5782 ** equal to pTabList->nSrc but might be shortened to 1 if the
5783 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00005784 */
drh9cd1c992012-09-25 20:43:35 +00005785 for(ii=0; ii<pTabList->nSrc; ii++){
5786 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005787 }
5788#ifndef NDEBUG
5789 {
5790 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00005791 for(ii=0; ii<pTabList->nSrc; ii++){
5792 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005793 assert( (m-1)==toTheLeft );
5794 toTheLeft |= m;
5795 }
5796 }
5797#endif
5798
drh29dda4a2005-07-21 18:23:20 +00005799 /* Analyze all of the subexpressions. Note that exprAnalyze() might
5800 ** add new virtual terms onto the end of the WHERE clause. We do not
5801 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00005802 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00005803 */
drh70d18342013-06-06 19:16:33 +00005804 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drh17435752007-08-16 04:30:38 +00005805 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00005806 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00005807 }
drh75897232000-05-29 14:26:00 +00005808
drh4f402f22013-06-11 18:59:38 +00005809 /* If the ORDER BY (or GROUP BY) clause contains references to general
5810 ** expressions, then we won't be able to satisfy it using indices, so
5811 ** go ahead and disable it now.
5812 */
drh6457a352013-06-21 00:35:37 +00005813 if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
drh4f402f22013-06-11 18:59:38 +00005814 for(ii=0; ii<pOrderBy->nExpr; ii++){
5815 Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
5816 if( pExpr->op!=TK_COLUMN ){
5817 pWInfo->pOrderBy = pOrderBy = 0;
5818 break;
drhe217efc2013-06-12 03:48:41 +00005819 }else if( pExpr->iColumn<0 ){
5820 break;
drh4f402f22013-06-11 18:59:38 +00005821 }
5822 }
5823 }
5824
drh6457a352013-06-21 00:35:37 +00005825 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5826 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
5827 /* The DISTINCT marking is pointless. Ignore it. */
drh4f402f22013-06-11 18:59:38 +00005828 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5829 }else if( pOrderBy==0 ){
drh6457a352013-06-21 00:35:37 +00005830 /* Try to ORDER BY the result set to make distinct processing easier */
drh4f402f22013-06-11 18:59:38 +00005831 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
drh6457a352013-06-21 00:35:37 +00005832 pWInfo->pOrderBy = pResultSet;
drh4f402f22013-06-11 18:59:38 +00005833 }
dan38cc40c2011-06-30 20:17:15 +00005834 }
5835
drhf1b5f5b2013-05-02 00:15:01 +00005836 /* Construct the WhereLoop objects */
drh3b48e8c2013-06-12 20:18:16 +00005837 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
drhb8a8e8a2013-06-10 19:12:39 +00005838 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
drh60c96cd2013-06-09 17:21:25 +00005839 rc = whereLoopAddAll(&sWLB);
5840 if( rc ) goto whereBeginError;
5841
5842 /* Display all of the WhereLoop objects if wheretrace is enabled */
drhd15cb172013-05-21 19:23:10 +00005843#ifdef WHERETRACE_ENABLED
drh60c96cd2013-06-09 17:21:25 +00005844 if( sqlite3WhereTrace ){
5845 WhereLoop *p;
drhfd636c72013-06-21 02:05:06 +00005846 int i;
drh60c96cd2013-06-09 17:21:25 +00005847 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5848 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
drhfd636c72013-06-21 02:05:06 +00005849 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5850 p->cId = zLabel[i%sizeof(zLabel)];
drh60c96cd2013-06-09 17:21:25 +00005851 whereLoopPrint(p, pTabList);
5852 }
5853 }
5854#endif
5855
drh4f402f22013-06-11 18:59:38 +00005856 wherePathSolver(pWInfo, 0);
drh60c96cd2013-06-09 17:21:25 +00005857 if( db->mallocFailed ) goto whereBeginError;
5858 if( pWInfo->pOrderBy ){
drhc7f0d222013-06-19 03:27:12 +00005859 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
drh60c96cd2013-06-09 17:21:25 +00005860 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00005861 }
5862 }
drh60c96cd2013-06-09 17:21:25 +00005863 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00005864 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00005865 }
drh81186b42013-06-18 01:52:41 +00005866 if( pParse->nErr || NEVER(db->mallocFailed) ){
drh75b93402013-05-31 20:43:57 +00005867 goto whereBeginError;
5868 }
drhd15cb172013-05-21 19:23:10 +00005869#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00005870 if( sqlite3WhereTrace ){
5871 int ii;
drh4f402f22013-06-11 18:59:38 +00005872 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
5873 if( pWInfo->bOBSat ){
5874 sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00005875 }
drh4f402f22013-06-11 18:59:38 +00005876 switch( pWInfo->eDistinct ){
5877 case WHERE_DISTINCT_UNIQUE: {
5878 sqlite3DebugPrintf(" DISTINCT=unique");
5879 break;
5880 }
5881 case WHERE_DISTINCT_ORDERED: {
5882 sqlite3DebugPrintf(" DISTINCT=ordered");
5883 break;
5884 }
5885 case WHERE_DISTINCT_UNORDERED: {
5886 sqlite3DebugPrintf(" DISTINCT=unordered");
5887 break;
5888 }
5889 }
5890 sqlite3DebugPrintf("\n");
drhfd636c72013-06-21 02:05:06 +00005891 for(ii=0; ii<pWInfo->nLevel; ii++){
drha18f3d22013-05-08 03:05:41 +00005892 whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
drhf1b5f5b2013-05-02 00:15:01 +00005893 }
5894 }
5895#endif
drhfd636c72013-06-21 02:05:06 +00005896 /* Attempt to omit tables from the join that do not effect the result */
drh1031bd92013-06-22 15:44:26 +00005897 if( pWInfo->nLevel>=2
5898 && pResultSet!=0
5899 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
5900 ){
drhfd636c72013-06-21 02:05:06 +00005901 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
5902 if( pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, pOrderBy);
5903 while( pWInfo->nLevel>=2 ){
drh9d5a5792013-06-28 13:43:33 +00005904 WhereTerm *pTerm, *pEnd;
drhfd636c72013-06-21 02:05:06 +00005905 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
drhbc71b1d2013-06-21 02:15:48 +00005906 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
5907 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
5908 && (pLoop->wsFlags & WHERE_ONEROW)==0
drhfd636c72013-06-21 02:05:06 +00005909 ){
drhfd636c72013-06-21 02:05:06 +00005910 break;
5911 }
drhbc71b1d2013-06-21 02:15:48 +00005912 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
drh9d5a5792013-06-28 13:43:33 +00005913 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
5914 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
5915 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
5916 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
5917 ){
5918 break;
5919 }
5920 }
5921 if( pTerm<pEnd ) break;
drhbc71b1d2013-06-21 02:15:48 +00005922 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
5923 pWInfo->nLevel--;
5924 nTabList--;
drhfd636c72013-06-21 02:05:06 +00005925 }
5926 }
drh3b48e8c2013-06-12 20:18:16 +00005927 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
drh8e23daf2013-06-11 13:30:04 +00005928 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
drhf1b5f5b2013-05-02 00:15:01 +00005929
drh08c88eb2008-04-10 13:33:18 +00005930 /* If the caller is an UPDATE or DELETE statement that is requesting
5931 ** to use a one-pass algorithm, determine if this is appropriate.
5932 ** The one-pass algorithm only works if the WHERE clause constraints
5933 ** the statement to update a single row.
5934 */
drh165be382008-12-05 02:36:33 +00005935 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh3b48e8c2013-06-12 20:18:16 +00005936 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
5937 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00005938 pWInfo->okOnePass = 1;
drh3b48e8c2013-06-12 20:18:16 +00005939 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
drh08c88eb2008-04-10 13:33:18 +00005940 }
drheb04de32013-05-10 15:16:30 +00005941
drh9012bcb2004-12-19 00:11:35 +00005942 /* Open all tables in the pTabList and any indices selected for
5943 ** searching those tables.
5944 */
drh8b307fb2010-04-06 15:57:05 +00005945 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00005946 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00005947 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00005948 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00005949 struct SrcList_item *pTabItem;
drh9012bcb2004-12-19 00:11:35 +00005950
drh29dda4a2005-07-21 18:23:20 +00005951 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005952 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00005953 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00005954 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00005955 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00005956 /* Do nothing */
5957 }else
drh9eff6162006-06-12 21:59:13 +00005958#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00005959 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00005960 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00005961 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00005962 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00005963 }else if( IsVirtual(pTab) ){
5964 /* noop */
drh9eff6162006-06-12 21:59:13 +00005965 }else
5966#endif
drh7ba39a92013-05-30 17:43:19 +00005967 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00005968 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drh08c88eb2008-04-10 13:33:18 +00005969 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
5970 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drh7963b0e2013-06-17 21:37:40 +00005971 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
5972 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
danielk197723432972008-11-17 16:42:00 +00005973 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
danielk19779792eef2006-01-13 15:58:43 +00005974 Bitmask b = pTabItem->colUsed;
5975 int n = 0;
drh74161702006-02-24 02:53:49 +00005976 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00005977 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
5978 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00005979 assert( n<=pTab->nCol );
5980 }
danielk1977c00da102006-01-07 13:21:04 +00005981 }else{
5982 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00005983 }
drhc6339082010-04-07 16:54:58 +00005984#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh986b3872013-06-28 21:12:20 +00005985 if( (pLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
drh70d18342013-06-06 19:16:33 +00005986 constructAutomaticIndex(pParse, &pWInfo->sWC, pTabItem, notReady, pLevel);
drhc6339082010-04-07 16:54:58 +00005987 }else
5988#endif
drh7e47cb82013-05-31 17:55:27 +00005989 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00005990 Index *pIx = pLoop->u.btree.pIndex;
danielk1977b3bf5562006-01-10 17:58:23 +00005991 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
drhae70cf12013-05-31 15:18:46 +00005992 /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
5993 int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
danielk1977da184232006-01-05 11:34:32 +00005994 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00005995 assert( iIndexCur>=0 );
5996 sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00005997 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00005998 VdbeComment((v, "%s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00005999 }
danielk1977da184232006-01-05 11:34:32 +00006000 sqlite3CodeVerifySchema(pParse, iDb);
drh70d18342013-06-06 19:16:33 +00006001 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00006002 }
6003 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00006004 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00006005
drh29dda4a2005-07-21 18:23:20 +00006006 /* Generate the code to do the search. Each iteration of the for
6007 ** loop below generates code for a single nested loop of the VM
6008 ** program.
drh75897232000-05-29 14:26:00 +00006009 */
drhfe05af82005-07-21 03:14:59 +00006010 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00006011 for(ii=0; ii<nTabList; ii++){
6012 pLevel = &pWInfo->a[ii];
6013 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
drh70d18342013-06-06 19:16:33 +00006014 notReady = codeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00006015 pWInfo->iContinue = pLevel->addrCont;
drh75897232000-05-29 14:26:00 +00006016 }
drh7ec764a2005-07-21 03:48:20 +00006017
drh6fa978d2013-05-30 19:29:19 +00006018 /* Done. */
drh75897232000-05-29 14:26:00 +00006019 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00006020
6021 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00006022whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00006023 if( pWInfo ){
6024 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6025 whereInfoFree(db, pWInfo);
6026 }
drhe23399f2005-07-22 00:31:39 +00006027 return 0;
drh75897232000-05-29 14:26:00 +00006028}
6029
6030/*
drhc27a1ce2002-06-14 20:58:45 +00006031** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00006032** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00006033*/
danielk19774adee202004-05-08 08:23:19 +00006034void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00006035 Parse *pParse = pWInfo->pParse;
6036 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00006037 int i;
drh6b563442001-11-07 16:48:26 +00006038 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00006039 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00006040 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00006041 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00006042
drh9012bcb2004-12-19 00:11:35 +00006043 /* Generate loop termination code.
6044 */
drhceea3322009-04-23 13:22:42 +00006045 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00006046 for(i=pWInfo->nLevel-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00006047 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00006048 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00006049 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00006050 if( pLevel->op!=OP_Noop ){
drh66a51672008-01-03 00:01:23 +00006051 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
drhd1d38482008-10-07 23:46:38 +00006052 sqlite3VdbeChangeP5(v, pLevel->p5);
drh19a775c2000-06-05 18:54:46 +00006053 }
drh7ba39a92013-05-30 17:43:19 +00006054 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00006055 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00006056 int j;
drhb3190c12008-12-08 21:37:14 +00006057 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00006058 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00006059 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00006060 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drhb3190c12008-12-08 21:37:14 +00006061 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00006062 }
drh111a6a72008-12-21 03:51:16 +00006063 sqlite3DbFree(db, pLevel->u.in.aInLoop);
drhd99f7062002-06-08 23:25:08 +00006064 }
drhb3190c12008-12-08 21:37:14 +00006065 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhad2d8302002-05-24 20:31:36 +00006066 if( pLevel->iLeftJoin ){
6067 int addr;
drh3c84ddf2008-01-09 02:15:38 +00006068 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
drh7ba39a92013-05-30 17:43:19 +00006069 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6070 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
6071 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00006072 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
6073 }
drh76f4cfb2013-05-31 18:20:52 +00006074 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00006075 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00006076 }
drh336a5302009-04-24 15:46:21 +00006077 if( pLevel->op==OP_Return ){
6078 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
6079 }else{
6080 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
6081 }
drhd654be82005-09-20 17:42:23 +00006082 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00006083 }
drh19a775c2000-06-05 18:54:46 +00006084 }
drh9012bcb2004-12-19 00:11:35 +00006085
6086 /* The "break" point is here, just past the end of the outer loop.
6087 ** Set it.
6088 */
danielk19774adee202004-05-08 08:23:19 +00006089 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00006090
drh29dda4a2005-07-21 18:23:20 +00006091 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00006092 */
drhfd636c72013-06-21 02:05:06 +00006093 assert( pWInfo->nLevel<=pTabList->nSrc );
drhc01a3c12009-12-16 22:10:49 +00006094 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
danbfca6a42012-08-24 10:52:35 +00006095 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00006096 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00006097 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00006098 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00006099 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00006100 if( (pTab->tabFlags & TF_Ephemeral)==0
6101 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00006102 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00006103 ){
drh7ba39a92013-05-30 17:43:19 +00006104 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00006105 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00006106 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
6107 }
drh986b3872013-06-28 21:12:20 +00006108 if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){
drh6df2acd2008-12-28 16:55:25 +00006109 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
6110 }
drh9012bcb2004-12-19 00:11:35 +00006111 }
6112
drhf0030762013-06-14 13:27:01 +00006113 /* If this scan uses an index, make VDBE code substitutions to read data
6114 ** from the index instead of from the table where possible. In some cases
6115 ** this optimization prevents the table from ever being read, which can
6116 ** yield a significant performance boost.
drh9012bcb2004-12-19 00:11:35 +00006117 **
6118 ** Calls to the code generator in between sqlite3WhereBegin and
6119 ** sqlite3WhereEnd will have created code that references the table
6120 ** directly. This loop scans all that code looking for opcodes
6121 ** that reference the table and converts them into opcodes that
6122 ** reference the index.
6123 */
drh7ba39a92013-05-30 17:43:19 +00006124 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
6125 pIdx = pLoop->u.btree.pIndex;
6126 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00006127 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00006128 }
drh7ba39a92013-05-30 17:43:19 +00006129 if( pIdx && !db->mallocFailed ){
danielk1977f0113002006-01-24 12:09:17 +00006130 int k, j, last;
drh9012bcb2004-12-19 00:11:35 +00006131 VdbeOp *pOp;
drh9012bcb2004-12-19 00:11:35 +00006132
drh9012bcb2004-12-19 00:11:35 +00006133 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
6134 last = sqlite3VdbeCurrentAddr(v);
danielk1977f0113002006-01-24 12:09:17 +00006135 for(k=pWInfo->iTop; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00006136 if( pOp->p1!=pLevel->iTabCur ) continue;
6137 if( pOp->opcode==OP_Column ){
drh9012bcb2004-12-19 00:11:35 +00006138 for(j=0; j<pIdx->nColumn; j++){
6139 if( pOp->p2==pIdx->aiColumn[j] ){
6140 pOp->p2 = j;
danielk197721de2e72007-11-29 17:43:27 +00006141 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00006142 break;
6143 }
6144 }
drh7ba39a92013-05-30 17:43:19 +00006145 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
drhf0863fe2005-06-12 21:35:51 +00006146 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00006147 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00006148 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00006149 }
6150 }
drh6b563442001-11-07 16:48:26 +00006151 }
drh19a775c2000-06-05 18:54:46 +00006152 }
drh9012bcb2004-12-19 00:11:35 +00006153
6154 /* Final cleanup
6155 */
drhf12cde52010-04-08 17:28:00 +00006156 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6157 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00006158 return;
6159}