blob: a43c5a39c0dd58e4e80d4f43cb7f82e6c6512259 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
12** This module contains C code that generates VDBE code used to process
drh909626d2008-05-30 14:58:37 +000013** the WHERE clause of SQL statements. This module is responsible for
drh51669862004-12-18 18:40:26 +000014** generating the code that loops through a table looking for applicable
15** rows. Indices are selected and used to speed the search when doing
16** so is applicable. Because this module is responsible for selecting
17** indices, you might also think of this module as the "query optimizer".
drh75897232000-05-29 14:26:00 +000018*/
19#include "sqliteInt.h"
20
drh7924f3e2011-02-09 03:04:27 +000021
22/*
drh51147ba2005-07-23 22:59:55 +000023** Trace output macros
24*/
25#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
drhcef4fc82012-09-21 22:50:45 +000026/***/ int sqlite3WhereTrace = 0;
drhe8f52c52008-07-12 14:52:20 +000027#endif
drhcef4fc82012-09-21 22:50:45 +000028#if defined(SQLITE_DEBUG) \
29 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
drh3b48e8c2013-06-12 20:18:16 +000030# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
drhd15cb172013-05-21 19:23:10 +000031# define WHERETRACE_ENABLED 1
drh51147ba2005-07-23 22:59:55 +000032#else
drh3b48e8c2013-06-12 20:18:16 +000033# define WHERETRACE(K,X)
drh51147ba2005-07-23 22:59:55 +000034#endif
35
drh4a6fc352013-08-07 01:18:38 +000036/* Forward references
drh0fcef5e2005-07-19 17:38:22 +000037*/
38typedef struct WhereClause WhereClause;
drh111a6a72008-12-21 03:51:16 +000039typedef struct WhereMaskSet WhereMaskSet;
drh700a2262008-12-17 19:22:15 +000040typedef struct WhereOrInfo WhereOrInfo;
41typedef struct WhereAndInfo WhereAndInfo;
drh6f328482013-06-05 23:39:34 +000042typedef struct WhereLevel WhereLevel;
drhf1b5f5b2013-05-02 00:15:01 +000043typedef struct WhereLoop WhereLoop;
44typedef struct WherePath WherePath;
45typedef struct WhereTerm WhereTerm;
drh1c8148f2013-05-04 20:25:23 +000046typedef struct WhereLoopBuilder WhereLoopBuilder;
47typedef struct WhereScan WhereScan;
drhaa32e3c2013-07-16 21:31:23 +000048typedef struct WhereOrCost WhereOrCost;
49typedef struct WhereOrSet WhereOrSet;
drhc63367e2013-06-10 20:46:50 +000050
51/*
drhf0030762013-06-14 13:27:01 +000052** This object contains information needed to implement a single nested
drh3b48e8c2013-06-12 20:18:16 +000053** loop in WHERE clause.
drh6f328482013-06-05 23:39:34 +000054**
drh3b48e8c2013-06-12 20:18:16 +000055** Contrast this object with WhereLoop. This object describes the
56** implementation of the loop. WhereLoop describes the algorithm.
57** This object contains a pointer to the WhereLoop algorithm as one of
58** its elements.
59**
60** The WhereInfo object contains a single instance of this object for
61** each term in the FROM clause (which is to say, for each of the
62** nested loops as implemented). The order of WhereLevel objects determines
63** the loop nested order, with WhereInfo.a[0] being the outer loop and
64** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
drh6f328482013-06-05 23:39:34 +000065*/
66struct WhereLevel {
67 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
68 int iTabCur; /* The VDBE cursor used to access the table */
69 int iIdxCur; /* The VDBE cursor used to access pIdx */
70 int addrBrk; /* Jump here to break out of the loop */
71 int addrNxt; /* Jump here to start the next IN combination */
72 int addrCont; /* Jump here to continue with the next loop cycle */
73 int addrFirst; /* First instruction of interior of the loop */
drhcc04afd2013-08-22 02:56:28 +000074 int addrBody; /* Beginning of the body of this loop */
drhe217efc2013-06-12 03:48:41 +000075 u8 iFrom; /* Which entry in the FROM clause */
drh6f328482013-06-05 23:39:34 +000076 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
77 int p1, p2; /* Operands of the opcode used to ends the loop */
drh37ca0482013-06-12 17:17:45 +000078 union { /* Information that depends on pWLoop->wsFlags */
drh6f328482013-06-05 23:39:34 +000079 struct {
80 int nIn; /* Number of entries in aInLoop[] */
81 struct InLoop {
82 int iCur; /* The VDBE cursor used by this IN operator */
83 int addrInTop; /* Top of the IN loop */
84 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
85 } *aInLoop; /* Information about each nested IN operator */
drh37ca0482013-06-12 17:17:45 +000086 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
drh6f328482013-06-05 23:39:34 +000087 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
88 } u;
89 struct WhereLoop *pWLoop; /* The selected WhereLoop object */
drh0259bc32013-09-09 19:37:46 +000090 Bitmask notReady; /* FROM entries not usable at this level */
drh6f328482013-06-05 23:39:34 +000091};
92
93/*
drh3b48e8c2013-06-12 20:18:16 +000094** Each instance of this object represents an algorithm for evaluating one
95** term of a join. Every term of the FROM clause will have at least
96** one corresponding WhereLoop object (unless INDEXED BY constraints
97** prevent a query solution - which is an error) and many terms of the
98** FROM clause will have multiple WhereLoop objects, each describing a
99** potential way of implementing that FROM-clause term, together with
100** dependencies and cost estimates for using the chosen algorithm.
101**
102** Query planning consists of building up a collection of these WhereLoop
103** objects, then computing a particular sequence of WhereLoop objects, with
104** one WhereLoop object per FROM clause term, that satisfy all dependencies
105** and that minimize the overall cost.
drhf1b5f5b2013-05-02 00:15:01 +0000106*/
107struct WhereLoop {
108 Bitmask prereq; /* Bitmask of other loops that must run first */
drha18f3d22013-05-08 03:05:41 +0000109 Bitmask maskSelf; /* Bitmask identifying table iTab */
drhd15cb172013-05-21 19:23:10 +0000110#ifdef SQLITE_DEBUG
111 char cId; /* Symbolic ID of this loop for debugging use */
112#endif
drh7ba39a92013-05-30 17:43:19 +0000113 u8 iTab; /* Position in FROM clause of table for this loop */
drh23f98da2013-05-21 15:52:07 +0000114 u8 iSortIdx; /* Sorting index number. 0==None */
drhbf539c42013-10-05 18:16:02 +0000115 LogEst rSetup; /* One-time setup cost (ex: create transient index) */
116 LogEst rRun; /* Cost of running each loop */
117 LogEst nOut; /* Estimated number of output rows */
drh5346e952013-05-08 14:14:26 +0000118 union {
119 struct { /* Information for internal btree tables */
120 int nEq; /* Number of equality constraints */
121 Index *pIndex; /* Index used, or NULL */
122 } btree;
drh6b7157b2013-05-10 02:00:35 +0000123 struct { /* Information for virtual tables */
drh5346e952013-05-08 14:14:26 +0000124 int idxNum; /* Index number */
drh6b7157b2013-05-10 02:00:35 +0000125 u8 needFree; /* True if sqlite3_free(idxStr) is needed */
126 u8 isOrdered; /* True if satisfies ORDER BY */
drh3bd26f02013-05-24 14:52:03 +0000127 u16 omitMask; /* Terms that may be omitted */
drh5346e952013-05-08 14:14:26 +0000128 char *idxStr; /* Index identifier string */
129 } vtab;
130 } u;
drha2014152013-06-07 00:29:23 +0000131 u32 wsFlags; /* WHERE_* flags describing the plan */
132 u16 nLTerm; /* Number of entries in aLTerm[] */
133 /**** whereLoopXfer() copies fields above ***********************/
134# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
135 u16 nLSlot; /* Number of slots allocated for aLTerm[] */
drh4efc9292013-06-06 23:02:03 +0000136 WhereTerm **aLTerm; /* WhereTerms used */
drhf1b5f5b2013-05-02 00:15:01 +0000137 WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
drh4efc9292013-06-06 23:02:03 +0000138 WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
drhf1b5f5b2013-05-02 00:15:01 +0000139};
140
drhaa32e3c2013-07-16 21:31:23 +0000141/* This object holds the prerequisites and the cost of running a
142** subquery on one operand of an OR operator in the WHERE clause.
143** See WhereOrSet for additional information
144*/
145struct WhereOrCost {
146 Bitmask prereq; /* Prerequisites */
drhbf539c42013-10-05 18:16:02 +0000147 LogEst rRun; /* Cost of running this subquery */
148 LogEst nOut; /* Number of outputs for this subquery */
drhaa32e3c2013-07-16 21:31:23 +0000149};
150
151/* The WhereOrSet object holds a set of possible WhereOrCosts that
drh4a6fc352013-08-07 01:18:38 +0000152** correspond to the subquery(s) of OR-clause processing. Only the
153** best N_OR_COST elements are retained.
drhaa32e3c2013-07-16 21:31:23 +0000154*/
155#define N_OR_COST 3
156struct WhereOrSet {
157 u16 n; /* Number of valid a[] entries */
158 WhereOrCost a[N_OR_COST]; /* Set of best costs */
159};
160
161
drh4efc9292013-06-06 23:02:03 +0000162/* Forward declaration of methods */
163static int whereLoopResize(sqlite3*, WhereLoop*, int);
164
drhf1b5f5b2013-05-02 00:15:01 +0000165/*
166** Each instance of this object holds a sequence of WhereLoop objects
drh3b48e8c2013-06-12 20:18:16 +0000167** that implement some or all of a query plan.
168**
dan51576f42013-07-02 10:06:15 +0000169** Think of each WhereLoop object as a node in a graph with arcs
drhe56dd3a2013-08-30 17:50:35 +0000170** showing dependencies and costs for travelling between nodes. (That is
drh3b48e8c2013-06-12 20:18:16 +0000171** not a completely accurate description because WhereLoop costs are a
drhe56dd3a2013-08-30 17:50:35 +0000172** vector, not a scalar, and because dependencies are many-to-one, not
drh3b48e8c2013-06-12 20:18:16 +0000173** one-to-one as are graph nodes. But it is a useful visualization aid.)
174** Then a WherePath object is a path through the graph that visits some
175** or all of the WhereLoop objects once.
176**
177** The "solver" works by creating the N best WherePath objects of length
178** 1. Then using those as a basis to compute the N best WherePath objects
179** of length 2. And so forth until the length of WherePaths equals the
180** number of nodes in the FROM clause. The best (lowest cost) WherePath
181** at the end is the choosen query plan.
drhf1b5f5b2013-05-02 00:15:01 +0000182*/
183struct WherePath {
184 Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
drh319f6772013-05-14 15:31:07 +0000185 Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
drhbf539c42013-10-05 18:16:02 +0000186 LogEst nRow; /* Estimated number of rows generated by this path */
187 LogEst rCost; /* Total cost of this path */
drh6b7157b2013-05-10 02:00:35 +0000188 u8 isOrdered; /* True if this path satisfies ORDER BY */
189 u8 isOrderedValid; /* True if the isOrdered field is valid */
drha18f3d22013-05-08 03:05:41 +0000190 WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
drhf1b5f5b2013-05-02 00:15:01 +0000191};
drh0aa74ed2005-07-16 13:33:20 +0000192
193/*
drh75897232000-05-29 14:26:00 +0000194** The query generator uses an array of instances of this structure to
195** help it analyze the subexpressions of the WHERE clause. Each WHERE
drh61495262009-04-22 15:32:59 +0000196** clause subexpression is separated from the others by AND operators,
197** usually, or sometimes subexpressions separated by OR.
drh51669862004-12-18 18:40:26 +0000198**
drh0fcef5e2005-07-19 17:38:22 +0000199** All WhereTerms are collected into a single WhereClause structure.
200** The following identity holds:
drh51669862004-12-18 18:40:26 +0000201**
drh0fcef5e2005-07-19 17:38:22 +0000202** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
drh51669862004-12-18 18:40:26 +0000203**
drh0fcef5e2005-07-19 17:38:22 +0000204** When a term is of the form:
205**
206** X <op> <expr>
207**
208** where X is a column name and <op> is one of certain operators,
drh700a2262008-12-17 19:22:15 +0000209** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
210** cursor number and column number for X. WhereTerm.eOperator records
drh51147ba2005-07-23 22:59:55 +0000211** the <op> using a bitmask encoding defined by WO_xxx below. The
212** use of a bitmask encoding for the operator allows us to search
213** quickly for terms that match any of several different operators.
drh0fcef5e2005-07-19 17:38:22 +0000214**
drh700a2262008-12-17 19:22:15 +0000215** A WhereTerm might also be two or more subterms connected by OR:
216**
217** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
218**
drh4a6fc352013-08-07 01:18:38 +0000219** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
drh700a2262008-12-17 19:22:15 +0000220** and the WhereTerm.u.pOrInfo field points to auxiliary information that
drh4a6fc352013-08-07 01:18:38 +0000221** is collected about the OR clause.
drh700a2262008-12-17 19:22:15 +0000222**
223** If a term in the WHERE clause does not match either of the two previous
224** categories, then eOperator==0. The WhereTerm.pExpr field is still set
225** to the original subexpression content and wtFlags is set up appropriately
226** but no other fields in the WhereTerm object are meaningful.
227**
228** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
drh111a6a72008-12-21 03:51:16 +0000229** but they do so indirectly. A single WhereMaskSet structure translates
drh51669862004-12-18 18:40:26 +0000230** cursor number into bits and the translated bit is stored in the prereq
231** fields. The translation is used in order to maximize the number of
232** bits that will fit in a Bitmask. The VDBE cursor numbers might be
233** spread out over the non-negative integers. For example, the cursor
drh111a6a72008-12-21 03:51:16 +0000234** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
drh51669862004-12-18 18:40:26 +0000235** translates these sparse cursor numbers into consecutive integers
236** beginning with 0 in order to make the best possible use of the available
237** bits in the Bitmask. So, in the example above, the cursor numbers
238** would be mapped into integers 0 through 7.
drh6a1e0712008-12-05 15:24:15 +0000239**
240** The number of terms in a join is limited by the number of bits
241** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
242** is only able to process joins with 64 or fewer tables.
drh75897232000-05-29 14:26:00 +0000243*/
drh0aa74ed2005-07-16 13:33:20 +0000244struct WhereTerm {
drh165be382008-12-05 02:36:33 +0000245 Expr *pExpr; /* Pointer to the subexpression that is this term */
drhec1724e2008-12-09 01:32:03 +0000246 int iParent; /* Disable pWC->a[iParent] when this term disabled */
247 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
drh700a2262008-12-17 19:22:15 +0000248 union {
249 int leftColumn; /* Column number of X in "X <op> <expr>" */
drh7a5bcc02013-01-16 17:08:58 +0000250 WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
251 WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
drh700a2262008-12-17 19:22:15 +0000252 } u;
drhbf539c42013-10-05 18:16:02 +0000253 LogEst truthProb; /* Probability of truth for this expression */
drhb52076c2006-01-23 13:22:09 +0000254 u16 eOperator; /* A WO_xx value describing <op> */
drh165be382008-12-05 02:36:33 +0000255 u8 wtFlags; /* TERM_xxx bit flags. See below */
drh45b1ee42005-08-02 17:48:22 +0000256 u8 nChild; /* Number of children that must disable us */
drh0fcef5e2005-07-19 17:38:22 +0000257 WhereClause *pWC; /* The clause this term is part of */
drh165be382008-12-05 02:36:33 +0000258 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
259 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
drh75897232000-05-29 14:26:00 +0000260};
261
262/*
drh165be382008-12-05 02:36:33 +0000263** Allowed values of WhereTerm.wtFlags
drh0aa74ed2005-07-16 13:33:20 +0000264*/
drh633e6d52008-07-28 19:34:53 +0000265#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
drh6c30be82005-07-29 15:10:17 +0000266#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
267#define TERM_CODED 0x04 /* This term is already coded */
drh45b1ee42005-08-02 17:48:22 +0000268#define TERM_COPIED 0x08 /* Has a child */
drh700a2262008-12-17 19:22:15 +0000269#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
270#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
271#define TERM_OR_OK 0x40 /* Used during OR-clause processing */
drh1435a9a2013-08-27 23:15:44 +0000272#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh59b61882011-02-11 02:43:14 +0000273# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
274#else
drhd3ed7342011-09-21 00:09:41 +0000275# define TERM_VNULL 0x00 /* Disabled if not using stat3 */
drh59b61882011-02-11 02:43:14 +0000276#endif
drh0aa74ed2005-07-16 13:33:20 +0000277
278/*
drh1c8148f2013-05-04 20:25:23 +0000279** An instance of the WhereScan object is used as an iterator for locating
280** terms in the WHERE clause that are useful to the query planner.
281*/
282struct WhereScan {
drh1c8148f2013-05-04 20:25:23 +0000283 WhereClause *pOrigWC; /* Original, innermost WhereClause */
284 WhereClause *pWC; /* WhereClause currently being scanned */
drh7ba39a92013-05-30 17:43:19 +0000285 char *zCollName; /* Required collating sequence, if not NULL */
drh1c8148f2013-05-04 20:25:23 +0000286 char idxaff; /* Must match this affinity, if zCollName!=NULL */
287 unsigned char nEquiv; /* Number of entries in aEquiv[] */
288 unsigned char iEquiv; /* Next unused slot in aEquiv[] */
289 u32 opMask; /* Acceptable operators */
290 int k; /* Resume scanning at this->pWC->a[this->k] */
291 int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
292};
293
294/*
drh0aa74ed2005-07-16 13:33:20 +0000295** An instance of the following structure holds all information about a
296** WHERE clause. Mostly this is a container for one or more WhereTerms.
drh8871ef52011-10-07 13:33:10 +0000297**
298** Explanation of pOuter: For a WHERE clause of the form
299**
300** a AND ((b AND c) OR (d AND e)) AND f
301**
302** There are separate WhereClause objects for the whole clause and for
303** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
304** subclauses points to the WhereClause object for the whole clause.
drh0aa74ed2005-07-16 13:33:20 +0000305*/
drh0aa74ed2005-07-16 13:33:20 +0000306struct WhereClause {
drh70d18342013-06-06 19:16:33 +0000307 WhereInfo *pWInfo; /* WHERE clause processing context */
drh8871ef52011-10-07 13:33:10 +0000308 WhereClause *pOuter; /* Outer conjunction */
drh29435252008-12-28 18:35:08 +0000309 u8 op; /* Split operator. TK_AND or TK_OR */
drh0aa74ed2005-07-16 13:33:20 +0000310 int nTerm; /* Number of terms */
311 int nSlot; /* Number of entries in a[] */
drh51147ba2005-07-23 22:59:55 +0000312 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
drh50d654d2009-06-03 01:24:54 +0000313#if defined(SQLITE_SMALL_STACK)
314 WhereTerm aStatic[1]; /* Initial static space for a[] */
315#else
316 WhereTerm aStatic[8]; /* Initial static space for a[] */
317#endif
drhe23399f2005-07-22 00:31:39 +0000318};
319
320/*
drh700a2262008-12-17 19:22:15 +0000321** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
322** a dynamically allocated instance of the following structure.
323*/
324struct WhereOrInfo {
drh111a6a72008-12-21 03:51:16 +0000325 WhereClause wc; /* Decomposition into subterms */
drh1a58fe02008-12-20 02:06:13 +0000326 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
drh700a2262008-12-17 19:22:15 +0000327};
328
329/*
330** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
331** a dynamically allocated instance of the following structure.
332*/
333struct WhereAndInfo {
drh29435252008-12-28 18:35:08 +0000334 WhereClause wc; /* The subexpression broken out */
drh700a2262008-12-17 19:22:15 +0000335};
336
337/*
drh6a3ea0e2003-05-02 14:32:12 +0000338** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000339** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000340**
341** The VDBE cursor numbers are small integers contained in
342** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
343** clause, the cursor numbers might not begin with 0 and they might
344** contain gaps in the numbering sequence. But we want to make maximum
345** use of the bits in our bitmasks. This structure provides a mapping
346** from the sparse cursor numbers into consecutive integers beginning
347** with 0.
348**
drh111a6a72008-12-21 03:51:16 +0000349** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
drh51669862004-12-18 18:40:26 +0000350** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
351**
352** For example, if the WHERE clause expression used these VDBE
drh111a6a72008-12-21 03:51:16 +0000353** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
drh51669862004-12-18 18:40:26 +0000354** would map those cursor numbers into bits 0 through 5.
355**
356** Note that the mapping is not necessarily ordered. In the example
357** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
358** 57->5, 73->4. Or one of 719 other combinations might be used. It
359** does not really matter. What is important is that sparse cursor
360** numbers all get mapped into bit numbers that begin with 0 and contain
361** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000362*/
drh111a6a72008-12-21 03:51:16 +0000363struct WhereMaskSet {
drh1398ad32005-01-19 23:24:50 +0000364 int n; /* Number of assigned cursor values */
danielk197723432972008-11-17 16:42:00 +0000365 int ix[BMS]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000366};
367
drh111a6a72008-12-21 03:51:16 +0000368/*
drh3b48e8c2013-06-12 20:18:16 +0000369** This object is a convenience wrapper holding all information needed
370** to construct WhereLoop objects for a particular query.
drh1c8148f2013-05-04 20:25:23 +0000371*/
372struct WhereLoopBuilder {
373 WhereInfo *pWInfo; /* Information about this WHERE */
drh1c8148f2013-05-04 20:25:23 +0000374 WhereClause *pWC; /* WHERE clause terms */
drh1c8148f2013-05-04 20:25:23 +0000375 ExprList *pOrderBy; /* ORDER BY clause */
376 WhereLoop *pNew; /* Template WhereLoop */
drhaa32e3c2013-07-16 21:31:23 +0000377 WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
drh1435a9a2013-08-27 23:15:44 +0000378#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +0000379 UnpackedRecord *pRec; /* Probe for stat4 (if required) */
380 int nRecValid; /* Number of valid fields currently in pRec */
dan7a419232013-08-06 20:01:43 +0000381#endif
drh1c8148f2013-05-04 20:25:23 +0000382};
383
384/*
drh70d18342013-06-06 19:16:33 +0000385** The WHERE clause processing routine has two halves. The
386** first part does the start of the WHERE loop and the second
387** half does the tail of the WHERE loop. An instance of
388** this structure is returned by the first half and passed
389** into the second half to give some continuity.
drh3b48e8c2013-06-12 20:18:16 +0000390**
391** An instance of this object holds the complete state of the query
392** planner.
drh70d18342013-06-06 19:16:33 +0000393*/
394struct WhereInfo {
395 Parse *pParse; /* Parsing and code generating context */
396 SrcList *pTabList; /* List of tables in the join */
397 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
drh6457a352013-06-21 00:35:37 +0000398 ExprList *pResultSet; /* Result set. DISTINCT operates on these */
drh4f402f22013-06-11 18:59:38 +0000399 WhereLoop *pLoops; /* List of all WhereLoop objects */
drh70d18342013-06-06 19:16:33 +0000400 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
drhbf539c42013-10-05 18:16:02 +0000401 LogEst nRowOut; /* Estimated number of output rows */
drh70d18342013-06-06 19:16:33 +0000402 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
drh4f402f22013-06-11 18:59:38 +0000403 u8 bOBSat; /* ORDER BY satisfied by indices */
drh70d18342013-06-06 19:16:33 +0000404 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
405 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
406 u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
drhfd636c72013-06-21 02:05:06 +0000407 u8 nLevel; /* Number of nested loop */
drh70d18342013-06-06 19:16:33 +0000408 int iTop; /* The very beginning of the WHERE loop */
409 int iContinue; /* Jump here to continue with next record */
410 int iBreak; /* Jump here to break out of the loop */
drh4f402f22013-06-11 18:59:38 +0000411 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
drh70d18342013-06-06 19:16:33 +0000412 WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
413 WhereClause sWC; /* Decomposition of the WHERE clause */
drh70d18342013-06-06 19:16:33 +0000414 WhereLevel a[1]; /* Information about each nest loop in WHERE */
415};
416
417/*
drh3b48e8c2013-06-12 20:18:16 +0000418** Bitmasks for the operators on WhereTerm objects. These are all
419** operators that are of interest to the query planner. An
drh51147ba2005-07-23 22:59:55 +0000420** OR-ed combination of these values can be used when searching for
drh3b48e8c2013-06-12 20:18:16 +0000421** particular WhereTerms within a WhereClause.
drh51147ba2005-07-23 22:59:55 +0000422*/
drh165be382008-12-05 02:36:33 +0000423#define WO_IN 0x001
424#define WO_EQ 0x002
drh51147ba2005-07-23 22:59:55 +0000425#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
426#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
427#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
428#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
drh165be382008-12-05 02:36:33 +0000429#define WO_MATCH 0x040
430#define WO_ISNULL 0x080
drh700a2262008-12-17 19:22:15 +0000431#define WO_OR 0x100 /* Two or more OR-connected terms */
432#define WO_AND 0x200 /* Two or more AND-connected terms */
drh7a5bcc02013-01-16 17:08:58 +0000433#define WO_EQUIV 0x400 /* Of the form A==B, both columns */
drh534230c2011-01-22 00:10:45 +0000434#define WO_NOOP 0x800 /* This term does not restrict search space */
drh51147ba2005-07-23 22:59:55 +0000435
drhec1724e2008-12-09 01:32:03 +0000436#define WO_ALL 0xfff /* Mask of all possible WO_* values */
drh1a58fe02008-12-20 02:06:13 +0000437#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
drhec1724e2008-12-09 01:32:03 +0000438
drh51147ba2005-07-23 22:59:55 +0000439/*
drh3b48e8c2013-06-12 20:18:16 +0000440** These are definitions of bits in the WhereLoop.wsFlags field.
441** The particular combination of bits in each WhereLoop help to
442** determine the algorithm that WhereLoop represents.
drh51147ba2005-07-23 22:59:55 +0000443*/
drhbe4fe3a2013-07-01 10:38:35 +0000444#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
drh6fa978d2013-05-30 19:29:19 +0000445#define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
446#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
447#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
drhef71c1f2013-06-04 12:58:02 +0000448#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
drh6fa978d2013-05-30 19:29:19 +0000449#define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
450#define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
451#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
452#define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
453#define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
454#define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
455#define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
456#define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
drh7699d1c2013-06-04 12:42:29 +0000457#define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
drh6fa978d2013-05-30 19:29:19 +0000458#define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
drh986b3872013-06-28 21:12:20 +0000459#define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
drh51147ba2005-07-23 22:59:55 +0000460
461/*
drh6f328482013-06-05 23:39:34 +0000462** Return the estimated number of output rows from a WHERE clause
463*/
drhc63367e2013-06-10 20:46:50 +0000464u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
drhbf539c42013-10-05 18:16:02 +0000465 return sqlite3LogEstToInt(pWInfo->nRowOut);
drh6f328482013-06-05 23:39:34 +0000466}
467
468/*
469** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
470** WHERE clause returns outputs for DISTINCT processing.
471*/
472int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
473 return pWInfo->eDistinct;
474}
475
476/*
477** Return TRUE if the WHERE clause returns rows in ORDER BY order.
478** Return FALSE if the output needs to be sorted.
479*/
480int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
drh4f402f22013-06-11 18:59:38 +0000481 return pWInfo->bOBSat!=0;
drh6f328482013-06-05 23:39:34 +0000482}
483
484/*
485** Return the VDBE address or label to jump to in order to continue
486** immediately with the next row of a WHERE clause.
487*/
488int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
489 return pWInfo->iContinue;
490}
491
492/*
493** Return the VDBE address or label to jump to in order to break
494** out of a WHERE loop.
495*/
496int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
497 return pWInfo->iBreak;
498}
499
500/*
501** Return TRUE if an UPDATE or DELETE statement can operate directly on
502** the rowids returned by a WHERE clause. Return FALSE if doing an
503** UPDATE or DELETE might change subsequent WHERE clause results.
504*/
505int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
506 return pWInfo->okOnePass;
507}
508
509/*
drhaa32e3c2013-07-16 21:31:23 +0000510** Move the content of pSrc into pDest
511*/
512static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
513 pDest->n = pSrc->n;
514 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
515}
516
517/*
518** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
519**
520** The new entry might overwrite an existing entry, or it might be
521** appended, or it might be discarded. Do whatever is the right thing
522** so that pSet keeps the N_OR_COST best entries seen so far.
523*/
524static int whereOrInsert(
525 WhereOrSet *pSet, /* The WhereOrSet to be updated */
526 Bitmask prereq, /* Prerequisites of the new entry */
drhbf539c42013-10-05 18:16:02 +0000527 LogEst rRun, /* Run-cost of the new entry */
528 LogEst nOut /* Number of outputs for the new entry */
drhaa32e3c2013-07-16 21:31:23 +0000529){
530 u16 i;
531 WhereOrCost *p;
532 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
533 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
534 goto whereOrInsert_done;
535 }
536 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
537 return 0;
538 }
539 }
540 if( pSet->n<N_OR_COST ){
541 p = &pSet->a[pSet->n++];
542 p->nOut = nOut;
543 }else{
544 p = pSet->a;
545 for(i=1; i<pSet->n; i++){
546 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
547 }
548 if( p->rRun<=rRun ) return 0;
549 }
550whereOrInsert_done:
551 p->prereq = prereq;
552 p->rRun = rRun;
553 if( p->nOut>nOut ) p->nOut = nOut;
554 return 1;
555}
556
557/*
drh0aa74ed2005-07-16 13:33:20 +0000558** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000559*/
drh7b4fc6a2007-02-06 13:26:32 +0000560static void whereClauseInit(
561 WhereClause *pWC, /* The WhereClause to be initialized */
drh70d18342013-06-06 19:16:33 +0000562 WhereInfo *pWInfo /* The WHERE processing context */
drh7b4fc6a2007-02-06 13:26:32 +0000563){
drh70d18342013-06-06 19:16:33 +0000564 pWC->pWInfo = pWInfo;
drh8871ef52011-10-07 13:33:10 +0000565 pWC->pOuter = 0;
drh0aa74ed2005-07-16 13:33:20 +0000566 pWC->nTerm = 0;
drhcad651e2007-04-20 12:22:01 +0000567 pWC->nSlot = ArraySize(pWC->aStatic);
drh0aa74ed2005-07-16 13:33:20 +0000568 pWC->a = pWC->aStatic;
569}
570
drh700a2262008-12-17 19:22:15 +0000571/* Forward reference */
572static void whereClauseClear(WhereClause*);
573
574/*
575** Deallocate all memory associated with a WhereOrInfo object.
576*/
577static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000578 whereClauseClear(&p->wc);
579 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000580}
581
582/*
583** Deallocate all memory associated with a WhereAndInfo object.
584*/
585static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000586 whereClauseClear(&p->wc);
587 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000588}
589
drh0aa74ed2005-07-16 13:33:20 +0000590/*
591** Deallocate a WhereClause structure. The WhereClause structure
592** itself is not freed. This routine is the inverse of whereClauseInit().
593*/
594static void whereClauseClear(WhereClause *pWC){
595 int i;
596 WhereTerm *a;
drh70d18342013-06-06 19:16:33 +0000597 sqlite3 *db = pWC->pWInfo->pParse->db;
drh0aa74ed2005-07-16 13:33:20 +0000598 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
drh165be382008-12-05 02:36:33 +0000599 if( a->wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000600 sqlite3ExprDelete(db, a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000601 }
drh700a2262008-12-17 19:22:15 +0000602 if( a->wtFlags & TERM_ORINFO ){
603 whereOrInfoDelete(db, a->u.pOrInfo);
604 }else if( a->wtFlags & TERM_ANDINFO ){
605 whereAndInfoDelete(db, a->u.pAndInfo);
606 }
drh0aa74ed2005-07-16 13:33:20 +0000607 }
608 if( pWC->a!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000609 sqlite3DbFree(db, pWC->a);
drh0aa74ed2005-07-16 13:33:20 +0000610 }
611}
612
613/*
drh6a1e0712008-12-05 15:24:15 +0000614** Add a single new WhereTerm entry to the WhereClause object pWC.
615** The new WhereTerm object is constructed from Expr p and with wtFlags.
616** The index in pWC->a[] of the new WhereTerm is returned on success.
617** 0 is returned if the new WhereTerm could not be added due to a memory
618** allocation error. The memory allocation failure will be recorded in
619** the db->mallocFailed flag so that higher-level functions can detect it.
620**
621** This routine will increase the size of the pWC->a[] array as necessary.
drh9eb20282005-08-24 03:52:18 +0000622**
drh165be382008-12-05 02:36:33 +0000623** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
drh6a1e0712008-12-05 15:24:15 +0000624** for freeing the expression p is assumed by the WhereClause object pWC.
625** This is true even if this routine fails to allocate a new WhereTerm.
drhb63a53d2007-03-31 01:34:44 +0000626**
drh9eb20282005-08-24 03:52:18 +0000627** WARNING: This routine might reallocate the space used to store
drh909626d2008-05-30 14:58:37 +0000628** WhereTerms. All pointers to WhereTerms should be invalidated after
drh9eb20282005-08-24 03:52:18 +0000629** calling this routine. Such pointers may be reinitialized by referencing
630** the pWC->a[] array.
drh0aa74ed2005-07-16 13:33:20 +0000631*/
drhec1724e2008-12-09 01:32:03 +0000632static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
drh0aa74ed2005-07-16 13:33:20 +0000633 WhereTerm *pTerm;
drh9eb20282005-08-24 03:52:18 +0000634 int idx;
drh39759742013-08-02 23:40:45 +0000635 testcase( wtFlags & TERM_VIRTUAL );
drh0aa74ed2005-07-16 13:33:20 +0000636 if( pWC->nTerm>=pWC->nSlot ){
637 WhereTerm *pOld = pWC->a;
drh70d18342013-06-06 19:16:33 +0000638 sqlite3 *db = pWC->pWInfo->pParse->db;
drh633e6d52008-07-28 19:34:53 +0000639 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
drhb63a53d2007-03-31 01:34:44 +0000640 if( pWC->a==0 ){
drh165be382008-12-05 02:36:33 +0000641 if( wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000642 sqlite3ExprDelete(db, p);
drhb63a53d2007-03-31 01:34:44 +0000643 }
drhf998b732007-11-26 13:36:00 +0000644 pWC->a = pOld;
drhb63a53d2007-03-31 01:34:44 +0000645 return 0;
646 }
drh0aa74ed2005-07-16 13:33:20 +0000647 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
648 if( pOld!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000649 sqlite3DbFree(db, pOld);
drh0aa74ed2005-07-16 13:33:20 +0000650 }
drh6a1e0712008-12-05 15:24:15 +0000651 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
drh0aa74ed2005-07-16 13:33:20 +0000652 }
drh6a1e0712008-12-05 15:24:15 +0000653 pTerm = &pWC->a[idx = pWC->nTerm++];
drha4c3c872013-09-12 17:29:25 +0000654 if( p && ExprHasProperty(p, EP_Unlikely) ){
drhbf539c42013-10-05 18:16:02 +0000655 pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
drhcca9f3d2013-09-06 15:23:29 +0000656 }else{
657 pTerm->truthProb = -1;
658 }
drh7ee751d2012-12-19 15:53:51 +0000659 pTerm->pExpr = sqlite3ExprSkipCollate(p);
drh165be382008-12-05 02:36:33 +0000660 pTerm->wtFlags = wtFlags;
drh0fcef5e2005-07-19 17:38:22 +0000661 pTerm->pWC = pWC;
drh45b1ee42005-08-02 17:48:22 +0000662 pTerm->iParent = -1;
drh9eb20282005-08-24 03:52:18 +0000663 return idx;
drh0aa74ed2005-07-16 13:33:20 +0000664}
drh75897232000-05-29 14:26:00 +0000665
666/*
drh51669862004-12-18 18:40:26 +0000667** This routine identifies subexpressions in the WHERE clause where
drhb6fb62d2005-09-20 08:47:20 +0000668** each subexpression is separated by the AND operator or some other
drh6c30be82005-07-29 15:10:17 +0000669** operator specified in the op parameter. The WhereClause structure
670** is filled with pointers to subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000671**
drh51669862004-12-18 18:40:26 +0000672** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
673** \________/ \_______________/ \________________/
674** slot[0] slot[1] slot[2]
675**
676** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000677** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000678**
drh51147ba2005-07-23 22:59:55 +0000679** In the previous sentence and in the diagram, "slot[]" refers to
drh902b9ee2008-12-05 17:17:07 +0000680** the WhereClause.a[] array. The slot[] array grows as needed to contain
drh51147ba2005-07-23 22:59:55 +0000681** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000682*/
drh74f91d42013-06-19 18:01:44 +0000683static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
684 pWC->op = op;
drh0aa74ed2005-07-16 13:33:20 +0000685 if( pExpr==0 ) return;
drh6c30be82005-07-29 15:10:17 +0000686 if( pExpr->op!=op ){
drh0aa74ed2005-07-16 13:33:20 +0000687 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000688 }else{
drh6c30be82005-07-29 15:10:17 +0000689 whereSplit(pWC, pExpr->pLeft, op);
690 whereSplit(pWC, pExpr->pRight, op);
drh75897232000-05-29 14:26:00 +0000691 }
drh75897232000-05-29 14:26:00 +0000692}
693
694/*
drh3b48e8c2013-06-12 20:18:16 +0000695** Initialize a WhereMaskSet object
drh6a3ea0e2003-05-02 14:32:12 +0000696*/
drhfd5874d2013-06-12 14:52:39 +0000697#define initMaskSet(P) (P)->n=0
drh6a3ea0e2003-05-02 14:32:12 +0000698
699/*
drh1398ad32005-01-19 23:24:50 +0000700** Return the bitmask for the given cursor number. Return 0 if
701** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000702*/
drh111a6a72008-12-21 03:51:16 +0000703static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000704 int i;
drhfcd71b62011-04-05 22:08:24 +0000705 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
drh6a3ea0e2003-05-02 14:32:12 +0000706 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000707 if( pMaskSet->ix[i]==iCursor ){
drh7699d1c2013-06-04 12:42:29 +0000708 return MASKBIT(i);
drh51669862004-12-18 18:40:26 +0000709 }
drh6a3ea0e2003-05-02 14:32:12 +0000710 }
drh6a3ea0e2003-05-02 14:32:12 +0000711 return 0;
712}
713
714/*
drh1398ad32005-01-19 23:24:50 +0000715** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000716**
717** There is one cursor per table in the FROM clause. The number of
718** tables in the FROM clause is limited by a test early in the
drhb6fb62d2005-09-20 08:47:20 +0000719** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
drh0fcef5e2005-07-19 17:38:22 +0000720** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000721*/
drh111a6a72008-12-21 03:51:16 +0000722static void createMask(WhereMaskSet *pMaskSet, int iCursor){
drhcad651e2007-04-20 12:22:01 +0000723 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
drh0fcef5e2005-07-19 17:38:22 +0000724 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000725}
726
727/*
drh4a6fc352013-08-07 01:18:38 +0000728** These routines walk (recursively) an expression tree and generate
drh75897232000-05-29 14:26:00 +0000729** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000730** tree.
drh75897232000-05-29 14:26:00 +0000731*/
drh111a6a72008-12-21 03:51:16 +0000732static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
733static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
734static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
drh51669862004-12-18 18:40:26 +0000735 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000736 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000737 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000738 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000739 return mask;
drh75897232000-05-29 14:26:00 +0000740 }
danielk1977b3bce662005-01-29 08:32:43 +0000741 mask = exprTableUsage(pMaskSet, p->pRight);
742 mask |= exprTableUsage(pMaskSet, p->pLeft);
danielk19776ab3a2e2009-02-19 14:39:25 +0000743 if( ExprHasProperty(p, EP_xIsSelect) ){
744 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
745 }else{
746 mask |= exprListTableUsage(pMaskSet, p->x.pList);
747 }
danielk1977b3bce662005-01-29 08:32:43 +0000748 return mask;
749}
drh111a6a72008-12-21 03:51:16 +0000750static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
danielk1977b3bce662005-01-29 08:32:43 +0000751 int i;
752 Bitmask mask = 0;
753 if( pList ){
754 for(i=0; i<pList->nExpr; i++){
755 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000756 }
757 }
drh75897232000-05-29 14:26:00 +0000758 return mask;
759}
drh111a6a72008-12-21 03:51:16 +0000760static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
drha430ae82007-09-12 15:41:01 +0000761 Bitmask mask = 0;
762 while( pS ){
drha464c232011-09-16 19:04:03 +0000763 SrcList *pSrc = pS->pSrc;
drha430ae82007-09-12 15:41:01 +0000764 mask |= exprListTableUsage(pMaskSet, pS->pEList);
drhf5b11382005-09-17 13:07:13 +0000765 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
766 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
767 mask |= exprTableUsage(pMaskSet, pS->pWhere);
768 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drha464c232011-09-16 19:04:03 +0000769 if( ALWAYS(pSrc!=0) ){
drh88501772011-09-16 17:43:06 +0000770 int i;
771 for(i=0; i<pSrc->nSrc; i++){
772 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
773 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
774 }
775 }
drha430ae82007-09-12 15:41:01 +0000776 pS = pS->pPrior;
drhf5b11382005-09-17 13:07:13 +0000777 }
778 return mask;
779}
drh75897232000-05-29 14:26:00 +0000780
781/*
drh487ab3c2001-11-08 00:45:21 +0000782** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000783** allowed for an indexable WHERE clause term. The allowed operators are
drh3b48e8c2013-06-12 20:18:16 +0000784** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
drh487ab3c2001-11-08 00:45:21 +0000785*/
786static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000787 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
788 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
789 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
790 assert( TK_GE==TK_EQ+4 );
drh50b39962006-10-28 00:28:09 +0000791 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
drh487ab3c2001-11-08 00:45:21 +0000792}
793
794/*
drh902b9ee2008-12-05 17:17:07 +0000795** Swap two objects of type TYPE.
drh193bd772004-07-20 18:23:14 +0000796*/
797#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
798
799/*
drh909626d2008-05-30 14:58:37 +0000800** Commute a comparison operator. Expressions of the form "X op Y"
drh0fcef5e2005-07-19 17:38:22 +0000801** are converted into "Y op X".
danielk1977eb5453d2007-07-30 14:40:48 +0000802**
mistachkin48864df2013-03-21 21:20:32 +0000803** If left/right precedence rules come into play when determining the
drh3b48e8c2013-06-12 20:18:16 +0000804** collating sequence, then COLLATE operators are adjusted to ensure
805** that the collating sequence does not change. For example:
806** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
danielk1977eb5453d2007-07-30 14:40:48 +0000807** the left hand side of a comparison overrides any collation sequence
drhae80dde2012-12-06 21:16:43 +0000808** attached to the right. For the same reason the EP_Collate flag
danielk1977eb5453d2007-07-30 14:40:48 +0000809** is not commuted.
drh193bd772004-07-20 18:23:14 +0000810*/
drh7d10d5a2008-08-20 16:35:10 +0000811static void exprCommute(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000812 u16 expRight = (pExpr->pRight->flags & EP_Collate);
813 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
drhfe05af82005-07-21 03:14:59 +0000814 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drhae80dde2012-12-06 21:16:43 +0000815 if( expRight==expLeft ){
816 /* Either X and Y both have COLLATE operator or neither do */
817 if( expRight ){
818 /* Both X and Y have COLLATE operators. Make sure X is always
819 ** used by clearing the EP_Collate flag from Y. */
820 pExpr->pRight->flags &= ~EP_Collate;
821 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
822 /* Neither X nor Y have COLLATE operators, but X has a non-default
823 ** collating sequence. So add the EP_Collate marker on X to cause
824 ** it to be searched first. */
825 pExpr->pLeft->flags |= EP_Collate;
826 }
827 }
drh0fcef5e2005-07-19 17:38:22 +0000828 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
829 if( pExpr->op>=TK_GT ){
830 assert( TK_LT==TK_GT+2 );
831 assert( TK_GE==TK_LE+2 );
832 assert( TK_GT>TK_EQ );
833 assert( TK_GT<TK_LE );
834 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
835 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000836 }
drh193bd772004-07-20 18:23:14 +0000837}
838
839/*
drhfe05af82005-07-21 03:14:59 +0000840** Translate from TK_xx operator to WO_xx bitmask.
841*/
drhec1724e2008-12-09 01:32:03 +0000842static u16 operatorMask(int op){
843 u16 c;
drhfe05af82005-07-21 03:14:59 +0000844 assert( allowedOp(op) );
845 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000846 c = WO_IN;
drh50b39962006-10-28 00:28:09 +0000847 }else if( op==TK_ISNULL ){
848 c = WO_ISNULL;
drhfe05af82005-07-21 03:14:59 +0000849 }else{
drhec1724e2008-12-09 01:32:03 +0000850 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
851 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000852 }
drh50b39962006-10-28 00:28:09 +0000853 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000854 assert( op!=TK_IN || c==WO_IN );
855 assert( op!=TK_EQ || c==WO_EQ );
856 assert( op!=TK_LT || c==WO_LT );
857 assert( op!=TK_LE || c==WO_LE );
858 assert( op!=TK_GT || c==WO_GT );
859 assert( op!=TK_GE || c==WO_GE );
860 return c;
drhfe05af82005-07-21 03:14:59 +0000861}
862
863/*
drh1c8148f2013-05-04 20:25:23 +0000864** Advance to the next WhereTerm that matches according to the criteria
865** established when the pScan object was initialized by whereScanInit().
866** Return NULL if there are no more matching WhereTerms.
867*/
danb2cfc142013-07-05 11:10:54 +0000868static WhereTerm *whereScanNext(WhereScan *pScan){
drh1c8148f2013-05-04 20:25:23 +0000869 int iCur; /* The cursor on the LHS of the term */
870 int iColumn; /* The column on the LHS of the term. -1 for IPK */
871 Expr *pX; /* An expression being tested */
872 WhereClause *pWC; /* Shorthand for pScan->pWC */
873 WhereTerm *pTerm; /* The term being tested */
drh43b85ef2013-06-10 12:34:45 +0000874 int k = pScan->k; /* Where to start scanning */
drh1c8148f2013-05-04 20:25:23 +0000875
876 while( pScan->iEquiv<=pScan->nEquiv ){
877 iCur = pScan->aEquiv[pScan->iEquiv-2];
878 iColumn = pScan->aEquiv[pScan->iEquiv-1];
879 while( (pWC = pScan->pWC)!=0 ){
drh43b85ef2013-06-10 12:34:45 +0000880 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
drh1c8148f2013-05-04 20:25:23 +0000881 if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
882 if( (pTerm->eOperator & WO_EQUIV)!=0
883 && pScan->nEquiv<ArraySize(pScan->aEquiv)
884 ){
885 int j;
886 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
887 assert( pX->op==TK_COLUMN );
888 for(j=0; j<pScan->nEquiv; j+=2){
889 if( pScan->aEquiv[j]==pX->iTable
890 && pScan->aEquiv[j+1]==pX->iColumn ){
891 break;
892 }
893 }
894 if( j==pScan->nEquiv ){
895 pScan->aEquiv[j] = pX->iTable;
896 pScan->aEquiv[j+1] = pX->iColumn;
897 pScan->nEquiv += 2;
898 }
899 }
900 if( (pTerm->eOperator & pScan->opMask)!=0 ){
901 /* Verify the affinity and collating sequence match */
902 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
903 CollSeq *pColl;
drh70d18342013-06-06 19:16:33 +0000904 Parse *pParse = pWC->pWInfo->pParse;
drh1c8148f2013-05-04 20:25:23 +0000905 pX = pTerm->pExpr;
906 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
907 continue;
908 }
909 assert(pX->pLeft);
drh70d18342013-06-06 19:16:33 +0000910 pColl = sqlite3BinaryCompareCollSeq(pParse,
drh1c8148f2013-05-04 20:25:23 +0000911 pX->pLeft, pX->pRight);
drh70d18342013-06-06 19:16:33 +0000912 if( pColl==0 ) pColl = pParse->db->pDfltColl;
drh1c8148f2013-05-04 20:25:23 +0000913 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
914 continue;
915 }
916 }
drha184fb82013-05-08 04:22:59 +0000917 if( (pTerm->eOperator & WO_EQ)!=0
918 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
919 && pX->iTable==pScan->aEquiv[0]
920 && pX->iColumn==pScan->aEquiv[1]
921 ){
922 continue;
923 }
drh43b85ef2013-06-10 12:34:45 +0000924 pScan->k = k+1;
drh1c8148f2013-05-04 20:25:23 +0000925 return pTerm;
926 }
927 }
928 }
drhad01d892013-06-19 13:59:49 +0000929 pScan->pWC = pScan->pWC->pOuter;
drh43b85ef2013-06-10 12:34:45 +0000930 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000931 }
932 pScan->pWC = pScan->pOrigWC;
drh43b85ef2013-06-10 12:34:45 +0000933 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000934 pScan->iEquiv += 2;
935 }
drh1c8148f2013-05-04 20:25:23 +0000936 return 0;
937}
938
939/*
940** Initialize a WHERE clause scanner object. Return a pointer to the
941** first match. Return NULL if there are no matches.
942**
943** The scanner will be searching the WHERE clause pWC. It will look
944** for terms of the form "X <op> <expr>" where X is column iColumn of table
945** iCur. The <op> must be one of the operators described by opMask.
946**
drh3b48e8c2013-06-12 20:18:16 +0000947** If the search is for X and the WHERE clause contains terms of the
948** form X=Y then this routine might also return terms of the form
949** "Y <op> <expr>". The number of levels of transitivity is limited,
950** but is enough to handle most commonly occurring SQL statements.
951**
drh1c8148f2013-05-04 20:25:23 +0000952** If X is not the INTEGER PRIMARY KEY then X must be compatible with
953** index pIdx.
954*/
danb2cfc142013-07-05 11:10:54 +0000955static WhereTerm *whereScanInit(
drh1c8148f2013-05-04 20:25:23 +0000956 WhereScan *pScan, /* The WhereScan object being initialized */
957 WhereClause *pWC, /* The WHERE clause to be scanned */
958 int iCur, /* Cursor to scan for */
959 int iColumn, /* Column to scan for */
960 u32 opMask, /* Operator(s) to scan for */
961 Index *pIdx /* Must be compatible with this index */
962){
963 int j;
964
drhe9d935a2013-06-05 16:19:59 +0000965 /* memset(pScan, 0, sizeof(*pScan)); */
drh1c8148f2013-05-04 20:25:23 +0000966 pScan->pOrigWC = pWC;
967 pScan->pWC = pWC;
968 if( pIdx && iColumn>=0 ){
969 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
970 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
drhbbbdc832013-10-22 18:01:40 +0000971 if( NEVER(j>=pIdx->nKeyCol) ) return 0;
drh1c8148f2013-05-04 20:25:23 +0000972 }
973 pScan->zCollName = pIdx->azColl[j];
drhe9d935a2013-06-05 16:19:59 +0000974 }else{
975 pScan->idxaff = 0;
976 pScan->zCollName = 0;
drh1c8148f2013-05-04 20:25:23 +0000977 }
978 pScan->opMask = opMask;
drhe9d935a2013-06-05 16:19:59 +0000979 pScan->k = 0;
drh1c8148f2013-05-04 20:25:23 +0000980 pScan->aEquiv[0] = iCur;
981 pScan->aEquiv[1] = iColumn;
982 pScan->nEquiv = 2;
983 pScan->iEquiv = 2;
984 return whereScanNext(pScan);
985}
986
987/*
drhfe05af82005-07-21 03:14:59 +0000988** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
989** where X is a reference to the iColumn of table iCur and <op> is one of
990** the WO_xx operator codes specified by the op parameter.
991** Return a pointer to the term. Return 0 if not found.
drh58eb1c02013-01-17 00:08:42 +0000992**
993** The term returned might by Y=<expr> if there is another constraint in
994** the WHERE clause that specifies that X=Y. Any such constraints will be
995** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
996** aEquiv[] array holds X and all its equivalents, with each SQL variable
997** taking up two slots in aEquiv[]. The first slot is for the cursor number
998** and the second is for the column number. There are 22 slots in aEquiv[]
999** so that means we can look for X plus up to 10 other equivalent values.
1000** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
1001** and ... and A9=A10 and A10=<expr>.
1002**
1003** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
1004** then try for the one with no dependencies on <expr> - in other words where
1005** <expr> is a constant expression of some kind. Only return entries of
1006** the form "X <op> Y" where Y is a column in another table if no terms of
drh459f63e2013-03-06 01:55:27 +00001007** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
1008** exist, try to return a term that does not use WO_EQUIV.
drhfe05af82005-07-21 03:14:59 +00001009*/
1010static WhereTerm *findTerm(
1011 WhereClause *pWC, /* The WHERE clause to be searched */
1012 int iCur, /* Cursor number of LHS */
1013 int iColumn, /* Column number of LHS */
1014 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +00001015 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +00001016 Index *pIdx /* Must be compatible with this index, if not NULL */
1017){
drh1c8148f2013-05-04 20:25:23 +00001018 WhereTerm *pResult = 0;
1019 WhereTerm *p;
1020 WhereScan scan;
drh7a5bcc02013-01-16 17:08:58 +00001021
drh1c8148f2013-05-04 20:25:23 +00001022 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
1023 while( p ){
1024 if( (p->prereqRight & notReady)==0 ){
1025 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
1026 return p;
drhfe05af82005-07-21 03:14:59 +00001027 }
drh1c8148f2013-05-04 20:25:23 +00001028 if( pResult==0 ) pResult = p;
drhfe05af82005-07-21 03:14:59 +00001029 }
drh1c8148f2013-05-04 20:25:23 +00001030 p = whereScanNext(&scan);
drhfe05af82005-07-21 03:14:59 +00001031 }
drh7a5bcc02013-01-16 17:08:58 +00001032 return pResult;
drhfe05af82005-07-21 03:14:59 +00001033}
1034
drh6c30be82005-07-29 15:10:17 +00001035/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +00001036static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +00001037
1038/*
1039** Call exprAnalyze on all terms in a WHERE clause.
drh6c30be82005-07-29 15:10:17 +00001040*/
1041static void exprAnalyzeAll(
1042 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +00001043 WhereClause *pWC /* the WHERE clause to be analyzed */
1044){
drh6c30be82005-07-29 15:10:17 +00001045 int i;
drh9eb20282005-08-24 03:52:18 +00001046 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +00001047 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +00001048 }
1049}
1050
drhd2687b72005-08-12 22:56:09 +00001051#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1052/*
1053** Check to see if the given expression is a LIKE or GLOB operator that
1054** can be optimized using inequality constraints. Return TRUE if it is
1055** so and false if not.
1056**
1057** In order for the operator to be optimizible, the RHS must be a string
1058** literal that does not begin with a wildcard.
1059*/
1060static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +00001061 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +00001062 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +00001063 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +00001064 int *pisComplete, /* True if the only wildcard is % in the last character */
1065 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +00001066){
dan937d0de2009-10-15 18:35:38 +00001067 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +00001068 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
1069 ExprList *pList; /* List of operands to the LIKE operator */
1070 int c; /* One character in z[] */
1071 int cnt; /* Number of non-wildcard prefix characters */
1072 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +00001073 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +00001074 sqlite3_value *pVal = 0;
1075 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +00001076
drh9f504ea2008-02-23 21:55:39 +00001077 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +00001078 return 0;
1079 }
drh9f504ea2008-02-23 21:55:39 +00001080#ifdef SQLITE_EBCDIC
1081 if( *pnoCase ) return 0;
1082#endif
danielk19776ab3a2e2009-02-19 14:39:25 +00001083 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +00001084 pLeft = pList->a[1].pExpr;
danc68939e2012-03-29 14:29:07 +00001085 if( pLeft->op!=TK_COLUMN
1086 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
1087 || IsVirtual(pLeft->pTab)
1088 ){
drhd91ca492009-10-22 20:50:36 +00001089 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
1090 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +00001091 return 0;
1092 }
drhd91ca492009-10-22 20:50:36 +00001093 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +00001094
1095 pRight = pList->a[0].pExpr;
1096 op = pRight->op;
1097 if( op==TK_REGISTER ){
1098 op = pRight->op2;
1099 }
1100 if( op==TK_VARIABLE ){
1101 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +00001102 int iCol = pRight->iColumn;
drhcf0fd4a2013-08-01 12:21:58 +00001103 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
dan937d0de2009-10-15 18:35:38 +00001104 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
1105 z = (char *)sqlite3_value_text(pVal);
1106 }
drhf9b22ca2011-10-21 16:47:31 +00001107 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +00001108 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
1109 }else if( op==TK_STRING ){
1110 z = pRight->u.zToken;
1111 }
1112 if( z ){
shane85095702009-06-15 16:27:08 +00001113 cnt = 0;
drhb7916a72009-05-27 10:31:29 +00001114 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +00001115 cnt++;
1116 }
drh93ee23c2010-07-22 12:33:57 +00001117 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +00001118 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +00001119 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +00001120 pPrefix = sqlite3Expr(db, TK_STRING, z);
1121 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
1122 *ppPrefix = pPrefix;
1123 if( op==TK_VARIABLE ){
1124 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +00001125 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +00001126 if( *pisComplete && pRight->u.zToken[1] ){
1127 /* If the rhs of the LIKE expression is a variable, and the current
1128 ** value of the variable means there is no need to invoke the LIKE
1129 ** function, then no OP_Variable will be added to the program.
1130 ** This causes problems for the sqlite3_bind_parameter_name()
drhbec451f2009-10-17 13:13:02 +00001131 ** API. To workaround them, add a dummy OP_Variable here.
1132 */
1133 int r1 = sqlite3GetTempReg(pParse);
1134 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +00001135 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +00001136 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +00001137 }
1138 }
1139 }else{
1140 z = 0;
shane85095702009-06-15 16:27:08 +00001141 }
drhf998b732007-11-26 13:36:00 +00001142 }
dan937d0de2009-10-15 18:35:38 +00001143
1144 sqlite3ValueFree(pVal);
1145 return (z!=0);
drhd2687b72005-08-12 22:56:09 +00001146}
1147#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1148
drhedb193b2006-06-27 13:20:21 +00001149
1150#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +00001151/*
drh7f375902006-06-13 17:38:59 +00001152** Check to see if the given expression is of the form
1153**
1154** column MATCH expr
1155**
1156** If it is then return TRUE. If not, return FALSE.
1157*/
1158static int isMatchOfColumn(
1159 Expr *pExpr /* Test this expression */
1160){
1161 ExprList *pList;
1162
1163 if( pExpr->op!=TK_FUNCTION ){
1164 return 0;
1165 }
drh33e619f2009-05-28 01:00:55 +00001166 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +00001167 return 0;
1168 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001169 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +00001170 if( pList->nExpr!=2 ){
1171 return 0;
1172 }
1173 if( pList->a[1].pExpr->op != TK_COLUMN ){
1174 return 0;
1175 }
1176 return 1;
1177}
drhedb193b2006-06-27 13:20:21 +00001178#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +00001179
1180/*
drh54a167d2005-11-26 14:08:07 +00001181** If the pBase expression originated in the ON or USING clause of
1182** a join, then transfer the appropriate markings over to derived.
1183*/
1184static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
drhd41d39f2013-08-28 16:27:01 +00001185 if( pDerived ){
1186 pDerived->flags |= pBase->flags & EP_FromJoin;
1187 pDerived->iRightJoinTable = pBase->iRightJoinTable;
1188 }
drh54a167d2005-11-26 14:08:07 +00001189}
1190
drh3e355802007-02-23 23:13:33 +00001191#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1192/*
drh1a58fe02008-12-20 02:06:13 +00001193** Analyze a term that consists of two or more OR-connected
1194** subterms. So in:
drh3e355802007-02-23 23:13:33 +00001195**
drh1a58fe02008-12-20 02:06:13 +00001196** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
1197** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +00001198**
drh1a58fe02008-12-20 02:06:13 +00001199** This routine analyzes terms such as the middle term in the above example.
1200** A WhereOrTerm object is computed and attached to the term under
1201** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +00001202**
drh1a58fe02008-12-20 02:06:13 +00001203** WhereTerm.wtFlags |= TERM_ORINFO
1204** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +00001205**
drh1a58fe02008-12-20 02:06:13 +00001206** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +00001207** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +00001208** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +00001209**
drh1a58fe02008-12-20 02:06:13 +00001210** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
1211** (B) x=expr1 OR expr2=x OR x=expr3
1212** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
1213** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
1214** (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 +00001215**
drh1a58fe02008-12-20 02:06:13 +00001216** CASE 1:
1217**
drhc3e552f2013-02-08 16:04:19 +00001218** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +00001219** a single table T (as shown in example B above) then create a new virtual
1220** term that is an equivalent IN expression. In other words, if the term
1221** being analyzed is:
1222**
1223** x = expr1 OR expr2 = x OR x = expr3
1224**
1225** then create a new virtual term like this:
1226**
1227** x IN (expr1,expr2,expr3)
1228**
1229** CASE 2:
1230**
1231** If all subterms are indexable by a single table T, then set
1232**
1233** WhereTerm.eOperator = WO_OR
1234** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
1235**
1236** A subterm is "indexable" if it is of the form
1237** "T.C <op> <expr>" where C is any column of table T and
1238** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
1239** A subterm is also indexable if it is an AND of two or more
1240** subsubterms at least one of which is indexable. Indexable AND
1241** subterms have their eOperator set to WO_AND and they have
1242** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
1243**
1244** From another point of view, "indexable" means that the subterm could
1245** potentially be used with an index if an appropriate index exists.
1246** This analysis does not consider whether or not the index exists; that
drh4a6fc352013-08-07 01:18:38 +00001247** is decided elsewhere. This analysis only looks at whether subterms
1248** appropriate for indexing exist.
drh1a58fe02008-12-20 02:06:13 +00001249**
drh4a6fc352013-08-07 01:18:38 +00001250** All examples A through E above satisfy case 2. But if a term
drh1a58fe02008-12-20 02:06:13 +00001251** also statisfies case 1 (such as B) we know that the optimizer will
1252** always prefer case 1, so in that case we pretend that case 2 is not
1253** satisfied.
1254**
1255** It might be the case that multiple tables are indexable. For example,
1256** (E) above is indexable on tables P, Q, and R.
1257**
1258** Terms that satisfy case 2 are candidates for lookup by using
1259** separate indices to find rowids for each subterm and composing
1260** the union of all rowids using a RowSet object. This is similar
1261** to "bitmap indices" in other database engines.
1262**
1263** OTHERWISE:
1264**
1265** If neither case 1 nor case 2 apply, then leave the eOperator set to
1266** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +00001267*/
drh1a58fe02008-12-20 02:06:13 +00001268static void exprAnalyzeOrTerm(
1269 SrcList *pSrc, /* the FROM clause */
1270 WhereClause *pWC, /* the complete WHERE clause */
1271 int idxTerm /* Index of the OR-term to be analyzed */
1272){
drh70d18342013-06-06 19:16:33 +00001273 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
1274 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +00001275 sqlite3 *db = pParse->db; /* Database connection */
1276 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
1277 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +00001278 int i; /* Loop counters */
1279 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
1280 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
1281 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
1282 Bitmask chngToIN; /* Tables that might satisfy case 1 */
1283 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +00001284
drh1a58fe02008-12-20 02:06:13 +00001285 /*
1286 ** Break the OR clause into its separate subterms. The subterms are
1287 ** stored in a WhereClause structure containing within the WhereOrInfo
1288 ** object that is attached to the original OR clause term.
1289 */
1290 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
1291 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +00001292 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +00001293 if( pOrInfo==0 ) return;
1294 pTerm->wtFlags |= TERM_ORINFO;
1295 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +00001296 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +00001297 whereSplit(pOrWc, pExpr, TK_OR);
1298 exprAnalyzeAll(pSrc, pOrWc);
1299 if( db->mallocFailed ) return;
1300 assert( pOrWc->nTerm>=2 );
1301
1302 /*
1303 ** Compute the set of tables that might satisfy cases 1 or 2.
1304 */
danielk1977e672c8e2009-05-22 15:43:26 +00001305 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +00001306 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +00001307 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
1308 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +00001309 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +00001310 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +00001311 chngToIN = 0;
drh29435252008-12-28 18:35:08 +00001312 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
1313 if( pAndInfo ){
1314 WhereClause *pAndWC;
1315 WhereTerm *pAndTerm;
1316 int j;
1317 Bitmask b = 0;
1318 pOrTerm->u.pAndInfo = pAndInfo;
1319 pOrTerm->wtFlags |= TERM_ANDINFO;
1320 pOrTerm->eOperator = WO_AND;
1321 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +00001322 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +00001323 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
1324 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +00001325 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +00001326 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +00001327 if( !db->mallocFailed ){
1328 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
1329 assert( pAndTerm->pExpr );
1330 if( allowedOp(pAndTerm->pExpr->op) ){
drh70d18342013-06-06 19:16:33 +00001331 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +00001332 }
drh29435252008-12-28 18:35:08 +00001333 }
1334 }
1335 indexable &= b;
1336 }
drh1a58fe02008-12-20 02:06:13 +00001337 }else if( pOrTerm->wtFlags & TERM_COPIED ){
1338 /* Skip this term for now. We revisit it when we process the
1339 ** corresponding TERM_VIRTUAL term */
1340 }else{
1341 Bitmask b;
drh70d18342013-06-06 19:16:33 +00001342 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001343 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
1344 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh70d18342013-06-06 19:16:33 +00001345 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001346 }
1347 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +00001348 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +00001349 chngToIN = 0;
1350 }else{
1351 chngToIN &= b;
1352 }
1353 }
drh3e355802007-02-23 23:13:33 +00001354 }
drh1a58fe02008-12-20 02:06:13 +00001355
1356 /*
1357 ** Record the set of tables that satisfy case 2. The set might be
drh111a6a72008-12-21 03:51:16 +00001358 ** empty.
drh1a58fe02008-12-20 02:06:13 +00001359 */
1360 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +00001361 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +00001362
1363 /*
1364 ** chngToIN holds a set of tables that *might* satisfy case 1. But
1365 ** we have to do some additional checking to see if case 1 really
1366 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +00001367 **
1368 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
1369 ** that there is no possibility of transforming the OR clause into an
1370 ** IN operator because one or more terms in the OR clause contain
1371 ** something other than == on a column in the single table. The 1-bit
1372 ** case means that every term of the OR clause is of the form
1373 ** "table.column=expr" for some single table. The one bit that is set
1374 ** will correspond to the common table. We still need to check to make
1375 ** sure the same column is used on all terms. The 2-bit case is when
1376 ** the all terms are of the form "table1.column=table2.column". It
1377 ** might be possible to form an IN operator with either table1.column
1378 ** or table2.column as the LHS if either is common to every term of
1379 ** the OR clause.
1380 **
1381 ** Note that terms of the form "table.column1=table.column2" (the
1382 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +00001383 */
1384 if( chngToIN ){
1385 int okToChngToIN = 0; /* True if the conversion to IN is valid */
1386 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +00001387 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +00001388 int j = 0; /* Loop counter */
1389
1390 /* Search for a table and column that appears on one side or the
1391 ** other of the == operator in every subterm. That table and column
1392 ** will be recorded in iCursor and iColumn. There might not be any
1393 ** such table and column. Set okToChngToIN if an appropriate table
1394 ** and column is found but leave okToChngToIN false if not found.
1395 */
1396 for(j=0; j<2 && !okToChngToIN; j++){
1397 pOrTerm = pOrWc->a;
1398 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001399 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001400 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +00001401 if( pOrTerm->leftCursor==iCursor ){
1402 /* This is the 2-bit case and we are on the second iteration and
1403 ** current term is from the first iteration. So skip this term. */
1404 assert( j==1 );
1405 continue;
1406 }
drh70d18342013-06-06 19:16:33 +00001407 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +00001408 /* This term must be of the form t1.a==t2.b where t2 is in the
1409 ** chngToIN set but t1 is not. This term will be either preceeded
1410 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
1411 ** and use its inversion. */
1412 testcase( pOrTerm->wtFlags & TERM_COPIED );
1413 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
1414 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
1415 continue;
1416 }
drh1a58fe02008-12-20 02:06:13 +00001417 iColumn = pOrTerm->u.leftColumn;
1418 iCursor = pOrTerm->leftCursor;
1419 break;
1420 }
1421 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +00001422 /* No candidate table+column was found. This can only occur
1423 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +00001424 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +00001425 assert( IsPowerOfTwo(chngToIN) );
drh70d18342013-06-06 19:16:33 +00001426 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +00001427 break;
1428 }
drh4e8be3b2009-06-08 17:11:08 +00001429 testcase( j==1 );
1430
1431 /* We have found a candidate table and column. Check to see if that
1432 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001433 okToChngToIN = 1;
1434 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001435 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001436 if( pOrTerm->leftCursor!=iCursor ){
1437 pOrTerm->wtFlags &= ~TERM_OR_OK;
1438 }else if( pOrTerm->u.leftColumn!=iColumn ){
1439 okToChngToIN = 0;
1440 }else{
1441 int affLeft, affRight;
1442 /* If the right-hand side is also a column, then the affinities
1443 ** of both right and left sides must be such that no type
1444 ** conversions are required on the right. (Ticket #2249)
1445 */
1446 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1447 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1448 if( affRight!=0 && affRight!=affLeft ){
1449 okToChngToIN = 0;
1450 }else{
1451 pOrTerm->wtFlags |= TERM_OR_OK;
1452 }
1453 }
1454 }
1455 }
1456
1457 /* At this point, okToChngToIN is true if original pTerm satisfies
1458 ** case 1. In that case, construct a new virtual term that is
1459 ** pTerm converted into an IN operator.
1460 */
1461 if( okToChngToIN ){
1462 Expr *pDup; /* A transient duplicate expression */
1463 ExprList *pList = 0; /* The RHS of the IN operator */
1464 Expr *pLeft = 0; /* The LHS of the IN operator */
1465 Expr *pNew; /* The complete IN operator */
1466
1467 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1468 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001469 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001470 assert( pOrTerm->leftCursor==iCursor );
1471 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001472 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001473 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001474 pLeft = pOrTerm->pExpr->pLeft;
1475 }
1476 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001477 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001478 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001479 if( pNew ){
1480 int idxNew;
1481 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001482 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1483 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001484 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1485 testcase( idxNew==0 );
1486 exprAnalyze(pSrc, pWC, idxNew);
1487 pTerm = &pWC->a[idxTerm];
1488 pWC->a[idxNew].iParent = idxTerm;
1489 pTerm->nChild = 1;
1490 }else{
1491 sqlite3ExprListDelete(db, pList);
1492 }
drh534230c2011-01-22 00:10:45 +00001493 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
drh1a58fe02008-12-20 02:06:13 +00001494 }
drh3e355802007-02-23 23:13:33 +00001495 }
drh3e355802007-02-23 23:13:33 +00001496}
1497#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001498
drh7a5bcc02013-01-16 17:08:58 +00001499/*
drh0aa74ed2005-07-16 13:33:20 +00001500** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001501** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001502** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001503** structure.
drh51147ba2005-07-23 22:59:55 +00001504**
1505** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001506** to the standard form of "X <op> <expr>".
1507**
1508** If the expression is of the form "X <op> Y" where both X and Y are
1509** columns, then the original expression is unchanged and a new virtual
1510** term of the form "Y <op> X" is added to the WHERE clause and
1511** analyzed separately. The original term is marked with TERM_COPIED
1512** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1513** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1514** is a commuted copy of a prior term.) The original term has nChild=1
1515** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001516*/
drh0fcef5e2005-07-19 17:38:22 +00001517static void exprAnalyze(
1518 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001519 WhereClause *pWC, /* the WHERE clause */
1520 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001521){
drh70d18342013-06-06 19:16:33 +00001522 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001523 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001524 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001525 Expr *pExpr; /* The expression to be analyzed */
1526 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1527 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001528 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001529 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1530 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1531 int noCase = 0; /* LIKE/GLOB distinguishes case */
drh1a58fe02008-12-20 02:06:13 +00001532 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001533 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001534 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001535
drhf998b732007-11-26 13:36:00 +00001536 if( db->mallocFailed ){
1537 return;
1538 }
1539 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001540 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001541 pExpr = pTerm->pExpr;
1542 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001543 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001544 op = pExpr->op;
1545 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001546 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001547 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1548 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1549 }else{
1550 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1551 }
drh50b39962006-10-28 00:28:09 +00001552 }else if( op==TK_ISNULL ){
1553 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001554 }else{
1555 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1556 }
drh22d6a532005-09-19 21:05:48 +00001557 prereqAll = exprTableUsage(pMaskSet, pExpr);
1558 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001559 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1560 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001561 extraRight = x-1; /* ON clause terms may not be used with an index
1562 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001563 }
1564 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001565 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001566 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001567 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001568 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001569 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1570 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001571 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001572 if( pLeft->op==TK_COLUMN ){
1573 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001574 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001575 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001576 }
drh0fcef5e2005-07-19 17:38:22 +00001577 if( pRight && pRight->op==TK_COLUMN ){
1578 WhereTerm *pNew;
1579 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001580 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001581 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001582 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001583 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001584 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001585 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001586 return;
1587 }
drh9eb20282005-08-24 03:52:18 +00001588 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1589 if( idxNew==0 ) return;
1590 pNew = &pWC->a[idxNew];
1591 pNew->iParent = idxTerm;
1592 pTerm = &pWC->a[idxTerm];
drh45b1ee42005-08-02 17:48:22 +00001593 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001594 pTerm->wtFlags |= TERM_COPIED;
drheb5bc922013-01-17 16:43:33 +00001595 if( pExpr->op==TK_EQ
1596 && !ExprHasProperty(pExpr, EP_FromJoin)
1597 && OptimizationEnabled(db, SQLITE_Transitive)
1598 ){
drh7a5bcc02013-01-16 17:08:58 +00001599 pTerm->eOperator |= WO_EQUIV;
1600 eExtraOp = WO_EQUIV;
1601 }
drh0fcef5e2005-07-19 17:38:22 +00001602 }else{
1603 pDup = pExpr;
1604 pNew = pTerm;
1605 }
drh7d10d5a2008-08-20 16:35:10 +00001606 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001607 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001608 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001609 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001610 testcase( (prereqLeft | extraRight) != prereqLeft );
1611 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001612 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001613 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001614 }
1615 }
drhed378002005-07-28 23:12:08 +00001616
drhd2687b72005-08-12 22:56:09 +00001617#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001618 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001619 ** that define the range that the BETWEEN implements. For example:
1620 **
1621 ** a BETWEEN b AND c
1622 **
1623 ** is converted into:
1624 **
1625 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1626 **
1627 ** The two new terms are added onto the end of the WhereClause object.
1628 ** The new terms are "dynamic" and are children of the original BETWEEN
1629 ** term. That means that if the BETWEEN term is coded, the children are
1630 ** skipped. Or, if the children are satisfied by an index, the original
1631 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001632 */
drh29435252008-12-28 18:35:08 +00001633 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001634 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001635 int i;
1636 static const u8 ops[] = {TK_GE, TK_LE};
1637 assert( pList!=0 );
1638 assert( pList->nExpr==2 );
1639 for(i=0; i<2; i++){
1640 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001641 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001642 pNewExpr = sqlite3PExpr(pParse, ops[i],
1643 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001644 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drhd41d39f2013-08-28 16:27:01 +00001645 transferJoinMarkings(pNewExpr, pExpr);
drh9eb20282005-08-24 03:52:18 +00001646 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001647 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001648 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001649 pTerm = &pWC->a[idxTerm];
1650 pWC->a[idxNew].iParent = idxTerm;
drhed378002005-07-28 23:12:08 +00001651 }
drh45b1ee42005-08-02 17:48:22 +00001652 pTerm->nChild = 2;
drhed378002005-07-28 23:12:08 +00001653 }
drhd2687b72005-08-12 22:56:09 +00001654#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001655
danielk19771576cd92006-01-14 08:02:28 +00001656#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001657 /* Analyze a term that is composed of two or more subterms connected by
1658 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001659 */
1660 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001661 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001662 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001663 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001664 }
drhd2687b72005-08-12 22:56:09 +00001665#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1666
1667#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1668 /* Add constraints to reduce the search space on a LIKE or GLOB
1669 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001670 **
1671 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1672 **
1673 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
1674 **
1675 ** The last character of the prefix "abc" is incremented to form the
shane7bc71e52008-05-28 18:01:44 +00001676 ** termination condition "abd".
drhd2687b72005-08-12 22:56:09 +00001677 */
dan937d0de2009-10-15 18:35:38 +00001678 if( pWC->op==TK_AND
1679 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1680 ){
drh1d452e12009-11-01 19:26:59 +00001681 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1682 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1683 Expr *pNewExpr1;
1684 Expr *pNewExpr2;
1685 int idxNew1;
1686 int idxNew2;
drhae80dde2012-12-06 21:16:43 +00001687 Token sCollSeqName; /* Name of collating sequence */
drh9eb20282005-08-24 03:52:18 +00001688
danielk19776ab3a2e2009-02-19 14:39:25 +00001689 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001690 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drhf998b732007-11-26 13:36:00 +00001691 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001692 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001693 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001694 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001695 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001696 /* The point is to increment the last character before the first
1697 ** wildcard. But if we increment '@', that will push it into the
1698 ** alphabetic range where case conversions will mess up the
1699 ** inequality. To avoid this, make sure to also run the full
1700 ** LIKE on all candidate expressions by clearing the isComplete flag
1701 */
drh39759742013-08-02 23:40:45 +00001702 if( c=='A'-1 ) isComplete = 0;
drh02a50b72008-05-26 18:33:40 +00001703 c = sqlite3UpperToLower[c];
1704 }
drh9f504ea2008-02-23 21:55:39 +00001705 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001706 }
drhae80dde2012-12-06 21:16:43 +00001707 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1708 sCollSeqName.n = 6;
1709 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001710 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
drh0a8a4062012-12-07 18:38:16 +00001711 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001712 pStr1, 0);
drhd41d39f2013-08-28 16:27:01 +00001713 transferJoinMarkings(pNewExpr1, pExpr);
drh9eb20282005-08-24 03:52:18 +00001714 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001715 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001716 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001717 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001718 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
drh0a8a4062012-12-07 18:38:16 +00001719 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001720 pStr2, 0);
drhd41d39f2013-08-28 16:27:01 +00001721 transferJoinMarkings(pNewExpr2, pExpr);
drh9eb20282005-08-24 03:52:18 +00001722 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001723 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001724 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001725 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001726 if( isComplete ){
drh9eb20282005-08-24 03:52:18 +00001727 pWC->a[idxNew1].iParent = idxTerm;
1728 pWC->a[idxNew2].iParent = idxTerm;
drhd2687b72005-08-12 22:56:09 +00001729 pTerm->nChild = 2;
1730 }
1731 }
1732#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001733
1734#ifndef SQLITE_OMIT_VIRTUALTABLE
1735 /* Add a WO_MATCH auxiliary term to the constraint set if the
1736 ** current expression is of the form: column MATCH expr.
1737 ** This information is used by the xBestIndex methods of
1738 ** virtual tables. The native query optimizer does not attempt
1739 ** to do anything with MATCH functions.
1740 */
1741 if( isMatchOfColumn(pExpr) ){
1742 int idxNew;
1743 Expr *pRight, *pLeft;
1744 WhereTerm *pNewTerm;
1745 Bitmask prereqColumn, prereqExpr;
1746
danielk19776ab3a2e2009-02-19 14:39:25 +00001747 pRight = pExpr->x.pList->a[0].pExpr;
1748 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001749 prereqExpr = exprTableUsage(pMaskSet, pRight);
1750 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1751 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001752 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001753 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1754 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001755 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001756 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001757 pNewTerm = &pWC->a[idxNew];
1758 pNewTerm->prereqRight = prereqExpr;
1759 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001760 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001761 pNewTerm->eOperator = WO_MATCH;
1762 pNewTerm->iParent = idxTerm;
drhd2ca60d2006-06-27 02:36:58 +00001763 pTerm = &pWC->a[idxTerm];
drh7f375902006-06-13 17:38:59 +00001764 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001765 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001766 pNewTerm->prereqAll = pTerm->prereqAll;
1767 }
1768 }
1769#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001770
drh1435a9a2013-08-27 23:15:44 +00001771#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drhd3ed7342011-09-21 00:09:41 +00001772 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001773 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1774 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1775 ** virtual term of that form.
1776 **
1777 ** Note that the virtual term must be tagged with TERM_VNULL. This
1778 ** TERM_VNULL tag will suppress the not-null check at the beginning
1779 ** of the loop. Without the TERM_VNULL flag, the not-null check at
1780 ** the start of the loop will prevent any results from being returned.
1781 */
drhea6dc442011-04-08 21:35:26 +00001782 if( pExpr->op==TK_NOTNULL
1783 && pExpr->pLeft->op==TK_COLUMN
1784 && pExpr->pLeft->iColumn>=0
drh40aa9362013-06-28 17:29:25 +00001785 && OptimizationEnabled(db, SQLITE_Stat3)
drhea6dc442011-04-08 21:35:26 +00001786 ){
drh534230c2011-01-22 00:10:45 +00001787 Expr *pNewExpr;
1788 Expr *pLeft = pExpr->pLeft;
1789 int idxNew;
1790 WhereTerm *pNewTerm;
1791
1792 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1793 sqlite3ExprDup(db, pLeft, 0),
1794 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1795
1796 idxNew = whereClauseInsert(pWC, pNewExpr,
1797 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001798 if( idxNew ){
1799 pNewTerm = &pWC->a[idxNew];
1800 pNewTerm->prereqRight = 0;
1801 pNewTerm->leftCursor = pLeft->iTable;
1802 pNewTerm->u.leftColumn = pLeft->iColumn;
1803 pNewTerm->eOperator = WO_GT;
1804 pNewTerm->iParent = idxTerm;
1805 pTerm = &pWC->a[idxTerm];
1806 pTerm->nChild = 1;
1807 pTerm->wtFlags |= TERM_COPIED;
1808 pNewTerm->prereqAll = pTerm->prereqAll;
1809 }
drh534230c2011-01-22 00:10:45 +00001810 }
drh1435a9a2013-08-27 23:15:44 +00001811#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh534230c2011-01-22 00:10:45 +00001812
drhdafc0ce2008-04-17 19:14:02 +00001813 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1814 ** an index for tables to the left of the join.
1815 */
1816 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001817}
1818
drh7b4fc6a2007-02-06 13:26:32 +00001819/*
drh3b48e8c2013-06-12 20:18:16 +00001820** This function searches pList for a entry that matches the iCol-th column
1821** of index pIdx.
dan6f343962011-07-01 18:26:40 +00001822**
1823** If such an expression is found, its index in pList->a[] is returned. If
1824** no expression is found, -1 is returned.
1825*/
1826static int findIndexCol(
1827 Parse *pParse, /* Parse context */
1828 ExprList *pList, /* Expression list to search */
1829 int iBase, /* Cursor for table associated with pIdx */
1830 Index *pIdx, /* Index to match column of */
1831 int iCol /* Column of index to match */
1832){
1833 int i;
1834 const char *zColl = pIdx->azColl[iCol];
1835
1836 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001837 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001838 if( p->op==TK_COLUMN
1839 && p->iColumn==pIdx->aiColumn[iCol]
1840 && p->iTable==iBase
1841 ){
drh580c8c12012-12-08 03:34:04 +00001842 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001843 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001844 return i;
1845 }
1846 }
1847 }
1848
1849 return -1;
1850}
1851
1852/*
dan6f343962011-07-01 18:26:40 +00001853** Return true if the DISTINCT expression-list passed as the third argument
drh4f402f22013-06-11 18:59:38 +00001854** is redundant.
1855**
drh3b48e8c2013-06-12 20:18:16 +00001856** A DISTINCT list is redundant if the database contains some subset of
drh4f402f22013-06-11 18:59:38 +00001857** columns that are unique and non-null.
dan6f343962011-07-01 18:26:40 +00001858*/
1859static int isDistinctRedundant(
drh4f402f22013-06-11 18:59:38 +00001860 Parse *pParse, /* Parsing context */
1861 SrcList *pTabList, /* The FROM clause */
1862 WhereClause *pWC, /* The WHERE clause */
1863 ExprList *pDistinct /* The result set that needs to be DISTINCT */
dan6f343962011-07-01 18:26:40 +00001864){
1865 Table *pTab;
1866 Index *pIdx;
1867 int i;
1868 int iBase;
1869
1870 /* If there is more than one table or sub-select in the FROM clause of
1871 ** this query, then it will not be possible to show that the DISTINCT
1872 ** clause is redundant. */
1873 if( pTabList->nSrc!=1 ) return 0;
1874 iBase = pTabList->a[0].iCursor;
1875 pTab = pTabList->a[0].pTab;
1876
dan94e08d92011-07-02 06:44:05 +00001877 /* If any of the expressions is an IPK column on table iBase, then return
1878 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1879 ** current SELECT is a correlated sub-query.
1880 */
dan6f343962011-07-01 18:26:40 +00001881 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001882 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001883 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001884 }
1885
1886 /* Loop through all indices on the table, checking each to see if it makes
1887 ** the DISTINCT qualifier redundant. It does so if:
1888 **
1889 ** 1. The index is itself UNIQUE, and
1890 **
1891 ** 2. All of the columns in the index are either part of the pDistinct
1892 ** list, or else the WHERE clause contains a term of the form "col=X",
1893 ** where X is a constant value. The collation sequences of the
1894 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001895 **
1896 ** 3. All of those index columns for which the WHERE clause does not
1897 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001898 */
1899 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1900 if( pIdx->onError==OE_None ) continue;
drhbbbdc832013-10-22 18:01:40 +00001901 for(i=0; i<pIdx->nKeyCol; i++){
1902 i16 iCol = pIdx->aiColumn[i];
dan6a36f432012-04-20 16:59:24 +00001903 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1904 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
drhbbbdc832013-10-22 18:01:40 +00001905 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
dan6a36f432012-04-20 16:59:24 +00001906 break;
1907 }
dan6f343962011-07-01 18:26:40 +00001908 }
1909 }
drhbbbdc832013-10-22 18:01:40 +00001910 if( i==pIdx->nKeyCol ){
dan6f343962011-07-01 18:26:40 +00001911 /* This index implies that the DISTINCT qualifier is redundant. */
1912 return 1;
1913 }
1914 }
1915
1916 return 0;
1917}
drh0fcef5e2005-07-19 17:38:22 +00001918
drh8636e9c2013-06-11 01:50:08 +00001919
drh75897232000-05-29 14:26:00 +00001920/*
drh3b48e8c2013-06-12 20:18:16 +00001921** Estimate the logarithm of the input value to base 2.
drh28c4cf42005-07-27 20:41:43 +00001922*/
drhbf539c42013-10-05 18:16:02 +00001923static LogEst estLog(LogEst N){
1924 LogEst x = sqlite3LogEst(N);
drh4fe425a2013-06-12 17:08:06 +00001925 return x>33 ? x - 33 : 0;
drh28c4cf42005-07-27 20:41:43 +00001926}
1927
drh6d209d82006-06-27 01:54:26 +00001928/*
1929** Two routines for printing the content of an sqlite3_index_info
1930** structure. Used for testing and debugging only. If neither
1931** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1932** are no-ops.
1933*/
drhd15cb172013-05-21 19:23:10 +00001934#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00001935static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1936 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001937 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001938 for(i=0; i<p->nConstraint; i++){
1939 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1940 i,
1941 p->aConstraint[i].iColumn,
1942 p->aConstraint[i].iTermOffset,
1943 p->aConstraint[i].op,
1944 p->aConstraint[i].usable);
1945 }
1946 for(i=0; i<p->nOrderBy; i++){
1947 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1948 i,
1949 p->aOrderBy[i].iColumn,
1950 p->aOrderBy[i].desc);
1951 }
1952}
1953static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1954 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001955 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001956 for(i=0; i<p->nConstraint; i++){
1957 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1958 i,
1959 p->aConstraintUsage[i].argvIndex,
1960 p->aConstraintUsage[i].omit);
1961 }
1962 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1963 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1964 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1965 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
1966}
1967#else
1968#define TRACE_IDX_INPUTS(A)
1969#define TRACE_IDX_OUTPUTS(A)
1970#endif
1971
drhc6339082010-04-07 16:54:58 +00001972#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001973/*
drh4139c992010-04-07 14:59:45 +00001974** Return TRUE if the WHERE clause term pTerm is of a form where it
1975** could be used with an index to access pSrc, assuming an appropriate
1976** index existed.
1977*/
1978static int termCanDriveIndex(
1979 WhereTerm *pTerm, /* WHERE clause term to check */
1980 struct SrcList_item *pSrc, /* Table we are trying to access */
1981 Bitmask notReady /* Tables in outer loops of the join */
1982){
1983 char aff;
1984 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drh7a5bcc02013-01-16 17:08:58 +00001985 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001986 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00001987 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001988 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1989 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
1990 return 1;
1991}
drhc6339082010-04-07 16:54:58 +00001992#endif
drh4139c992010-04-07 14:59:45 +00001993
drhc6339082010-04-07 16:54:58 +00001994
1995#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001996/*
drhc6339082010-04-07 16:54:58 +00001997** Generate code to construct the Index object for an automatic index
1998** and to set up the WhereLevel object pLevel so that the code generator
1999** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00002000*/
drhc6339082010-04-07 16:54:58 +00002001static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00002002 Parse *pParse, /* The parsing context */
2003 WhereClause *pWC, /* The WHERE clause */
2004 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
2005 Bitmask notReady, /* Mask of cursors that are not available */
2006 WhereLevel *pLevel /* Write new index here */
2007){
drhbbbdc832013-10-22 18:01:40 +00002008 int nKeyCol; /* Number of columns in the constructed index */
drh8b307fb2010-04-06 15:57:05 +00002009 WhereTerm *pTerm; /* A single term of the WHERE clause */
2010 WhereTerm *pWCEnd; /* End of pWC->a[] */
drh8b307fb2010-04-06 15:57:05 +00002011 Index *pIdx; /* Object describing the transient index */
2012 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00002013 int addrInit; /* Address of the initialization bypass jump */
2014 Table *pTable; /* The table being indexed */
2015 KeyInfo *pKeyinfo; /* Key information for the index */
2016 int addrTop; /* Top of the index fill loop */
2017 int regRecord; /* Register holding an index record */
2018 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00002019 int i; /* Loop counter */
2020 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00002021 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00002022 WhereLoop *pLoop; /* The Loop object */
drh77e57df2013-10-22 14:28:02 +00002023 char *zNotUsed; /* Extra space on the end of pIdx */
drh4139c992010-04-07 14:59:45 +00002024 Bitmask idxCols; /* Bitmap of columns used for indexing */
2025 Bitmask extraCols; /* Bitmap of additional columns */
drh8d56e202013-06-28 23:55:45 +00002026 u8 sentWarning = 0; /* True if a warnning has been issued */
drh8b307fb2010-04-06 15:57:05 +00002027
2028 /* Generate code to skip over the creation and initialization of the
2029 ** transient index on 2nd and subsequent iterations of the loop. */
2030 v = pParse->pVdbe;
2031 assert( v!=0 );
dan1d8cb212011-12-09 13:24:16 +00002032 addrInit = sqlite3CodeOnce(pParse);
drh8b307fb2010-04-06 15:57:05 +00002033
drh4139c992010-04-07 14:59:45 +00002034 /* Count the number of columns that will be added to the index
2035 ** and used to match WHERE clause constraints */
drhbbbdc832013-10-22 18:01:40 +00002036 nKeyCol = 0;
drh424aab82010-04-06 18:28:20 +00002037 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00002038 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00002039 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00002040 idxCols = 0;
drh81186b42013-06-18 01:52:41 +00002041 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00002042 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
2043 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00002044 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00002045 testcase( iCol==BMS );
2046 testcase( iCol==BMS-1 );
drh8d56e202013-06-28 23:55:45 +00002047 if( !sentWarning ){
2048 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
2049 "automatic index on %s(%s)", pTable->zName,
2050 pTable->aCol[iCol].zName);
2051 sentWarning = 1;
2052 }
drh0013e722010-04-08 00:40:15 +00002053 if( (idxCols & cMask)==0 ){
drhbbbdc832013-10-22 18:01:40 +00002054 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
2055 pLoop->aLTerm[nKeyCol++] = pTerm;
drh0013e722010-04-08 00:40:15 +00002056 idxCols |= cMask;
2057 }
drh8b307fb2010-04-06 15:57:05 +00002058 }
2059 }
drhbbbdc832013-10-22 18:01:40 +00002060 assert( nKeyCol>0 );
2061 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
drh53b52f72013-05-31 11:57:39 +00002062 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
drh986b3872013-06-28 21:12:20 +00002063 | WHERE_AUTO_INDEX;
drh4139c992010-04-07 14:59:45 +00002064
2065 /* Count the number of additional columns needed to create a
2066 ** covering index. A "covering index" is an index that contains all
2067 ** columns that are needed by the query. With a covering index, the
2068 ** original table never needs to be accessed. Automatic indices must
2069 ** be a covering index because the index will not be updated if the
2070 ** original table changes and the index and table cannot both be used
2071 ** if they go out of sync.
2072 */
drh7699d1c2013-06-04 12:42:29 +00002073 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drh4139c992010-04-07 14:59:45 +00002074 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
drh52ff8ea2010-04-08 14:15:56 +00002075 testcase( pTable->nCol==BMS-1 );
2076 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00002077 for(i=0; i<mxBitCol; i++){
drhbbbdc832013-10-22 18:01:40 +00002078 if( extraCols & MASKBIT(i) ) nKeyCol++;
drh4139c992010-04-07 14:59:45 +00002079 }
drh7699d1c2013-06-04 12:42:29 +00002080 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drhbbbdc832013-10-22 18:01:40 +00002081 nKeyCol += pTable->nCol - BMS + 1;
drh4139c992010-04-07 14:59:45 +00002082 }
drh7ba39a92013-05-30 17:43:19 +00002083 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
drh8b307fb2010-04-06 15:57:05 +00002084
2085 /* Construct the Index object to describe this index */
drhbbbdc832013-10-22 18:01:40 +00002086 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
drh8b307fb2010-04-06 15:57:05 +00002087 if( pIdx==0 ) return;
drh7ba39a92013-05-30 17:43:19 +00002088 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00002089 pIdx->zName = "auto-index";
drh424aab82010-04-06 18:28:20 +00002090 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00002091 n = 0;
drh0013e722010-04-08 00:40:15 +00002092 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00002093 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00002094 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00002095 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00002096 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh7963b0e2013-06-17 21:37:40 +00002097 testcase( iCol==BMS-1 );
2098 testcase( iCol==BMS );
drh0013e722010-04-08 00:40:15 +00002099 if( (idxCols & cMask)==0 ){
2100 Expr *pX = pTerm->pExpr;
2101 idxCols |= cMask;
2102 pIdx->aiColumn[n] = pTerm->u.leftColumn;
2103 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh6f2e6c02011-02-17 13:33:15 +00002104 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00002105 n++;
2106 }
drh8b307fb2010-04-06 15:57:05 +00002107 }
2108 }
drh7ba39a92013-05-30 17:43:19 +00002109 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00002110
drhc6339082010-04-07 16:54:58 +00002111 /* Add additional columns needed to make the automatic index into
2112 ** a covering index */
drh4139c992010-04-07 14:59:45 +00002113 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00002114 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00002115 pIdx->aiColumn[n] = i;
2116 pIdx->azColl[n] = "BINARY";
2117 n++;
2118 }
2119 }
drh7699d1c2013-06-04 12:42:29 +00002120 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00002121 for(i=BMS-1; i<pTable->nCol; i++){
2122 pIdx->aiColumn[n] = i;
2123 pIdx->azColl[n] = "BINARY";
2124 n++;
2125 }
2126 }
drhbbbdc832013-10-22 18:01:40 +00002127 assert( n==nKeyCol );
drh44156282013-10-23 22:23:03 +00002128 pIdx->aiColumn[n] = -1;
2129 pIdx->azColl[n] = "BINARY";
drh8b307fb2010-04-06 15:57:05 +00002130
drhc6339082010-04-07 16:54:58 +00002131 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00002132 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
2133 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00002134 pLevel->iIdxCur = pParse->nTab++;
drhbbbdc832013-10-22 18:01:40 +00002135 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1, 0,
drh8b307fb2010-04-06 15:57:05 +00002136 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
drha21a64d2010-04-06 22:33:55 +00002137 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00002138
drhc6339082010-04-07 16:54:58 +00002139 /* Fill the automatic index with content */
drh8b307fb2010-04-06 15:57:05 +00002140 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
2141 regRecord = sqlite3GetTempReg(pParse);
drhb2b9d3d2013-08-01 01:14:43 +00002142 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0);
drh8b307fb2010-04-06 15:57:05 +00002143 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
2144 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2145 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
drha21a64d2010-04-06 22:33:55 +00002146 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00002147 sqlite3VdbeJumpHere(v, addrTop);
2148 sqlite3ReleaseTempReg(pParse, regRecord);
2149
2150 /* Jump here when skipping the initialization */
2151 sqlite3VdbeJumpHere(v, addrInit);
2152}
drhc6339082010-04-07 16:54:58 +00002153#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00002154
drh9eff6162006-06-12 21:59:13 +00002155#ifndef SQLITE_OMIT_VIRTUALTABLE
2156/*
danielk19771d461462009-04-21 09:02:45 +00002157** Allocate and populate an sqlite3_index_info structure. It is the
2158** responsibility of the caller to eventually release the structure
2159** by passing the pointer returned by this function to sqlite3_free().
2160*/
drh5346e952013-05-08 14:14:26 +00002161static sqlite3_index_info *allocateIndexInfo(
2162 Parse *pParse,
2163 WhereClause *pWC,
2164 struct SrcList_item *pSrc,
2165 ExprList *pOrderBy
2166){
danielk19771d461462009-04-21 09:02:45 +00002167 int i, j;
2168 int nTerm;
2169 struct sqlite3_index_constraint *pIdxCons;
2170 struct sqlite3_index_orderby *pIdxOrderBy;
2171 struct sqlite3_index_constraint_usage *pUsage;
2172 WhereTerm *pTerm;
2173 int nOrderBy;
2174 sqlite3_index_info *pIdxInfo;
2175
danielk19771d461462009-04-21 09:02:45 +00002176 /* Count the number of possible WHERE clause constraints referring
2177 ** to this virtual table */
2178 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
2179 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00002180 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2181 testcase( pTerm->eOperator & WO_IN );
2182 testcase( pTerm->eOperator & WO_ISNULL );
drh281bbe22012-10-16 23:17:14 +00002183 if( pTerm->eOperator & (WO_ISNULL) ) continue;
drhb4256992011-08-02 01:57:39 +00002184 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00002185 nTerm++;
2186 }
2187
2188 /* If the ORDER BY clause contains only columns in the current
2189 ** virtual table then allocate space for the aOrderBy part of
2190 ** the sqlite3_index_info structure.
2191 */
2192 nOrderBy = 0;
2193 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00002194 int n = pOrderBy->nExpr;
2195 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00002196 Expr *pExpr = pOrderBy->a[i].pExpr;
2197 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
2198 }
drh56f1b992012-09-25 14:29:39 +00002199 if( i==n){
2200 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00002201 }
2202 }
2203
2204 /* Allocate the sqlite3_index_info structure
2205 */
2206 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
2207 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
2208 + sizeof(*pIdxOrderBy)*nOrderBy );
2209 if( pIdxInfo==0 ){
2210 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00002211 return 0;
2212 }
2213
2214 /* Initialize the structure. The sqlite3_index_info structure contains
2215 ** many fields that are declared "const" to prevent xBestIndex from
2216 ** changing them. We have to do some funky casting in order to
2217 ** initialize those fields.
2218 */
2219 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
2220 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
2221 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
2222 *(int*)&pIdxInfo->nConstraint = nTerm;
2223 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
2224 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
2225 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
2226 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
2227 pUsage;
2228
2229 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00002230 u8 op;
danielk19771d461462009-04-21 09:02:45 +00002231 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00002232 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2233 testcase( pTerm->eOperator & WO_IN );
2234 testcase( pTerm->eOperator & WO_ISNULL );
drh281bbe22012-10-16 23:17:14 +00002235 if( pTerm->eOperator & (WO_ISNULL) ) continue;
drhb4256992011-08-02 01:57:39 +00002236 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00002237 pIdxCons[j].iColumn = pTerm->u.leftColumn;
2238 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00002239 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00002240 if( op==WO_IN ) op = WO_EQ;
2241 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00002242 /* The direct assignment in the previous line is possible only because
2243 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
2244 ** following asserts verify this fact. */
2245 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
2246 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
2247 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
2248 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
2249 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
2250 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00002251 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00002252 j++;
2253 }
2254 for(i=0; i<nOrderBy; i++){
2255 Expr *pExpr = pOrderBy->a[i].pExpr;
2256 pIdxOrderBy[i].iColumn = pExpr->iColumn;
2257 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
2258 }
2259
2260 return pIdxInfo;
2261}
2262
2263/*
2264** The table object reference passed as the second argument to this function
2265** must represent a virtual table. This function invokes the xBestIndex()
drh3b48e8c2013-06-12 20:18:16 +00002266** method of the virtual table with the sqlite3_index_info object that
2267** comes in as the 3rd argument to this function.
danielk19771d461462009-04-21 09:02:45 +00002268**
2269** If an error occurs, pParse is populated with an error message and a
2270** non-zero value is returned. Otherwise, 0 is returned and the output
2271** part of the sqlite3_index_info structure is left populated.
2272**
2273** Whether or not an error is returned, it is the responsibility of the
2274** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
2275** that this is required.
2276*/
2277static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00002278 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00002279 int i;
2280 int rc;
2281
danielk19771d461462009-04-21 09:02:45 +00002282 TRACE_IDX_INPUTS(p);
2283 rc = pVtab->pModule->xBestIndex(pVtab, p);
2284 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00002285
2286 if( rc!=SQLITE_OK ){
2287 if( rc==SQLITE_NOMEM ){
2288 pParse->db->mallocFailed = 1;
2289 }else if( !pVtab->zErrMsg ){
2290 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
2291 }else{
2292 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
2293 }
2294 }
drhb9755982010-07-24 16:34:37 +00002295 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00002296 pVtab->zErrMsg = 0;
2297
2298 for(i=0; i<p->nConstraint; i++){
2299 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
2300 sqlite3ErrorMsg(pParse,
2301 "table %s: xBestIndex returned an invalid plan", pTab->zName);
2302 }
2303 }
2304
2305 return pParse->nErr;
2306}
drh7ba39a92013-05-30 17:43:19 +00002307#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00002308
2309
drh1435a9a2013-08-27 23:15:44 +00002310#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh28c4cf42005-07-27 20:41:43 +00002311/*
drhfaacf172011-08-12 01:51:45 +00002312** Estimate the location of a particular key among all keys in an
2313** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00002314**
drhfaacf172011-08-12 01:51:45 +00002315** aStat[0] Est. number of rows less than pVal
2316** aStat[1] Est. number of rows equal to pVal
dan02fa4692009-08-17 17:06:58 +00002317**
drhfaacf172011-08-12 01:51:45 +00002318** Return SQLITE_OK on success.
dan02fa4692009-08-17 17:06:58 +00002319*/
danb3c02e22013-08-08 19:38:40 +00002320static void whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00002321 Parse *pParse, /* Database connection */
2322 Index *pIdx, /* Index to consider domain of */
dan7a419232013-08-06 20:01:43 +00002323 UnpackedRecord *pRec, /* Vector of values to consider */
drhfaacf172011-08-12 01:51:45 +00002324 int roundUp, /* Round up if true. Round down if false */
2325 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00002326){
danf52bb8d2013-08-03 20:24:58 +00002327 IndexSample *aSample = pIdx->aSample;
drhfbc38de2013-09-03 19:26:22 +00002328 int iCol; /* Index of required stats in anEq[] etc. */
dan84c309b2013-08-08 16:17:12 +00002329 int iMin = 0; /* Smallest sample not yet tested */
2330 int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
2331 int iTest; /* Next sample to test */
2332 int res; /* Result of comparison operation */
dan02fa4692009-08-17 17:06:58 +00002333
drh4f991892013-10-11 15:05:05 +00002334#ifndef SQLITE_DEBUG
2335 UNUSED_PARAMETER( pParse );
2336#endif
drhfbc38de2013-09-03 19:26:22 +00002337 assert( pRec!=0 || pParse->db->mallocFailed );
2338 if( pRec==0 ) return;
2339 iCol = pRec->nField - 1;
drh5c624862011-09-22 18:46:34 +00002340 assert( pIdx->nSample>0 );
dan8ad169a2013-08-12 20:14:04 +00002341 assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
dan84c309b2013-08-08 16:17:12 +00002342 do{
2343 iTest = (iMin+i)/2;
2344 res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
2345 if( res<0 ){
2346 iMin = iTest+1;
2347 }else{
2348 i = iTest;
dan02fa4692009-08-17 17:06:58 +00002349 }
dan84c309b2013-08-08 16:17:12 +00002350 }while( res && iMin<i );
drh51147ba2005-07-23 22:59:55 +00002351
dan84c309b2013-08-08 16:17:12 +00002352#ifdef SQLITE_DEBUG
2353 /* The following assert statements check that the binary search code
2354 ** above found the right answer. This block serves no purpose other
2355 ** than to invoke the asserts. */
2356 if( res==0 ){
2357 /* If (res==0) is true, then sample $i must be equal to pRec */
2358 assert( i<pIdx->nSample );
drh0e1f0022013-08-16 14:49:00 +00002359 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
2360 || pParse->db->mallocFailed );
dan02fa4692009-08-17 17:06:58 +00002361 }else{
dan84c309b2013-08-08 16:17:12 +00002362 /* Otherwise, pRec must be smaller than sample $i and larger than
2363 ** sample ($i-1). */
2364 assert( i==pIdx->nSample
drh0e1f0022013-08-16 14:49:00 +00002365 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
2366 || pParse->db->mallocFailed );
dan84c309b2013-08-08 16:17:12 +00002367 assert( i==0
drh0e1f0022013-08-16 14:49:00 +00002368 || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
2369 || pParse->db->mallocFailed );
drhfaacf172011-08-12 01:51:45 +00002370 }
dan84c309b2013-08-08 16:17:12 +00002371#endif /* ifdef SQLITE_DEBUG */
dan02fa4692009-08-17 17:06:58 +00002372
drhfaacf172011-08-12 01:51:45 +00002373 /* At this point, aSample[i] is the first sample that is greater than
2374 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
dan84c309b2013-08-08 16:17:12 +00002375 ** than pVal. If aSample[i]==pVal, then res==0.
drhfaacf172011-08-12 01:51:45 +00002376 */
dan84c309b2013-08-08 16:17:12 +00002377 if( res==0 ){
daneea568d2013-08-07 19:46:15 +00002378 aStat[0] = aSample[i].anLt[iCol];
2379 aStat[1] = aSample[i].anEq[iCol];
drhfaacf172011-08-12 01:51:45 +00002380 }else{
2381 tRowcnt iLower, iUpper, iGap;
2382 if( i==0 ){
2383 iLower = 0;
daneea568d2013-08-07 19:46:15 +00002384 iUpper = aSample[0].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00002385 }else{
daneea568d2013-08-07 19:46:15 +00002386 iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol];
2387 iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00002388 }
drhbbbdc832013-10-22 18:01:40 +00002389 aStat[1] = (pIdx->nKeyCol>iCol ? pIdx->aAvgEq[iCol] : 1);
drhfaacf172011-08-12 01:51:45 +00002390 if( iLower>=iUpper ){
2391 iGap = 0;
2392 }else{
2393 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00002394 }
2395 if( roundUp ){
2396 iGap = (iGap*2)/3;
2397 }else{
2398 iGap = iGap/3;
2399 }
2400 aStat[0] = iLower + iGap;
dan02fa4692009-08-17 17:06:58 +00002401 }
dan02fa4692009-08-17 17:06:58 +00002402}
drh1435a9a2013-08-27 23:15:44 +00002403#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
dan937d0de2009-10-15 18:35:38 +00002404
2405/*
dan02fa4692009-08-17 17:06:58 +00002406** This function is used to estimate the number of rows that will be visited
2407** by scanning an index for a range of values. The range may have an upper
2408** bound, a lower bound, or both. The WHERE clause terms that set the upper
2409** and lower bounds are represented by pLower and pUpper respectively. For
2410** example, assuming that index p is on t1(a):
2411**
2412** ... FROM t1 WHERE a > ? AND a < ? ...
2413** |_____| |_____|
2414** | |
2415** pLower pUpper
2416**
drh98cdf622009-08-20 18:14:42 +00002417** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00002418** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00002419**
dan6cb8d762013-08-08 11:48:57 +00002420** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
2421** column subject to the range constraint. Or, equivalently, the number of
2422** equality constraints optimized by the proposed index scan. For example,
2423** assuming index p is on t1(a, b), and the SQL query is:
dan02fa4692009-08-17 17:06:58 +00002424**
2425** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2426**
dan6cb8d762013-08-08 11:48:57 +00002427** then nEq is set to 1 (as the range restricted column, b, is the second
2428** left-most column of the index). Or, if the query is:
dan02fa4692009-08-17 17:06:58 +00002429**
2430** ... FROM t1 WHERE a > ? AND a < ? ...
2431**
dan6cb8d762013-08-08 11:48:57 +00002432** then nEq is set to 0.
dan02fa4692009-08-17 17:06:58 +00002433**
drhbf539c42013-10-05 18:16:02 +00002434** When this function is called, *pnOut is set to the sqlite3LogEst() of the
dan6cb8d762013-08-08 11:48:57 +00002435** number of rows that the index scan is expected to visit without
2436** considering the range constraints. If nEq is 0, this is the number of
2437** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
2438** to account for the range contraints pLower and pUpper.
2439**
2440** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
2441** used, each range inequality reduces the search space by a factor of 4.
2442** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
2443** rows visited by a factor of 16.
dan02fa4692009-08-17 17:06:58 +00002444*/
2445static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002446 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002447 WhereLoopBuilder *pBuilder,
drhcdaca552009-08-20 13:45:07 +00002448 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2449 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
drh186ad8c2013-10-08 18:40:37 +00002450 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
dan02fa4692009-08-17 17:06:58 +00002451){
dan69188d92009-08-19 08:18:32 +00002452 int rc = SQLITE_OK;
drh186ad8c2013-10-08 18:40:37 +00002453 int nOut = pLoop->nOut;
drhbf539c42013-10-05 18:16:02 +00002454 LogEst nNew;
dan69188d92009-08-19 08:18:32 +00002455
drh1435a9a2013-08-27 23:15:44 +00002456#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh186ad8c2013-10-08 18:40:37 +00002457 Index *p = pLoop->u.btree.pIndex;
drh4f991892013-10-11 15:05:05 +00002458 int nEq = pLoop->u.btree.nEq;
dan02fa4692009-08-17 17:06:58 +00002459
drh74dade22013-09-04 18:14:53 +00002460 if( p->nSample>0
2461 && nEq==pBuilder->nRecValid
dan8ad169a2013-08-12 20:14:04 +00002462 && nEq<p->nSampleCol
dan7a419232013-08-06 20:01:43 +00002463 && OptimizationEnabled(pParse->db, SQLITE_Stat3)
2464 ){
2465 UnpackedRecord *pRec = pBuilder->pRec;
drhfaacf172011-08-12 01:51:45 +00002466 tRowcnt a[2];
dan575ab2f2013-09-02 07:16:40 +00002467 u8 aff;
drh98cdf622009-08-20 18:14:42 +00002468
danb3c02e22013-08-08 19:38:40 +00002469 /* Variable iLower will be set to the estimate of the number of rows in
2470 ** the index that are less than the lower bound of the range query. The
2471 ** lower bound being the concatenation of $P and $L, where $P is the
2472 ** key-prefix formed by the nEq values matched against the nEq left-most
2473 ** columns of the index, and $L is the value in pLower.
2474 **
2475 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
2476 ** is not a simple variable or literal value), the lower bound of the
2477 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
2478 ** if $L is available, whereKeyStats() is called for both ($P) and
2479 ** ($P:$L) and the larger of the two returned values used.
2480 **
2481 ** Similarly, iUpper is to be set to the estimate of the number of rows
2482 ** less than the upper bound of the range query. Where the upper bound
2483 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
2484 ** of iUpper are requested of whereKeyStats() and the smaller used.
2485 */
2486 tRowcnt iLower;
2487 tRowcnt iUpper;
2488
drhbbbdc832013-10-22 18:01:40 +00002489 if( nEq==p->nKeyCol ){
mistachkinc2cfb512013-09-04 04:04:08 +00002490 aff = SQLITE_AFF_INTEGER;
2491 }else{
2492 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
2493 }
danb3c02e22013-08-08 19:38:40 +00002494 /* Determine iLower and iUpper using ($P) only. */
2495 if( nEq==0 ){
2496 iLower = 0;
2497 iUpper = p->aiRowEst[0];
2498 }else{
2499 /* Note: this call could be optimized away - since the same values must
2500 ** have been requested when testing key $P in whereEqualScanEst(). */
2501 whereKeyStats(pParse, p, pRec, 0, a);
2502 iLower = a[0];
2503 iUpper = a[0] + a[1];
2504 }
2505
2506 /* If possible, improve on the iLower estimate using ($P:$L). */
dan02fa4692009-08-17 17:06:58 +00002507 if( pLower ){
dan7a419232013-08-06 20:01:43 +00002508 int bOk; /* True if value is extracted from pExpr */
dan02fa4692009-08-17 17:06:58 +00002509 Expr *pExpr = pLower->pExpr->pRight;
drh7a5bcc02013-01-16 17:08:58 +00002510 assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
dan87cd9322013-08-07 15:52:41 +00002511 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
danb3c02e22013-08-08 19:38:40 +00002512 if( rc==SQLITE_OK && bOk ){
2513 tRowcnt iNew;
2514 whereKeyStats(pParse, p, pRec, 0, a);
2515 iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
2516 if( iNew>iLower ) iLower = iNew;
drhabfa6d52013-09-11 03:53:22 +00002517 nOut--;
drhfaacf172011-08-12 01:51:45 +00002518 }
dan02fa4692009-08-17 17:06:58 +00002519 }
danb3c02e22013-08-08 19:38:40 +00002520
2521 /* If possible, improve on the iUpper estimate using ($P:$U). */
2522 if( pUpper ){
dan7a419232013-08-06 20:01:43 +00002523 int bOk; /* True if value is extracted from pExpr */
dan02fa4692009-08-17 17:06:58 +00002524 Expr *pExpr = pUpper->pExpr->pRight;
drh7a5bcc02013-01-16 17:08:58 +00002525 assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
dan87cd9322013-08-07 15:52:41 +00002526 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
danb3c02e22013-08-08 19:38:40 +00002527 if( rc==SQLITE_OK && bOk ){
2528 tRowcnt iNew;
2529 whereKeyStats(pParse, p, pRec, 1, a);
2530 iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
2531 if( iNew<iUpper ) iUpper = iNew;
drhabfa6d52013-09-11 03:53:22 +00002532 nOut--;
dan02fa4692009-08-17 17:06:58 +00002533 }
2534 }
danb3c02e22013-08-08 19:38:40 +00002535
dan87cd9322013-08-07 15:52:41 +00002536 pBuilder->pRec = pRec;
drhfaacf172011-08-12 01:51:45 +00002537 if( rc==SQLITE_OK ){
drhb8a8e8a2013-06-10 19:12:39 +00002538 if( iUpper>iLower ){
drhbf539c42013-10-05 18:16:02 +00002539 nNew = sqlite3LogEst(iUpper - iLower);
dan7a419232013-08-06 20:01:43 +00002540 }else{
drhbf539c42013-10-05 18:16:02 +00002541 nNew = 10; assert( 10==sqlite3LogEst(2) );
drhfaacf172011-08-12 01:51:45 +00002542 }
dan6cb8d762013-08-08 11:48:57 +00002543 if( nNew<nOut ){
2544 nOut = nNew;
2545 }
drh186ad8c2013-10-08 18:40:37 +00002546 pLoop->nOut = (LogEst)nOut;
dan6cb8d762013-08-08 11:48:57 +00002547 WHERETRACE(0x100, ("range scan regions: %u..%u est=%d\n",
2548 (u32)iLower, (u32)iUpper, nOut));
drhfaacf172011-08-12 01:51:45 +00002549 return SQLITE_OK;
drh98cdf622009-08-20 18:14:42 +00002550 }
dan02fa4692009-08-17 17:06:58 +00002551 }
drh3f022182009-09-09 16:10:50 +00002552#else
2553 UNUSED_PARAMETER(pParse);
dan7a419232013-08-06 20:01:43 +00002554 UNUSED_PARAMETER(pBuilder);
dan69188d92009-08-19 08:18:32 +00002555#endif
dan02fa4692009-08-17 17:06:58 +00002556 assert( pLower || pUpper );
drhe1e2e9a2013-06-13 15:16:53 +00002557 /* TUNING: Each inequality constraint reduces the search space 4-fold.
2558 ** A BETWEEN operator, therefore, reduces the search space 16-fold */
drhabfa6d52013-09-11 03:53:22 +00002559 nNew = nOut;
drhb8a8e8a2013-06-10 19:12:39 +00002560 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
drhbf539c42013-10-05 18:16:02 +00002561 nNew -= 20; assert( 20==sqlite3LogEst(4) );
drhabfa6d52013-09-11 03:53:22 +00002562 nOut--;
drhb8a8e8a2013-06-10 19:12:39 +00002563 }
2564 if( pUpper ){
drhbf539c42013-10-05 18:16:02 +00002565 nNew -= 20; assert( 20==sqlite3LogEst(4) );
drhabfa6d52013-09-11 03:53:22 +00002566 nOut--;
drhb8a8e8a2013-06-10 19:12:39 +00002567 }
drhabfa6d52013-09-11 03:53:22 +00002568 if( nNew<10 ) nNew = 10;
2569 if( nNew<nOut ) nOut = nNew;
drh186ad8c2013-10-08 18:40:37 +00002570 pLoop->nOut = (LogEst)nOut;
dan02fa4692009-08-17 17:06:58 +00002571 return rc;
2572}
2573
drh1435a9a2013-08-27 23:15:44 +00002574#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh82759752011-01-20 16:52:09 +00002575/*
2576** Estimate the number of rows that will be returned based on
2577** an equality constraint x=VALUE and where that VALUE occurs in
2578** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002579** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002580** for that index. When pExpr==NULL that means the constraint is
2581** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002582**
drh0c50fa02011-01-21 16:27:18 +00002583** Write the estimated row count into *pnRow and return SQLITE_OK.
2584** If unable to make an estimate, leave *pnRow unchanged and return
2585** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002586**
2587** This routine can fail if it is unable to load a collating sequence
2588** required for string comparison, or if unable to allocate memory
2589** for a UTF conversion required for comparison. The error is stored
2590** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002591*/
drh041e09f2011-04-07 19:56:21 +00002592static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002593 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002594 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002595 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drhb8a8e8a2013-06-10 19:12:39 +00002596 tRowcnt *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002597){
dan7a419232013-08-06 20:01:43 +00002598 Index *p = pBuilder->pNew->u.btree.pIndex;
2599 int nEq = pBuilder->pNew->u.btree.nEq;
2600 UnpackedRecord *pRec = pBuilder->pRec;
drh82759752011-01-20 16:52:09 +00002601 u8 aff; /* Column affinity */
2602 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002603 tRowcnt a[2]; /* Statistics */
dan7a419232013-08-06 20:01:43 +00002604 int bOk;
drh82759752011-01-20 16:52:09 +00002605
dan7a419232013-08-06 20:01:43 +00002606 assert( nEq>=1 );
drhbbbdc832013-10-22 18:01:40 +00002607 assert( nEq<=(p->nKeyCol+1) );
drh82759752011-01-20 16:52:09 +00002608 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002609 assert( p->nSample>0 );
dan7a419232013-08-06 20:01:43 +00002610 assert( pBuilder->nRecValid<nEq );
2611
2612 /* If values are not available for all fields of the index to the left
2613 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2614 if( pBuilder->nRecValid<(nEq-1) ){
2615 return SQLITE_NOTFOUND;
drh1f9c7662011-03-17 01:34:26 +00002616 }
dan7a419232013-08-06 20:01:43 +00002617
dandd6e1f12013-08-10 19:08:30 +00002618 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2619 ** below would return the same value. */
drhbbbdc832013-10-22 18:01:40 +00002620 if( nEq>p->nKeyCol ){
dan7a419232013-08-06 20:01:43 +00002621 *pnRow = 1;
2622 return SQLITE_OK;
drh82759752011-01-20 16:52:09 +00002623 }
dan7a419232013-08-06 20:01:43 +00002624
daneea568d2013-08-07 19:46:15 +00002625 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
dan87cd9322013-08-07 15:52:41 +00002626 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
2627 pBuilder->pRec = pRec;
dan7a419232013-08-06 20:01:43 +00002628 if( rc!=SQLITE_OK ) return rc;
2629 if( bOk==0 ) return SQLITE_NOTFOUND;
dan7a419232013-08-06 20:01:43 +00002630 pBuilder->nRecValid = nEq;
dan7a419232013-08-06 20:01:43 +00002631
danb3c02e22013-08-08 19:38:40 +00002632 whereKeyStats(pParse, p, pRec, 0, a);
2633 WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
2634 *pnRow = a[1];
daneea568d2013-08-07 19:46:15 +00002635
drh0c50fa02011-01-21 16:27:18 +00002636 return rc;
2637}
drh1435a9a2013-08-27 23:15:44 +00002638#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh0c50fa02011-01-21 16:27:18 +00002639
drh1435a9a2013-08-27 23:15:44 +00002640#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh0c50fa02011-01-21 16:27:18 +00002641/*
2642** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002643** an IN constraint where the right-hand side of the IN operator
2644** is a list of values. Example:
2645**
2646** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002647**
2648** Write the estimated row count into *pnRow and return SQLITE_OK.
2649** If unable to make an estimate, leave *pnRow unchanged and return
2650** non-zero.
2651**
2652** This routine can fail if it is unable to load a collating sequence
2653** required for string comparison, or if unable to allocate memory
2654** for a UTF conversion required for comparison. The error is stored
2655** in the pParse structure.
2656*/
drh041e09f2011-04-07 19:56:21 +00002657static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002658 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002659 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002660 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drhb8a8e8a2013-06-10 19:12:39 +00002661 tRowcnt *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002662){
dan7a419232013-08-06 20:01:43 +00002663 Index *p = pBuilder->pNew->u.btree.pIndex;
2664 int nRecValid = pBuilder->nRecValid;
drhb8a8e8a2013-06-10 19:12:39 +00002665 int rc = SQLITE_OK; /* Subfunction return code */
2666 tRowcnt nEst; /* Number of rows for a single term */
2667 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2668 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002669
2670 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002671 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2672 nEst = p->aiRowEst[0];
dan7a419232013-08-06 20:01:43 +00002673 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
drhfaacf172011-08-12 01:51:45 +00002674 nRowEst += nEst;
dan7a419232013-08-06 20:01:43 +00002675 pBuilder->nRecValid = nRecValid;
drh0c50fa02011-01-21 16:27:18 +00002676 }
dan7a419232013-08-06 20:01:43 +00002677
drh0c50fa02011-01-21 16:27:18 +00002678 if( rc==SQLITE_OK ){
drh0c50fa02011-01-21 16:27:18 +00002679 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
2680 *pnRow = nRowEst;
drh3b48e8c2013-06-12 20:18:16 +00002681 WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
drh0c50fa02011-01-21 16:27:18 +00002682 }
dan7a419232013-08-06 20:01:43 +00002683 assert( pBuilder->nRecValid==nRecValid );
drh0c50fa02011-01-21 16:27:18 +00002684 return rc;
drh82759752011-01-20 16:52:09 +00002685}
drh1435a9a2013-08-27 23:15:44 +00002686#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh82759752011-01-20 16:52:09 +00002687
drh46c35f92012-09-26 23:17:01 +00002688/*
drh2ffb1182004-07-19 19:14:01 +00002689** Disable a term in the WHERE clause. Except, do not disable the term
2690** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2691** or USING clause of that join.
2692**
2693** Consider the term t2.z='ok' in the following queries:
2694**
2695** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2696** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2697** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2698**
drh23bf66d2004-12-14 03:34:34 +00002699** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002700** in the ON clause. The term is disabled in (3) because it is not part
2701** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2702**
2703** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002704** of the join. Disabling is an optimization. When terms are satisfied
2705** by indices, we disable them to prevent redundant tests in the inner
2706** loop. We would get the correct results if nothing were ever disabled,
2707** but joins might run a little slower. The trick is to disable as much
2708** as we can without disabling too much. If we disabled in (1), we'd get
2709** the wrong answer. See ticket #813.
drh2ffb1182004-07-19 19:14:01 +00002710*/
drh0fcef5e2005-07-19 17:38:22 +00002711static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
2712 if( pTerm
drhbe837bd2010-04-30 21:03:24 +00002713 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002714 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
drh0259bc32013-09-09 19:37:46 +00002715 && (pLevel->notReady & pTerm->prereqAll)==0
drh0fcef5e2005-07-19 17:38:22 +00002716 ){
drh165be382008-12-05 02:36:33 +00002717 pTerm->wtFlags |= TERM_CODED;
drh45b1ee42005-08-02 17:48:22 +00002718 if( pTerm->iParent>=0 ){
2719 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
2720 if( (--pOther->nChild)==0 ){
drhed378002005-07-28 23:12:08 +00002721 disableTerm(pLevel, pOther);
2722 }
drh0fcef5e2005-07-19 17:38:22 +00002723 }
drh2ffb1182004-07-19 19:14:01 +00002724 }
2725}
2726
2727/*
dan69f8bb92009-08-13 19:21:16 +00002728** Code an OP_Affinity opcode to apply the column affinity string zAff
2729** to the n registers starting at base.
2730**
drh039fc322009-11-17 18:31:47 +00002731** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2732** beginning and end of zAff are ignored. If all entries in zAff are
2733** SQLITE_AFF_NONE, then no code gets generated.
2734**
2735** This routine makes its own copy of zAff so that the caller is free
2736** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002737*/
dan69f8bb92009-08-13 19:21:16 +00002738static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2739 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002740 if( zAff==0 ){
2741 assert( pParse->db->mallocFailed );
2742 return;
2743 }
dan69f8bb92009-08-13 19:21:16 +00002744 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002745
2746 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2747 ** and end of the affinity string.
2748 */
2749 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2750 n--;
2751 base++;
2752 zAff++;
2753 }
2754 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2755 n--;
2756 }
2757
2758 /* Code the OP_Affinity opcode if there is anything left to do. */
2759 if( n>0 ){
2760 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2761 sqlite3VdbeChangeP4(v, -1, zAff, n);
2762 sqlite3ExprCacheAffinityChange(pParse, base, n);
2763 }
drh94a11212004-09-25 13:12:14 +00002764}
2765
drhe8b97272005-07-19 22:22:12 +00002766
2767/*
drh51147ba2005-07-23 22:59:55 +00002768** Generate code for a single equality term of the WHERE clause. An equality
2769** term can be either X=expr or X IN (...). pTerm is the term to be
2770** coded.
2771**
drh1db639c2008-01-17 02:36:28 +00002772** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002773**
2774** For a constraint of the form X=expr, the expression is evaluated and its
2775** result is left on the stack. For constraints of the form X IN (...)
2776** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002777*/
drh678ccce2008-03-31 18:19:54 +00002778static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002779 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002780 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh0fe456b2013-03-12 18:34:50 +00002781 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
2782 int iEq, /* Index of the equality term within this level */
drh7ba39a92013-05-30 17:43:19 +00002783 int bRev, /* True for reverse-order IN operations */
drh678ccce2008-03-31 18:19:54 +00002784 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002785){
drh0fcef5e2005-07-19 17:38:22 +00002786 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002787 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002788 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002789
danielk19772d605492008-10-01 08:43:03 +00002790 assert( iTarget>0 );
drh50b39962006-10-28 00:28:09 +00002791 if( pX->op==TK_EQ ){
drh678ccce2008-03-31 18:19:54 +00002792 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002793 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002794 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002795 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002796#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002797 }else{
danielk19779a96b662007-11-29 17:05:18 +00002798 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002799 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002800 struct InLoop *pIn;
drh7ba39a92013-05-30 17:43:19 +00002801 WhereLoop *pLoop = pLevel->pWLoop;
danielk1977b3bce662005-01-29 08:32:43 +00002802
drh7ba39a92013-05-30 17:43:19 +00002803 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
2804 && pLoop->u.btree.pIndex!=0
2805 && pLoop->u.btree.pIndex->aSortOrder[iEq]
drhd3832162013-03-12 18:49:25 +00002806 ){
drh725e1ae2013-03-12 23:58:42 +00002807 testcase( iEq==0 );
drh725e1ae2013-03-12 23:58:42 +00002808 testcase( bRev );
drh1ccce442013-03-12 20:38:51 +00002809 bRev = !bRev;
drh0fe456b2013-03-12 18:34:50 +00002810 }
drh50b39962006-10-28 00:28:09 +00002811 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002812 iReg = iTarget;
danielk19770cdc0222008-06-26 18:04:03 +00002813 eType = sqlite3FindInIndex(pParse, pX, 0);
drh725e1ae2013-03-12 23:58:42 +00002814 if( eType==IN_INDEX_INDEX_DESC ){
2815 testcase( bRev );
2816 bRev = !bRev;
2817 }
danielk1977b3bce662005-01-29 08:32:43 +00002818 iTab = pX->iTable;
drh2d96b932013-02-08 18:48:23 +00002819 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
drh6fa978d2013-05-30 19:29:19 +00002820 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
2821 pLoop->wsFlags |= WHERE_IN_ABLE;
drh111a6a72008-12-21 03:51:16 +00002822 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002823 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00002824 }
drh111a6a72008-12-21 03:51:16 +00002825 pLevel->u.in.nIn++;
2826 pLevel->u.in.aInLoop =
2827 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2828 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2829 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00002830 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00002831 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00002832 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00002833 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00002834 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00002835 }else{
drhb3190c12008-12-08 21:37:14 +00002836 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00002837 }
drh2d96b932013-02-08 18:48:23 +00002838 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
drh1db639c2008-01-17 02:36:28 +00002839 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
drha6110402005-07-28 20:51:19 +00002840 }else{
drh111a6a72008-12-21 03:51:16 +00002841 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00002842 }
danielk1977b3bce662005-01-29 08:32:43 +00002843#endif
drh94a11212004-09-25 13:12:14 +00002844 }
drh0fcef5e2005-07-19 17:38:22 +00002845 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00002846 return iReg;
drh94a11212004-09-25 13:12:14 +00002847}
2848
drh51147ba2005-07-23 22:59:55 +00002849/*
2850** Generate code that will evaluate all == and IN constraints for an
drh039fc322009-11-17 18:31:47 +00002851** index.
drh51147ba2005-07-23 22:59:55 +00002852**
2853** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2854** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
2855** The index has as many as three equality constraints, but in this
2856** example, the third "c" value is an inequality. So only two
2857** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00002858** a==5 and b IN (1,2,3). The current values for a and b will be stored
2859** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00002860**
2861** In the example above nEq==2. But this subroutine works for any value
2862** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00002863** The only thing it does is allocate the pLevel->iMem memory cell and
2864** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00002865**
drh700a2262008-12-17 19:22:15 +00002866** This routine always allocates at least one memory cell and returns
2867** the index of that memory cell. The code that
2868** calls this routine will use that memory cell to store the termination
drh51147ba2005-07-23 22:59:55 +00002869** key value of the loop. If one or more IN operators appear, then
2870** this routine allocates an additional nEq memory cells for internal
2871** use.
dan69f8bb92009-08-13 19:21:16 +00002872**
2873** Before returning, *pzAff is set to point to a buffer containing a
2874** copy of the column affinity string of the index allocated using
2875** sqlite3DbMalloc(). Except, entries in the copy of the string associated
2876** with equality constraints that use NONE affinity are set to
2877** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
2878**
2879** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
2880** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
2881**
2882** In the example above, the index on t1(a) has TEXT affinity. But since
2883** the right hand side of the equality constraint (t2.b) has NONE affinity,
2884** no conversion should be attempted before using a t2.b value as part of
2885** a key to search the index. Hence the first byte in the returned affinity
2886** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00002887*/
drh1db639c2008-01-17 02:36:28 +00002888static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00002889 Parse *pParse, /* Parsing context */
2890 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
drh7ba39a92013-05-30 17:43:19 +00002891 int bRev, /* Reverse the order of IN operators */
dan69f8bb92009-08-13 19:21:16 +00002892 int nExtraReg, /* Number of extra registers to allocate */
2893 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00002894){
drh7ba39a92013-05-30 17:43:19 +00002895 int nEq; /* The number of == or IN constraints to code */
drh111a6a72008-12-21 03:51:16 +00002896 Vdbe *v = pParse->pVdbe; /* The vm under construction */
2897 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00002898 WhereTerm *pTerm; /* A single constraint term */
drh7ba39a92013-05-30 17:43:19 +00002899 WhereLoop *pLoop; /* The WhereLoop object */
drh51147ba2005-07-23 22:59:55 +00002900 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00002901 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00002902 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00002903 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00002904
drh111a6a72008-12-21 03:51:16 +00002905 /* This module is only called on query plans that use an index. */
drh7ba39a92013-05-30 17:43:19 +00002906 pLoop = pLevel->pWLoop;
2907 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
2908 nEq = pLoop->u.btree.nEq;
2909 pIdx = pLoop->u.btree.pIndex;
2910 assert( pIdx!=0 );
drh111a6a72008-12-21 03:51:16 +00002911
drh51147ba2005-07-23 22:59:55 +00002912 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00002913 */
drh700a2262008-12-17 19:22:15 +00002914 regBase = pParse->nMem + 1;
drh7ba39a92013-05-30 17:43:19 +00002915 nReg = pLoop->u.btree.nEq + nExtraReg;
drh6df2acd2008-12-28 16:55:25 +00002916 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00002917
dan69f8bb92009-08-13 19:21:16 +00002918 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
2919 if( !zAff ){
2920 pParse->db->mallocFailed = 1;
2921 }
2922
drh51147ba2005-07-23 22:59:55 +00002923 /* Evaluate the equality constraints
2924 */
mistachkinf6418892013-08-28 01:54:12 +00002925 assert( zAff==0 || (int)strlen(zAff)>=nEq );
drhc49de5d2007-01-19 01:06:01 +00002926 for(j=0; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00002927 int r1;
drh4efc9292013-06-06 23:02:03 +00002928 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00002929 assert( pTerm!=0 );
drhbe837bd2010-04-30 21:03:24 +00002930 /* The following true for indices with redundant columns.
2931 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
2932 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drh39759742013-08-02 23:40:45 +00002933 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00002934 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
drh678ccce2008-03-31 18:19:54 +00002935 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00002936 if( nReg==1 ){
2937 sqlite3ReleaseTempReg(pParse, regBase);
2938 regBase = r1;
2939 }else{
2940 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
2941 }
drh678ccce2008-03-31 18:19:54 +00002942 }
drh981642f2008-04-19 14:40:43 +00002943 testcase( pTerm->eOperator & WO_ISNULL );
2944 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00002945 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00002946 Expr *pRight = pTerm->pExpr->pRight;
drh2f2855b2009-11-18 01:25:26 +00002947 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
drh039fc322009-11-17 18:31:47 +00002948 if( zAff ){
2949 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
2950 zAff[j] = SQLITE_AFF_NONE;
2951 }
2952 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
2953 zAff[j] = SQLITE_AFF_NONE;
2954 }
dan69f8bb92009-08-13 19:21:16 +00002955 }
drh51147ba2005-07-23 22:59:55 +00002956 }
2957 }
dan69f8bb92009-08-13 19:21:16 +00002958 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00002959 return regBase;
drh51147ba2005-07-23 22:59:55 +00002960}
2961
dan2ce22452010-11-08 19:01:16 +00002962#ifndef SQLITE_OMIT_EXPLAIN
dan17c0bc02010-11-09 17:35:19 +00002963/*
drh69174c42010-11-12 15:35:59 +00002964** This routine is a helper for explainIndexRange() below
2965**
2966** pStr holds the text of an expression that we are building up one term
2967** at a time. This routine adds a new term to the end of the expression.
2968** Terms are separated by AND so add the "AND" text for second and subsequent
2969** terms only.
2970*/
2971static void explainAppendTerm(
2972 StrAccum *pStr, /* The text expression being built */
2973 int iTerm, /* Index of this term. First is zero */
2974 const char *zColumn, /* Name of the column */
2975 const char *zOp /* Name of the operator */
2976){
2977 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
2978 sqlite3StrAccumAppend(pStr, zColumn, -1);
2979 sqlite3StrAccumAppend(pStr, zOp, 1);
2980 sqlite3StrAccumAppend(pStr, "?", 1);
2981}
2982
2983/*
dan17c0bc02010-11-09 17:35:19 +00002984** Argument pLevel describes a strategy for scanning table pTab. This
2985** function returns a pointer to a string buffer containing a description
2986** of the subset of table rows scanned by the strategy in the form of an
2987** SQL expression. Or, if all rows are scanned, NULL is returned.
2988**
2989** For example, if the query:
2990**
2991** SELECT * FROM t1 WHERE a=1 AND b>2;
2992**
2993** is run and there is an index on (a, b), then this function returns a
2994** string similar to:
2995**
2996** "a=? AND b>?"
2997**
2998** The returned pointer points to memory obtained from sqlite3DbMalloc().
2999** It is the responsibility of the caller to free the buffer when it is
3000** no longer required.
3001*/
drhef866372013-05-22 20:49:02 +00003002static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
3003 Index *pIndex = pLoop->u.btree.pIndex;
3004 int nEq = pLoop->u.btree.nEq;
drh69174c42010-11-12 15:35:59 +00003005 int i, j;
3006 Column *aCol = pTab->aCol;
drhbbbdc832013-10-22 18:01:40 +00003007 i16 *aiColumn = pIndex->aiColumn;
drh69174c42010-11-12 15:35:59 +00003008 StrAccum txt;
dan2ce22452010-11-08 19:01:16 +00003009
drhef866372013-05-22 20:49:02 +00003010 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
drh69174c42010-11-12 15:35:59 +00003011 return 0;
3012 }
3013 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
drh03b6df12010-11-15 16:29:30 +00003014 txt.db = db;
drh69174c42010-11-12 15:35:59 +00003015 sqlite3StrAccumAppend(&txt, " (", 2);
dan2ce22452010-11-08 19:01:16 +00003016 for(i=0; i<nEq; i++){
drhbbbdc832013-10-22 18:01:40 +00003017 char *z = (i==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[i]].zName;
dane934e632013-08-20 17:14:57 +00003018 explainAppendTerm(&txt, i, z, "=");
dan2ce22452010-11-08 19:01:16 +00003019 }
3020
drh69174c42010-11-12 15:35:59 +00003021 j = i;
drhef866372013-05-22 20:49:02 +00003022 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
drhbbbdc832013-10-22 18:01:40 +00003023 char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
dan0c733f62011-11-16 15:27:09 +00003024 explainAppendTerm(&txt, i++, z, ">");
dan2ce22452010-11-08 19:01:16 +00003025 }
drhef866372013-05-22 20:49:02 +00003026 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
drhbbbdc832013-10-22 18:01:40 +00003027 char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
dan0c733f62011-11-16 15:27:09 +00003028 explainAppendTerm(&txt, i, z, "<");
dan2ce22452010-11-08 19:01:16 +00003029 }
drh69174c42010-11-12 15:35:59 +00003030 sqlite3StrAccumAppend(&txt, ")", 1);
3031 return sqlite3StrAccumFinish(&txt);
dan2ce22452010-11-08 19:01:16 +00003032}
3033
dan17c0bc02010-11-09 17:35:19 +00003034/*
3035** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
3036** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
3037** record is added to the output to describe the table scan strategy in
3038** pLevel.
3039*/
3040static void explainOneScan(
dan2ce22452010-11-08 19:01:16 +00003041 Parse *pParse, /* Parse context */
3042 SrcList *pTabList, /* Table list this loop refers to */
3043 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
3044 int iLevel, /* Value for "level" column of output */
dan4a07e3d2010-11-09 14:48:59 +00003045 int iFrom, /* Value for "from" column of output */
3046 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
dan2ce22452010-11-08 19:01:16 +00003047){
3048 if( pParse->explain==2 ){
dan2ce22452010-11-08 19:01:16 +00003049 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
dan17c0bc02010-11-09 17:35:19 +00003050 Vdbe *v = pParse->pVdbe; /* VM being constructed */
3051 sqlite3 *db = pParse->db; /* Database handle */
3052 char *zMsg; /* Text to add to EQP output */
dan4a07e3d2010-11-09 14:48:59 +00003053 int iId = pParse->iSelectId; /* Select id (left-most output column) */
dan4bc39fa2010-11-13 16:42:27 +00003054 int isSearch; /* True for a SEARCH. False for SCAN. */
drhef866372013-05-22 20:49:02 +00003055 WhereLoop *pLoop; /* The controlling WhereLoop object */
3056 u32 flags; /* Flags that describe this loop */
dan2ce22452010-11-08 19:01:16 +00003057
drhef866372013-05-22 20:49:02 +00003058 pLoop = pLevel->pWLoop;
3059 flags = pLoop->wsFlags;
dan4a07e3d2010-11-09 14:48:59 +00003060 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
dan2ce22452010-11-08 19:01:16 +00003061
drhef866372013-05-22 20:49:02 +00003062 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
3063 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
3064 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
dan4bc39fa2010-11-13 16:42:27 +00003065
3066 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
dan4a07e3d2010-11-09 14:48:59 +00003067 if( pItem->pSelect ){
dan4bc39fa2010-11-13 16:42:27 +00003068 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
dan4a07e3d2010-11-09 14:48:59 +00003069 }else{
dan4bc39fa2010-11-13 16:42:27 +00003070 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
dan4a07e3d2010-11-09 14:48:59 +00003071 }
3072
dan2ce22452010-11-08 19:01:16 +00003073 if( pItem->zAlias ){
3074 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
3075 }
drhef866372013-05-22 20:49:02 +00003076 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
drh7963b0e2013-06-17 21:37:40 +00003077 && ALWAYS(pLoop->u.btree.pIndex!=0)
drhef866372013-05-22 20:49:02 +00003078 ){
3079 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
drh986b3872013-06-28 21:12:20 +00003080 zMsg = sqlite3MAppendf(db, zMsg,
3081 ((flags & WHERE_AUTO_INDEX) ?
3082 "%s USING AUTOMATIC %sINDEX%.0s%s" :
3083 "%s USING %sINDEX %s%s"),
3084 zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
3085 pLoop->u.btree.pIndex->zName, zWhere);
dan2ce22452010-11-08 19:01:16 +00003086 sqlite3DbFree(db, zWhere);
drhef71c1f2013-06-04 12:58:02 +00003087 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
dan4bc39fa2010-11-13 16:42:27 +00003088 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
dan2ce22452010-11-08 19:01:16 +00003089
drh8e23daf2013-06-11 13:30:04 +00003090 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
dan2ce22452010-11-08 19:01:16 +00003091 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
drh04098e62010-11-15 21:50:19 +00003092 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
dan2ce22452010-11-08 19:01:16 +00003093 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
3094 }else if( flags&WHERE_BTM_LIMIT ){
3095 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
drh7963b0e2013-06-17 21:37:40 +00003096 }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
dan2ce22452010-11-08 19:01:16 +00003097 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
3098 }
3099 }
3100#ifndef SQLITE_OMIT_VIRTUALTABLE
3101 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
dan2ce22452010-11-08 19:01:16 +00003102 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
drhef866372013-05-22 20:49:02 +00003103 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
dan2ce22452010-11-08 19:01:16 +00003104 }
3105#endif
drhb8a8e8a2013-06-10 19:12:39 +00003106 zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
dan4a07e3d2010-11-09 14:48:59 +00003107 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
dan2ce22452010-11-08 19:01:16 +00003108 }
3109}
3110#else
dan17c0bc02010-11-09 17:35:19 +00003111# define explainOneScan(u,v,w,x,y,z)
dan2ce22452010-11-08 19:01:16 +00003112#endif /* SQLITE_OMIT_EXPLAIN */
3113
3114
drh111a6a72008-12-21 03:51:16 +00003115/*
3116** Generate code for the start of the iLevel-th loop in the WHERE clause
3117** implementation described by pWInfo.
3118*/
3119static Bitmask codeOneLoopStart(
3120 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
3121 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh7a484802012-03-16 00:28:11 +00003122 Bitmask notReady /* Which tables are currently available */
drh111a6a72008-12-21 03:51:16 +00003123){
3124 int j, k; /* Loop counters */
3125 int iCur; /* The VDBE cursor for the table */
3126 int addrNxt; /* Where to jump to continue with the next IN case */
3127 int omitTable; /* True if we use the index only */
3128 int bRev; /* True if we need to scan in reverse order */
3129 WhereLevel *pLevel; /* The where level to be coded */
drh7ba39a92013-05-30 17:43:19 +00003130 WhereLoop *pLoop; /* The WhereLoop object being coded */
drh111a6a72008-12-21 03:51:16 +00003131 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
3132 WhereTerm *pTerm; /* A WHERE clause term */
3133 Parse *pParse; /* Parsing context */
drh6b36e822013-07-30 15:10:32 +00003134 sqlite3 *db; /* Database connection */
drh111a6a72008-12-21 03:51:16 +00003135 Vdbe *v; /* The prepared stmt under constructions */
3136 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00003137 int addrBrk; /* Jump here to break out of the loop */
3138 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00003139 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
3140 int iReleaseReg = 0; /* Temp register to free before returning */
drh111a6a72008-12-21 03:51:16 +00003141
3142 pParse = pWInfo->pParse;
3143 v = pParse->pVdbe;
drh70d18342013-06-06 19:16:33 +00003144 pWC = &pWInfo->sWC;
drh6b36e822013-07-30 15:10:32 +00003145 db = pParse->db;
drh111a6a72008-12-21 03:51:16 +00003146 pLevel = &pWInfo->a[iLevel];
drh7ba39a92013-05-30 17:43:19 +00003147 pLoop = pLevel->pWLoop;
drh111a6a72008-12-21 03:51:16 +00003148 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
3149 iCur = pTabItem->iCursor;
drh0259bc32013-09-09 19:37:46 +00003150 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
drh7ba39a92013-05-30 17:43:19 +00003151 bRev = (pWInfo->revMask>>iLevel)&1;
3152 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drh70d18342013-06-06 19:16:33 +00003153 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
drh0c41d222013-04-22 02:39:10 +00003154 VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
drh111a6a72008-12-21 03:51:16 +00003155
3156 /* Create labels for the "break" and "continue" instructions
3157 ** for the current loop. Jump to addrBrk to break out of a loop.
3158 ** Jump to cont to go immediately to the next iteration of the
3159 ** loop.
3160 **
3161 ** When there is an IN operator, we also have a "addrNxt" label that
3162 ** means to continue with the next IN value combination. When
3163 ** there are no IN operators in the constraints, the "addrNxt" label
3164 ** is the same as "addrBrk".
3165 */
3166 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
3167 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
3168
3169 /* If this is the right table of a LEFT OUTER JOIN, allocate and
3170 ** initialize a memory cell that records if this table matches any
3171 ** row of the left table of the join.
3172 */
3173 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
3174 pLevel->iLeftJoin = ++pParse->nMem;
3175 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
3176 VdbeComment((v, "init LEFT JOIN no-match flag"));
3177 }
3178
drh21172c42012-10-30 00:29:07 +00003179 /* Special case of a FROM clause subquery implemented as a co-routine */
3180 if( pTabItem->viaCoroutine ){
3181 int regYield = pTabItem->regReturn;
3182 sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
3183 pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
3184 VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
3185 sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
3186 pLevel->op = OP_Goto;
3187 }else
3188
drh111a6a72008-12-21 03:51:16 +00003189#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00003190 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
3191 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
drh111a6a72008-12-21 03:51:16 +00003192 ** to access the data.
3193 */
3194 int iReg; /* P3 Value for OP_VFilter */
drh281bbe22012-10-16 23:17:14 +00003195 int addrNotFound;
drh4efc9292013-06-06 23:02:03 +00003196 int nConstraint = pLoop->nLTerm;
drh111a6a72008-12-21 03:51:16 +00003197
drha62bb8d2009-11-23 21:23:45 +00003198 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00003199 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh281bbe22012-10-16 23:17:14 +00003200 addrNotFound = pLevel->addrBrk;
drh111a6a72008-12-21 03:51:16 +00003201 for(j=0; j<nConstraint; j++){
drhe2250172013-05-31 18:13:50 +00003202 int iTarget = iReg+j+2;
drh4efc9292013-06-06 23:02:03 +00003203 pTerm = pLoop->aLTerm[j];
drh95ed68d2013-06-12 17:55:50 +00003204 if( pTerm==0 ) continue;
drh7ba39a92013-05-30 17:43:19 +00003205 if( pTerm->eOperator & WO_IN ){
3206 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
3207 addrNotFound = pLevel->addrNxt;
3208 }else{
3209 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
3210 }
3211 }
3212 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
drh7e47cb82013-05-31 17:55:27 +00003213 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
drh7ba39a92013-05-30 17:43:19 +00003214 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
3215 pLoop->u.vtab.idxStr,
3216 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
3217 pLoop->u.vtab.needFree = 0;
3218 for(j=0; j<nConstraint && j<16; j++){
3219 if( (pLoop->u.vtab.omitMask>>j)&1 ){
drh4efc9292013-06-06 23:02:03 +00003220 disableTerm(pLevel, pLoop->aLTerm[j]);
drh111a6a72008-12-21 03:51:16 +00003221 }
3222 }
3223 pLevel->op = OP_VNext;
3224 pLevel->p1 = iCur;
3225 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00003226 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drha62bb8d2009-11-23 21:23:45 +00003227 sqlite3ExprCachePop(pParse, 1);
drh111a6a72008-12-21 03:51:16 +00003228 }else
3229#endif /* SQLITE_OMIT_VIRTUALTABLE */
3230
drh7ba39a92013-05-30 17:43:19 +00003231 if( (pLoop->wsFlags & WHERE_IPK)!=0
3232 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
3233 ){
3234 /* Case 2: We can directly reference a single row using an
drh111a6a72008-12-21 03:51:16 +00003235 ** equality comparison against the ROWID field. Or
3236 ** we reference multiple rows using a "rowid IN (...)"
3237 ** construct.
3238 */
drh7ba39a92013-05-30 17:43:19 +00003239 assert( pLoop->u.btree.nEq==1 );
danielk19771d461462009-04-21 09:02:45 +00003240 iReleaseReg = sqlite3GetTempReg(pParse);
drh4efc9292013-06-06 23:02:03 +00003241 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003242 assert( pTerm!=0 );
3243 assert( pTerm->pExpr!=0 );
drh111a6a72008-12-21 03:51:16 +00003244 assert( omitTable==0 );
drh39759742013-08-02 23:40:45 +00003245 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00003246 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00003247 addrNxt = pLevel->addrNxt;
danielk19771d461462009-04-21 09:02:45 +00003248 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
3249 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drh459f63e2013-03-06 01:55:27 +00003250 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
drhceea3322009-04-23 13:22:42 +00003251 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00003252 VdbeComment((v, "pk"));
3253 pLevel->op = OP_Noop;
drh7ba39a92013-05-30 17:43:19 +00003254 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
3255 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
3256 ){
3257 /* Case 3: We have an inequality comparison against the ROWID field.
drh111a6a72008-12-21 03:51:16 +00003258 */
3259 int testOp = OP_Noop;
3260 int start;
3261 int memEndValue = 0;
3262 WhereTerm *pStart, *pEnd;
3263
3264 assert( omitTable==0 );
drh7ba39a92013-05-30 17:43:19 +00003265 j = 0;
3266 pStart = pEnd = 0;
drh4efc9292013-06-06 23:02:03 +00003267 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
3268 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
drh81186b42013-06-18 01:52:41 +00003269 assert( pStart!=0 || pEnd!=0 );
drh111a6a72008-12-21 03:51:16 +00003270 if( bRev ){
3271 pTerm = pStart;
3272 pStart = pEnd;
3273 pEnd = pTerm;
3274 }
3275 if( pStart ){
3276 Expr *pX; /* The expression that defines the start bound */
3277 int r1, rTemp; /* Registers for holding the start boundary */
3278
3279 /* The following constant maps TK_xx codes into corresponding
3280 ** seek opcodes. It depends on a particular ordering of TK_xx
3281 */
3282 const u8 aMoveOp[] = {
3283 /* TK_GT */ OP_SeekGt,
3284 /* TK_LE */ OP_SeekLe,
3285 /* TK_LT */ OP_SeekLt,
3286 /* TK_GE */ OP_SeekGe
3287 };
3288 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
3289 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
3290 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
3291
drhb5246e52013-07-08 21:12:57 +00003292 assert( (pStart->wtFlags & TERM_VNULL)==0 );
drh39759742013-08-02 23:40:45 +00003293 testcase( pStart->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003294 pX = pStart->pExpr;
3295 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003296 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
drh111a6a72008-12-21 03:51:16 +00003297 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
3298 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
3299 VdbeComment((v, "pk"));
3300 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
3301 sqlite3ReleaseTempReg(pParse, rTemp);
3302 disableTerm(pLevel, pStart);
3303 }else{
3304 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
3305 }
3306 if( pEnd ){
3307 Expr *pX;
3308 pX = pEnd->pExpr;
3309 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003310 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
3311 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
drh39759742013-08-02 23:40:45 +00003312 testcase( pEnd->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003313 memEndValue = ++pParse->nMem;
3314 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
3315 if( pX->op==TK_LT || pX->op==TK_GT ){
3316 testOp = bRev ? OP_Le : OP_Ge;
3317 }else{
3318 testOp = bRev ? OP_Lt : OP_Gt;
3319 }
3320 disableTerm(pLevel, pEnd);
3321 }
3322 start = sqlite3VdbeCurrentAddr(v);
3323 pLevel->op = bRev ? OP_Prev : OP_Next;
3324 pLevel->p1 = iCur;
3325 pLevel->p2 = start;
drh81186b42013-06-18 01:52:41 +00003326 assert( pLevel->p5==0 );
danielk19771d461462009-04-21 09:02:45 +00003327 if( testOp!=OP_Noop ){
3328 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3329 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003330 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003331 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
3332 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003333 }
drh1b0f0262013-05-30 22:27:09 +00003334 }else if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00003335 /* Case 4: A scan using an index.
drh111a6a72008-12-21 03:51:16 +00003336 **
3337 ** The WHERE clause may contain zero or more equality
3338 ** terms ("==" or "IN" operators) that refer to the N
3339 ** left-most columns of the index. It may also contain
3340 ** inequality constraints (>, <, >= or <=) on the indexed
3341 ** column that immediately follows the N equalities. Only
3342 ** the right-most column can be an inequality - the rest must
3343 ** use the "==" and "IN" operators. For example, if the
3344 ** index is on (x,y,z), then the following clauses are all
3345 ** optimized:
3346 **
3347 ** x=5
3348 ** x=5 AND y=10
3349 ** x=5 AND y<10
3350 ** x=5 AND y>5 AND y<10
3351 ** x=5 AND y=5 AND z<=10
3352 **
3353 ** The z<10 term of the following cannot be used, only
3354 ** the x=5 term:
3355 **
3356 ** x=5 AND z<10
3357 **
3358 ** N may be zero if there are inequality constraints.
3359 ** If there are no inequality constraints, then N is at
3360 ** least one.
3361 **
3362 ** This case is also used when there are no WHERE clause
3363 ** constraints but an index is selected anyway, in order
3364 ** to force the output order to conform to an ORDER BY.
3365 */
drh3bb9b932010-08-06 02:10:00 +00003366 static const u8 aStartOp[] = {
drh111a6a72008-12-21 03:51:16 +00003367 0,
3368 0,
3369 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
3370 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
3371 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
3372 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
3373 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
3374 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
3375 };
drh3bb9b932010-08-06 02:10:00 +00003376 static const u8 aEndOp[] = {
drh111a6a72008-12-21 03:51:16 +00003377 OP_Noop, /* 0: (!end_constraints) */
3378 OP_IdxGE, /* 1: (end_constraints && !bRev) */
3379 OP_IdxLT /* 2: (end_constraints && bRev) */
3380 };
drh7ba39a92013-05-30 17:43:19 +00003381 int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
3382 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
drh111a6a72008-12-21 03:51:16 +00003383 int regBase; /* Base register holding constraint values */
3384 int r1; /* Temp register */
3385 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
3386 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
3387 int startEq; /* True if range start uses ==, >= or <= */
3388 int endEq; /* True if range end uses ==, >= or <= */
3389 int start_constraints; /* Start of range is constrained */
3390 int nConstraint; /* Number of constraint terms */
drh3bb9b932010-08-06 02:10:00 +00003391 Index *pIdx; /* The index we will be using */
3392 int iIdxCur; /* The VDBE cursor for the index */
3393 int nExtraReg = 0; /* Number of extra registers needed */
3394 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00003395 char *zStartAff; /* Affinity for start of range constraint */
3396 char *zEndAff; /* Affinity for end of range constraint */
drh111a6a72008-12-21 03:51:16 +00003397
drh7ba39a92013-05-30 17:43:19 +00003398 pIdx = pLoop->u.btree.pIndex;
drh111a6a72008-12-21 03:51:16 +00003399 iIdxCur = pLevel->iIdxCur;
drh111a6a72008-12-21 03:51:16 +00003400
drh111a6a72008-12-21 03:51:16 +00003401 /* If this loop satisfies a sort order (pOrderBy) request that
3402 ** was passed to this function to implement a "SELECT min(x) ..."
3403 ** query, then the caller will only allow the loop to run for
3404 ** a single iteration. This means that the first row returned
3405 ** should not have a NULL value stored in 'x'. If column 'x' is
3406 ** the first one after the nEq equality constraints in the index,
3407 ** this requires some special handling.
3408 */
drh70d18342013-06-06 19:16:33 +00003409 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
drh4f402f22013-06-11 18:59:38 +00003410 && (pWInfo->bOBSat!=0)
drhbbbdc832013-10-22 18:01:40 +00003411 && (pIdx->nKeyCol>nEq)
drh111a6a72008-12-21 03:51:16 +00003412 ){
3413 /* assert( pOrderBy->nExpr==1 ); */
3414 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
3415 isMinQuery = 1;
drh6df2acd2008-12-28 16:55:25 +00003416 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003417 }
3418
3419 /* Find any inequality constraint terms for the start and end
3420 ** of the range.
3421 */
drh7ba39a92013-05-30 17:43:19 +00003422 j = nEq;
3423 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003424 pRangeStart = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003425 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003426 }
drh7ba39a92013-05-30 17:43:19 +00003427 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003428 pRangeEnd = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003429 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003430 }
3431
drh6df2acd2008-12-28 16:55:25 +00003432 /* Generate code to evaluate all constraint terms using == or IN
3433 ** and store the values of those terms in an array of registers
3434 ** starting at regBase.
3435 */
drh613ba1e2013-06-15 15:11:45 +00003436 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
drh6b36e822013-07-30 15:10:32 +00003437 zEndAff = sqlite3DbStrDup(db, zStartAff);
drh6df2acd2008-12-28 16:55:25 +00003438 addrNxt = pLevel->addrNxt;
3439
drh111a6a72008-12-21 03:51:16 +00003440 /* If we are doing a reverse order scan on an ascending index, or
3441 ** a forward order scan on a descending index, interchange the
3442 ** start and end terms (pRangeStart and pRangeEnd).
3443 */
drhbbbdc832013-10-22 18:01:40 +00003444 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3445 || (bRev && pIdx->nKeyCol==nEq)
dan0c733f62011-11-16 15:27:09 +00003446 ){
drh111a6a72008-12-21 03:51:16 +00003447 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
3448 }
3449
drh7963b0e2013-06-17 21:37:40 +00003450 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
3451 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
3452 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
3453 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
drh111a6a72008-12-21 03:51:16 +00003454 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3455 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3456 start_constraints = pRangeStart || nEq>0;
3457
3458 /* Seek the index cursor to the start of the range. */
3459 nConstraint = nEq;
3460 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003461 Expr *pRight = pRangeStart->pExpr->pRight;
3462 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003463 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
3464 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3465 }
dan6ac43392010-06-09 15:47:11 +00003466 if( zStartAff ){
3467 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003468 /* Since the comparison is to be performed with no conversions
3469 ** applied to the operands, set the affinity to apply to pRight to
3470 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003471 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003472 }
dan6ac43392010-06-09 15:47:11 +00003473 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3474 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003475 }
3476 }
drh111a6a72008-12-21 03:51:16 +00003477 nConstraint++;
drh39759742013-08-02 23:40:45 +00003478 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003479 }else if( isMinQuery ){
3480 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3481 nConstraint++;
3482 startEq = 0;
3483 start_constraints = 1;
3484 }
dan6ac43392010-06-09 15:47:11 +00003485 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003486 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3487 assert( op!=0 );
3488 testcase( op==OP_Rewind );
3489 testcase( op==OP_Last );
3490 testcase( op==OP_SeekGt );
3491 testcase( op==OP_SeekGe );
3492 testcase( op==OP_SeekLe );
3493 testcase( op==OP_SeekLt );
drh8cff69d2009-11-12 19:59:44 +00003494 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh111a6a72008-12-21 03:51:16 +00003495
3496 /* Load the value for the inequality constraint at the end of the
3497 ** range (if any).
3498 */
3499 nConstraint = nEq;
3500 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003501 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003502 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003503 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003504 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
3505 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3506 }
dan6ac43392010-06-09 15:47:11 +00003507 if( zEndAff ){
3508 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003509 /* Since the comparison is to be performed with no conversions
3510 ** applied to the operands, set the affinity to apply to pRight to
3511 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003512 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003513 }
dan6ac43392010-06-09 15:47:11 +00003514 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
3515 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003516 }
3517 }
dan6ac43392010-06-09 15:47:11 +00003518 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003519 nConstraint++;
drh39759742013-08-02 23:40:45 +00003520 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003521 }
drh6b36e822013-07-30 15:10:32 +00003522 sqlite3DbFree(db, zStartAff);
3523 sqlite3DbFree(db, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003524
3525 /* Top of the loop body */
3526 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3527
3528 /* Check if the index cursor is past the end of the range. */
3529 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
3530 testcase( op==OP_Noop );
3531 testcase( op==OP_IdxGE );
3532 testcase( op==OP_IdxLT );
drh6df2acd2008-12-28 16:55:25 +00003533 if( op!=OP_Noop ){
drh8cff69d2009-11-12 19:59:44 +00003534 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh6df2acd2008-12-28 16:55:25 +00003535 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
3536 }
drh111a6a72008-12-21 03:51:16 +00003537
3538 /* If there are inequality constraints, check that the value
3539 ** of the table column that the inequality contrains is not NULL.
3540 ** If it is, jump to the next iteration of the loop.
3541 */
3542 r1 = sqlite3GetTempReg(pParse);
drh37ca0482013-06-12 17:17:45 +00003543 testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
3544 testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
drh7ba39a92013-05-30 17:43:19 +00003545 if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
drh111a6a72008-12-21 03:51:16 +00003546 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
3547 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
3548 }
danielk19771d461462009-04-21 09:02:45 +00003549 sqlite3ReleaseTempReg(pParse, r1);
drh111a6a72008-12-21 03:51:16 +00003550
3551 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003552 disableTerm(pLevel, pRangeStart);
3553 disableTerm(pLevel, pRangeEnd);
drh85c1c552013-10-24 00:18:18 +00003554 if( omitTable ){
3555 /* pIdx is a covering index. No need to access the main table. */
3556 }else if( HasRowid(pIdx->pTable) ){
danielk19771d461462009-04-21 09:02:45 +00003557 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3558 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003559 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003560 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drh85c1c552013-10-24 00:18:18 +00003561 }else{
3562 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
3563 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
3564 for(j=0; j<pPk->nKeyCol; j++){
3565 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
3566 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
3567 }
3568 sqlite3VdbeAddOp4(v, OP_NotFound, iCur, addrCont, iRowidReg,
3569 SQLITE_INT_TO_PTR(pPk->nKeyCol), P4_INT32);
drh111a6a72008-12-21 03:51:16 +00003570 }
drh111a6a72008-12-21 03:51:16 +00003571
3572 /* Record the instruction used to terminate the loop. Disable
3573 ** WHERE clause terms made redundant by the index range scan.
3574 */
drh7699d1c2013-06-04 12:42:29 +00003575 if( pLoop->wsFlags & WHERE_ONEROW ){
drh95e037b2011-03-09 21:02:31 +00003576 pLevel->op = OP_Noop;
3577 }else if( bRev ){
3578 pLevel->op = OP_Prev;
3579 }else{
3580 pLevel->op = OP_Next;
3581 }
drh111a6a72008-12-21 03:51:16 +00003582 pLevel->p1 = iIdxCur;
drh53cfbe92013-06-13 17:28:22 +00003583 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
drh3f4d1d12012-09-15 18:45:54 +00003584 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3585 }else{
3586 assert( pLevel->p5==0 );
3587 }
drhdd5f5a62008-12-23 13:35:23 +00003588 }else
3589
drh23d04d52008-12-23 23:56:22 +00003590#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drh7ba39a92013-05-30 17:43:19 +00003591 if( pLoop->wsFlags & WHERE_MULTI_OR ){
3592 /* Case 5: Two or more separately indexed terms connected by OR
drh111a6a72008-12-21 03:51:16 +00003593 **
3594 ** Example:
3595 **
3596 ** CREATE TABLE t1(a,b,c,d);
3597 ** CREATE INDEX i1 ON t1(a);
3598 ** CREATE INDEX i2 ON t1(b);
3599 ** CREATE INDEX i3 ON t1(c);
3600 **
3601 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3602 **
3603 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003604 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003605 **
drh1b26c7c2009-04-22 02:15:47 +00003606 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003607 **
danielk19771d461462009-04-21 09:02:45 +00003608 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003609 ** RowSetTest are such that the rowid of the current row is inserted
3610 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003611 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003612 **
danielk19771d461462009-04-21 09:02:45 +00003613 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003614 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003615 ** Gosub 2 A
3616 ** sqlite3WhereEnd()
3617 **
3618 ** Following the above, code to terminate the loop. Label A, the target
3619 ** of the Gosub above, jumps to the instruction right after the Goto.
3620 **
drh1b26c7c2009-04-22 02:15:47 +00003621 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003622 ** Goto B # The loop is finished.
3623 **
3624 ** A: <loop body> # Return data, whatever.
3625 **
3626 ** Return 2 # Jump back to the Gosub
3627 **
3628 ** B: <after the loop>
3629 **
drh111a6a72008-12-21 03:51:16 +00003630 */
drh111a6a72008-12-21 03:51:16 +00003631 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
drhc01a3c12009-12-16 22:10:49 +00003632 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
dan0efb72c2012-08-24 18:44:56 +00003633 Index *pCov = 0; /* Potential covering index (or NULL) */
3634 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
danielk19771d461462009-04-21 09:02:45 +00003635
3636 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003637 int regRowset = 0; /* Register for RowSet object */
3638 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003639 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3640 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003641 int untestedTerms = 0; /* Some terms not completely tested */
drh8871ef52011-10-07 13:33:10 +00003642 int ii; /* Loop counter */
3643 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
drh111a6a72008-12-21 03:51:16 +00003644
drh4efc9292013-06-06 23:02:03 +00003645 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003646 assert( pTerm!=0 );
drh7a5bcc02013-01-16 17:08:58 +00003647 assert( pTerm->eOperator & WO_OR );
drh111a6a72008-12-21 03:51:16 +00003648 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3649 pOrWc = &pTerm->u.pOrInfo->wc;
drhc01a3c12009-12-16 22:10:49 +00003650 pLevel->op = OP_Return;
3651 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003652
danbfca6a42012-08-24 10:52:35 +00003653 /* Set up a new SrcList in pOrTab containing the table being scanned
drhc01a3c12009-12-16 22:10:49 +00003654 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3655 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3656 */
3657 if( pWInfo->nLevel>1 ){
3658 int nNotReady; /* The number of notReady tables */
3659 struct SrcList_item *origSrc; /* Original list of tables */
3660 nNotReady = pWInfo->nLevel - iLevel - 1;
drh6b36e822013-07-30 15:10:32 +00003661 pOrTab = sqlite3StackAllocRaw(db,
drhc01a3c12009-12-16 22:10:49 +00003662 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3663 if( pOrTab==0 ) return notReady;
drhad01d892013-06-19 13:59:49 +00003664 pOrTab->nAlloc = (u8)(nNotReady + 1);
shaneh46aae3c2009-12-31 19:06:23 +00003665 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003666 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3667 origSrc = pWInfo->pTabList->a;
3668 for(k=1; k<=nNotReady; k++){
3669 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3670 }
3671 }else{
3672 pOrTab = pWInfo->pTabList;
3673 }
danielk19771d461462009-04-21 09:02:45 +00003674
drh1b26c7c2009-04-22 02:15:47 +00003675 /* Initialize the rowset register to contain NULL. An SQL NULL is
3676 ** equivalent to an empty rowset.
danielk19771d461462009-04-21 09:02:45 +00003677 **
3678 ** Also initialize regReturn to contain the address of the instruction
3679 ** immediately following the OP_Return at the bottom of the loop. This
3680 ** is required in a few obscure LEFT JOIN cases where control jumps
3681 ** over the top of the loop into the body of it. In this case the
3682 ** correct response for the end-of-loop code (the OP_Return) is to
3683 ** fall through to the next instruction, just as an OP_Next does if
3684 ** called on an uninitialized cursor.
3685 */
drh70d18342013-06-06 19:16:33 +00003686 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003687 regRowset = ++pParse->nMem;
3688 regRowid = ++pParse->nMem;
3689 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3690 }
danielk19771d461462009-04-21 09:02:45 +00003691 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3692
drh8871ef52011-10-07 13:33:10 +00003693 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
3694 ** Then for every term xN, evaluate as the subexpression: xN AND z
3695 ** That way, terms in y that are factored into the disjunction will
3696 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
drh331b67c2012-03-09 22:02:08 +00003697 **
3698 ** Actually, each subexpression is converted to "xN AND w" where w is
3699 ** the "interesting" terms of z - terms that did not originate in the
3700 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3701 ** indices.
drhb3129fa2013-05-09 14:20:11 +00003702 **
3703 ** This optimization also only applies if the (x1 OR x2 OR ...) term
3704 ** is not contained in the ON clause of a LEFT JOIN.
3705 ** See ticket http://www.sqlite.org/src/info/f2369304e4
drh8871ef52011-10-07 13:33:10 +00003706 */
3707 if( pWC->nTerm>1 ){
drh7a484802012-03-16 00:28:11 +00003708 int iTerm;
3709 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3710 Expr *pExpr = pWC->a[iTerm].pExpr;
drhaa32e3c2013-07-16 21:31:23 +00003711 if( &pWC->a[iTerm] == pTerm ) continue;
drh331b67c2012-03-09 22:02:08 +00003712 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drhaa32e3c2013-07-16 21:31:23 +00003713 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue;
drh7a484802012-03-16 00:28:11 +00003714 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
drh6b36e822013-07-30 15:10:32 +00003715 pExpr = sqlite3ExprDup(db, pExpr, 0);
3716 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
drh331b67c2012-03-09 22:02:08 +00003717 }
3718 if( pAndExpr ){
3719 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3720 }
drh8871ef52011-10-07 13:33:10 +00003721 }
3722
danielk19771d461462009-04-21 09:02:45 +00003723 for(ii=0; ii<pOrWc->nTerm; ii++){
3724 WhereTerm *pOrTerm = &pOrWc->a[ii];
drh7a5bcc02013-01-16 17:08:58 +00003725 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
danielk19771d461462009-04-21 09:02:45 +00003726 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
drh8871ef52011-10-07 13:33:10 +00003727 Expr *pOrExpr = pOrTerm->pExpr;
drhb3129fa2013-05-09 14:20:11 +00003728 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
drh8871ef52011-10-07 13:33:10 +00003729 pAndExpr->pLeft = pOrExpr;
3730 pOrExpr = pAndExpr;
3731 }
danielk19771d461462009-04-21 09:02:45 +00003732 /* Loop through table entries that match term pOrTerm. */
drh8871ef52011-10-07 13:33:10 +00003733 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
drh9ef61f42011-10-07 14:40:59 +00003734 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
dan0efb72c2012-08-24 18:44:56 +00003735 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
drh6b36e822013-07-30 15:10:32 +00003736 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
danielk19771d461462009-04-21 09:02:45 +00003737 if( pSubWInfo ){
drh7ba39a92013-05-30 17:43:19 +00003738 WhereLoop *pSubLoop;
dan17c0bc02010-11-09 17:35:19 +00003739 explainOneScan(
dan4a07e3d2010-11-09 14:48:59 +00003740 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
dan2ce22452010-11-08 19:01:16 +00003741 );
drh70d18342013-06-06 19:16:33 +00003742 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003743 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3744 int r;
3745 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
drha748fdc2012-03-28 01:34:47 +00003746 regRowid, 0);
drh8cff69d2009-11-12 19:59:44 +00003747 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
3748 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
drh336a5302009-04-24 15:46:21 +00003749 }
danielk19771d461462009-04-21 09:02:45 +00003750 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
3751
drhc01a3c12009-12-16 22:10:49 +00003752 /* The pSubWInfo->untestedTerms flag means that this OR term
3753 ** contained one or more AND term from a notReady table. The
3754 ** terms from the notReady table could not be tested and will
3755 ** need to be tested later.
3756 */
3757 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3758
danbfca6a42012-08-24 10:52:35 +00003759 /* If all of the OR-connected terms are optimized using the same
3760 ** index, and the index is opened using the same cursor number
3761 ** by each call to sqlite3WhereBegin() made by this loop, it may
3762 ** be possible to use that index as a covering index.
3763 **
3764 ** If the call to sqlite3WhereBegin() above resulted in a scan that
3765 ** uses an index, and this is either the first OR-connected term
3766 ** processed or the index is the same as that used by all previous
dan0efb72c2012-08-24 18:44:56 +00003767 ** terms, set pCov to the candidate covering index. Otherwise, set
3768 ** pCov to NULL to indicate that no candidate covering index will
3769 ** be available.
danbfca6a42012-08-24 10:52:35 +00003770 */
drh7ba39a92013-05-30 17:43:19 +00003771 pSubLoop = pSubWInfo->a[0].pWLoop;
drh986b3872013-06-28 21:12:20 +00003772 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drh7ba39a92013-05-30 17:43:19 +00003773 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
drh7ba39a92013-05-30 17:43:19 +00003774 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
danbfca6a42012-08-24 10:52:35 +00003775 ){
drh7ba39a92013-05-30 17:43:19 +00003776 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
drh907717f2013-06-04 18:03:22 +00003777 pCov = pSubLoop->u.btree.pIndex;
danbfca6a42012-08-24 10:52:35 +00003778 }else{
3779 pCov = 0;
3780 }
3781
danielk19771d461462009-04-21 09:02:45 +00003782 /* Finish the loop through table entries that match term pOrTerm. */
3783 sqlite3WhereEnd(pSubWInfo);
3784 }
drhdd5f5a62008-12-23 13:35:23 +00003785 }
3786 }
drhd40e2082012-08-24 23:24:15 +00003787 pLevel->u.pCovidx = pCov;
drh90abfd02012-10-09 21:07:23 +00003788 if( pCov ) pLevel->iIdxCur = iCovCur;
drh331b67c2012-03-09 22:02:08 +00003789 if( pAndExpr ){
3790 pAndExpr->pLeft = 0;
drh6b36e822013-07-30 15:10:32 +00003791 sqlite3ExprDelete(db, pAndExpr);
drh331b67c2012-03-09 22:02:08 +00003792 }
danielk19771d461462009-04-21 09:02:45 +00003793 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00003794 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
3795 sqlite3VdbeResolveLabel(v, iLoopBody);
3796
drh6b36e822013-07-30 15:10:32 +00003797 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
drhc01a3c12009-12-16 22:10:49 +00003798 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00003799 }else
drh23d04d52008-12-23 23:56:22 +00003800#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00003801
3802 {
drh7ba39a92013-05-30 17:43:19 +00003803 /* Case 6: There is no usable index. We must do a complete
drh111a6a72008-12-21 03:51:16 +00003804 ** scan of the entire table.
3805 */
drh699b3d42009-02-23 16:52:07 +00003806 static const u8 aStep[] = { OP_Next, OP_Prev };
3807 static const u8 aStart[] = { OP_Rewind, OP_Last };
3808 assert( bRev==0 || bRev==1 );
drh699b3d42009-02-23 16:52:07 +00003809 pLevel->op = aStep[bRev];
drh111a6a72008-12-21 03:51:16 +00003810 pLevel->p1 = iCur;
drh699b3d42009-02-23 16:52:07 +00003811 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh111a6a72008-12-21 03:51:16 +00003812 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3813 }
drh111a6a72008-12-21 03:51:16 +00003814
3815 /* Insert code to test every subexpression that can be completely
3816 ** computed using the current set of tables.
3817 */
drh111a6a72008-12-21 03:51:16 +00003818 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3819 Expr *pE;
drh39759742013-08-02 23:40:45 +00003820 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003821 testcase( pTerm->wtFlags & TERM_CODED );
3822 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003823 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhc01a3c12009-12-16 22:10:49 +00003824 testcase( pWInfo->untestedTerms==0
3825 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
3826 pWInfo->untestedTerms = 1;
3827 continue;
3828 }
drh111a6a72008-12-21 03:51:16 +00003829 pE = pTerm->pExpr;
3830 assert( pE!=0 );
3831 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
3832 continue;
3833 }
drh111a6a72008-12-21 03:51:16 +00003834 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003835 pTerm->wtFlags |= TERM_CODED;
3836 }
3837
drh0c41d222013-04-22 02:39:10 +00003838 /* Insert code to test for implied constraints based on transitivity
3839 ** of the "==" operator.
3840 **
3841 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
3842 ** and we are coding the t1 loop and the t2 loop has not yet coded,
3843 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
3844 ** the implied "t1.a=123" constraint.
3845 */
3846 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
drh6b36e822013-07-30 15:10:32 +00003847 Expr *pE, *pEAlt;
drh0c41d222013-04-22 02:39:10 +00003848 WhereTerm *pAlt;
drh0c41d222013-04-22 02:39:10 +00003849 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3850 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
3851 if( pTerm->leftCursor!=iCur ) continue;
drhcdc2e432013-07-01 17:27:19 +00003852 if( pLevel->iLeftJoin ) continue;
drh0c41d222013-04-22 02:39:10 +00003853 pE = pTerm->pExpr;
3854 assert( !ExprHasProperty(pE, EP_FromJoin) );
drh0259bc32013-09-09 19:37:46 +00003855 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
drh0c41d222013-04-22 02:39:10 +00003856 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
3857 if( pAlt==0 ) continue;
drh5c10f3b2013-05-01 17:22:38 +00003858 if( pAlt->wtFlags & (TERM_CODED) ) continue;
drh7963b0e2013-06-17 21:37:40 +00003859 testcase( pAlt->eOperator & WO_EQ );
3860 testcase( pAlt->eOperator & WO_IN );
drh0c41d222013-04-22 02:39:10 +00003861 VdbeNoopComment((v, "begin transitive constraint"));
drh6b36e822013-07-30 15:10:32 +00003862 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
3863 if( pEAlt ){
3864 *pEAlt = *pAlt->pExpr;
3865 pEAlt->pLeft = pE->pLeft;
3866 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
3867 sqlite3StackFree(db, pEAlt);
3868 }
drh0c41d222013-04-22 02:39:10 +00003869 }
3870
drh111a6a72008-12-21 03:51:16 +00003871 /* For a LEFT OUTER JOIN, generate code that will record the fact that
3872 ** at least one row of the right table has matched the left table.
3873 */
3874 if( pLevel->iLeftJoin ){
3875 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
3876 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
3877 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00003878 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00003879 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drh39759742013-08-02 23:40:45 +00003880 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003881 testcase( pTerm->wtFlags & TERM_CODED );
3882 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003883 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00003884 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00003885 continue;
3886 }
drh111a6a72008-12-21 03:51:16 +00003887 assert( pTerm->pExpr );
3888 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3889 pTerm->wtFlags |= TERM_CODED;
3890 }
3891 }
danielk19771d461462009-04-21 09:02:45 +00003892 sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh23d04d52008-12-23 23:56:22 +00003893
drh0259bc32013-09-09 19:37:46 +00003894 return pLevel->notReady;
drh111a6a72008-12-21 03:51:16 +00003895}
3896
drhd15cb172013-05-21 19:23:10 +00003897#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00003898/*
3899** Print a WhereLoop object for debugging purposes
3900*/
3901static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
drhb8a8e8a2013-06-10 19:12:39 +00003902 int nb = 1+(pTabList->nSrc+7)/8;
drha18f3d22013-05-08 03:05:41 +00003903 struct SrcList_item *pItem = pTabList->a + p->iTab;
3904 Table *pTab = pItem->pTab;
drh6457a352013-06-21 00:35:37 +00003905 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00003906 p->iTab, nb, p->maskSelf, nb, p->prereq);
drh6457a352013-06-21 00:35:37 +00003907 sqlite3DebugPrintf(" %12s",
drha18f3d22013-05-08 03:05:41 +00003908 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00003909 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
3910 if( p->u.btree.pIndex ){
drh319f6772013-05-14 15:31:07 +00003911 const char *zName = p->u.btree.pIndex->zName;
drhae70cf12013-05-31 15:18:46 +00003912 if( zName==0 ) zName = "ipk";
drh319f6772013-05-14 15:31:07 +00003913 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
3914 int i = sqlite3Strlen30(zName) - 1;
3915 while( zName[i]!='_' ) i--;
3916 zName += i;
3917 }
drh6457a352013-06-21 00:35:37 +00003918 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00003919 }else{
drh6457a352013-06-21 00:35:37 +00003920 sqlite3DebugPrintf("%20s","");
drh5346e952013-05-08 14:14:26 +00003921 }
drha18f3d22013-05-08 03:05:41 +00003922 }else{
drh5346e952013-05-08 14:14:26 +00003923 char *z;
3924 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00003925 z = sqlite3_mprintf("(%d,\"%s\",%x)",
3926 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003927 }else{
drh3bd26f02013-05-24 14:52:03 +00003928 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003929 }
drh6457a352013-06-21 00:35:37 +00003930 sqlite3DebugPrintf(" %-19s", z);
drh5346e952013-05-08 14:14:26 +00003931 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00003932 }
drh6457a352013-06-21 00:35:37 +00003933 sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
drhb8a8e8a2013-06-10 19:12:39 +00003934 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
drha18f3d22013-05-08 03:05:41 +00003935}
3936#endif
3937
drhf1b5f5b2013-05-02 00:15:01 +00003938/*
drh4efc9292013-06-06 23:02:03 +00003939** Convert bulk memory into a valid WhereLoop that can be passed
3940** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00003941*/
drh4efc9292013-06-06 23:02:03 +00003942static void whereLoopInit(WhereLoop *p){
3943 p->aLTerm = p->aLTermSpace;
3944 p->nLTerm = 0;
3945 p->nLSlot = ArraySize(p->aLTermSpace);
3946 p->wsFlags = 0;
3947}
3948
3949/*
3950** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
3951*/
3952static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh986b3872013-06-28 21:12:20 +00003953 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
drh13e11b42013-06-06 23:44:25 +00003954 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
3955 sqlite3_free(p->u.vtab.idxStr);
3956 p->u.vtab.needFree = 0;
3957 p->u.vtab.idxStr = 0;
drh986b3872013-06-28 21:12:20 +00003958 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
drh13e11b42013-06-06 23:44:25 +00003959 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
3960 sqlite3DbFree(db, p->u.btree.pIndex);
3961 p->u.btree.pIndex = 0;
3962 }
drh5346e952013-05-08 14:14:26 +00003963 }
3964}
3965
drh4efc9292013-06-06 23:02:03 +00003966/*
3967** Deallocate internal memory used by a WhereLoop object
3968*/
3969static void whereLoopClear(sqlite3 *db, WhereLoop *p){
3970 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3971 whereLoopClearUnion(db, p);
3972 whereLoopInit(p);
3973}
3974
3975/*
3976** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
3977*/
3978static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
3979 WhereTerm **paNew;
3980 if( p->nLSlot>=n ) return SQLITE_OK;
3981 n = (n+7)&~7;
3982 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
3983 if( paNew==0 ) return SQLITE_NOMEM;
3984 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
3985 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3986 p->aLTerm = paNew;
3987 p->nLSlot = n;
3988 return SQLITE_OK;
3989}
3990
3991/*
3992** Transfer content from the second pLoop into the first.
3993*/
3994static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
drh4efc9292013-06-06 23:02:03 +00003995 whereLoopClearUnion(db, pTo);
drh0d31dc32013-09-06 00:40:59 +00003996 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
3997 memset(&pTo->u, 0, sizeof(pTo->u));
3998 return SQLITE_NOMEM;
3999 }
drha2014152013-06-07 00:29:23 +00004000 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
4001 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00004002 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
4003 pFrom->u.vtab.needFree = 0;
drh986b3872013-06-28 21:12:20 +00004004 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00004005 pFrom->u.btree.pIndex = 0;
4006 }
4007 return SQLITE_OK;
4008}
4009
drh5346e952013-05-08 14:14:26 +00004010/*
drhf1b5f5b2013-05-02 00:15:01 +00004011** Delete a WhereLoop object
4012*/
4013static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00004014 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00004015 sqlite3DbFree(db, p);
4016}
drh84bfda42005-07-15 13:05:21 +00004017
drh9eff6162006-06-12 21:59:13 +00004018/*
4019** Free a WhereInfo structure
4020*/
drh10fe8402008-10-11 16:47:35 +00004021static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00004022 if( ALWAYS(pWInfo) ){
drh70d18342013-06-06 19:16:33 +00004023 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00004024 while( pWInfo->pLoops ){
4025 WhereLoop *p = pWInfo->pLoops;
4026 pWInfo->pLoops = p->pNextLoop;
4027 whereLoopDelete(db, p);
4028 }
drh633e6d52008-07-28 19:34:53 +00004029 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00004030 }
4031}
4032
drhf1b5f5b2013-05-02 00:15:01 +00004033/*
4034** Insert or replace a WhereLoop entry using the template supplied.
4035**
4036** An existing WhereLoop entry might be overwritten if the new template
4037** is better and has fewer dependencies. Or the template will be ignored
4038** and no insert will occur if an existing WhereLoop is faster and has
4039** fewer dependencies than the template. Otherwise a new WhereLoop is
drhd044d202013-05-31 12:43:55 +00004040** added based on the template.
drh23f98da2013-05-21 15:52:07 +00004041**
drhaa32e3c2013-07-16 21:31:23 +00004042** If pBuilder->pOrSet is not NULL then we only care about only the
4043** prerequisites and rRun and nOut costs of the N best loops. That
4044** information is gathered in the pBuilder->pOrSet object. This special
4045** processing mode is used only for OR clause processing.
drh23f98da2013-05-21 15:52:07 +00004046**
drhaa32e3c2013-07-16 21:31:23 +00004047** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
drh23f98da2013-05-21 15:52:07 +00004048** still might overwrite similar loops with the new template if the
4049** template is better. Loops may be overwritten if the following
4050** conditions are met:
4051**
4052** (1) They have the same iTab.
4053** (2) They have the same iSortIdx.
4054** (3) The template has same or fewer dependencies than the current loop
4055** (4) The template has the same or lower cost than the current loop
drhd044d202013-05-31 12:43:55 +00004056** (5) The template uses more terms of the same index but has no additional
4057** dependencies
drhf1b5f5b2013-05-02 00:15:01 +00004058*/
drhcf8fa7a2013-05-10 20:26:22 +00004059static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh4efc9292013-06-06 23:02:03 +00004060 WhereLoop **ppPrev, *p, *pNext = 0;
drhcf8fa7a2013-05-10 20:26:22 +00004061 WhereInfo *pWInfo = pBuilder->pWInfo;
drh70d18342013-06-06 19:16:33 +00004062 sqlite3 *db = pWInfo->pParse->db;
drhcf8fa7a2013-05-10 20:26:22 +00004063
drhaa32e3c2013-07-16 21:31:23 +00004064 /* If pBuilder->pOrSet is defined, then only keep track of the costs
4065 ** and prereqs.
drh23f98da2013-05-21 15:52:07 +00004066 */
drhaa32e3c2013-07-16 21:31:23 +00004067 if( pBuilder->pOrSet!=0 ){
4068#if WHERETRACE_ENABLED
4069 u16 n = pBuilder->pOrSet->n;
4070 int x =
4071#endif
4072 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
4073 pTemplate->nOut);
drhae70cf12013-05-31 15:18:46 +00004074#if WHERETRACE_ENABLED
4075 if( sqlite3WhereTrace & 0x8 ){
drhaa32e3c2013-07-16 21:31:23 +00004076 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
drh70d18342013-06-06 19:16:33 +00004077 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004078 }
4079#endif
drhcf8fa7a2013-05-10 20:26:22 +00004080 return SQLITE_OK;
4081 }
drhf1b5f5b2013-05-02 00:15:01 +00004082
4083 /* Search for an existing WhereLoop to overwrite, or which takes
4084 ** priority over pTemplate.
4085 */
4086 for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
drhdbb80232013-06-19 12:34:13 +00004087 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
4088 /* If either the iTab or iSortIdx values for two WhereLoop are different
4089 ** then those WhereLoops need to be considered separately. Neither is
4090 ** a candidate to replace the other. */
4091 continue;
4092 }
4093 /* In the current implementation, the rSetup value is either zero
4094 ** or the cost of building an automatic index (NlogN) and the NlogN
4095 ** is the same for compatible WhereLoops. */
4096 assert( p->rSetup==0 || pTemplate->rSetup==0
4097 || p->rSetup==pTemplate->rSetup );
4098
4099 /* whereLoopAddBtree() always generates and inserts the automatic index
4100 ** case first. Hence compatible candidate WhereLoops never have a larger
4101 ** rSetup. Call this SETUP-INVARIANT */
4102 assert( p->rSetup>=pTemplate->rSetup );
4103
drhf1b5f5b2013-05-02 00:15:01 +00004104 if( (p->prereq & pTemplate->prereq)==p->prereq
drhf1b5f5b2013-05-02 00:15:01 +00004105 && p->rSetup<=pTemplate->rSetup
4106 && p->rRun<=pTemplate->rRun
drhf46af732013-08-30 17:35:44 +00004107 && p->nOut<=pTemplate->nOut
drhf1b5f5b2013-05-02 00:15:01 +00004108 ){
drh4a5acf82013-06-18 20:06:23 +00004109 /* This branch taken when p is equal or better than pTemplate in
drhe56dd3a2013-08-30 17:50:35 +00004110 ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
drhf46af732013-08-30 17:35:44 +00004111 ** (4) number of output rows. */
drhdbb80232013-06-19 12:34:13 +00004112 assert( p->rSetup==pTemplate->rSetup );
drh05db3c72013-09-02 20:22:18 +00004113 if( p->prereq==pTemplate->prereq
4114 && p->nLTerm<pTemplate->nLTerm
drhadd5ce32013-09-07 00:29:06 +00004115 && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
4116 && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
drhabfa6d52013-09-11 03:53:22 +00004117 || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
drhcd0f4072013-06-05 12:47:59 +00004118 ){
4119 /* Overwrite an existing WhereLoop with an similar one that uses
4120 ** more terms of the index */
4121 pNext = p->pNextLoop;
drhcd0f4072013-06-05 12:47:59 +00004122 break;
4123 }else{
4124 /* pTemplate is not helpful.
4125 ** Return without changing or adding anything */
4126 goto whereLoopInsert_noop;
4127 }
drhf1b5f5b2013-05-02 00:15:01 +00004128 }
4129 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
drhf1b5f5b2013-05-02 00:15:01 +00004130 && p->rRun>=pTemplate->rRun
drhf46af732013-08-30 17:35:44 +00004131 && p->nOut>=pTemplate->nOut
drhf1b5f5b2013-05-02 00:15:01 +00004132 ){
drh4a5acf82013-06-18 20:06:23 +00004133 /* Overwrite an existing WhereLoop with a better one: one that is
drhe56dd3a2013-08-30 17:50:35 +00004134 ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
drhf46af732013-08-30 17:35:44 +00004135 ** or (4) number of output rows, and is no worse in any of those
4136 ** categories. */
drhadd5ce32013-09-07 00:29:06 +00004137 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
drh43fe25f2013-05-07 23:06:23 +00004138 pNext = p->pNextLoop;
drhf1b5f5b2013-05-02 00:15:01 +00004139 break;
4140 }
4141 }
4142
4143 /* If we reach this point it means that either p[] should be overwritten
4144 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
4145 ** WhereLoop and insert it.
4146 */
drhae70cf12013-05-31 15:18:46 +00004147#if WHERETRACE_ENABLED
4148 if( sqlite3WhereTrace & 0x8 ){
4149 if( p!=0 ){
4150 sqlite3DebugPrintf("ins-del: ");
drh70d18342013-06-06 19:16:33 +00004151 whereLoopPrint(p, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004152 }
4153 sqlite3DebugPrintf("ins-new: ");
drh70d18342013-06-06 19:16:33 +00004154 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004155 }
4156#endif
drhf1b5f5b2013-05-02 00:15:01 +00004157 if( p==0 ){
drh4efc9292013-06-06 23:02:03 +00004158 p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00004159 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00004160 whereLoopInit(p);
drhf1b5f5b2013-05-02 00:15:01 +00004161 }
drh4efc9292013-06-06 23:02:03 +00004162 whereLoopXfer(db, p, pTemplate);
drh43fe25f2013-05-07 23:06:23 +00004163 p->pNextLoop = pNext;
4164 *ppPrev = p;
drh5346e952013-05-08 14:14:26 +00004165 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00004166 Index *pIndex = p->u.btree.pIndex;
4167 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004168 p->u.btree.pIndex = 0;
4169 }
drh5346e952013-05-08 14:14:26 +00004170 }
drhf1b5f5b2013-05-02 00:15:01 +00004171 return SQLITE_OK;
drhae70cf12013-05-31 15:18:46 +00004172
4173 /* Jump here if the insert is a no-op */
4174whereLoopInsert_noop:
4175#if WHERETRACE_ENABLED
4176 if( sqlite3WhereTrace & 0x8 ){
drhaa32e3c2013-07-16 21:31:23 +00004177 sqlite3DebugPrintf("ins-noop: ");
drh70d18342013-06-06 19:16:33 +00004178 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004179 }
4180#endif
4181 return SQLITE_OK;
drhf1b5f5b2013-05-02 00:15:01 +00004182}
4183
4184/*
drhcca9f3d2013-09-06 15:23:29 +00004185** Adjust the WhereLoop.nOut value downward to account for terms of the
4186** WHERE clause that reference the loop but which are not used by an
4187** index.
4188**
4189** In the current implementation, the first extra WHERE clause term reduces
4190** the number of output rows by a factor of 10 and each additional term
4191** reduces the number of output rows by sqrt(2).
4192*/
drh4f991892013-10-11 15:05:05 +00004193static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
drh7d9e7d82013-09-11 17:39:09 +00004194 WhereTerm *pTerm, *pX;
drhcca9f3d2013-09-06 15:23:29 +00004195 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
drh7d9e7d82013-09-11 17:39:09 +00004196 int i, j;
drhadd5ce32013-09-07 00:29:06 +00004197
4198 if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
4199 return;
4200 }
drhcca9f3d2013-09-06 15:23:29 +00004201 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
drh7d9e7d82013-09-11 17:39:09 +00004202 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
drhcca9f3d2013-09-06 15:23:29 +00004203 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
4204 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00004205 for(j=pLoop->nLTerm-1; j>=0; j--){
4206 pX = pLoop->aLTerm[j];
4207 if( pX==pTerm ) break;
4208 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
4209 }
4210 if( j<0 ) pLoop->nOut += pTerm->truthProb;
drhcca9f3d2013-09-06 15:23:29 +00004211 }
drhcca9f3d2013-09-06 15:23:29 +00004212}
4213
4214/*
drh5346e952013-05-08 14:14:26 +00004215** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
drh1c8148f2013-05-04 20:25:23 +00004216** Try to match one more.
4217**
4218** If pProbe->tnum==0, that means pIndex is a fake index used for the
4219** INTEGER PRIMARY KEY.
4220*/
drh5346e952013-05-08 14:14:26 +00004221static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00004222 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
4223 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
4224 Index *pProbe, /* An index on pSrc */
drhbf539c42013-10-05 18:16:02 +00004225 LogEst nInMul /* log(Number of iterations due to IN) */
drh1c8148f2013-05-04 20:25:23 +00004226){
drh70d18342013-06-06 19:16:33 +00004227 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
4228 Parse *pParse = pWInfo->pParse; /* Parsing context */
4229 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00004230 WhereLoop *pNew; /* Template WhereLoop under construction */
4231 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00004232 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00004233 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00004234 Bitmask saved_prereq; /* Original value of pNew->prereq */
4235 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
4236 int saved_nEq; /* Original value of pNew->u.btree.nEq */
4237 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
drhbf539c42013-10-05 18:16:02 +00004238 LogEst saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00004239 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00004240 int rc = SQLITE_OK; /* Return code */
drhbf539c42013-10-05 18:16:02 +00004241 LogEst nRowEst; /* Estimated index selectivity */
4242 LogEst rLogSize; /* Logarithm of table size */
drhc7f0d222013-06-19 03:27:12 +00004243 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00004244
drh1c8148f2013-05-04 20:25:23 +00004245 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00004246 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00004247
drh5346e952013-05-08 14:14:26 +00004248 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh43fe25f2013-05-07 23:06:23 +00004249 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
4250 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
4251 opMask = WO_LT|WO_LE;
4252 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
4253 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004254 }else{
drh43fe25f2013-05-07 23:06:23 +00004255 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004256 }
drhef866372013-05-22 20:49:02 +00004257 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00004258
drhbbbdc832013-10-22 18:01:40 +00004259 assert( pNew->u.btree.nEq<=pProbe->nKeyCol );
4260 if( pNew->u.btree.nEq < pProbe->nKeyCol ){
drh0f133a42013-05-22 17:01:17 +00004261 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
drhbf539c42013-10-05 18:16:02 +00004262 nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
drhc7f0d222013-06-19 03:27:12 +00004263 if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
drh0f133a42013-05-22 17:01:17 +00004264 }else{
4265 iCol = -1;
drhb8a8e8a2013-06-10 19:12:39 +00004266 nRowEst = 0;
drh0f133a42013-05-22 17:01:17 +00004267 }
drha18f3d22013-05-08 03:05:41 +00004268 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00004269 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00004270 saved_nEq = pNew->u.btree.nEq;
4271 saved_nLTerm = pNew->nLTerm;
4272 saved_wsFlags = pNew->wsFlags;
4273 saved_prereq = pNew->prereq;
4274 saved_nOut = pNew->nOut;
drhb8a8e8a2013-06-10 19:12:39 +00004275 pNew->rSetup = 0;
drhbf539c42013-10-05 18:16:02 +00004276 rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
drh5346e952013-05-08 14:14:26 +00004277 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
drhb8a8e8a2013-06-10 19:12:39 +00004278 int nIn = 0;
drh1435a9a2013-08-27 23:15:44 +00004279#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004280 int nRecValid = pBuilder->nRecValid;
drhb5246e52013-07-08 21:12:57 +00004281#endif
dan8bff07a2013-08-29 14:56:14 +00004282 if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
4283 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
4284 ){
4285 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
4286 }
dan7a419232013-08-06 20:01:43 +00004287 if( pTerm->prereqRight & pNew->maskSelf ) continue;
4288
danad45ed72013-08-08 12:21:32 +00004289 assert( pNew->nOut==saved_nOut );
4290
drh4efc9292013-06-06 23:02:03 +00004291 pNew->wsFlags = saved_wsFlags;
4292 pNew->u.btree.nEq = saved_nEq;
4293 pNew->nLTerm = saved_nLTerm;
4294 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4295 pNew->aLTerm[pNew->nLTerm++] = pTerm;
4296 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
drhe1e2e9a2013-06-13 15:16:53 +00004297 pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
drha18f3d22013-05-08 03:05:41 +00004298 if( pTerm->eOperator & WO_IN ){
4299 Expr *pExpr = pTerm->pExpr;
4300 pNew->wsFlags |= WHERE_COLUMN_IN;
4301 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhe1e2e9a2013-06-13 15:16:53 +00004302 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
drhbf539c42013-10-05 18:16:02 +00004303 nIn = 46; assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00004304 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
4305 /* "x IN (value, value, ...)" */
drhbf539c42013-10-05 18:16:02 +00004306 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
drhf1645f02013-05-07 19:44:38 +00004307 }
drhb8a8e8a2013-06-10 19:12:39 +00004308 pNew->rRun += nIn;
drh5346e952013-05-08 14:14:26 +00004309 pNew->u.btree.nEq++;
drhb8a8e8a2013-06-10 19:12:39 +00004310 pNew->nOut = nRowEst + nInMul + nIn;
drh6fa978d2013-05-30 19:29:19 +00004311 }else if( pTerm->eOperator & (WO_EQ) ){
drh7699d1c2013-06-04 12:42:29 +00004312 assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
drhb8a8e8a2013-06-10 19:12:39 +00004313 || nInMul==0 );
drha18f3d22013-05-08 03:05:41 +00004314 pNew->wsFlags |= WHERE_COLUMN_EQ;
drh7699d1c2013-06-04 12:42:29 +00004315 if( iCol<0
drhb8a8e8a2013-06-10 19:12:39 +00004316 || (pProbe->onError!=OE_None && nInMul==0
drhbbbdc832013-10-22 18:01:40 +00004317 && pNew->u.btree.nEq==pProbe->nKeyCol-1)
drh21f7ff72013-06-03 15:07:23 +00004318 ){
drh4a5acf82013-06-18 20:06:23 +00004319 assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
drh7699d1c2013-06-04 12:42:29 +00004320 pNew->wsFlags |= WHERE_ONEROW;
drh21f7ff72013-06-03 15:07:23 +00004321 }
drh5346e952013-05-08 14:14:26 +00004322 pNew->u.btree.nEq++;
drhb8a8e8a2013-06-10 19:12:39 +00004323 pNew->nOut = nRowEst + nInMul;
drh6fa978d2013-05-30 19:29:19 +00004324 }else if( pTerm->eOperator & (WO_ISNULL) ){
4325 pNew->wsFlags |= WHERE_COLUMN_NULL;
4326 pNew->u.btree.nEq++;
drhe1e2e9a2013-06-13 15:16:53 +00004327 /* TUNING: IS NULL selects 2 rows */
drhbf539c42013-10-05 18:16:02 +00004328 nIn = 10; assert( 10==sqlite3LogEst(2) );
drhb8a8e8a2013-06-10 19:12:39 +00004329 pNew->nOut = nRowEst + nInMul + nIn;
drha18f3d22013-05-08 03:05:41 +00004330 }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
drh7963b0e2013-06-17 21:37:40 +00004331 testcase( pTerm->eOperator & WO_GT );
4332 testcase( pTerm->eOperator & WO_GE );
drha18f3d22013-05-08 03:05:41 +00004333 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004334 pBtm = pTerm;
4335 pTop = 0;
drh7963b0e2013-06-17 21:37:40 +00004336 }else{
4337 assert( pTerm->eOperator & (WO_LT|WO_LE) );
4338 testcase( pTerm->eOperator & WO_LT );
4339 testcase( pTerm->eOperator & WO_LE );
drha18f3d22013-05-08 03:05:41 +00004340 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004341 pTop = pTerm;
4342 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00004343 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00004344 }
drh6f2bfad2013-06-03 17:35:22 +00004345 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
4346 /* Adjust nOut and rRun for STAT3 range values */
dan6cb8d762013-08-08 11:48:57 +00004347 assert( pNew->nOut==saved_nOut );
drh186ad8c2013-10-08 18:40:37 +00004348 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
drh6f2bfad2013-06-03 17:35:22 +00004349 }
drh1435a9a2013-08-27 23:15:44 +00004350#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan8ad169a2013-08-12 20:14:04 +00004351 if( nInMul==0
4352 && pProbe->nSample
4353 && pNew->u.btree.nEq<=pProbe->nSampleCol
4354 && OptimizationEnabled(db, SQLITE_Stat3)
4355 ){
dan7a419232013-08-06 20:01:43 +00004356 Expr *pExpr = pTerm->pExpr;
drhb8a8e8a2013-06-10 19:12:39 +00004357 tRowcnt nOut = 0;
drh6f2bfad2013-06-03 17:35:22 +00004358 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
drh93ec45d2013-06-17 18:20:48 +00004359 testcase( pTerm->eOperator & WO_EQ );
4360 testcase( pTerm->eOperator & WO_ISNULL );
dan7a419232013-08-06 20:01:43 +00004361 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
drh6f2bfad2013-06-03 17:35:22 +00004362 }else if( (pTerm->eOperator & WO_IN)
dan7a419232013-08-06 20:01:43 +00004363 && !ExprHasProperty(pExpr, EP_xIsSelect) ){
4364 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
drh6f2bfad2013-06-03 17:35:22 +00004365 }
drh82846332013-08-01 17:21:26 +00004366 assert( nOut==0 || rc==SQLITE_OK );
dan6cb8d762013-08-08 11:48:57 +00004367 if( nOut ){
drh4f991892013-10-11 15:05:05 +00004368 pNew->nOut = sqlite3LogEst(nOut);
4369 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
dan6cb8d762013-08-08 11:48:57 +00004370 }
drh6f2bfad2013-06-03 17:35:22 +00004371 }
4372#endif
drhe217efc2013-06-12 03:48:41 +00004373 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
drheb04de32013-05-10 15:16:30 +00004374 /* Each row involves a step of the index, then a binary search of
4375 ** the main table */
drhbf539c42013-10-05 18:16:02 +00004376 pNew->rRun = sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
drheb04de32013-05-10 15:16:30 +00004377 }
drhe217efc2013-06-12 03:48:41 +00004378 /* Step cost for each output row */
drhb50596d2013-10-08 20:42:41 +00004379 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
drh4f991892013-10-11 15:05:05 +00004380 whereLoopOutputAdjust(pBuilder->pWC, pNew);
drhcf8fa7a2013-05-10 20:26:22 +00004381 rc = whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004382 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
drhbbbdc832013-10-22 18:01:40 +00004383 && pNew->u.btree.nEq<(pProbe->nKeyCol + (pProbe->zName!=0))
drh5346e952013-05-08 14:14:26 +00004384 ){
drhb8a8e8a2013-06-10 19:12:39 +00004385 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
drha18f3d22013-05-08 03:05:41 +00004386 }
danad45ed72013-08-08 12:21:32 +00004387 pNew->nOut = saved_nOut;
drh1435a9a2013-08-27 23:15:44 +00004388#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004389 pBuilder->nRecValid = nRecValid;
dan7a419232013-08-06 20:01:43 +00004390#endif
drh1c8148f2013-05-04 20:25:23 +00004391 }
drh4efc9292013-06-06 23:02:03 +00004392 pNew->prereq = saved_prereq;
4393 pNew->u.btree.nEq = saved_nEq;
4394 pNew->wsFlags = saved_wsFlags;
4395 pNew->nOut = saved_nOut;
4396 pNew->nLTerm = saved_nLTerm;
drh5346e952013-05-08 14:14:26 +00004397 return rc;
drh1c8148f2013-05-04 20:25:23 +00004398}
4399
4400/*
drh23f98da2013-05-21 15:52:07 +00004401** Return True if it is possible that pIndex might be useful in
4402** implementing the ORDER BY clause in pBuilder.
4403**
4404** Return False if pBuilder does not contain an ORDER BY clause or
4405** if there is no way for pIndex to be useful in implementing that
4406** ORDER BY clause.
4407*/
4408static int indexMightHelpWithOrderBy(
4409 WhereLoopBuilder *pBuilder,
4410 Index *pIndex,
4411 int iCursor
4412){
4413 ExprList *pOB;
drh6d381472013-06-13 17:58:08 +00004414 int ii, jj;
drh23f98da2013-05-21 15:52:07 +00004415
drh53cfbe92013-06-13 17:28:22 +00004416 if( pIndex->bUnordered ) return 0;
drh70d18342013-06-06 19:16:33 +00004417 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00004418 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00004419 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00004420 if( pExpr->op!=TK_COLUMN ) return 0;
4421 if( pExpr->iTable==iCursor ){
drhbbbdc832013-10-22 18:01:40 +00004422 for(jj=0; jj<pIndex->nKeyCol; jj++){
drh6d381472013-06-13 17:58:08 +00004423 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
4424 }
drh23f98da2013-05-21 15:52:07 +00004425 }
4426 }
4427 return 0;
4428}
4429
4430/*
drh92a121f2013-06-10 12:15:47 +00004431** Return a bitmask where 1s indicate that the corresponding column of
4432** the table is used by an index. Only the first 63 columns are considered.
4433*/
drhfd5874d2013-06-12 14:52:39 +00004434static Bitmask columnsInIndex(Index *pIdx){
drh92a121f2013-06-10 12:15:47 +00004435 Bitmask m = 0;
4436 int j;
drhec95c442013-10-23 01:57:32 +00004437 for(j=pIdx->nColumn-1; j>=0; j--){
drh92a121f2013-06-10 12:15:47 +00004438 int x = pIdx->aiColumn[j];
drhec95c442013-10-23 01:57:32 +00004439 if( x>=0 ){
4440 testcase( x==BMS-1 );
4441 testcase( x==BMS-2 );
4442 if( x<BMS-1 ) m |= MASKBIT(x);
4443 }
drh92a121f2013-06-10 12:15:47 +00004444 }
4445 return m;
4446}
4447
drh4bd5f732013-07-31 23:22:39 +00004448/* Check to see if a partial index with pPartIndexWhere can be used
4449** in the current query. Return true if it can be and false if not.
4450*/
4451static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
4452 int i;
4453 WhereTerm *pTerm;
4454 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
4455 if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
4456 }
4457 return 0;
4458}
drh92a121f2013-06-10 12:15:47 +00004459
4460/*
dan51576f42013-07-02 10:06:15 +00004461** Add all WhereLoop objects for a single table of the join where the table
drh0823c892013-05-11 00:06:23 +00004462** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
4463** a b-tree table, not a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004464*/
drh5346e952013-05-08 14:14:26 +00004465static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00004466 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00004467 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00004468){
drh70d18342013-06-06 19:16:33 +00004469 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00004470 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00004471 Index sPk; /* A fake index object for the primary key */
4472 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
drhbbbdc832013-10-22 18:01:40 +00004473 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00004474 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00004475 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00004476 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00004477 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00004478 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00004479 int b; /* A boolean value */
drhbf539c42013-10-05 18:16:02 +00004480 LogEst rSize; /* number of rows in the table */
4481 LogEst rLogSize; /* Logarithm of the number of rows in the table */
drh4bd5f732013-07-31 23:22:39 +00004482 WhereClause *pWC; /* The parsed WHERE clause */
drh3495d202013-10-07 17:32:15 +00004483 Table *pTab; /* Table being queried */
drh23f98da2013-05-21 15:52:07 +00004484
drh1c8148f2013-05-04 20:25:23 +00004485 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004486 pWInfo = pBuilder->pWInfo;
4487 pTabList = pWInfo->pTabList;
4488 pSrc = pTabList->a + pNew->iTab;
drh3495d202013-10-07 17:32:15 +00004489 pTab = pSrc->pTab;
drh4bd5f732013-07-31 23:22:39 +00004490 pWC = pBuilder->pWC;
drh0823c892013-05-11 00:06:23 +00004491 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00004492
4493 if( pSrc->pIndex ){
4494 /* An INDEXED BY clause specifies a particular index to use */
4495 pProbe = pSrc->pIndex;
drhec95c442013-10-23 01:57:32 +00004496 }else if( !HasRowid(pTab) ){
4497 pProbe = pTab->pIndex;
drh1c8148f2013-05-04 20:25:23 +00004498 }else{
4499 /* There is no INDEXED BY clause. Create a fake Index object in local
4500 ** variable sPk to represent the rowid primary key index. Make this
4501 ** fake index the first in a chain of Index objects with all of the real
4502 ** indices to follow */
4503 Index *pFirst; /* First of real indices on the table */
4504 memset(&sPk, 0, sizeof(Index));
drhbbbdc832013-10-22 18:01:40 +00004505 sPk.nKeyCol = 1;
drh1c8148f2013-05-04 20:25:23 +00004506 sPk.aiColumn = &aiColumnPk;
4507 sPk.aiRowEst = aiRowEstPk;
4508 sPk.onError = OE_Replace;
drh3495d202013-10-07 17:32:15 +00004509 sPk.pTable = pTab;
4510 aiRowEstPk[0] = pTab->nRowEst;
drh1c8148f2013-05-04 20:25:23 +00004511 aiRowEstPk[1] = 1;
4512 pFirst = pSrc->pTab->pIndex;
4513 if( pSrc->notIndexed==0 ){
4514 /* The real indices of the table are only considered if the
4515 ** NOT INDEXED qualifier is omitted from the FROM clause */
4516 sPk.pNext = pFirst;
4517 }
4518 pProbe = &sPk;
4519 }
drh3495d202013-10-07 17:32:15 +00004520 rSize = sqlite3LogEst(pTab->nRowEst);
drheb04de32013-05-10 15:16:30 +00004521 rLogSize = estLog(rSize);
4522
drhfeb56e02013-08-23 17:33:46 +00004523#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drheb04de32013-05-10 15:16:30 +00004524 /* Automatic indexes */
drhaa32e3c2013-07-16 21:31:23 +00004525 if( !pBuilder->pOrSet
drh4fe425a2013-06-12 17:08:06 +00004526 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
4527 && pSrc->pIndex==0
drheb04de32013-05-10 15:16:30 +00004528 && !pSrc->viaCoroutine
4529 && !pSrc->notIndexed
drhec95c442013-10-23 01:57:32 +00004530 && HasRowid(pTab)
drheb04de32013-05-10 15:16:30 +00004531 && !pSrc->isCorrelated
4532 ){
4533 /* Generate auto-index WhereLoops */
drheb04de32013-05-10 15:16:30 +00004534 WhereTerm *pTerm;
4535 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
4536 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00004537 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00004538 if( termCanDriveIndex(pTerm, pSrc, 0) ){
4539 pNew->u.btree.nEq = 1;
drhef866372013-05-22 20:49:02 +00004540 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00004541 pNew->nLTerm = 1;
4542 pNew->aLTerm[0] = pTerm;
drhe1e2e9a2013-06-13 15:16:53 +00004543 /* TUNING: One-time cost for computing the automatic index is
drh986b3872013-06-28 21:12:20 +00004544 ** approximately 7*N*log2(N) where N is the number of rows in
drhe1e2e9a2013-06-13 15:16:53 +00004545 ** the table being indexed. */
drhbf539c42013-10-05 18:16:02 +00004546 pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) );
drh986b3872013-06-28 21:12:20 +00004547 /* TUNING: Each index lookup yields 20 rows in the table. This
4548 ** is more than the usual guess of 10 rows, since we have no way
4549 ** of knowning how selective the index will ultimately be. It would
4550 ** not be unreasonable to make this value much larger. */
drhbf539c42013-10-05 18:16:02 +00004551 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
drhb50596d2013-10-08 20:42:41 +00004552 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
drh986b3872013-06-28 21:12:20 +00004553 pNew->wsFlags = WHERE_AUTO_INDEX;
drheb04de32013-05-10 15:16:30 +00004554 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00004555 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00004556 }
4557 }
4558 }
drhfeb56e02013-08-23 17:33:46 +00004559#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh1c8148f2013-05-04 20:25:23 +00004560
4561 /* Loop over all indices
4562 */
drh23f98da2013-05-21 15:52:07 +00004563 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh4bd5f732013-07-31 23:22:39 +00004564 if( pProbe->pPartIdxWhere!=0
4565 && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
4566 continue; /* Partial index inappropriate for this query */
4567 }
drh5346e952013-05-08 14:14:26 +00004568 pNew->u.btree.nEq = 0;
drh4efc9292013-06-06 23:02:03 +00004569 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00004570 pNew->iSortIdx = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004571 pNew->rSetup = 0;
drh23f98da2013-05-21 15:52:07 +00004572 pNew->prereq = mExtra;
drh74f91d42013-06-19 18:01:44 +00004573 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004574 pNew->u.btree.pIndex = pProbe;
4575 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh53cfbe92013-06-13 17:28:22 +00004576 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
4577 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
drh43fe25f2013-05-07 23:06:23 +00004578 if( pProbe->tnum<=0 ){
4579 /* Integer primary key index */
4580 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00004581
4582 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00004583 pNew->iSortIdx = b ? iSortIdx : 0;
drhe1e2e9a2013-06-13 15:16:53 +00004584 /* TUNING: Cost of full table scan is 3*(N + log2(N)).
drhbf539c42013-10-05 18:16:02 +00004585 ** + The extra 3 factor is to encourage the use of indexed lookups
drhe13e9f52013-10-05 19:18:00 +00004586 ** over full scans. FIXME */
drhb50596d2013-10-08 20:42:41 +00004587 pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
drh4f991892013-10-11 15:05:05 +00004588 whereLoopOutputAdjust(pWC, pNew);
drh23f98da2013-05-21 15:52:07 +00004589 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00004590 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004591 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00004592 }else{
drhec95c442013-10-23 01:57:32 +00004593 Bitmask m;
4594 if( pProbe->isCovering ){
4595 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
4596 m = 0;
4597 }else{
4598 m = pSrc->colUsed & ~columnsInIndex(pProbe);
4599 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
4600 }
drh1c8148f2013-05-04 20:25:23 +00004601
drh23f98da2013-05-21 15:52:07 +00004602 /* Full scan via index */
drh53cfbe92013-06-13 17:28:22 +00004603 if( b
4604 || ( m==0
4605 && pProbe->bUnordered==0
drhb50596d2013-10-08 20:42:41 +00004606 && pProbe->szIdxRow<pTab->szTabRow
drh53cfbe92013-06-13 17:28:22 +00004607 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
4608 && sqlite3GlobalConfig.bUseCis
4609 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
4610 )
drhe3b7c922013-06-03 19:17:40 +00004611 ){
drh23f98da2013-05-21 15:52:07 +00004612 pNew->iSortIdx = b ? iSortIdx : 0;
drhe1e2e9a2013-06-13 15:16:53 +00004613 if( m==0 ){
drhd9e3cad2013-10-04 02:36:19 +00004614 /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
drhb50596d2013-10-08 20:42:41 +00004615 ** + The extra factor K of between 1.1 and 3.0 that depends
4616 ** on the relative sizes of the table and the index. K
4617 ** is smaller for smaller indices, thus favoring them.
drhd9e3cad2013-10-04 02:36:19 +00004618 */
drhb50596d2013-10-08 20:42:41 +00004619 pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
4620 (15*pProbe->szIdxRow)/pTab->szTabRow;
drhe1e2e9a2013-06-13 15:16:53 +00004621 }else{
4622 assert( b!=0 );
4623 /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
4624 ** which we will simplify to just N*log2(N) */
4625 pNew->rRun = rSize + rLogSize;
4626 }
drh4f991892013-10-11 15:05:05 +00004627 whereLoopOutputAdjust(pWC, pNew);
drh23f98da2013-05-21 15:52:07 +00004628 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00004629 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004630 if( rc ) break;
4631 }
4632 }
dan7a419232013-08-06 20:01:43 +00004633
drhb8a8e8a2013-06-10 19:12:39 +00004634 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
drh1435a9a2013-08-27 23:15:44 +00004635#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan87cd9322013-08-07 15:52:41 +00004636 sqlite3Stat4ProbeFree(pBuilder->pRec);
4637 pBuilder->nRecValid = 0;
4638 pBuilder->pRec = 0;
danddc2d6e2013-08-06 20:15:06 +00004639#endif
drh1c8148f2013-05-04 20:25:23 +00004640
4641 /* If there was an INDEXED BY clause, then only that one index is
4642 ** considered. */
4643 if( pSrc->pIndex ) break;
4644 }
drh5346e952013-05-08 14:14:26 +00004645 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004646}
4647
drh8636e9c2013-06-11 01:50:08 +00004648#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf1b5f5b2013-05-02 00:15:01 +00004649/*
drh0823c892013-05-11 00:06:23 +00004650** Add all WhereLoop objects for a table of the join identified by
4651** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004652*/
drh5346e952013-05-08 14:14:26 +00004653static int whereLoopAddVirtual(
drh613ba1e2013-06-15 15:11:45 +00004654 WhereLoopBuilder *pBuilder /* WHERE clause information */
drhf1b5f5b2013-05-02 00:15:01 +00004655){
drh70d18342013-06-06 19:16:33 +00004656 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00004657 Parse *pParse; /* The parsing context */
4658 WhereClause *pWC; /* The WHERE clause */
4659 struct SrcList_item *pSrc; /* The FROM clause term to search */
4660 Table *pTab;
4661 sqlite3 *db;
4662 sqlite3_index_info *pIdxInfo;
4663 struct sqlite3_index_constraint *pIdxCons;
4664 struct sqlite3_index_constraint_usage *pUsage;
4665 WhereTerm *pTerm;
4666 int i, j;
4667 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00004668 int nConstraint;
drh5346e952013-05-08 14:14:26 +00004669 int seenIn = 0; /* True if an IN operator is seen */
4670 int seenVar = 0; /* True if a non-constant constraint is seen */
4671 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
4672 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00004673 int rc = SQLITE_OK;
4674
drh70d18342013-06-06 19:16:33 +00004675 pWInfo = pBuilder->pWInfo;
4676 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00004677 db = pParse->db;
4678 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00004679 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004680 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00004681 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00004682 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00004683 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00004684 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00004685 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00004686 pNew->rSetup = 0;
4687 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00004688 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00004689 pNew->u.vtab.needFree = 0;
4690 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00004691 nConstraint = pIdxInfo->nConstraint;
drh7963b0e2013-06-17 21:37:40 +00004692 if( whereLoopResize(db, pNew, nConstraint) ){
4693 sqlite3DbFree(db, pIdxInfo);
4694 return SQLITE_NOMEM;
4695 }
drh5346e952013-05-08 14:14:26 +00004696
drh0823c892013-05-11 00:06:23 +00004697 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00004698 if( !seenIn && (iPhase&1)!=0 ){
4699 iPhase++;
4700 if( iPhase>3 ) break;
4701 }
4702 if( !seenVar && iPhase>1 ) break;
4703 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4704 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
4705 j = pIdxCons->iTermOffset;
4706 pTerm = &pWC->a[j];
4707 switch( iPhase ){
4708 case 0: /* Constants without IN operator */
4709 pIdxCons->usable = 0;
4710 if( (pTerm->eOperator & WO_IN)!=0 ){
4711 seenIn = 1;
drh7963b0e2013-06-17 21:37:40 +00004712 }
4713 if( pTerm->prereqRight!=0 ){
drh5346e952013-05-08 14:14:26 +00004714 seenVar = 1;
drh7963b0e2013-06-17 21:37:40 +00004715 }else if( (pTerm->eOperator & WO_IN)==0 ){
drh5346e952013-05-08 14:14:26 +00004716 pIdxCons->usable = 1;
4717 }
4718 break;
4719 case 1: /* Constants with IN operators */
4720 assert( seenIn );
4721 pIdxCons->usable = (pTerm->prereqRight==0);
4722 break;
4723 case 2: /* Variables without IN */
4724 assert( seenVar );
4725 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
4726 break;
4727 default: /* Variables with IN */
4728 assert( seenVar && seenIn );
4729 pIdxCons->usable = 1;
4730 break;
4731 }
4732 }
4733 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
4734 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4735 pIdxInfo->idxStr = 0;
4736 pIdxInfo->idxNum = 0;
4737 pIdxInfo->needToFreeIdxStr = 0;
4738 pIdxInfo->orderByConsumed = 0;
drh8636e9c2013-06-11 01:50:08 +00004739 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
drh5346e952013-05-08 14:14:26 +00004740 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
4741 if( rc ) goto whereLoopAddVtab_exit;
4742 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4743 pNew->prereq = 0;
drhc718f1c2013-05-08 20:05:58 +00004744 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00004745 assert( pNew->nLSlot>=nConstraint );
4746 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00004747 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00004748 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00004749 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4750 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00004751 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00004752 || j<0
4753 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00004754 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00004755 ){
4756 rc = SQLITE_ERROR;
4757 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
4758 goto whereLoopAddVtab_exit;
4759 }
drh7963b0e2013-06-17 21:37:40 +00004760 testcase( iTerm==nConstraint-1 );
4761 testcase( j==0 );
4762 testcase( j==pWC->nTerm-1 );
drh5346e952013-05-08 14:14:26 +00004763 pTerm = &pWC->a[j];
4764 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00004765 assert( iTerm<pNew->nLSlot );
4766 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00004767 if( iTerm>mxTerm ) mxTerm = iTerm;
drh7963b0e2013-06-17 21:37:40 +00004768 testcase( iTerm==15 );
4769 testcase( iTerm==16 );
drh52986302013-06-03 16:03:16 +00004770 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00004771 if( (pTerm->eOperator & WO_IN)!=0 ){
4772 if( pUsage[i].omit==0 ){
4773 /* Do not attempt to use an IN constraint if the virtual table
4774 ** says that the equivalent EQ constraint cannot be safely omitted.
4775 ** If we do attempt to use such a constraint, some rows might be
4776 ** repeated in the output. */
4777 break;
4778 }
4779 /* A virtual table that is constrained by an IN clause may not
4780 ** consume the ORDER BY clause because (1) the order of IN terms
4781 ** is not necessarily related to the order of output terms and
4782 ** (2) Multiple outputs from a single IN value will not merge
4783 ** together. */
4784 pIdxInfo->orderByConsumed = 0;
4785 }
4786 }
4787 }
drh4efc9292013-06-06 23:02:03 +00004788 if( i>=nConstraint ){
4789 pNew->nLTerm = mxTerm+1;
4790 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00004791 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4792 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4793 pIdxInfo->needToFreeIdxStr = 0;
4794 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh3b1d8082013-06-03 16:56:37 +00004795 pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
4796 && pIdxInfo->orderByConsumed);
drhb8a8e8a2013-06-10 19:12:39 +00004797 pNew->rSetup = 0;
drhb50596d2013-10-08 20:42:41 +00004798 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
drhe1e2e9a2013-06-13 15:16:53 +00004799 /* TUNING: Every virtual table query returns 25 rows */
drhbf539c42013-10-05 18:16:02 +00004800 pNew->nOut = 46; assert( 46==sqlite3LogEst(25) );
drhcf8fa7a2013-05-10 20:26:22 +00004801 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004802 if( pNew->u.vtab.needFree ){
4803 sqlite3_free(pNew->u.vtab.idxStr);
4804 pNew->u.vtab.needFree = 0;
4805 }
4806 }
4807 }
4808
4809whereLoopAddVtab_exit:
4810 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4811 sqlite3DbFree(db, pIdxInfo);
4812 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004813}
drh8636e9c2013-06-11 01:50:08 +00004814#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhf1b5f5b2013-05-02 00:15:01 +00004815
4816/*
drhcf8fa7a2013-05-10 20:26:22 +00004817** Add WhereLoop entries to handle OR terms. This works for either
4818** btrees or virtual tables.
4819*/
4820static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00004821 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00004822 WhereClause *pWC;
4823 WhereLoop *pNew;
4824 WhereTerm *pTerm, *pWCEnd;
4825 int rc = SQLITE_OK;
4826 int iCur;
4827 WhereClause tempWC;
4828 WhereLoopBuilder sSubBuild;
drhaa32e3c2013-07-16 21:31:23 +00004829 WhereOrSet sSum, sCur, sPrev;
drhcf8fa7a2013-05-10 20:26:22 +00004830 struct SrcList_item *pItem;
4831
drhcf8fa7a2013-05-10 20:26:22 +00004832 pWC = pBuilder->pWC;
drh70d18342013-06-06 19:16:33 +00004833 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
drhcf8fa7a2013-05-10 20:26:22 +00004834 pWCEnd = pWC->a + pWC->nTerm;
4835 pNew = pBuilder->pNew;
drh77dfd5b2013-08-19 11:15:48 +00004836 memset(&sSum, 0, sizeof(sSum));
drh186ad8c2013-10-08 18:40:37 +00004837 pItem = pWInfo->pTabList->a + pNew->iTab;
4838 iCur = pItem->iCursor;
drhcf8fa7a2013-05-10 20:26:22 +00004839
4840 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4841 if( (pTerm->eOperator & WO_OR)!=0
4842 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4843 ){
4844 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4845 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4846 WhereTerm *pOrTerm;
drhaa32e3c2013-07-16 21:31:23 +00004847 int once = 1;
4848 int i, j;
drh783dece2013-06-05 17:53:43 +00004849
drh783dece2013-06-05 17:53:43 +00004850 sSubBuild = *pBuilder;
4851 sSubBuild.pOrderBy = 0;
drhaa32e3c2013-07-16 21:31:23 +00004852 sSubBuild.pOrSet = &sCur;
drhcf8fa7a2013-05-10 20:26:22 +00004853
drhc7f0d222013-06-19 03:27:12 +00004854 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00004855 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004856 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4857 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00004858 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00004859 tempWC.pOuter = pWC;
4860 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00004861 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00004862 tempWC.a = pOrTerm;
4863 sSubBuild.pWC = &tempWC;
4864 }else{
4865 continue;
4866 }
drhaa32e3c2013-07-16 21:31:23 +00004867 sCur.n = 0;
drh8636e9c2013-06-11 01:50:08 +00004868#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcf8fa7a2013-05-10 20:26:22 +00004869 if( IsVirtual(pItem->pTab) ){
drh613ba1e2013-06-15 15:11:45 +00004870 rc = whereLoopAddVirtual(&sSubBuild);
drhaa32e3c2013-07-16 21:31:23 +00004871 for(i=0; i<sCur.n; i++) sCur.a[i].prereq |= mExtra;
drh8636e9c2013-06-11 01:50:08 +00004872 }else
4873#endif
4874 {
drhcf8fa7a2013-05-10 20:26:22 +00004875 rc = whereLoopAddBtree(&sSubBuild, mExtra);
4876 }
drhaa32e3c2013-07-16 21:31:23 +00004877 assert( rc==SQLITE_OK || sCur.n==0 );
4878 if( sCur.n==0 ){
4879 sSum.n = 0;
4880 break;
4881 }else if( once ){
4882 whereOrMove(&sSum, &sCur);
4883 once = 0;
4884 }else{
4885 whereOrMove(&sPrev, &sSum);
4886 sSum.n = 0;
4887 for(i=0; i<sPrev.n; i++){
4888 for(j=0; j<sCur.n; j++){
4889 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
drhbf539c42013-10-05 18:16:02 +00004890 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4891 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
drhaa32e3c2013-07-16 21:31:23 +00004892 }
4893 }
4894 }
drhcf8fa7a2013-05-10 20:26:22 +00004895 }
drhaa32e3c2013-07-16 21:31:23 +00004896 pNew->nLTerm = 1;
4897 pNew->aLTerm[0] = pTerm;
4898 pNew->wsFlags = WHERE_MULTI_OR;
4899 pNew->rSetup = 0;
4900 pNew->iSortIdx = 0;
4901 memset(&pNew->u, 0, sizeof(pNew->u));
4902 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
drh74f91d42013-06-19 18:01:44 +00004903 /* TUNING: Multiple by 3.5 for the secondary table lookup */
drhaa32e3c2013-07-16 21:31:23 +00004904 pNew->rRun = sSum.a[i].rRun + 18;
4905 pNew->nOut = sSum.a[i].nOut;
4906 pNew->prereq = sSum.a[i].prereq;
drhfd5874d2013-06-12 14:52:39 +00004907 rc = whereLoopInsert(pBuilder, pNew);
4908 }
drhcf8fa7a2013-05-10 20:26:22 +00004909 }
4910 }
4911 return rc;
4912}
4913
4914/*
drhf1b5f5b2013-05-02 00:15:01 +00004915** Add all WhereLoop objects for all tables
4916*/
drh5346e952013-05-08 14:14:26 +00004917static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00004918 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00004919 Bitmask mExtra = 0;
4920 Bitmask mPrior = 0;
4921 int iTab;
drh70d18342013-06-06 19:16:33 +00004922 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00004923 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00004924 sqlite3 *db = pWInfo->pParse->db;
4925 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00004926 int rc = SQLITE_OK;
drhc63367e2013-06-10 20:46:50 +00004927 u8 priorJoinType = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004928 WhereLoop *pNew;
drhf1b5f5b2013-05-02 00:15:01 +00004929
4930 /* Loop over the tables in the join, from left to right */
drhb8a8e8a2013-06-10 19:12:39 +00004931 pNew = pBuilder->pNew;
drha2014152013-06-07 00:29:23 +00004932 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00004933 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00004934 pNew->iTab = iTab;
drh70d18342013-06-06 19:16:33 +00004935 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
drhc63367e2013-06-10 20:46:50 +00004936 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
drhf1b5f5b2013-05-02 00:15:01 +00004937 mExtra = mPrior;
4938 }
drhc63367e2013-06-10 20:46:50 +00004939 priorJoinType = pItem->jointype;
drhb2a90f02013-05-10 03:30:49 +00004940 if( IsVirtual(pItem->pTab) ){
drh613ba1e2013-06-15 15:11:45 +00004941 rc = whereLoopAddVirtual(pBuilder);
drhb2a90f02013-05-10 03:30:49 +00004942 }else{
4943 rc = whereLoopAddBtree(pBuilder, mExtra);
4944 }
drhb2a90f02013-05-10 03:30:49 +00004945 if( rc==SQLITE_OK ){
4946 rc = whereLoopAddOr(pBuilder, mExtra);
4947 }
drhb2a90f02013-05-10 03:30:49 +00004948 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00004949 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00004950 }
drha2014152013-06-07 00:29:23 +00004951 whereLoopClear(db, pNew);
drh5346e952013-05-08 14:14:26 +00004952 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004953}
4954
drha18f3d22013-05-08 03:05:41 +00004955/*
drh7699d1c2013-06-04 12:42:29 +00004956** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00004957** parameters) to see if it outputs rows in the requested ORDER BY
drh94433422013-07-01 11:05:50 +00004958** (or GROUP BY) without requiring a separate sort operation. Return:
drh319f6772013-05-14 15:31:07 +00004959**
4960** 0: ORDER BY is not satisfied. Sorting required
4961** 1: ORDER BY is satisfied. Omit sorting
4962** -1: Unknown at this time
4963**
drh94433422013-07-01 11:05:50 +00004964** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4965** strict. With GROUP BY and DISTINCT the only requirement is that
4966** equivalent rows appear immediately adjacent to one another. GROUP BY
4967** and DISTINT do not require rows to appear in any particular order as long
4968** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
4969** the pOrderBy terms can be matched in any order. With ORDER BY, the
4970** pOrderBy terms must be matched in strict left-to-right order.
drh6b7157b2013-05-10 02:00:35 +00004971*/
4972static int wherePathSatisfiesOrderBy(
4973 WhereInfo *pWInfo, /* The WHERE clause */
drh4f402f22013-06-11 18:59:38 +00004974 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
drh6b7157b2013-05-10 02:00:35 +00004975 WherePath *pPath, /* The WherePath to check */
drh4f402f22013-06-11 18:59:38 +00004976 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
4977 u16 nLoop, /* Number of entries in pPath->aLoop[] */
drh319f6772013-05-14 15:31:07 +00004978 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
drh4f402f22013-06-11 18:59:38 +00004979 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00004980){
drh88da6442013-05-27 17:59:37 +00004981 u8 revSet; /* True if rev is known */
4982 u8 rev; /* Composite sort order */
4983 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00004984 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
4985 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
4986 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drhbbbdc832013-10-22 18:01:40 +00004987 u16 nKeyCol; /* Number of columns in pIndex */
drh7699d1c2013-06-04 12:42:29 +00004988 u16 nOrderBy; /* Number terms in the ORDER BY clause */
4989 int iLoop; /* Index of WhereLoop in pPath being processed */
4990 int i, j; /* Loop counters */
4991 int iCur; /* Cursor number for current WhereLoop */
4992 int iColumn; /* A column number within table iCur */
drhe8ae5832013-06-19 13:32:46 +00004993 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
drh7699d1c2013-06-04 12:42:29 +00004994 WhereTerm *pTerm; /* A single term of the WHERE clause */
4995 Expr *pOBExpr; /* An expression from the ORDER BY clause */
4996 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
4997 Index *pIndex; /* The index associated with pLoop */
4998 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
4999 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
5000 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00005001 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drhb8916be2013-06-14 02:51:48 +00005002 Bitmask ready; /* Mask of inner loops */
drh319f6772013-05-14 15:31:07 +00005003
5004 /*
drh7699d1c2013-06-04 12:42:29 +00005005 ** We say the WhereLoop is "one-row" if it generates no more than one
5006 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00005007 ** (a) All index columns match with WHERE_COLUMN_EQ.
5008 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00005009 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
5010 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00005011 **
drhe353ee32013-06-04 23:40:53 +00005012 ** We say the WhereLoop is "order-distinct" if the set of columns from
5013 ** that WhereLoop that are in the ORDER BY clause are different for every
5014 ** row of the WhereLoop. Every one-row WhereLoop is automatically
5015 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
5016 ** is not order-distinct. To be order-distinct is not quite the same as being
5017 ** UNIQUE since a UNIQUE column or index can have multiple rows that
5018 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
5019 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
5020 **
5021 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
5022 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
5023 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00005024 */
5025
5026 assert( pOrderBy!=0 );
5027
5028 /* Sortability of virtual tables is determined by the xBestIndex method
5029 ** of the virtual table itself */
5030 if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
drh7699d1c2013-06-04 12:42:29 +00005031 testcase( nLoop>0 ); /* True when outer loops are one-row and match
5032 ** no ORDER BY terms */
drh319f6772013-05-14 15:31:07 +00005033 return pLast->u.vtab.isOrdered;
drh6b7157b2013-05-10 02:00:35 +00005034 }
drh7699d1c2013-06-04 12:42:29 +00005035 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00005036
drh319f6772013-05-14 15:31:07 +00005037 nOrderBy = pOrderBy->nExpr;
drh7963b0e2013-06-17 21:37:40 +00005038 testcase( nOrderBy==BMS-1 );
drhe353ee32013-06-04 23:40:53 +00005039 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
5040 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00005041 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00005042 orderDistinctMask = 0;
drhb8916be2013-06-14 02:51:48 +00005043 ready = 0;
drhe353ee32013-06-04 23:40:53 +00005044 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drhb8916be2013-06-14 02:51:48 +00005045 if( iLoop>0 ) ready |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005046 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh319f6772013-05-14 15:31:07 +00005047 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh319f6772013-05-14 15:31:07 +00005048 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drhb8916be2013-06-14 02:51:48 +00005049
5050 /* Mark off any ORDER BY term X that is a column in the table of
5051 ** the current loop for which there is term in the WHERE
5052 ** clause of the form X IS NULL or X=? that reference only outer
5053 ** loops.
5054 */
5055 for(i=0; i<nOrderBy; i++){
5056 if( MASKBIT(i) & obSat ) continue;
5057 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
5058 if( pOBExpr->op!=TK_COLUMN ) continue;
5059 if( pOBExpr->iTable!=iCur ) continue;
5060 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
5061 ~ready, WO_EQ|WO_ISNULL, 0);
5062 if( pTerm==0 ) continue;
drh7963b0e2013-06-17 21:37:40 +00005063 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
drhb8916be2013-06-14 02:51:48 +00005064 const char *z1, *z2;
5065 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5066 if( !pColl ) pColl = db->pDfltColl;
5067 z1 = pColl->zName;
5068 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
5069 if( !pColl ) pColl = db->pDfltColl;
5070 z2 = pColl->zName;
5071 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
5072 }
5073 obSat |= MASKBIT(i);
5074 }
5075
drh7699d1c2013-06-04 12:42:29 +00005076 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
5077 if( pLoop->wsFlags & WHERE_IPK ){
5078 pIndex = 0;
drhbbbdc832013-10-22 18:01:40 +00005079 nKeyCol = 0;
drh7699d1c2013-06-04 12:42:29 +00005080 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00005081 return 0;
drh7699d1c2013-06-04 12:42:29 +00005082 }else{
drhbbbdc832013-10-22 18:01:40 +00005083 nKeyCol = pIndex->nKeyCol;
drhe353ee32013-06-04 23:40:53 +00005084 isOrderDistinct = pIndex->onError!=OE_None;
drh1b0f0262013-05-30 22:27:09 +00005085 }
drh7699d1c2013-06-04 12:42:29 +00005086
drh7699d1c2013-06-04 12:42:29 +00005087 /* Loop through all columns of the index and deal with the ones
5088 ** that are not constrained by == or IN.
5089 */
5090 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00005091 distinctColumns = 0;
drhbbbdc832013-10-22 18:01:40 +00005092 for(j=0; j<=nKeyCol; j++){
drh7699d1c2013-06-04 12:42:29 +00005093 u8 bOnce; /* True to run the ORDER BY search loop */
5094
drhe353ee32013-06-04 23:40:53 +00005095 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00005096 if( j<pLoop->u.btree.nEq
drh4efc9292013-06-06 23:02:03 +00005097 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
drh7699d1c2013-06-04 12:42:29 +00005098 ){
drh7963b0e2013-06-17 21:37:40 +00005099 if( i & WO_ISNULL ){
5100 testcase( isOrderDistinct );
5101 isOrderDistinct = 0;
5102 }
drhe353ee32013-06-04 23:40:53 +00005103 continue;
drh7699d1c2013-06-04 12:42:29 +00005104 }
5105
drhe353ee32013-06-04 23:40:53 +00005106 /* Get the column number in the table (iColumn) and sort order
5107 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00005108 */
drhbbbdc832013-10-22 18:01:40 +00005109 if( j<nKeyCol ){
drh7699d1c2013-06-04 12:42:29 +00005110 /* Normal index columns */
5111 iColumn = pIndex->aiColumn[j];
5112 revIdx = pIndex->aSortOrder[j];
5113 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00005114 }else{
drh7699d1c2013-06-04 12:42:29 +00005115 /* The ROWID column at the end */
drhbbbdc832013-10-22 18:01:40 +00005116 assert( j==nKeyCol );
drh7699d1c2013-06-04 12:42:29 +00005117 iColumn = -1;
5118 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00005119 }
drh7699d1c2013-06-04 12:42:29 +00005120
5121 /* An unconstrained column that might be NULL means that this
5122 ** WhereLoop is not well-ordered
5123 */
drhe353ee32013-06-04 23:40:53 +00005124 if( isOrderDistinct
5125 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00005126 && j>=pLoop->u.btree.nEq
5127 && pIndex->pTable->aCol[iColumn].notNull==0
5128 ){
drhe353ee32013-06-04 23:40:53 +00005129 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00005130 }
5131
5132 /* Find the ORDER BY term that corresponds to the j-th column
5133 ** of the index and and mark that ORDER BY term off
5134 */
5135 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00005136 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00005137 for(i=0; bOnce && i<nOrderBy; i++){
5138 if( MASKBIT(i) & obSat ) continue;
5139 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh93ec45d2013-06-17 18:20:48 +00005140 testcase( wctrlFlags & WHERE_GROUPBY );
5141 testcase( wctrlFlags & WHERE_DISTINCTBY );
drh4f402f22013-06-11 18:59:38 +00005142 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00005143 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00005144 if( pOBExpr->iTable!=iCur ) continue;
5145 if( pOBExpr->iColumn!=iColumn ) continue;
5146 if( iColumn>=0 ){
5147 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5148 if( !pColl ) pColl = db->pDfltColl;
5149 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
5150 }
drhe353ee32013-06-04 23:40:53 +00005151 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00005152 break;
5153 }
drhe353ee32013-06-04 23:40:53 +00005154 if( isMatch ){
drh7963b0e2013-06-17 21:37:40 +00005155 if( iColumn<0 ){
5156 testcase( distinctColumns==0 );
5157 distinctColumns = 1;
5158 }
drh7699d1c2013-06-04 12:42:29 +00005159 obSat |= MASKBIT(i);
5160 if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
drhe353ee32013-06-04 23:40:53 +00005161 /* Make sure the sort order is compatible in an ORDER BY clause.
5162 ** Sort order is irrelevant for a GROUP BY clause. */
drh7699d1c2013-06-04 12:42:29 +00005163 if( revSet ){
5164 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
5165 }else{
5166 rev = revIdx ^ pOrderBy->a[i].sortOrder;
5167 if( rev ) *pRevMask |= MASKBIT(iLoop);
5168 revSet = 1;
5169 }
5170 }
5171 }else{
5172 /* No match found */
drhbbbdc832013-10-22 18:01:40 +00005173 if( j==0 || j<nKeyCol ){
drh7963b0e2013-06-17 21:37:40 +00005174 testcase( isOrderDistinct!=0 );
5175 isOrderDistinct = 0;
5176 }
drh7699d1c2013-06-04 12:42:29 +00005177 break;
5178 }
5179 } /* end Loop over all index columns */
drh81186b42013-06-18 01:52:41 +00005180 if( distinctColumns ){
5181 testcase( isOrderDistinct==0 );
5182 isOrderDistinct = 1;
5183 }
drh7699d1c2013-06-04 12:42:29 +00005184 } /* end-if not one-row */
5185
5186 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00005187 if( isOrderDistinct ){
5188 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005189 for(i=0; i<nOrderBy; i++){
5190 Expr *p;
5191 if( MASKBIT(i) & obSat ) continue;
5192 p = pOrderBy->a[i].pExpr;
drh70d18342013-06-06 19:16:33 +00005193 if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00005194 obSat |= MASKBIT(i);
5195 }
drh0afb4232013-05-31 13:36:32 +00005196 }
drh319f6772013-05-14 15:31:07 +00005197 }
drhb8916be2013-06-14 02:51:48 +00005198 } /* End the loop over all WhereLoops from outer-most down to inner-most */
drh7699d1c2013-06-04 12:42:29 +00005199 if( obSat==obDone ) return 1;
drhe353ee32013-06-04 23:40:53 +00005200 if( !isOrderDistinct ) return 0;
drh319f6772013-05-14 15:31:07 +00005201 return -1;
drh6b7157b2013-05-10 02:00:35 +00005202}
5203
drhd15cb172013-05-21 19:23:10 +00005204#ifdef WHERETRACE_ENABLED
5205/* For debugging use only: */
5206static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
5207 static char zName[65];
5208 int i;
5209 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
5210 if( pLast ) zName[i++] = pLast->cId;
5211 zName[i] = 0;
5212 return zName;
5213}
5214#endif
5215
drh6b7157b2013-05-10 02:00:35 +00005216
5217/*
dan51576f42013-07-02 10:06:15 +00005218** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
drha18f3d22013-05-08 03:05:41 +00005219** attempts to find the lowest cost path that visits each WhereLoop
5220** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5221**
drhc7f0d222013-06-19 03:27:12 +00005222** Assume that the total number of output rows that will need to be sorted
5223** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
5224** costs if nRowEst==0.
5225**
drha18f3d22013-05-08 03:05:41 +00005226** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5227** error occurs.
5228*/
drhbf539c42013-10-05 18:16:02 +00005229static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
drh783dece2013-06-05 17:53:43 +00005230 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00005231 int nLoop; /* Number of terms in the join */
drhe1e2e9a2013-06-13 15:16:53 +00005232 Parse *pParse; /* Parsing context */
drha18f3d22013-05-08 03:05:41 +00005233 sqlite3 *db; /* The database connection */
5234 int iLoop; /* Loop counter over the terms of the join */
5235 int ii, jj; /* Loop counters */
drhfde1e6b2013-09-06 17:45:42 +00005236 int mxI = 0; /* Index of next entry to replace */
drhbf539c42013-10-05 18:16:02 +00005237 LogEst rCost; /* Cost of a path */
5238 LogEst nOut; /* Number of outputs */
5239 LogEst mxCost = 0; /* Maximum cost of a set of paths */
5240 LogEst mxOut = 0; /* Maximum nOut value on the set of paths */
5241 LogEst rSortCost; /* Cost to do a sort */
drha18f3d22013-05-08 03:05:41 +00005242 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
5243 WherePath *aFrom; /* All nFrom paths at the previous level */
5244 WherePath *aTo; /* The nTo best paths at the current level */
5245 WherePath *pFrom; /* An element of aFrom[] that we are working on */
5246 WherePath *pTo; /* An element of aTo[] that we are working on */
5247 WhereLoop *pWLoop; /* One of the WhereLoop objects */
5248 WhereLoop **pX; /* Used to divy up the pSpace memory */
5249 char *pSpace; /* Temporary memory used by this routine */
5250
drhe1e2e9a2013-06-13 15:16:53 +00005251 pParse = pWInfo->pParse;
5252 db = pParse->db;
drha18f3d22013-05-08 03:05:41 +00005253 nLoop = pWInfo->nLevel;
drhe1e2e9a2013-06-13 15:16:53 +00005254 /* TUNING: For simple queries, only the best path is tracked.
5255 ** For 2-way joins, the 5 best paths are followed.
5256 ** For joins of 3 or more tables, track the 10 best paths */
drhe9d935a2013-06-05 16:19:59 +00005257 mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00005258 assert( nLoop<=pWInfo->pTabList->nSrc );
drh3b48e8c2013-06-12 20:18:16 +00005259 WHERETRACE(0x002, ("---- begin solver\n"));
drha18f3d22013-05-08 03:05:41 +00005260
5261 /* Allocate and initialize space for aTo and aFrom */
5262 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
5263 pSpace = sqlite3DbMallocRaw(db, ii);
5264 if( pSpace==0 ) return SQLITE_NOMEM;
5265 aTo = (WherePath*)pSpace;
5266 aFrom = aTo+mxChoice;
5267 memset(aFrom, 0, sizeof(aFrom[0]));
5268 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00005269 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00005270 pFrom->aLoop = pX;
5271 }
5272
drhe1e2e9a2013-06-13 15:16:53 +00005273 /* Seed the search with a single WherePath containing zero WhereLoops.
5274 **
5275 ** TUNING: Do not let the number of iterations go above 25. If the cost
5276 ** of computing an automatic index is not paid back within the first 25
5277 ** rows, then do not use the automatic index. */
drhbf539c42013-10-05 18:16:02 +00005278 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00005279 nFrom = 1;
drh6b7157b2013-05-10 02:00:35 +00005280
5281 /* Precompute the cost of sorting the final result set, if the caller
5282 ** to sqlite3WhereBegin() was concerned about sorting */
drhb8a8e8a2013-06-10 19:12:39 +00005283 rSortCost = 0;
5284 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
drh6b7157b2013-05-10 02:00:35 +00005285 aFrom[0].isOrderedValid = 1;
5286 }else{
drh186ad8c2013-10-08 18:40:37 +00005287 /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
5288 ** number of output rows. The 48 is the expected size of a row to sort.
5289 ** FIXME: compute a better estimate of the 48 multiplier based on the
5290 ** result set expressions. */
drhb50596d2013-10-08 20:42:41 +00005291 rSortCost = nRowEst + estLog(nRowEst);
drh3b48e8c2013-06-12 20:18:16 +00005292 WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
drh6b7157b2013-05-10 02:00:35 +00005293 }
5294
5295 /* Compute successively longer WherePaths using the previous generation
5296 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5297 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00005298 for(iLoop=0; iLoop<nLoop; iLoop++){
5299 nTo = 0;
5300 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
5301 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
5302 Bitmask maskNew;
drh319f6772013-05-14 15:31:07 +00005303 Bitmask revMask = 0;
drh6b7157b2013-05-10 02:00:35 +00005304 u8 isOrderedValid = pFrom->isOrderedValid;
5305 u8 isOrdered = pFrom->isOrdered;
drha18f3d22013-05-08 03:05:41 +00005306 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5307 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00005308 /* At this point, pWLoop is a candidate to be the next loop.
5309 ** Compute its cost */
drhbf539c42013-10-05 18:16:02 +00005310 rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
5311 rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
drhfde1e6b2013-09-06 17:45:42 +00005312 nOut = pFrom->nRow + pWLoop->nOut;
drha18f3d22013-05-08 03:05:41 +00005313 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh6b7157b2013-05-10 02:00:35 +00005314 if( !isOrderedValid ){
drh4f402f22013-06-11 18:59:38 +00005315 switch( wherePathSatisfiesOrderBy(pWInfo,
5316 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
drh93ec45d2013-06-17 18:20:48 +00005317 iLoop, pWLoop, &revMask) ){
drh6b7157b2013-05-10 02:00:35 +00005318 case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
5319 isOrdered = 1;
5320 isOrderedValid = 1;
5321 break;
5322 case 0: /* No. pFrom+pWLoop will require a separate sort */
5323 isOrdered = 0;
5324 isOrderedValid = 1;
drhbf539c42013-10-05 18:16:02 +00005325 rCost = sqlite3LogEstAdd(rCost, rSortCost);
drh6b7157b2013-05-10 02:00:35 +00005326 break;
5327 default: /* Cannot tell yet. Try again on the next iteration */
5328 break;
5329 }
drh3a5ba8b2013-06-03 15:34:48 +00005330 }else{
5331 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00005332 }
5333 /* Check to see if pWLoop should be added to the mxChoice best so far */
5334 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00005335 if( pTo->maskLoop==maskNew
5336 && pTo->isOrderedValid==isOrderedValid
5337 && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
5338 (pTo->rCost>=rCost && pTo->nRow>=nOut))
5339 ){
drh7963b0e2013-06-17 21:37:40 +00005340 testcase( jj==nTo-1 );
drh6b7157b2013-05-10 02:00:35 +00005341 break;
5342 }
5343 }
drha18f3d22013-05-08 03:05:41 +00005344 if( jj>=nTo ){
drh7d9e7d82013-09-11 17:39:09 +00005345 if( nTo>=mxChoice && rCost>=mxCost ){
drhae70cf12013-05-31 15:18:46 +00005346#ifdef WHERETRACE_ENABLED
5347 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00005348 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
5349 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drhd15cb172013-05-21 19:23:10 +00005350 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5351 }
5352#endif
5353 continue;
5354 }
5355 /* Add a new Path to the aTo[] set */
drha18f3d22013-05-08 03:05:41 +00005356 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00005357 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00005358 jj = nTo++;
5359 }else{
drhd15cb172013-05-21 19:23:10 +00005360 /* New path replaces the prior worst to keep count below mxChoice */
drhfde1e6b2013-09-06 17:45:42 +00005361 jj = mxI;
drha18f3d22013-05-08 03:05:41 +00005362 }
5363 pTo = &aTo[jj];
drhd15cb172013-05-21 19:23:10 +00005364#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005365 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00005366 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
5367 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drhd15cb172013-05-21 19:23:10 +00005368 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5369 }
5370#endif
drhf204dac2013-05-08 03:22:07 +00005371 }else{
drhfde1e6b2013-09-06 17:45:42 +00005372 if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
drhd15cb172013-05-21 19:23:10 +00005373#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005374 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005375 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00005376 "Skip %s cost=%-3d,%3d order=%c",
5377 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drhd15cb172013-05-21 19:23:10 +00005378 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
drhfde1e6b2013-09-06 17:45:42 +00005379 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
5380 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00005381 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5382 }
5383#endif
drh7963b0e2013-06-17 21:37:40 +00005384 testcase( pTo->rCost==rCost );
drhd15cb172013-05-21 19:23:10 +00005385 continue;
5386 }
drh7963b0e2013-06-17 21:37:40 +00005387 testcase( pTo->rCost==rCost+1 );
drhd15cb172013-05-21 19:23:10 +00005388 /* A new and better score for a previously created equivalent path */
5389#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005390 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005391 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00005392 "Update %s cost=%-3d,%3d order=%c",
5393 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drhd15cb172013-05-21 19:23:10 +00005394 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
drhfde1e6b2013-09-06 17:45:42 +00005395 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
5396 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00005397 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5398 }
5399#endif
drha18f3d22013-05-08 03:05:41 +00005400 }
drh6b7157b2013-05-10 02:00:35 +00005401 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00005402 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00005403 pTo->revLoop = revMask;
drhfde1e6b2013-09-06 17:45:42 +00005404 pTo->nRow = nOut;
drha18f3d22013-05-08 03:05:41 +00005405 pTo->rCost = rCost;
drh6b7157b2013-05-10 02:00:35 +00005406 pTo->isOrderedValid = isOrderedValid;
5407 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00005408 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5409 pTo->aLoop[iLoop] = pWLoop;
5410 if( nTo>=mxChoice ){
drhfde1e6b2013-09-06 17:45:42 +00005411 mxI = 0;
drha18f3d22013-05-08 03:05:41 +00005412 mxCost = aTo[0].rCost;
drhfde1e6b2013-09-06 17:45:42 +00005413 mxOut = aTo[0].nRow;
drha18f3d22013-05-08 03:05:41 +00005414 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00005415 if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
5416 mxCost = pTo->rCost;
5417 mxOut = pTo->nRow;
5418 mxI = jj;
5419 }
drha18f3d22013-05-08 03:05:41 +00005420 }
5421 }
5422 }
5423 }
5424
drhd15cb172013-05-21 19:23:10 +00005425#ifdef WHERETRACE_ENABLED
5426 if( sqlite3WhereTrace>=2 ){
drha50ef112013-05-22 02:06:59 +00005427 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00005428 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drhb8a8e8a2013-06-10 19:12:39 +00005429 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
drha50ef112013-05-22 02:06:59 +00005430 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00005431 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
drh88da6442013-05-27 17:59:37 +00005432 if( pTo->isOrderedValid && pTo->isOrdered ){
5433 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5434 }else{
5435 sqlite3DebugPrintf("\n");
5436 }
drhf204dac2013-05-08 03:22:07 +00005437 }
5438 }
5439#endif
5440
drh6b7157b2013-05-10 02:00:35 +00005441 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00005442 pFrom = aTo;
5443 aTo = aFrom;
5444 aFrom = pFrom;
5445 nFrom = nTo;
5446 }
5447
drh75b93402013-05-31 20:43:57 +00005448 if( nFrom==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00005449 sqlite3ErrorMsg(pParse, "no query solution");
drh75b93402013-05-31 20:43:57 +00005450 sqlite3DbFree(db, pSpace);
5451 return SQLITE_ERROR;
5452 }
drha18f3d22013-05-08 03:05:41 +00005453
drh6b7157b2013-05-10 02:00:35 +00005454 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00005455 pFrom = aFrom;
5456 for(ii=1; ii<nFrom; ii++){
5457 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5458 }
5459 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00005460 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00005461 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00005462 WhereLevel *pLevel = pWInfo->a + iLoop;
5463 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
drhe217efc2013-06-12 03:48:41 +00005464 pLevel->iFrom = pWLoop->iTab;
drh7ba39a92013-05-30 17:43:19 +00005465 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00005466 }
drhfd636c72013-06-21 02:05:06 +00005467 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5468 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5469 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
drh4f402f22013-06-11 18:59:38 +00005470 && nRowEst
5471 ){
5472 Bitmask notUsed;
drh6457a352013-06-21 00:35:37 +00005473 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
drh93ec45d2013-06-17 18:20:48 +00005474 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
drh4f402f22013-06-11 18:59:38 +00005475 if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5476 }
drh6b7157b2013-05-10 02:00:35 +00005477 if( pFrom->isOrdered ){
drh4f402f22013-06-11 18:59:38 +00005478 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
5479 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5480 }else{
5481 pWInfo->bOBSat = 1;
5482 pWInfo->revMask = pFrom->revLoop;
5483 }
drh6b7157b2013-05-10 02:00:35 +00005484 }
drha50ef112013-05-22 02:06:59 +00005485 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00005486
5487 /* Free temporary memory and return success */
5488 sqlite3DbFree(db, pSpace);
5489 return SQLITE_OK;
5490}
drh94a11212004-09-25 13:12:14 +00005491
5492/*
drh60c96cd2013-06-09 17:21:25 +00005493** Most queries use only a single table (they are not joins) and have
5494** simple == constraints against indexed fields. This routine attempts
5495** to plan those simple cases using much less ceremony than the
5496** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5497** times for the common case.
5498**
5499** Return non-zero on success, if this query can be handled by this
5500** no-frills query planner. Return zero if this query needs the
5501** general-purpose query planner.
5502*/
drhb8a8e8a2013-06-10 19:12:39 +00005503static int whereShortCut(WhereLoopBuilder *pBuilder){
drh60c96cd2013-06-09 17:21:25 +00005504 WhereInfo *pWInfo;
5505 struct SrcList_item *pItem;
5506 WhereClause *pWC;
5507 WhereTerm *pTerm;
5508 WhereLoop *pLoop;
5509 int iCur;
drh92a121f2013-06-10 12:15:47 +00005510 int j;
drh60c96cd2013-06-09 17:21:25 +00005511 Table *pTab;
5512 Index *pIdx;
5513
5514 pWInfo = pBuilder->pWInfo;
drh5822d6f2013-06-10 23:30:09 +00005515 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
drh60c96cd2013-06-09 17:21:25 +00005516 assert( pWInfo->pTabList->nSrc>=1 );
5517 pItem = pWInfo->pTabList->a;
5518 pTab = pItem->pTab;
5519 if( IsVirtual(pTab) ) return 0;
5520 if( pItem->zIndex ) return 0;
5521 iCur = pItem->iCursor;
5522 pWC = &pWInfo->sWC;
5523 pLoop = pBuilder->pNew;
drh60c96cd2013-06-09 17:21:25 +00005524 pLoop->wsFlags = 0;
drh3b75ffa2013-06-10 14:56:25 +00005525 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
drh60c96cd2013-06-09 17:21:25 +00005526 if( pTerm ){
5527 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5528 pLoop->aLTerm[0] = pTerm;
5529 pLoop->nLTerm = 1;
5530 pLoop->u.btree.nEq = 1;
drhe1e2e9a2013-06-13 15:16:53 +00005531 /* TUNING: Cost of a rowid lookup is 10 */
drhbf539c42013-10-05 18:16:02 +00005532 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
drh60c96cd2013-06-09 17:21:25 +00005533 }else{
5534 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
dancd40abb2013-08-29 10:46:05 +00005535 assert( pLoop->aLTermSpace==pLoop->aLTerm );
5536 assert( ArraySize(pLoop->aLTermSpace)==4 );
5537 if( pIdx->onError==OE_None
5538 || pIdx->pPartIdxWhere!=0
drhbbbdc832013-10-22 18:01:40 +00005539 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
dancd40abb2013-08-29 10:46:05 +00005540 ) continue;
drhbbbdc832013-10-22 18:01:40 +00005541 for(j=0; j<pIdx->nKeyCol; j++){
drh3b75ffa2013-06-10 14:56:25 +00005542 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
drh60c96cd2013-06-09 17:21:25 +00005543 if( pTerm==0 ) break;
drh60c96cd2013-06-09 17:21:25 +00005544 pLoop->aLTerm[j] = pTerm;
5545 }
drhbbbdc832013-10-22 18:01:40 +00005546 if( j!=pIdx->nKeyCol ) continue;
drh92a121f2013-06-10 12:15:47 +00005547 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
drhec95c442013-10-23 01:57:32 +00005548 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
drh92a121f2013-06-10 12:15:47 +00005549 pLoop->wsFlags |= WHERE_IDX_ONLY;
5550 }
drh60c96cd2013-06-09 17:21:25 +00005551 pLoop->nLTerm = j;
5552 pLoop->u.btree.nEq = j;
5553 pLoop->u.btree.pIndex = pIdx;
drhe1e2e9a2013-06-13 15:16:53 +00005554 /* TUNING: Cost of a unique index lookup is 15 */
drhbf539c42013-10-05 18:16:02 +00005555 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
drh60c96cd2013-06-09 17:21:25 +00005556 break;
5557 }
5558 }
drh3b75ffa2013-06-10 14:56:25 +00005559 if( pLoop->wsFlags ){
drhbf539c42013-10-05 18:16:02 +00005560 pLoop->nOut = (LogEst)1;
drh3b75ffa2013-06-10 14:56:25 +00005561 pWInfo->a[0].pWLoop = pLoop;
5562 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
5563 pWInfo->a[0].iTabCur = iCur;
5564 pWInfo->nRowOut = 1;
drh4f402f22013-06-11 18:59:38 +00005565 if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
drh6457a352013-06-21 00:35:37 +00005566 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5567 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5568 }
drh3b75ffa2013-06-10 14:56:25 +00005569#ifdef SQLITE_DEBUG
5570 pLoop->cId = '0';
5571#endif
5572 return 1;
5573 }
5574 return 0;
drh60c96cd2013-06-09 17:21:25 +00005575}
5576
5577/*
drhe3184742002-06-19 14:27:05 +00005578** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00005579** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00005580** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00005581** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00005582** in order to complete the WHERE clause processing.
5583**
5584** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00005585**
5586** The basic idea is to do a nested loop, one loop for each table in
5587** the FROM clause of a select. (INSERT and UPDATE statements are the
5588** same as a SELECT with only a single table in the FROM clause.) For
5589** example, if the SQL is this:
5590**
5591** SELECT * FROM t1, t2, t3 WHERE ...;
5592**
5593** Then the code generated is conceptually like the following:
5594**
5595** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005596** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00005597** foreach row3 in t3 do /
5598** ...
5599** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005600** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00005601** end /
5602**
drh29dda4a2005-07-21 18:23:20 +00005603** Note that the loops might not be nested in the order in which they
5604** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00005605** use of indices. Note also that when the IN operator appears in
5606** the WHERE clause, it might result in additional nested loops for
5607** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00005608**
drhc27a1ce2002-06-14 20:58:45 +00005609** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00005610** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5611** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00005612** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00005613**
drhe6f85e72004-12-25 01:03:13 +00005614** The code that sqlite3WhereBegin() generates leaves the cursors named
5615** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00005616** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00005617** data from the various tables of the loop.
5618**
drhc27a1ce2002-06-14 20:58:45 +00005619** If the WHERE clause is empty, the foreach loops must each scan their
5620** entire tables. Thus a three-way join is an O(N^3) operation. But if
5621** the tables have indices and there are terms in the WHERE clause that
5622** refer to those indices, a complete table scan can be avoided and the
5623** code will run much faster. Most of the work of this routine is checking
5624** to see if there are indices that can be used to speed up the loop.
5625**
5626** Terms of the WHERE clause are also used to limit which rows actually
5627** make it to the "..." in the middle of the loop. After each "foreach",
5628** terms of the WHERE clause that use only terms in that loop and outer
5629** loops are evaluated and if false a jump is made around all subsequent
5630** inner loops (or around the "..." if the test occurs within the inner-
5631** most loop)
5632**
5633** OUTER JOINS
5634**
5635** An outer join of tables t1 and t2 is conceptally coded as follows:
5636**
5637** foreach row1 in t1 do
5638** flag = 0
5639** foreach row2 in t2 do
5640** start:
5641** ...
5642** flag = 1
5643** end
drhe3184742002-06-19 14:27:05 +00005644** if flag==0 then
5645** move the row2 cursor to a null row
5646** goto start
5647** fi
drhc27a1ce2002-06-14 20:58:45 +00005648** end
5649**
drhe3184742002-06-19 14:27:05 +00005650** ORDER BY CLAUSE PROCESSING
5651**
drh94433422013-07-01 11:05:50 +00005652** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
5653** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
drhe3184742002-06-19 14:27:05 +00005654** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00005655** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drh75897232000-05-29 14:26:00 +00005656*/
danielk19774adee202004-05-08 08:23:19 +00005657WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00005658 Parse *pParse, /* The parser context */
drh6457a352013-06-21 00:35:37 +00005659 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
danielk1977ed326d72004-11-16 15:50:19 +00005660 Expr *pWhere, /* The WHERE clause */
drh46ec5b62012-09-24 15:30:54 +00005661 ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
drh6457a352013-06-21 00:35:37 +00005662 ExprList *pResultSet, /* Result set of the query */
dan0efb72c2012-08-24 18:44:56 +00005663 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
5664 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00005665){
danielk1977be229652009-03-20 14:18:51 +00005666 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00005667 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00005668 WhereInfo *pWInfo; /* Will become the return value of this function */
5669 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00005670 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00005671 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00005672 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00005673 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drhfd636c72013-06-21 02:05:06 +00005674 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
drh9cd1c992012-09-25 20:43:35 +00005675 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00005676 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00005677 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00005678
drh56f1b992012-09-25 14:29:39 +00005679
5680 /* Variable initialization */
drhfd636c72013-06-21 02:05:06 +00005681 db = pParse->db;
drh1c8148f2013-05-04 20:25:23 +00005682 memset(&sWLB, 0, sizeof(sWLB));
drh1c8148f2013-05-04 20:25:23 +00005683 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00005684
drhfd636c72013-06-21 02:05:06 +00005685 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
5686 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
5687 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
5688 wctrlFlags &= ~WHERE_WANT_DISTINCT;
5689 }
5690
drh29dda4a2005-07-21 18:23:20 +00005691 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00005692 ** bits in a Bitmask
5693 */
drh67ae0cb2010-04-08 14:38:51 +00005694 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00005695 if( pTabList->nSrc>BMS ){
5696 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00005697 return 0;
5698 }
5699
drhc01a3c12009-12-16 22:10:49 +00005700 /* This function normally generates a nested loop for all tables in
5701 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
5702 ** only generate code for the first table in pTabList and assume that
5703 ** any cursors associated with subsequent tables are uninitialized.
5704 */
5705 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
5706
drh75897232000-05-29 14:26:00 +00005707 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00005708 ** return value. A single allocation is used to store the WhereInfo
5709 ** struct, the contents of WhereInfo.a[], the WhereClause structure
5710 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5711 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5712 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00005713 */
drhc01a3c12009-12-16 22:10:49 +00005714 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00005715 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00005716 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00005717 sqlite3DbFree(db, pWInfo);
5718 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00005719 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00005720 }
drhc01a3c12009-12-16 22:10:49 +00005721 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00005722 pWInfo->pParse = pParse;
5723 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00005724 pWInfo->pOrderBy = pOrderBy;
drh6457a352013-06-21 00:35:37 +00005725 pWInfo->pResultSet = pResultSet;
danielk19774adee202004-05-08 08:23:19 +00005726 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00005727 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00005728 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00005729 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00005730 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00005731 sWLB.pWC = &pWInfo->sWC;
drh1ac87e12013-07-18 14:50:56 +00005732 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
5733 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
drh60c96cd2013-06-09 17:21:25 +00005734 whereLoopInit(sWLB.pNew);
drhb8a8e8a2013-06-10 19:12:39 +00005735#ifdef SQLITE_DEBUG
5736 sWLB.pNew->cId = '*';
5737#endif
drh08192d52002-04-30 19:20:28 +00005738
drh111a6a72008-12-21 03:51:16 +00005739 /* Split the WHERE clause into separate subexpressions where each
5740 ** subexpression is separated by an AND operator.
5741 */
5742 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00005743 whereClauseInit(&pWInfo->sWC, pWInfo);
drh111a6a72008-12-21 03:51:16 +00005744 sqlite3ExprCodeConstants(pParse, pWhere);
drh39759742013-08-02 23:40:45 +00005745 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
drh5e128b22013-07-09 03:04:32 +00005746 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
drh111a6a72008-12-21 03:51:16 +00005747
drh08192d52002-04-30 19:20:28 +00005748 /* Special case: a WHERE clause that is constant. Evaluate the
5749 ** expression and either jump over all of the code or fall thru.
5750 */
drhc01a3c12009-12-16 22:10:49 +00005751 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
drh35573352008-01-08 23:54:25 +00005752 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
drhdf199a22002-06-14 22:38:41 +00005753 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00005754 }
drh75897232000-05-29 14:26:00 +00005755
drh4fe425a2013-06-12 17:08:06 +00005756 /* Special case: No FROM clause
5757 */
5758 if( nTabList==0 ){
5759 if( pOrderBy ) pWInfo->bOBSat = 1;
drh6457a352013-06-21 00:35:37 +00005760 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5761 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5762 }
drh4fe425a2013-06-12 17:08:06 +00005763 }
5764
drh42165be2008-03-26 14:56:34 +00005765 /* Assign a bit from the bitmask to every term in the FROM clause.
5766 **
5767 ** When assigning bitmask values to FROM clause cursors, it must be
5768 ** the case that if X is the bitmask for the N-th FROM clause term then
5769 ** the bitmask for all FROM clause terms to the left of the N-th term
5770 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
5771 ** its Expr.iRightJoinTable value to find the bitmask of the right table
5772 ** of the join. Subtracting one from the right table bitmask gives a
5773 ** bitmask for all tables to the left of the join. Knowing the bitmask
5774 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00005775 **
drhc01a3c12009-12-16 22:10:49 +00005776 ** Note that bitmasks are created for all pTabList->nSrc tables in
5777 ** pTabList, not just the first nTabList tables. nTabList is normally
5778 ** equal to pTabList->nSrc but might be shortened to 1 if the
5779 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00005780 */
drh9cd1c992012-09-25 20:43:35 +00005781 for(ii=0; ii<pTabList->nSrc; ii++){
5782 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005783 }
5784#ifndef NDEBUG
5785 {
5786 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00005787 for(ii=0; ii<pTabList->nSrc; ii++){
5788 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005789 assert( (m-1)==toTheLeft );
5790 toTheLeft |= m;
5791 }
5792 }
5793#endif
5794
drh29dda4a2005-07-21 18:23:20 +00005795 /* Analyze all of the subexpressions. Note that exprAnalyze() might
5796 ** add new virtual terms onto the end of the WHERE clause. We do not
5797 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00005798 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00005799 */
drh70d18342013-06-06 19:16:33 +00005800 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drh17435752007-08-16 04:30:38 +00005801 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00005802 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00005803 }
drh75897232000-05-29 14:26:00 +00005804
drh4f402f22013-06-11 18:59:38 +00005805 /* If the ORDER BY (or GROUP BY) clause contains references to general
5806 ** expressions, then we won't be able to satisfy it using indices, so
5807 ** go ahead and disable it now.
5808 */
drh6457a352013-06-21 00:35:37 +00005809 if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
drh4f402f22013-06-11 18:59:38 +00005810 for(ii=0; ii<pOrderBy->nExpr; ii++){
5811 Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
5812 if( pExpr->op!=TK_COLUMN ){
5813 pWInfo->pOrderBy = pOrderBy = 0;
5814 break;
drhe217efc2013-06-12 03:48:41 +00005815 }else if( pExpr->iColumn<0 ){
5816 break;
drh4f402f22013-06-11 18:59:38 +00005817 }
5818 }
5819 }
5820
drh6457a352013-06-21 00:35:37 +00005821 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5822 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
5823 /* The DISTINCT marking is pointless. Ignore it. */
drh4f402f22013-06-11 18:59:38 +00005824 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5825 }else if( pOrderBy==0 ){
drh6457a352013-06-21 00:35:37 +00005826 /* Try to ORDER BY the result set to make distinct processing easier */
drh4f402f22013-06-11 18:59:38 +00005827 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
drh6457a352013-06-21 00:35:37 +00005828 pWInfo->pOrderBy = pResultSet;
drh4f402f22013-06-11 18:59:38 +00005829 }
dan38cc40c2011-06-30 20:17:15 +00005830 }
5831
drhf1b5f5b2013-05-02 00:15:01 +00005832 /* Construct the WhereLoop objects */
drh3b48e8c2013-06-12 20:18:16 +00005833 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
drhb8a8e8a2013-06-10 19:12:39 +00005834 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
drh60c96cd2013-06-09 17:21:25 +00005835 rc = whereLoopAddAll(&sWLB);
5836 if( rc ) goto whereBeginError;
5837
5838 /* Display all of the WhereLoop objects if wheretrace is enabled */
drhd15cb172013-05-21 19:23:10 +00005839#ifdef WHERETRACE_ENABLED
drh60c96cd2013-06-09 17:21:25 +00005840 if( sqlite3WhereTrace ){
5841 WhereLoop *p;
drhfd636c72013-06-21 02:05:06 +00005842 int i;
drh60c96cd2013-06-09 17:21:25 +00005843 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5844 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
drhfd636c72013-06-21 02:05:06 +00005845 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5846 p->cId = zLabel[i%sizeof(zLabel)];
drh60c96cd2013-06-09 17:21:25 +00005847 whereLoopPrint(p, pTabList);
5848 }
5849 }
5850#endif
5851
drh4f402f22013-06-11 18:59:38 +00005852 wherePathSolver(pWInfo, 0);
drh60c96cd2013-06-09 17:21:25 +00005853 if( db->mallocFailed ) goto whereBeginError;
5854 if( pWInfo->pOrderBy ){
drhc7f0d222013-06-19 03:27:12 +00005855 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
drh60c96cd2013-06-09 17:21:25 +00005856 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00005857 }
5858 }
drh60c96cd2013-06-09 17:21:25 +00005859 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00005860 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00005861 }
drh81186b42013-06-18 01:52:41 +00005862 if( pParse->nErr || NEVER(db->mallocFailed) ){
drh75b93402013-05-31 20:43:57 +00005863 goto whereBeginError;
5864 }
drhd15cb172013-05-21 19:23:10 +00005865#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00005866 if( sqlite3WhereTrace ){
5867 int ii;
drh4f402f22013-06-11 18:59:38 +00005868 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
5869 if( pWInfo->bOBSat ){
5870 sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00005871 }
drh4f402f22013-06-11 18:59:38 +00005872 switch( pWInfo->eDistinct ){
5873 case WHERE_DISTINCT_UNIQUE: {
5874 sqlite3DebugPrintf(" DISTINCT=unique");
5875 break;
5876 }
5877 case WHERE_DISTINCT_ORDERED: {
5878 sqlite3DebugPrintf(" DISTINCT=ordered");
5879 break;
5880 }
5881 case WHERE_DISTINCT_UNORDERED: {
5882 sqlite3DebugPrintf(" DISTINCT=unordered");
5883 break;
5884 }
5885 }
5886 sqlite3DebugPrintf("\n");
drhfd636c72013-06-21 02:05:06 +00005887 for(ii=0; ii<pWInfo->nLevel; ii++){
drha18f3d22013-05-08 03:05:41 +00005888 whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
drhf1b5f5b2013-05-02 00:15:01 +00005889 }
5890 }
5891#endif
drhfd636c72013-06-21 02:05:06 +00005892 /* Attempt to omit tables from the join that do not effect the result */
drh1031bd92013-06-22 15:44:26 +00005893 if( pWInfo->nLevel>=2
5894 && pResultSet!=0
5895 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
5896 ){
drhfd636c72013-06-21 02:05:06 +00005897 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
drh67a5ec72013-09-03 14:03:47 +00005898 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
drhfd636c72013-06-21 02:05:06 +00005899 while( pWInfo->nLevel>=2 ){
drh9d5a5792013-06-28 13:43:33 +00005900 WhereTerm *pTerm, *pEnd;
drhfd636c72013-06-21 02:05:06 +00005901 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
drhbc71b1d2013-06-21 02:15:48 +00005902 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
5903 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
5904 && (pLoop->wsFlags & WHERE_ONEROW)==0
drhfd636c72013-06-21 02:05:06 +00005905 ){
drhfd636c72013-06-21 02:05:06 +00005906 break;
5907 }
drhbc71b1d2013-06-21 02:15:48 +00005908 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
drh9d5a5792013-06-28 13:43:33 +00005909 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
5910 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
5911 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
5912 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
5913 ){
5914 break;
5915 }
5916 }
5917 if( pTerm<pEnd ) break;
drhbc71b1d2013-06-21 02:15:48 +00005918 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
5919 pWInfo->nLevel--;
5920 nTabList--;
drhfd636c72013-06-21 02:05:06 +00005921 }
5922 }
drh3b48e8c2013-06-12 20:18:16 +00005923 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
drh8e23daf2013-06-11 13:30:04 +00005924 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
drhf1b5f5b2013-05-02 00:15:01 +00005925
drh08c88eb2008-04-10 13:33:18 +00005926 /* If the caller is an UPDATE or DELETE statement that is requesting
5927 ** to use a one-pass algorithm, determine if this is appropriate.
drh24b7fe92013-09-30 19:33:06 +00005928 ** The one-pass algorithm only works if the WHERE clause constrains
drh08c88eb2008-04-10 13:33:18 +00005929 ** the statement to update a single row.
5930 */
drh165be382008-12-05 02:36:33 +00005931 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh3b48e8c2013-06-12 20:18:16 +00005932 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
5933 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00005934 pWInfo->okOnePass = 1;
drh3b48e8c2013-06-12 20:18:16 +00005935 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
drh08c88eb2008-04-10 13:33:18 +00005936 }
drheb04de32013-05-10 15:16:30 +00005937
drh9012bcb2004-12-19 00:11:35 +00005938 /* Open all tables in the pTabList and any indices selected for
5939 ** searching those tables.
5940 */
drh8b307fb2010-04-06 15:57:05 +00005941 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00005942 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00005943 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00005944 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00005945 struct SrcList_item *pTabItem;
drh9012bcb2004-12-19 00:11:35 +00005946
drh29dda4a2005-07-21 18:23:20 +00005947 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005948 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00005949 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00005950 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00005951 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00005952 /* Do nothing */
5953 }else
drh9eff6162006-06-12 21:59:13 +00005954#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00005955 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00005956 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00005957 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00005958 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00005959 }else if( IsVirtual(pTab) ){
5960 /* noop */
drh9eff6162006-06-12 21:59:13 +00005961 }else
5962#endif
drh7ba39a92013-05-30 17:43:19 +00005963 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00005964 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drh08c88eb2008-04-10 13:33:18 +00005965 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
5966 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drh7963b0e2013-06-17 21:37:40 +00005967 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
5968 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
drhdd9930e2013-10-23 23:37:02 +00005969 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
danielk19779792eef2006-01-13 15:58:43 +00005970 Bitmask b = pTabItem->colUsed;
5971 int n = 0;
drh74161702006-02-24 02:53:49 +00005972 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00005973 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
5974 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00005975 assert( n<=pTab->nCol );
5976 }
danielk1977c00da102006-01-07 13:21:04 +00005977 }else{
5978 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00005979 }
drh7e47cb82013-05-31 17:55:27 +00005980 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00005981 Index *pIx = pLoop->u.btree.pIndex;
danielk1977b3bf5562006-01-10 17:58:23 +00005982 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
drhae70cf12013-05-31 15:18:46 +00005983 /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
5984 int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
danielk1977da184232006-01-05 11:34:32 +00005985 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00005986 assert( iIndexCur>=0 );
5987 sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00005988 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00005989 VdbeComment((v, "%s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00005990 }
danielk1977da184232006-01-05 11:34:32 +00005991 sqlite3CodeVerifySchema(pParse, iDb);
drh70d18342013-06-06 19:16:33 +00005992 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00005993 }
5994 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00005995 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00005996
drh29dda4a2005-07-21 18:23:20 +00005997 /* Generate the code to do the search. Each iteration of the for
5998 ** loop below generates code for a single nested loop of the VM
5999 ** program.
drh75897232000-05-29 14:26:00 +00006000 */
drhfe05af82005-07-21 03:14:59 +00006001 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00006002 for(ii=0; ii<nTabList; ii++){
6003 pLevel = &pWInfo->a[ii];
drhcc04afd2013-08-22 02:56:28 +00006004#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
6005 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
6006 constructAutomaticIndex(pParse, &pWInfo->sWC,
6007 &pTabList->a[pLevel->iFrom], notReady, pLevel);
6008 if( db->mallocFailed ) goto whereBeginError;
6009 }
6010#endif
drh9cd1c992012-09-25 20:43:35 +00006011 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
drhcc04afd2013-08-22 02:56:28 +00006012 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
drh70d18342013-06-06 19:16:33 +00006013 notReady = codeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00006014 pWInfo->iContinue = pLevel->addrCont;
drh75897232000-05-29 14:26:00 +00006015 }
drh7ec764a2005-07-21 03:48:20 +00006016
drh6fa978d2013-05-30 19:29:19 +00006017 /* Done. */
drh75897232000-05-29 14:26:00 +00006018 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00006019
6020 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00006021whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00006022 if( pWInfo ){
6023 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6024 whereInfoFree(db, pWInfo);
6025 }
drhe23399f2005-07-22 00:31:39 +00006026 return 0;
drh75897232000-05-29 14:26:00 +00006027}
6028
6029/*
drhc27a1ce2002-06-14 20:58:45 +00006030** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00006031** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00006032*/
danielk19774adee202004-05-08 08:23:19 +00006033void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00006034 Parse *pParse = pWInfo->pParse;
6035 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00006036 int i;
drh6b563442001-11-07 16:48:26 +00006037 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00006038 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00006039 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00006040 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00006041
drh9012bcb2004-12-19 00:11:35 +00006042 /* Generate loop termination code.
6043 */
drhceea3322009-04-23 13:22:42 +00006044 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00006045 for(i=pWInfo->nLevel-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00006046 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00006047 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00006048 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00006049 if( pLevel->op!=OP_Noop ){
drh66a51672008-01-03 00:01:23 +00006050 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
drhd1d38482008-10-07 23:46:38 +00006051 sqlite3VdbeChangeP5(v, pLevel->p5);
drh19a775c2000-06-05 18:54:46 +00006052 }
drh7ba39a92013-05-30 17:43:19 +00006053 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00006054 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00006055 int j;
drhb3190c12008-12-08 21:37:14 +00006056 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00006057 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00006058 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00006059 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drhb3190c12008-12-08 21:37:14 +00006060 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00006061 }
drh111a6a72008-12-21 03:51:16 +00006062 sqlite3DbFree(db, pLevel->u.in.aInLoop);
drhd99f7062002-06-08 23:25:08 +00006063 }
drhb3190c12008-12-08 21:37:14 +00006064 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhad2d8302002-05-24 20:31:36 +00006065 if( pLevel->iLeftJoin ){
6066 int addr;
drh3c84ddf2008-01-09 02:15:38 +00006067 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
drh7ba39a92013-05-30 17:43:19 +00006068 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6069 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
6070 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00006071 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
6072 }
drh76f4cfb2013-05-31 18:20:52 +00006073 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00006074 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00006075 }
drh336a5302009-04-24 15:46:21 +00006076 if( pLevel->op==OP_Return ){
6077 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
6078 }else{
6079 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
6080 }
drhd654be82005-09-20 17:42:23 +00006081 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00006082 }
drh19a775c2000-06-05 18:54:46 +00006083 }
drh9012bcb2004-12-19 00:11:35 +00006084
6085 /* The "break" point is here, just past the end of the outer loop.
6086 ** Set it.
6087 */
danielk19774adee202004-05-08 08:23:19 +00006088 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00006089
drh29dda4a2005-07-21 18:23:20 +00006090 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00006091 */
drhfd636c72013-06-21 02:05:06 +00006092 assert( pWInfo->nLevel<=pTabList->nSrc );
drhc01a3c12009-12-16 22:10:49 +00006093 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
danbfca6a42012-08-24 10:52:35 +00006094 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00006095 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00006096 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00006097 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00006098 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00006099 if( (pTab->tabFlags & TF_Ephemeral)==0
6100 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00006101 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00006102 ){
drh7ba39a92013-05-30 17:43:19 +00006103 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00006104 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00006105 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
6106 }
drh986b3872013-06-28 21:12:20 +00006107 if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){
drh6df2acd2008-12-28 16:55:25 +00006108 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
6109 }
drh9012bcb2004-12-19 00:11:35 +00006110 }
6111
drhf0030762013-06-14 13:27:01 +00006112 /* If this scan uses an index, make VDBE code substitutions to read data
6113 ** from the index instead of from the table where possible. In some cases
6114 ** this optimization prevents the table from ever being read, which can
6115 ** yield a significant performance boost.
drh9012bcb2004-12-19 00:11:35 +00006116 **
6117 ** Calls to the code generator in between sqlite3WhereBegin and
6118 ** sqlite3WhereEnd will have created code that references the table
6119 ** directly. This loop scans all that code looking for opcodes
6120 ** that reference the table and converts them into opcodes that
6121 ** reference the index.
6122 */
drh7ba39a92013-05-30 17:43:19 +00006123 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
6124 pIdx = pLoop->u.btree.pIndex;
6125 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00006126 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00006127 }
drh7ba39a92013-05-30 17:43:19 +00006128 if( pIdx && !db->mallocFailed ){
drh44156282013-10-23 22:23:03 +00006129 int k, last;
drh9012bcb2004-12-19 00:11:35 +00006130 VdbeOp *pOp;
drh9012bcb2004-12-19 00:11:35 +00006131
drh9012bcb2004-12-19 00:11:35 +00006132 last = sqlite3VdbeCurrentAddr(v);
drhcc04afd2013-08-22 02:56:28 +00006133 k = pLevel->addrBody;
6134 pOp = sqlite3VdbeGetOp(v, k);
6135 for(; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00006136 if( pOp->p1!=pLevel->iTabCur ) continue;
6137 if( pOp->opcode==OP_Column ){
drh44156282013-10-23 22:23:03 +00006138 i16 x = sqlite3ColumnOfIndex(pIdx, pOp->p2);
6139 if( x>=0 ){
6140 pOp->p2 = x;
6141 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00006142 }
drh44156282013-10-23 22:23:03 +00006143 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
drhf0863fe2005-06-12 21:35:51 +00006144 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00006145 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00006146 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00006147 }
6148 }
drh6b563442001-11-07 16:48:26 +00006149 }
drh19a775c2000-06-05 18:54:46 +00006150 }
drh9012bcb2004-12-19 00:11:35 +00006151
6152 /* Final cleanup
6153 */
drhf12cde52010-04-08 17:28:00 +00006154 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6155 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00006156 return;
6157}