blob: 135633e1cf4cc9f2c5d6ad1207f5c4a5bebd128c [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))
mlcreech3a00f902008-03-04 17:45:01 +000030# define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
drhd15cb172013-05-21 19:23:10 +000031# define WHERETRACE_ENABLED 1
drh51147ba2005-07-23 22:59:55 +000032#else
drh4f0c5872007-03-26 22:05:01 +000033# define WHERETRACE(X)
drh51147ba2005-07-23 22:59:55 +000034#endif
35
drh0fcef5e2005-07-19 17:38:22 +000036/* Forward reference
37*/
38typedef struct WhereClause WhereClause;
drh111a6a72008-12-21 03:51:16 +000039typedef struct WhereMaskSet WhereMaskSet;
drh700a2262008-12-17 19:22:15 +000040typedef struct WhereOrInfo WhereOrInfo;
41typedef struct WhereAndInfo WhereAndInfo;
drh6f328482013-06-05 23:39:34 +000042typedef struct WhereLevel WhereLevel;
drhf1b5f5b2013-05-02 00:15:01 +000043typedef struct WhereLoop WhereLoop;
44typedef struct WherePath WherePath;
45typedef struct WhereTerm WhereTerm;
drh1c8148f2013-05-04 20:25:23 +000046typedef struct WhereLoopBuilder WhereLoopBuilder;
47typedef struct WhereScan WhereScan;
drh4efc9292013-06-06 23:02:03 +000048typedef float WhereCost;
drhf1b5f5b2013-05-02 00:15:01 +000049
50/*
drh6f328482013-06-05 23:39:34 +000051** For each nested loop in a WHERE clause implementation, the WhereInfo
52** structure contains a single instance of this structure. This structure
53** is intended to be private to the where.c module and should not be
54** access or modified by other modules.
55**
56** The pIdxInfo field is used to help pick the best index on a
57** virtual table. The pIdxInfo pointer contains indexing
58** information for the i-th table in the FROM clause before reordering.
59** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
60** All other information in the i-th WhereLevel object for the i-th table
61** after FROM clause ordering.
62*/
63struct WhereLevel {
64 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
65 int iTabCur; /* The VDBE cursor used to access the table */
66 int iIdxCur; /* The VDBE cursor used to access pIdx */
67 int addrBrk; /* Jump here to break out of the loop */
68 int addrNxt; /* Jump here to start the next IN combination */
69 int addrCont; /* Jump here to continue with the next loop cycle */
70 int addrFirst; /* First instruction of interior of the loop */
71 u8 iFrom; /* FIXME: Which entry in the FROM clause */
72 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
73 int p1, p2; /* Operands of the opcode used to ends the loop */
74 union { /* Information that depends on plan.wsFlags */
75 struct {
76 int nIn; /* Number of entries in aInLoop[] */
77 struct InLoop {
78 int iCur; /* The VDBE cursor used by this IN operator */
79 int addrInTop; /* Top of the IN loop */
80 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
81 } *aInLoop; /* Information about each nested IN operator */
82 } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
83 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
84 } u;
85 struct WhereLoop *pWLoop; /* The selected WhereLoop object */
86};
87
88/*
drhf1b5f5b2013-05-02 00:15:01 +000089** Each instance of this object represents a way of evaluating one
90** term of a join. The WhereClause object holds a table of these
drh6b7157b2013-05-10 02:00:35 +000091** objects using (maskSelf,prereq,) as the primary key. Note that the
drhf1b5f5b2013-05-02 00:15:01 +000092** same join term might have multiple associated WhereLoop objects.
93*/
94struct WhereLoop {
95 Bitmask prereq; /* Bitmask of other loops that must run first */
drha18f3d22013-05-08 03:05:41 +000096 Bitmask maskSelf; /* Bitmask identifying table iTab */
drhd15cb172013-05-21 19:23:10 +000097#ifdef SQLITE_DEBUG
98 char cId; /* Symbolic ID of this loop for debugging use */
99#endif
drh7ba39a92013-05-30 17:43:19 +0000100 u8 iTab; /* Position in FROM clause of table for this loop */
drh23f98da2013-05-21 15:52:07 +0000101 u8 iSortIdx; /* Sorting index number. 0==None */
drh4efc9292013-06-06 23:02:03 +0000102 WhereCost rSetup; /* One-time setup cost (ex: create transient index) */
103 WhereCost rRun; /* Cost of running each loop */
104 WhereCost nOut; /* Estimated number of output rows */
drh5346e952013-05-08 14:14:26 +0000105 union {
106 struct { /* Information for internal btree tables */
107 int nEq; /* Number of equality constraints */
108 Index *pIndex; /* Index used, or NULL */
109 } btree;
drh6b7157b2013-05-10 02:00:35 +0000110 struct { /* Information for virtual tables */
drh5346e952013-05-08 14:14:26 +0000111 int idxNum; /* Index number */
drh6b7157b2013-05-10 02:00:35 +0000112 u8 needFree; /* True if sqlite3_free(idxStr) is needed */
113 u8 isOrdered; /* True if satisfies ORDER BY */
drh3bd26f02013-05-24 14:52:03 +0000114 u16 omitMask; /* Terms that may be omitted */
drh5346e952013-05-08 14:14:26 +0000115 char *idxStr; /* Index identifier string */
116 } vtab;
117 } u;
drha2014152013-06-07 00:29:23 +0000118 u32 wsFlags; /* WHERE_* flags describing the plan */
119 u16 nLTerm; /* Number of entries in aLTerm[] */
120 /**** whereLoopXfer() copies fields above ***********************/
121# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
122 u16 nLSlot; /* Number of slots allocated for aLTerm[] */
drh4efc9292013-06-06 23:02:03 +0000123 WhereTerm **aLTerm; /* WhereTerms used */
drhf1b5f5b2013-05-02 00:15:01 +0000124 WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
drh4efc9292013-06-06 23:02:03 +0000125 WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
drhf1b5f5b2013-05-02 00:15:01 +0000126};
127
drh4efc9292013-06-06 23:02:03 +0000128/* Forward declaration of methods */
129static int whereLoopResize(sqlite3*, WhereLoop*, int);
130
drhf1b5f5b2013-05-02 00:15:01 +0000131/*
132** Each instance of this object holds a sequence of WhereLoop objects
133** that implement some or all of the entire query plan.
134*/
135struct WherePath {
136 Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
drh319f6772013-05-14 15:31:07 +0000137 Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
drh4efc9292013-06-06 23:02:03 +0000138 WhereCost nRow; /* Estimated number of rows generated by this path */
139 WhereCost rCost; /* Total cost of this path */
drh6b7157b2013-05-10 02:00:35 +0000140 u8 isOrdered; /* True if this path satisfies ORDER BY */
141 u8 isOrderedValid; /* True if the isOrdered field is valid */
drha18f3d22013-05-08 03:05:41 +0000142 WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
drhf1b5f5b2013-05-02 00:15:01 +0000143};
drh0aa74ed2005-07-16 13:33:20 +0000144
145/*
drh75897232000-05-29 14:26:00 +0000146** The query generator uses an array of instances of this structure to
147** help it analyze the subexpressions of the WHERE clause. Each WHERE
drh61495262009-04-22 15:32:59 +0000148** clause subexpression is separated from the others by AND operators,
149** usually, or sometimes subexpressions separated by OR.
drh51669862004-12-18 18:40:26 +0000150**
drh0fcef5e2005-07-19 17:38:22 +0000151** All WhereTerms are collected into a single WhereClause structure.
152** The following identity holds:
drh51669862004-12-18 18:40:26 +0000153**
drh0fcef5e2005-07-19 17:38:22 +0000154** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
drh51669862004-12-18 18:40:26 +0000155**
drh0fcef5e2005-07-19 17:38:22 +0000156** When a term is of the form:
157**
158** X <op> <expr>
159**
160** where X is a column name and <op> is one of certain operators,
drh700a2262008-12-17 19:22:15 +0000161** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
162** cursor number and column number for X. WhereTerm.eOperator records
drh51147ba2005-07-23 22:59:55 +0000163** the <op> using a bitmask encoding defined by WO_xxx below. The
164** use of a bitmask encoding for the operator allows us to search
165** quickly for terms that match any of several different operators.
drh0fcef5e2005-07-19 17:38:22 +0000166**
drh700a2262008-12-17 19:22:15 +0000167** A WhereTerm might also be two or more subterms connected by OR:
168**
169** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
170**
171** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
172** and the WhereTerm.u.pOrInfo field points to auxiliary information that
173** is collected about the
174**
175** If a term in the WHERE clause does not match either of the two previous
176** categories, then eOperator==0. The WhereTerm.pExpr field is still set
177** to the original subexpression content and wtFlags is set up appropriately
178** but no other fields in the WhereTerm object are meaningful.
179**
180** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
drh111a6a72008-12-21 03:51:16 +0000181** but they do so indirectly. A single WhereMaskSet structure translates
drh51669862004-12-18 18:40:26 +0000182** cursor number into bits and the translated bit is stored in the prereq
183** fields. The translation is used in order to maximize the number of
184** bits that will fit in a Bitmask. The VDBE cursor numbers might be
185** spread out over the non-negative integers. For example, the cursor
drh111a6a72008-12-21 03:51:16 +0000186** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
drh51669862004-12-18 18:40:26 +0000187** translates these sparse cursor numbers into consecutive integers
188** beginning with 0 in order to make the best possible use of the available
189** bits in the Bitmask. So, in the example above, the cursor numbers
190** would be mapped into integers 0 through 7.
drh6a1e0712008-12-05 15:24:15 +0000191**
192** The number of terms in a join is limited by the number of bits
193** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
194** is only able to process joins with 64 or fewer tables.
drh75897232000-05-29 14:26:00 +0000195*/
drh0aa74ed2005-07-16 13:33:20 +0000196struct WhereTerm {
drh165be382008-12-05 02:36:33 +0000197 Expr *pExpr; /* Pointer to the subexpression that is this term */
drhec1724e2008-12-09 01:32:03 +0000198 int iParent; /* Disable pWC->a[iParent] when this term disabled */
199 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
drh700a2262008-12-17 19:22:15 +0000200 union {
201 int leftColumn; /* Column number of X in "X <op> <expr>" */
drh7a5bcc02013-01-16 17:08:58 +0000202 WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
203 WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
drh700a2262008-12-17 19:22:15 +0000204 } u;
drhb52076c2006-01-23 13:22:09 +0000205 u16 eOperator; /* A WO_xx value describing <op> */
drh165be382008-12-05 02:36:33 +0000206 u8 wtFlags; /* TERM_xxx bit flags. See below */
drh45b1ee42005-08-02 17:48:22 +0000207 u8 nChild; /* Number of children that must disable us */
drh0fcef5e2005-07-19 17:38:22 +0000208 WhereClause *pWC; /* The clause this term is part of */
drh165be382008-12-05 02:36:33 +0000209 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
210 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
drh75897232000-05-29 14:26:00 +0000211};
212
213/*
drh165be382008-12-05 02:36:33 +0000214** Allowed values of WhereTerm.wtFlags
drh0aa74ed2005-07-16 13:33:20 +0000215*/
drh633e6d52008-07-28 19:34:53 +0000216#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
drh6c30be82005-07-29 15:10:17 +0000217#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
218#define TERM_CODED 0x04 /* This term is already coded */
drh45b1ee42005-08-02 17:48:22 +0000219#define TERM_COPIED 0x08 /* Has a child */
drh700a2262008-12-17 19:22:15 +0000220#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
221#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
222#define TERM_OR_OK 0x40 /* Used during OR-clause processing */
drhfaacf172011-08-12 01:51:45 +0000223#ifdef SQLITE_ENABLE_STAT3
drh59b61882011-02-11 02:43:14 +0000224# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
225#else
drhd3ed7342011-09-21 00:09:41 +0000226# define TERM_VNULL 0x00 /* Disabled if not using stat3 */
drh59b61882011-02-11 02:43:14 +0000227#endif
drh0aa74ed2005-07-16 13:33:20 +0000228
229/*
drh1c8148f2013-05-04 20:25:23 +0000230** An instance of the WhereScan object is used as an iterator for locating
231** terms in the WHERE clause that are useful to the query planner.
232*/
233struct WhereScan {
234 WhereTerm *pCurrent; /* Most recent match */
235 WhereClause *pOrigWC; /* Original, innermost WhereClause */
236 WhereClause *pWC; /* WhereClause currently being scanned */
drh7ba39a92013-05-30 17:43:19 +0000237 char *zCollName; /* Required collating sequence, if not NULL */
drh1c8148f2013-05-04 20:25:23 +0000238 char idxaff; /* Must match this affinity, if zCollName!=NULL */
239 unsigned char nEquiv; /* Number of entries in aEquiv[] */
240 unsigned char iEquiv; /* Next unused slot in aEquiv[] */
241 u32 opMask; /* Acceptable operators */
242 int k; /* Resume scanning at this->pWC->a[this->k] */
243 int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
244};
245
246/*
drh0aa74ed2005-07-16 13:33:20 +0000247** An instance of the following structure holds all information about a
248** WHERE clause. Mostly this is a container for one or more WhereTerms.
drh8871ef52011-10-07 13:33:10 +0000249**
250** Explanation of pOuter: For a WHERE clause of the form
251**
252** a AND ((b AND c) OR (d AND e)) AND f
253**
254** There are separate WhereClause objects for the whole clause and for
255** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
256** subclauses points to the WhereClause object for the whole clause.
drh0aa74ed2005-07-16 13:33:20 +0000257*/
drh0aa74ed2005-07-16 13:33:20 +0000258struct WhereClause {
drh70d18342013-06-06 19:16:33 +0000259 WhereInfo *pWInfo; /* WHERE clause processing context */
drh8871ef52011-10-07 13:33:10 +0000260 WhereClause *pOuter; /* Outer conjunction */
drh29435252008-12-28 18:35:08 +0000261 u8 op; /* Split operator. TK_AND or TK_OR */
drh0aa74ed2005-07-16 13:33:20 +0000262 int nTerm; /* Number of terms */
263 int nSlot; /* Number of entries in a[] */
drh51147ba2005-07-23 22:59:55 +0000264 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
drh50d654d2009-06-03 01:24:54 +0000265#if defined(SQLITE_SMALL_STACK)
266 WhereTerm aStatic[1]; /* Initial static space for a[] */
267#else
268 WhereTerm aStatic[8]; /* Initial static space for a[] */
269#endif
drhe23399f2005-07-22 00:31:39 +0000270};
271
272/*
drh700a2262008-12-17 19:22:15 +0000273** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
274** a dynamically allocated instance of the following structure.
275*/
276struct WhereOrInfo {
drh111a6a72008-12-21 03:51:16 +0000277 WhereClause wc; /* Decomposition into subterms */
drh1a58fe02008-12-20 02:06:13 +0000278 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
drh700a2262008-12-17 19:22:15 +0000279};
280
281/*
282** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
283** a dynamically allocated instance of the following structure.
284*/
285struct WhereAndInfo {
drh29435252008-12-28 18:35:08 +0000286 WhereClause wc; /* The subexpression broken out */
drh700a2262008-12-17 19:22:15 +0000287};
288
289/*
drh6a3ea0e2003-05-02 14:32:12 +0000290** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000291** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000292**
293** The VDBE cursor numbers are small integers contained in
294** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
295** clause, the cursor numbers might not begin with 0 and they might
296** contain gaps in the numbering sequence. But we want to make maximum
297** use of the bits in our bitmasks. This structure provides a mapping
298** from the sparse cursor numbers into consecutive integers beginning
299** with 0.
300**
drh111a6a72008-12-21 03:51:16 +0000301** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
drh51669862004-12-18 18:40:26 +0000302** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
303**
304** For example, if the WHERE clause expression used these VDBE
drh111a6a72008-12-21 03:51:16 +0000305** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
drh51669862004-12-18 18:40:26 +0000306** would map those cursor numbers into bits 0 through 5.
307**
308** Note that the mapping is not necessarily ordered. In the example
309** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
310** 57->5, 73->4. Or one of 719 other combinations might be used. It
311** does not really matter. What is important is that sparse cursor
312** numbers all get mapped into bit numbers that begin with 0 and contain
313** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000314*/
drh111a6a72008-12-21 03:51:16 +0000315struct WhereMaskSet {
drh1398ad32005-01-19 23:24:50 +0000316 int n; /* Number of assigned cursor values */
danielk197723432972008-11-17 16:42:00 +0000317 int ix[BMS]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000318};
319
drh111a6a72008-12-21 03:51:16 +0000320/*
drh1c8148f2013-05-04 20:25:23 +0000321** This object is a factory for WhereLoop objects for a particular query.
322*/
323struct WhereLoopBuilder {
324 WhereInfo *pWInfo; /* Information about this WHERE */
drh1c8148f2013-05-04 20:25:23 +0000325 WhereClause *pWC; /* WHERE clause terms */
drh1c8148f2013-05-04 20:25:23 +0000326 ExprList *pOrderBy; /* ORDER BY clause */
327 WhereLoop *pNew; /* Template WhereLoop */
drhcf8fa7a2013-05-10 20:26:22 +0000328 WhereLoop *pBest; /* If non-NULL, store single best loop here */
drh1c8148f2013-05-04 20:25:23 +0000329};
330
331/*
drh70d18342013-06-06 19:16:33 +0000332** The WHERE clause processing routine has two halves. The
333** first part does the start of the WHERE loop and the second
334** half does the tail of the WHERE loop. An instance of
335** this structure is returned by the first half and passed
336** into the second half to give some continuity.
337*/
338struct WhereInfo {
339 Parse *pParse; /* Parsing and code generating context */
340 SrcList *pTabList; /* List of tables in the join */
341 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
342 ExprList *pDistinct; /* DISTINCT ON values, or NULL */
343 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
344 u16 nOBSat; /* Number of ORDER BY terms satisfied by indices */
345 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
346 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
347 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
348 u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
349 int iTop; /* The very beginning of the WHERE loop */
350 int iContinue; /* Jump here to continue with next record */
351 int iBreak; /* Jump here to break out of the loop */
352 int nLevel; /* Number of nested loop */
353 WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
354 WhereClause sWC; /* Decomposition of the WHERE clause */
355 WhereLoop *pLoops; /* List of all WhereLoop objects */
drh4efc9292013-06-06 23:02:03 +0000356 WhereCost savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
357 WhereCost nRowOut; /* Estimated number of output rows */
drh70d18342013-06-06 19:16:33 +0000358 WhereLevel a[1]; /* Information about each nest loop in WHERE */
359};
360
361/*
drh51147ba2005-07-23 22:59:55 +0000362** Bitmasks for the operators that indices are able to exploit. An
363** OR-ed combination of these values can be used when searching for
364** terms in the where clause.
365*/
drh165be382008-12-05 02:36:33 +0000366#define WO_IN 0x001
367#define WO_EQ 0x002
drh51147ba2005-07-23 22:59:55 +0000368#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
369#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
370#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
371#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
drh165be382008-12-05 02:36:33 +0000372#define WO_MATCH 0x040
373#define WO_ISNULL 0x080
drh700a2262008-12-17 19:22:15 +0000374#define WO_OR 0x100 /* Two or more OR-connected terms */
375#define WO_AND 0x200 /* Two or more AND-connected terms */
drh7a5bcc02013-01-16 17:08:58 +0000376#define WO_EQUIV 0x400 /* Of the form A==B, both columns */
drh534230c2011-01-22 00:10:45 +0000377#define WO_NOOP 0x800 /* This term does not restrict search space */
drh51147ba2005-07-23 22:59:55 +0000378
drhec1724e2008-12-09 01:32:03 +0000379#define WO_ALL 0xfff /* Mask of all possible WO_* values */
drh1a58fe02008-12-20 02:06:13 +0000380#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
drhec1724e2008-12-09 01:32:03 +0000381
drh51147ba2005-07-23 22:59:55 +0000382/*
drh700a2262008-12-17 19:22:15 +0000383** Value for wsFlags returned by bestIndex() and stored in
384** WhereLevel.wsFlags. These flags determine which search
385** strategies are appropriate.
drh51147ba2005-07-23 22:59:55 +0000386*/
drh6fa978d2013-05-30 19:29:19 +0000387#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR or x IN (...) or x IS NULL */
388#define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
389#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
390#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
drhef71c1f2013-06-04 12:58:02 +0000391#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
drh6fa978d2013-05-30 19:29:19 +0000392#define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
393#define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
394#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
395#define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
396#define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
397#define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
398#define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
399#define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
drh7699d1c2013-06-04 12:42:29 +0000400#define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
drh6fa978d2013-05-30 19:29:19 +0000401#define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
402#define WHERE_TEMP_INDEX 0x00004000 /* Uses an ephemeral index */
403#define WHERE_COVER_SCAN 0x00008000 /* Full scan of a covering index */
drh51147ba2005-07-23 22:59:55 +0000404
405/*
drh6f328482013-06-05 23:39:34 +0000406** Return the estimated number of output rows from a WHERE clause
407*/
408double sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
drh4efc9292013-06-06 23:02:03 +0000409 return (double)pWInfo->nRowOut;
drh6f328482013-06-05 23:39:34 +0000410}
411
412/*
413** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
414** WHERE clause returns outputs for DISTINCT processing.
415*/
416int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
417 return pWInfo->eDistinct;
418}
419
420/*
421** Return TRUE if the WHERE clause returns rows in ORDER BY order.
422** Return FALSE if the output needs to be sorted.
423*/
424int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
425 return pWInfo->nOBSat>0;
426}
427
428/*
429** Return the VDBE address or label to jump to in order to continue
430** immediately with the next row of a WHERE clause.
431*/
432int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
433 return pWInfo->iContinue;
434}
435
436/*
437** Return the VDBE address or label to jump to in order to break
438** out of a WHERE loop.
439*/
440int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
441 return pWInfo->iBreak;
442}
443
444/*
445** Return TRUE if an UPDATE or DELETE statement can operate directly on
446** the rowids returned by a WHERE clause. Return FALSE if doing an
447** UPDATE or DELETE might change subsequent WHERE clause results.
448*/
449int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
450 return pWInfo->okOnePass;
451}
452
453/*
drh0aa74ed2005-07-16 13:33:20 +0000454** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000455*/
drh7b4fc6a2007-02-06 13:26:32 +0000456static void whereClauseInit(
457 WhereClause *pWC, /* The WhereClause to be initialized */
drh70d18342013-06-06 19:16:33 +0000458 WhereInfo *pWInfo /* The WHERE processing context */
drh7b4fc6a2007-02-06 13:26:32 +0000459){
drh70d18342013-06-06 19:16:33 +0000460 pWC->pWInfo = pWInfo;
drh8871ef52011-10-07 13:33:10 +0000461 pWC->pOuter = 0;
drh0aa74ed2005-07-16 13:33:20 +0000462 pWC->nTerm = 0;
drhcad651e2007-04-20 12:22:01 +0000463 pWC->nSlot = ArraySize(pWC->aStatic);
drh0aa74ed2005-07-16 13:33:20 +0000464 pWC->a = pWC->aStatic;
465}
466
drh700a2262008-12-17 19:22:15 +0000467/* Forward reference */
468static void whereClauseClear(WhereClause*);
469
470/*
471** Deallocate all memory associated with a WhereOrInfo object.
472*/
473static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000474 whereClauseClear(&p->wc);
475 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000476}
477
478/*
479** Deallocate all memory associated with a WhereAndInfo object.
480*/
481static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000482 whereClauseClear(&p->wc);
483 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000484}
485
drh0aa74ed2005-07-16 13:33:20 +0000486/*
487** Deallocate a WhereClause structure. The WhereClause structure
488** itself is not freed. This routine is the inverse of whereClauseInit().
489*/
490static void whereClauseClear(WhereClause *pWC){
491 int i;
492 WhereTerm *a;
drh70d18342013-06-06 19:16:33 +0000493 sqlite3 *db = pWC->pWInfo->pParse->db;
drh0aa74ed2005-07-16 13:33:20 +0000494 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
drh165be382008-12-05 02:36:33 +0000495 if( a->wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000496 sqlite3ExprDelete(db, a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000497 }
drh700a2262008-12-17 19:22:15 +0000498 if( a->wtFlags & TERM_ORINFO ){
499 whereOrInfoDelete(db, a->u.pOrInfo);
500 }else if( a->wtFlags & TERM_ANDINFO ){
501 whereAndInfoDelete(db, a->u.pAndInfo);
502 }
drh0aa74ed2005-07-16 13:33:20 +0000503 }
504 if( pWC->a!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000505 sqlite3DbFree(db, pWC->a);
drh0aa74ed2005-07-16 13:33:20 +0000506 }
507}
508
509/*
drh6a1e0712008-12-05 15:24:15 +0000510** Add a single new WhereTerm entry to the WhereClause object pWC.
511** The new WhereTerm object is constructed from Expr p and with wtFlags.
512** The index in pWC->a[] of the new WhereTerm is returned on success.
513** 0 is returned if the new WhereTerm could not be added due to a memory
514** allocation error. The memory allocation failure will be recorded in
515** the db->mallocFailed flag so that higher-level functions can detect it.
516**
517** This routine will increase the size of the pWC->a[] array as necessary.
drh9eb20282005-08-24 03:52:18 +0000518**
drh165be382008-12-05 02:36:33 +0000519** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
drh6a1e0712008-12-05 15:24:15 +0000520** for freeing the expression p is assumed by the WhereClause object pWC.
521** This is true even if this routine fails to allocate a new WhereTerm.
drhb63a53d2007-03-31 01:34:44 +0000522**
drh9eb20282005-08-24 03:52:18 +0000523** WARNING: This routine might reallocate the space used to store
drh909626d2008-05-30 14:58:37 +0000524** WhereTerms. All pointers to WhereTerms should be invalidated after
drh9eb20282005-08-24 03:52:18 +0000525** calling this routine. Such pointers may be reinitialized by referencing
526** the pWC->a[] array.
drh0aa74ed2005-07-16 13:33:20 +0000527*/
drhec1724e2008-12-09 01:32:03 +0000528static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
drh0aa74ed2005-07-16 13:33:20 +0000529 WhereTerm *pTerm;
drh9eb20282005-08-24 03:52:18 +0000530 int idx;
drhe9cdcea2010-07-22 22:40:03 +0000531 testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
drh0aa74ed2005-07-16 13:33:20 +0000532 if( pWC->nTerm>=pWC->nSlot ){
533 WhereTerm *pOld = pWC->a;
drh70d18342013-06-06 19:16:33 +0000534 sqlite3 *db = pWC->pWInfo->pParse->db;
drh633e6d52008-07-28 19:34:53 +0000535 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
drhb63a53d2007-03-31 01:34:44 +0000536 if( pWC->a==0 ){
drh165be382008-12-05 02:36:33 +0000537 if( wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000538 sqlite3ExprDelete(db, p);
drhb63a53d2007-03-31 01:34:44 +0000539 }
drhf998b732007-11-26 13:36:00 +0000540 pWC->a = pOld;
drhb63a53d2007-03-31 01:34:44 +0000541 return 0;
542 }
drh0aa74ed2005-07-16 13:33:20 +0000543 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
544 if( pOld!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000545 sqlite3DbFree(db, pOld);
drh0aa74ed2005-07-16 13:33:20 +0000546 }
drh6a1e0712008-12-05 15:24:15 +0000547 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
drh0aa74ed2005-07-16 13:33:20 +0000548 }
drh6a1e0712008-12-05 15:24:15 +0000549 pTerm = &pWC->a[idx = pWC->nTerm++];
drh7ee751d2012-12-19 15:53:51 +0000550 pTerm->pExpr = sqlite3ExprSkipCollate(p);
drh165be382008-12-05 02:36:33 +0000551 pTerm->wtFlags = wtFlags;
drh0fcef5e2005-07-19 17:38:22 +0000552 pTerm->pWC = pWC;
drh45b1ee42005-08-02 17:48:22 +0000553 pTerm->iParent = -1;
drh9eb20282005-08-24 03:52:18 +0000554 return idx;
drh0aa74ed2005-07-16 13:33:20 +0000555}
drh75897232000-05-29 14:26:00 +0000556
557/*
drh51669862004-12-18 18:40:26 +0000558** This routine identifies subexpressions in the WHERE clause where
drhb6fb62d2005-09-20 08:47:20 +0000559** each subexpression is separated by the AND operator or some other
drh6c30be82005-07-29 15:10:17 +0000560** operator specified in the op parameter. The WhereClause structure
561** is filled with pointers to subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000562**
drh51669862004-12-18 18:40:26 +0000563** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
564** \________/ \_______________/ \________________/
565** slot[0] slot[1] slot[2]
566**
567** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000568** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000569**
drh51147ba2005-07-23 22:59:55 +0000570** In the previous sentence and in the diagram, "slot[]" refers to
drh902b9ee2008-12-05 17:17:07 +0000571** the WhereClause.a[] array. The slot[] array grows as needed to contain
drh51147ba2005-07-23 22:59:55 +0000572** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000573*/
drh6c30be82005-07-29 15:10:17 +0000574static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
drh29435252008-12-28 18:35:08 +0000575 pWC->op = (u8)op;
drh0aa74ed2005-07-16 13:33:20 +0000576 if( pExpr==0 ) return;
drh6c30be82005-07-29 15:10:17 +0000577 if( pExpr->op!=op ){
drh0aa74ed2005-07-16 13:33:20 +0000578 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000579 }else{
drh6c30be82005-07-29 15:10:17 +0000580 whereSplit(pWC, pExpr->pLeft, op);
581 whereSplit(pWC, pExpr->pRight, op);
drh75897232000-05-29 14:26:00 +0000582 }
drh75897232000-05-29 14:26:00 +0000583}
584
585/*
drh61495262009-04-22 15:32:59 +0000586** Initialize an expression mask set (a WhereMaskSet object)
drh6a3ea0e2003-05-02 14:32:12 +0000587*/
588#define initMaskSet(P) memset(P, 0, sizeof(*P))
589
590/*
drh1398ad32005-01-19 23:24:50 +0000591** Return the bitmask for the given cursor number. Return 0 if
592** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000593*/
drh111a6a72008-12-21 03:51:16 +0000594static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000595 int i;
drhfcd71b62011-04-05 22:08:24 +0000596 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
drh6a3ea0e2003-05-02 14:32:12 +0000597 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000598 if( pMaskSet->ix[i]==iCursor ){
drh7699d1c2013-06-04 12:42:29 +0000599 return MASKBIT(i);
drh51669862004-12-18 18:40:26 +0000600 }
drh6a3ea0e2003-05-02 14:32:12 +0000601 }
drh6a3ea0e2003-05-02 14:32:12 +0000602 return 0;
603}
604
605/*
drh1398ad32005-01-19 23:24:50 +0000606** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000607**
608** There is one cursor per table in the FROM clause. The number of
609** tables in the FROM clause is limited by a test early in the
drhb6fb62d2005-09-20 08:47:20 +0000610** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
drh0fcef5e2005-07-19 17:38:22 +0000611** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000612*/
drh111a6a72008-12-21 03:51:16 +0000613static void createMask(WhereMaskSet *pMaskSet, int iCursor){
drhcad651e2007-04-20 12:22:01 +0000614 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
drh0fcef5e2005-07-19 17:38:22 +0000615 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000616}
617
618/*
drh75897232000-05-29 14:26:00 +0000619** This routine walks (recursively) an expression tree and generates
620** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000621** tree.
drh75897232000-05-29 14:26:00 +0000622**
623** In order for this routine to work, the calling function must have
drh7d10d5a2008-08-20 16:35:10 +0000624** previously invoked sqlite3ResolveExprNames() on the expression. See
drh75897232000-05-29 14:26:00 +0000625** the header comment on that routine for additional information.
drh7d10d5a2008-08-20 16:35:10 +0000626** The sqlite3ResolveExprNames() routines looks for column names and
drh6a3ea0e2003-05-02 14:32:12 +0000627** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
drh51147ba2005-07-23 22:59:55 +0000628** the VDBE cursor number of the table. This routine just has to
629** translate the cursor numbers into bitmask values and OR all
630** the bitmasks together.
drh75897232000-05-29 14:26:00 +0000631*/
drh111a6a72008-12-21 03:51:16 +0000632static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
633static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
634static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
drh51669862004-12-18 18:40:26 +0000635 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000636 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000637 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000638 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000639 return mask;
drh75897232000-05-29 14:26:00 +0000640 }
danielk1977b3bce662005-01-29 08:32:43 +0000641 mask = exprTableUsage(pMaskSet, p->pRight);
642 mask |= exprTableUsage(pMaskSet, p->pLeft);
danielk19776ab3a2e2009-02-19 14:39:25 +0000643 if( ExprHasProperty(p, EP_xIsSelect) ){
644 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
645 }else{
646 mask |= exprListTableUsage(pMaskSet, p->x.pList);
647 }
danielk1977b3bce662005-01-29 08:32:43 +0000648 return mask;
649}
drh111a6a72008-12-21 03:51:16 +0000650static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
danielk1977b3bce662005-01-29 08:32:43 +0000651 int i;
652 Bitmask mask = 0;
653 if( pList ){
654 for(i=0; i<pList->nExpr; i++){
655 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000656 }
657 }
drh75897232000-05-29 14:26:00 +0000658 return mask;
659}
drh111a6a72008-12-21 03:51:16 +0000660static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
drha430ae82007-09-12 15:41:01 +0000661 Bitmask mask = 0;
662 while( pS ){
drha464c232011-09-16 19:04:03 +0000663 SrcList *pSrc = pS->pSrc;
drha430ae82007-09-12 15:41:01 +0000664 mask |= exprListTableUsage(pMaskSet, pS->pEList);
drhf5b11382005-09-17 13:07:13 +0000665 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
666 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
667 mask |= exprTableUsage(pMaskSet, pS->pWhere);
668 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drha464c232011-09-16 19:04:03 +0000669 if( ALWAYS(pSrc!=0) ){
drh88501772011-09-16 17:43:06 +0000670 int i;
671 for(i=0; i<pSrc->nSrc; i++){
672 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
673 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
674 }
675 }
drha430ae82007-09-12 15:41:01 +0000676 pS = pS->pPrior;
drhf5b11382005-09-17 13:07:13 +0000677 }
678 return mask;
679}
drh75897232000-05-29 14:26:00 +0000680
681/*
drh487ab3c2001-11-08 00:45:21 +0000682** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000683** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000684** "=", "<", ">", "<=", ">=", and "IN".
drhe9cdcea2010-07-22 22:40:03 +0000685**
686** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
687** of one of the following forms: column = expression column > expression
688** column >= expression column < expression column <= expression
689** expression = column expression > column expression >= column
690** expression < column expression <= column column IN
691** (expression-list) column IN (subquery) column IS NULL
drh487ab3c2001-11-08 00:45:21 +0000692*/
693static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000694 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
695 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
696 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
697 assert( TK_GE==TK_EQ+4 );
drh50b39962006-10-28 00:28:09 +0000698 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
drh487ab3c2001-11-08 00:45:21 +0000699}
700
701/*
drh902b9ee2008-12-05 17:17:07 +0000702** Swap two objects of type TYPE.
drh193bd772004-07-20 18:23:14 +0000703*/
704#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
705
706/*
drh909626d2008-05-30 14:58:37 +0000707** Commute a comparison operator. Expressions of the form "X op Y"
drh0fcef5e2005-07-19 17:38:22 +0000708** are converted into "Y op X".
danielk1977eb5453d2007-07-30 14:40:48 +0000709**
mistachkin48864df2013-03-21 21:20:32 +0000710** If left/right precedence rules come into play when determining the
drhae80dde2012-12-06 21:16:43 +0000711** collating
danielk1977eb5453d2007-07-30 14:40:48 +0000712** side of the comparison, it remains associated with the same side after
713** the commutation. So "Y collate NOCASE op X" becomes
drhae80dde2012-12-06 21:16:43 +0000714** "X op Y". This is because any collation sequence on
danielk1977eb5453d2007-07-30 14:40:48 +0000715** the left hand side of a comparison overrides any collation sequence
drhae80dde2012-12-06 21:16:43 +0000716** attached to the right. For the same reason the EP_Collate flag
danielk1977eb5453d2007-07-30 14:40:48 +0000717** is not commuted.
drh193bd772004-07-20 18:23:14 +0000718*/
drh7d10d5a2008-08-20 16:35:10 +0000719static void exprCommute(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000720 u16 expRight = (pExpr->pRight->flags & EP_Collate);
721 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
drhfe05af82005-07-21 03:14:59 +0000722 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drhae80dde2012-12-06 21:16:43 +0000723 if( expRight==expLeft ){
724 /* Either X and Y both have COLLATE operator or neither do */
725 if( expRight ){
726 /* Both X and Y have COLLATE operators. Make sure X is always
727 ** used by clearing the EP_Collate flag from Y. */
728 pExpr->pRight->flags &= ~EP_Collate;
729 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
730 /* Neither X nor Y have COLLATE operators, but X has a non-default
731 ** collating sequence. So add the EP_Collate marker on X to cause
732 ** it to be searched first. */
733 pExpr->pLeft->flags |= EP_Collate;
734 }
735 }
drh0fcef5e2005-07-19 17:38:22 +0000736 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
737 if( pExpr->op>=TK_GT ){
738 assert( TK_LT==TK_GT+2 );
739 assert( TK_GE==TK_LE+2 );
740 assert( TK_GT>TK_EQ );
741 assert( TK_GT<TK_LE );
742 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
743 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000744 }
drh193bd772004-07-20 18:23:14 +0000745}
746
747/*
drhfe05af82005-07-21 03:14:59 +0000748** Translate from TK_xx operator to WO_xx bitmask.
749*/
drhec1724e2008-12-09 01:32:03 +0000750static u16 operatorMask(int op){
751 u16 c;
drhfe05af82005-07-21 03:14:59 +0000752 assert( allowedOp(op) );
753 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000754 c = WO_IN;
drh50b39962006-10-28 00:28:09 +0000755 }else if( op==TK_ISNULL ){
756 c = WO_ISNULL;
drhfe05af82005-07-21 03:14:59 +0000757 }else{
drhec1724e2008-12-09 01:32:03 +0000758 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
759 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000760 }
drh50b39962006-10-28 00:28:09 +0000761 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000762 assert( op!=TK_IN || c==WO_IN );
763 assert( op!=TK_EQ || c==WO_EQ );
764 assert( op!=TK_LT || c==WO_LT );
765 assert( op!=TK_LE || c==WO_LE );
766 assert( op!=TK_GT || c==WO_GT );
767 assert( op!=TK_GE || c==WO_GE );
768 return c;
drhfe05af82005-07-21 03:14:59 +0000769}
770
771/*
drh1c8148f2013-05-04 20:25:23 +0000772** Advance to the next WhereTerm that matches according to the criteria
773** established when the pScan object was initialized by whereScanInit().
774** Return NULL if there are no more matching WhereTerms.
775*/
776WhereTerm *whereScanNext(WhereScan *pScan){
777 int iCur; /* The cursor on the LHS of the term */
778 int iColumn; /* The column on the LHS of the term. -1 for IPK */
779 Expr *pX; /* An expression being tested */
780 WhereClause *pWC; /* Shorthand for pScan->pWC */
781 WhereTerm *pTerm; /* The term being tested */
782
783 while( pScan->iEquiv<=pScan->nEquiv ){
784 iCur = pScan->aEquiv[pScan->iEquiv-2];
785 iColumn = pScan->aEquiv[pScan->iEquiv-1];
786 while( (pWC = pScan->pWC)!=0 ){
787 for(pTerm=pWC->a+pScan->k; pScan->k<pWC->nTerm; pScan->k++, pTerm++){
788 if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
789 if( (pTerm->eOperator & WO_EQUIV)!=0
790 && pScan->nEquiv<ArraySize(pScan->aEquiv)
791 ){
792 int j;
793 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
794 assert( pX->op==TK_COLUMN );
795 for(j=0; j<pScan->nEquiv; j+=2){
796 if( pScan->aEquiv[j]==pX->iTable
797 && pScan->aEquiv[j+1]==pX->iColumn ){
798 break;
799 }
800 }
801 if( j==pScan->nEquiv ){
802 pScan->aEquiv[j] = pX->iTable;
803 pScan->aEquiv[j+1] = pX->iColumn;
804 pScan->nEquiv += 2;
805 }
806 }
807 if( (pTerm->eOperator & pScan->opMask)!=0 ){
808 /* Verify the affinity and collating sequence match */
809 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
810 CollSeq *pColl;
drh70d18342013-06-06 19:16:33 +0000811 Parse *pParse = pWC->pWInfo->pParse;
drh1c8148f2013-05-04 20:25:23 +0000812 pX = pTerm->pExpr;
813 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
814 continue;
815 }
816 assert(pX->pLeft);
drh70d18342013-06-06 19:16:33 +0000817 pColl = sqlite3BinaryCompareCollSeq(pParse,
drh1c8148f2013-05-04 20:25:23 +0000818 pX->pLeft, pX->pRight);
drh70d18342013-06-06 19:16:33 +0000819 if( pColl==0 ) pColl = pParse->db->pDfltColl;
drh1c8148f2013-05-04 20:25:23 +0000820 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
821 continue;
822 }
823 }
drha184fb82013-05-08 04:22:59 +0000824 if( (pTerm->eOperator & WO_EQ)!=0
825 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
826 && pX->iTable==pScan->aEquiv[0]
827 && pX->iColumn==pScan->aEquiv[1]
828 ){
829 continue;
830 }
drh1c8148f2013-05-04 20:25:23 +0000831 pScan->pCurrent = pTerm;
832 pScan->k++;
833 return pTerm;
834 }
835 }
836 }
837 pWC = pScan->pWC = pScan->pWC->pOuter;
838 pScan->k = 0;
839 }
840 pScan->pWC = pScan->pOrigWC;
841 pScan->k = 0;
842 pScan->iEquiv += 2;
843 }
844 pScan->pCurrent = 0;
845 return 0;
846}
847
848/*
849** Initialize a WHERE clause scanner object. Return a pointer to the
850** first match. Return NULL if there are no matches.
851**
852** The scanner will be searching the WHERE clause pWC. It will look
853** for terms of the form "X <op> <expr>" where X is column iColumn of table
854** iCur. The <op> must be one of the operators described by opMask.
855**
856** If X is not the INTEGER PRIMARY KEY then X must be compatible with
857** index pIdx.
858*/
859WhereTerm *whereScanInit(
860 WhereScan *pScan, /* The WhereScan object being initialized */
861 WhereClause *pWC, /* The WHERE clause to be scanned */
862 int iCur, /* Cursor to scan for */
863 int iColumn, /* Column to scan for */
864 u32 opMask, /* Operator(s) to scan for */
865 Index *pIdx /* Must be compatible with this index */
866){
867 int j;
868
drhe9d935a2013-06-05 16:19:59 +0000869 /* memset(pScan, 0, sizeof(*pScan)); */
870 pScan->pCurrent = 0;
drh1c8148f2013-05-04 20:25:23 +0000871 pScan->pOrigWC = pWC;
872 pScan->pWC = pWC;
873 if( pIdx && iColumn>=0 ){
874 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
875 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
876 if( NEVER(j>=pIdx->nColumn) ) return 0;
877 }
878 pScan->zCollName = pIdx->azColl[j];
drhe9d935a2013-06-05 16:19:59 +0000879 }else{
880 pScan->idxaff = 0;
881 pScan->zCollName = 0;
drh1c8148f2013-05-04 20:25:23 +0000882 }
883 pScan->opMask = opMask;
drhe9d935a2013-06-05 16:19:59 +0000884 pScan->k = 0;
drh1c8148f2013-05-04 20:25:23 +0000885 pScan->aEquiv[0] = iCur;
886 pScan->aEquiv[1] = iColumn;
887 pScan->nEquiv = 2;
888 pScan->iEquiv = 2;
889 return whereScanNext(pScan);
890}
891
892/*
drhfe05af82005-07-21 03:14:59 +0000893** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
894** where X is a reference to the iColumn of table iCur and <op> is one of
895** the WO_xx operator codes specified by the op parameter.
896** Return a pointer to the term. Return 0 if not found.
drh58eb1c02013-01-17 00:08:42 +0000897**
898** The term returned might by Y=<expr> if there is another constraint in
899** the WHERE clause that specifies that X=Y. Any such constraints will be
900** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
901** aEquiv[] array holds X and all its equivalents, with each SQL variable
902** taking up two slots in aEquiv[]. The first slot is for the cursor number
903** and the second is for the column number. There are 22 slots in aEquiv[]
904** so that means we can look for X plus up to 10 other equivalent values.
905** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
906** and ... and A9=A10 and A10=<expr>.
907**
908** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
909** then try for the one with no dependencies on <expr> - in other words where
910** <expr> is a constant expression of some kind. Only return entries of
911** the form "X <op> Y" where Y is a column in another table if no terms of
drh459f63e2013-03-06 01:55:27 +0000912** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
913** exist, try to return a term that does not use WO_EQUIV.
drhfe05af82005-07-21 03:14:59 +0000914*/
915static WhereTerm *findTerm(
916 WhereClause *pWC, /* The WHERE clause to be searched */
917 int iCur, /* Cursor number of LHS */
918 int iColumn, /* Column number of LHS */
919 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +0000920 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000921 Index *pIdx /* Must be compatible with this index, if not NULL */
922){
drh1c8148f2013-05-04 20:25:23 +0000923 WhereTerm *pResult = 0;
924 WhereTerm *p;
925 WhereScan scan;
drh7a5bcc02013-01-16 17:08:58 +0000926
drh1c8148f2013-05-04 20:25:23 +0000927 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
928 while( p ){
929 if( (p->prereqRight & notReady)==0 ){
930 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
931 return p;
drhfe05af82005-07-21 03:14:59 +0000932 }
drh1c8148f2013-05-04 20:25:23 +0000933 if( pResult==0 ) pResult = p;
drhfe05af82005-07-21 03:14:59 +0000934 }
drh1c8148f2013-05-04 20:25:23 +0000935 p = whereScanNext(&scan);
drhfe05af82005-07-21 03:14:59 +0000936 }
drh7a5bcc02013-01-16 17:08:58 +0000937 return pResult;
drhfe05af82005-07-21 03:14:59 +0000938}
939
drh6c30be82005-07-29 15:10:17 +0000940/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +0000941static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +0000942
943/*
944** Call exprAnalyze on all terms in a WHERE clause.
945**
946**
947*/
948static void exprAnalyzeAll(
949 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +0000950 WhereClause *pWC /* the WHERE clause to be analyzed */
951){
drh6c30be82005-07-29 15:10:17 +0000952 int i;
drh9eb20282005-08-24 03:52:18 +0000953 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +0000954 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +0000955 }
956}
957
drhd2687b72005-08-12 22:56:09 +0000958#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
959/*
960** Check to see if the given expression is a LIKE or GLOB operator that
961** can be optimized using inequality constraints. Return TRUE if it is
962** so and false if not.
963**
964** In order for the operator to be optimizible, the RHS must be a string
965** literal that does not begin with a wildcard.
966*/
967static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +0000968 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +0000969 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +0000970 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +0000971 int *pisComplete, /* True if the only wildcard is % in the last character */
972 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +0000973){
dan937d0de2009-10-15 18:35:38 +0000974 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +0000975 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
976 ExprList *pList; /* List of operands to the LIKE operator */
977 int c; /* One character in z[] */
978 int cnt; /* Number of non-wildcard prefix characters */
979 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +0000980 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +0000981 sqlite3_value *pVal = 0;
982 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +0000983
drh9f504ea2008-02-23 21:55:39 +0000984 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +0000985 return 0;
986 }
drh9f504ea2008-02-23 21:55:39 +0000987#ifdef SQLITE_EBCDIC
988 if( *pnoCase ) return 0;
989#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000990 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +0000991 pLeft = pList->a[1].pExpr;
danc68939e2012-03-29 14:29:07 +0000992 if( pLeft->op!=TK_COLUMN
993 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
994 || IsVirtual(pLeft->pTab)
995 ){
drhd91ca492009-10-22 20:50:36 +0000996 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
997 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +0000998 return 0;
999 }
drhd91ca492009-10-22 20:50:36 +00001000 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +00001001
1002 pRight = pList->a[0].pExpr;
1003 op = pRight->op;
1004 if( op==TK_REGISTER ){
1005 op = pRight->op2;
1006 }
1007 if( op==TK_VARIABLE ){
1008 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +00001009 int iCol = pRight->iColumn;
1010 pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
dan937d0de2009-10-15 18:35:38 +00001011 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
1012 z = (char *)sqlite3_value_text(pVal);
1013 }
drhf9b22ca2011-10-21 16:47:31 +00001014 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +00001015 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
1016 }else if( op==TK_STRING ){
1017 z = pRight->u.zToken;
1018 }
1019 if( z ){
shane85095702009-06-15 16:27:08 +00001020 cnt = 0;
drhb7916a72009-05-27 10:31:29 +00001021 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +00001022 cnt++;
1023 }
drh93ee23c2010-07-22 12:33:57 +00001024 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +00001025 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +00001026 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +00001027 pPrefix = sqlite3Expr(db, TK_STRING, z);
1028 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
1029 *ppPrefix = pPrefix;
1030 if( op==TK_VARIABLE ){
1031 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +00001032 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +00001033 if( *pisComplete && pRight->u.zToken[1] ){
1034 /* If the rhs of the LIKE expression is a variable, and the current
1035 ** value of the variable means there is no need to invoke the LIKE
1036 ** function, then no OP_Variable will be added to the program.
1037 ** This causes problems for the sqlite3_bind_parameter_name()
drhbec451f2009-10-17 13:13:02 +00001038 ** API. To workaround them, add a dummy OP_Variable here.
1039 */
1040 int r1 = sqlite3GetTempReg(pParse);
1041 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +00001042 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +00001043 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +00001044 }
1045 }
1046 }else{
1047 z = 0;
shane85095702009-06-15 16:27:08 +00001048 }
drhf998b732007-11-26 13:36:00 +00001049 }
dan937d0de2009-10-15 18:35:38 +00001050
1051 sqlite3ValueFree(pVal);
1052 return (z!=0);
drhd2687b72005-08-12 22:56:09 +00001053}
1054#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1055
drhedb193b2006-06-27 13:20:21 +00001056
1057#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +00001058/*
drh7f375902006-06-13 17:38:59 +00001059** Check to see if the given expression is of the form
1060**
1061** column MATCH expr
1062**
1063** If it is then return TRUE. If not, return FALSE.
1064*/
1065static int isMatchOfColumn(
1066 Expr *pExpr /* Test this expression */
1067){
1068 ExprList *pList;
1069
1070 if( pExpr->op!=TK_FUNCTION ){
1071 return 0;
1072 }
drh33e619f2009-05-28 01:00:55 +00001073 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +00001074 return 0;
1075 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001076 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +00001077 if( pList->nExpr!=2 ){
1078 return 0;
1079 }
1080 if( pList->a[1].pExpr->op != TK_COLUMN ){
1081 return 0;
1082 }
1083 return 1;
1084}
drhedb193b2006-06-27 13:20:21 +00001085#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +00001086
1087/*
drh54a167d2005-11-26 14:08:07 +00001088** If the pBase expression originated in the ON or USING clause of
1089** a join, then transfer the appropriate markings over to derived.
1090*/
1091static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
1092 pDerived->flags |= pBase->flags & EP_FromJoin;
1093 pDerived->iRightJoinTable = pBase->iRightJoinTable;
1094}
1095
drh3e355802007-02-23 23:13:33 +00001096#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1097/*
drh1a58fe02008-12-20 02:06:13 +00001098** Analyze a term that consists of two or more OR-connected
1099** subterms. So in:
drh3e355802007-02-23 23:13:33 +00001100**
drh1a58fe02008-12-20 02:06:13 +00001101** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
1102** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +00001103**
drh1a58fe02008-12-20 02:06:13 +00001104** This routine analyzes terms such as the middle term in the above example.
1105** A WhereOrTerm object is computed and attached to the term under
1106** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +00001107**
drh1a58fe02008-12-20 02:06:13 +00001108** WhereTerm.wtFlags |= TERM_ORINFO
1109** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +00001110**
drh1a58fe02008-12-20 02:06:13 +00001111** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +00001112** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +00001113** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +00001114**
drh1a58fe02008-12-20 02:06:13 +00001115** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
1116** (B) x=expr1 OR expr2=x OR x=expr3
1117** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
1118** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
1119** (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 +00001120**
drh1a58fe02008-12-20 02:06:13 +00001121** CASE 1:
1122**
drhc3e552f2013-02-08 16:04:19 +00001123** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +00001124** a single table T (as shown in example B above) then create a new virtual
1125** term that is an equivalent IN expression. In other words, if the term
1126** being analyzed is:
1127**
1128** x = expr1 OR expr2 = x OR x = expr3
1129**
1130** then create a new virtual term like this:
1131**
1132** x IN (expr1,expr2,expr3)
1133**
1134** CASE 2:
1135**
1136** If all subterms are indexable by a single table T, then set
1137**
1138** WhereTerm.eOperator = WO_OR
1139** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
1140**
1141** A subterm is "indexable" if it is of the form
1142** "T.C <op> <expr>" where C is any column of table T and
1143** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
1144** A subterm is also indexable if it is an AND of two or more
1145** subsubterms at least one of which is indexable. Indexable AND
1146** subterms have their eOperator set to WO_AND and they have
1147** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
1148**
1149** From another point of view, "indexable" means that the subterm could
1150** potentially be used with an index if an appropriate index exists.
1151** This analysis does not consider whether or not the index exists; that
1152** is something the bestIndex() routine will determine. This analysis
1153** only looks at whether subterms appropriate for indexing exist.
1154**
1155** All examples A through E above all satisfy case 2. But if a term
1156** also statisfies case 1 (such as B) we know that the optimizer will
1157** always prefer case 1, so in that case we pretend that case 2 is not
1158** satisfied.
1159**
1160** It might be the case that multiple tables are indexable. For example,
1161** (E) above is indexable on tables P, Q, and R.
1162**
1163** Terms that satisfy case 2 are candidates for lookup by using
1164** separate indices to find rowids for each subterm and composing
1165** the union of all rowids using a RowSet object. This is similar
1166** to "bitmap indices" in other database engines.
1167**
1168** OTHERWISE:
1169**
1170** If neither case 1 nor case 2 apply, then leave the eOperator set to
1171** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +00001172*/
drh1a58fe02008-12-20 02:06:13 +00001173static void exprAnalyzeOrTerm(
1174 SrcList *pSrc, /* the FROM clause */
1175 WhereClause *pWC, /* the complete WHERE clause */
1176 int idxTerm /* Index of the OR-term to be analyzed */
1177){
drh70d18342013-06-06 19:16:33 +00001178 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
1179 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +00001180 sqlite3 *db = pParse->db; /* Database connection */
1181 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
1182 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +00001183 int i; /* Loop counters */
1184 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
1185 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
1186 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
1187 Bitmask chngToIN; /* Tables that might satisfy case 1 */
1188 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +00001189
drh1a58fe02008-12-20 02:06:13 +00001190 /*
1191 ** Break the OR clause into its separate subterms. The subterms are
1192 ** stored in a WhereClause structure containing within the WhereOrInfo
1193 ** object that is attached to the original OR clause term.
1194 */
1195 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
1196 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +00001197 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +00001198 if( pOrInfo==0 ) return;
1199 pTerm->wtFlags |= TERM_ORINFO;
1200 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +00001201 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +00001202 whereSplit(pOrWc, pExpr, TK_OR);
1203 exprAnalyzeAll(pSrc, pOrWc);
1204 if( db->mallocFailed ) return;
1205 assert( pOrWc->nTerm>=2 );
1206
1207 /*
1208 ** Compute the set of tables that might satisfy cases 1 or 2.
1209 */
danielk1977e672c8e2009-05-22 15:43:26 +00001210 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +00001211 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +00001212 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
1213 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +00001214 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +00001215 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +00001216 chngToIN = 0;
drh29435252008-12-28 18:35:08 +00001217 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
1218 if( pAndInfo ){
1219 WhereClause *pAndWC;
1220 WhereTerm *pAndTerm;
1221 int j;
1222 Bitmask b = 0;
1223 pOrTerm->u.pAndInfo = pAndInfo;
1224 pOrTerm->wtFlags |= TERM_ANDINFO;
1225 pOrTerm->eOperator = WO_AND;
1226 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +00001227 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +00001228 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
1229 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +00001230 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +00001231 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +00001232 if( !db->mallocFailed ){
1233 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
1234 assert( pAndTerm->pExpr );
1235 if( allowedOp(pAndTerm->pExpr->op) ){
drh70d18342013-06-06 19:16:33 +00001236 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +00001237 }
drh29435252008-12-28 18:35:08 +00001238 }
1239 }
1240 indexable &= b;
1241 }
drh1a58fe02008-12-20 02:06:13 +00001242 }else if( pOrTerm->wtFlags & TERM_COPIED ){
1243 /* Skip this term for now. We revisit it when we process the
1244 ** corresponding TERM_VIRTUAL term */
1245 }else{
1246 Bitmask b;
drh70d18342013-06-06 19:16:33 +00001247 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001248 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
1249 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh70d18342013-06-06 19:16:33 +00001250 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001251 }
1252 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +00001253 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +00001254 chngToIN = 0;
1255 }else{
1256 chngToIN &= b;
1257 }
1258 }
drh3e355802007-02-23 23:13:33 +00001259 }
drh1a58fe02008-12-20 02:06:13 +00001260
1261 /*
1262 ** Record the set of tables that satisfy case 2. The set might be
drh111a6a72008-12-21 03:51:16 +00001263 ** empty.
drh1a58fe02008-12-20 02:06:13 +00001264 */
1265 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +00001266 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +00001267
1268 /*
1269 ** chngToIN holds a set of tables that *might* satisfy case 1. But
1270 ** we have to do some additional checking to see if case 1 really
1271 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +00001272 **
1273 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
1274 ** that there is no possibility of transforming the OR clause into an
1275 ** IN operator because one or more terms in the OR clause contain
1276 ** something other than == on a column in the single table. The 1-bit
1277 ** case means that every term of the OR clause is of the form
1278 ** "table.column=expr" for some single table. The one bit that is set
1279 ** will correspond to the common table. We still need to check to make
1280 ** sure the same column is used on all terms. The 2-bit case is when
1281 ** the all terms are of the form "table1.column=table2.column". It
1282 ** might be possible to form an IN operator with either table1.column
1283 ** or table2.column as the LHS if either is common to every term of
1284 ** the OR clause.
1285 **
1286 ** Note that terms of the form "table.column1=table.column2" (the
1287 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +00001288 */
1289 if( chngToIN ){
1290 int okToChngToIN = 0; /* True if the conversion to IN is valid */
1291 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +00001292 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +00001293 int j = 0; /* Loop counter */
1294
1295 /* Search for a table and column that appears on one side or the
1296 ** other of the == operator in every subterm. That table and column
1297 ** will be recorded in iCursor and iColumn. There might not be any
1298 ** such table and column. Set okToChngToIN if an appropriate table
1299 ** and column is found but leave okToChngToIN false if not found.
1300 */
1301 for(j=0; j<2 && !okToChngToIN; j++){
1302 pOrTerm = pOrWc->a;
1303 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001304 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001305 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +00001306 if( pOrTerm->leftCursor==iCursor ){
1307 /* This is the 2-bit case and we are on the second iteration and
1308 ** current term is from the first iteration. So skip this term. */
1309 assert( j==1 );
1310 continue;
1311 }
drh70d18342013-06-06 19:16:33 +00001312 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +00001313 /* This term must be of the form t1.a==t2.b where t2 is in the
1314 ** chngToIN set but t1 is not. This term will be either preceeded
1315 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
1316 ** and use its inversion. */
1317 testcase( pOrTerm->wtFlags & TERM_COPIED );
1318 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
1319 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
1320 continue;
1321 }
drh1a58fe02008-12-20 02:06:13 +00001322 iColumn = pOrTerm->u.leftColumn;
1323 iCursor = pOrTerm->leftCursor;
1324 break;
1325 }
1326 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +00001327 /* No candidate table+column was found. This can only occur
1328 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +00001329 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +00001330 assert( IsPowerOfTwo(chngToIN) );
drh70d18342013-06-06 19:16:33 +00001331 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +00001332 break;
1333 }
drh4e8be3b2009-06-08 17:11:08 +00001334 testcase( j==1 );
1335
1336 /* We have found a candidate table and column. Check to see if that
1337 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001338 okToChngToIN = 1;
1339 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001340 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001341 if( pOrTerm->leftCursor!=iCursor ){
1342 pOrTerm->wtFlags &= ~TERM_OR_OK;
1343 }else if( pOrTerm->u.leftColumn!=iColumn ){
1344 okToChngToIN = 0;
1345 }else{
1346 int affLeft, affRight;
1347 /* If the right-hand side is also a column, then the affinities
1348 ** of both right and left sides must be such that no type
1349 ** conversions are required on the right. (Ticket #2249)
1350 */
1351 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1352 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1353 if( affRight!=0 && affRight!=affLeft ){
1354 okToChngToIN = 0;
1355 }else{
1356 pOrTerm->wtFlags |= TERM_OR_OK;
1357 }
1358 }
1359 }
1360 }
1361
1362 /* At this point, okToChngToIN is true if original pTerm satisfies
1363 ** case 1. In that case, construct a new virtual term that is
1364 ** pTerm converted into an IN operator.
drhe9cdcea2010-07-22 22:40:03 +00001365 **
1366 ** EV: R-00211-15100
drh1a58fe02008-12-20 02:06:13 +00001367 */
1368 if( okToChngToIN ){
1369 Expr *pDup; /* A transient duplicate expression */
1370 ExprList *pList = 0; /* The RHS of the IN operator */
1371 Expr *pLeft = 0; /* The LHS of the IN operator */
1372 Expr *pNew; /* The complete IN operator */
1373
1374 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1375 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001376 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001377 assert( pOrTerm->leftCursor==iCursor );
1378 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001379 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001380 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001381 pLeft = pOrTerm->pExpr->pLeft;
1382 }
1383 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001384 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001385 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001386 if( pNew ){
1387 int idxNew;
1388 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001389 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1390 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001391 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1392 testcase( idxNew==0 );
1393 exprAnalyze(pSrc, pWC, idxNew);
1394 pTerm = &pWC->a[idxTerm];
1395 pWC->a[idxNew].iParent = idxTerm;
1396 pTerm->nChild = 1;
1397 }else{
1398 sqlite3ExprListDelete(db, pList);
1399 }
drh534230c2011-01-22 00:10:45 +00001400 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
drh1a58fe02008-12-20 02:06:13 +00001401 }
drh3e355802007-02-23 23:13:33 +00001402 }
drh3e355802007-02-23 23:13:33 +00001403}
1404#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001405
drh7a5bcc02013-01-16 17:08:58 +00001406/*
drh0aa74ed2005-07-16 13:33:20 +00001407** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001408** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001409** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001410** structure.
drh51147ba2005-07-23 22:59:55 +00001411**
1412** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001413** to the standard form of "X <op> <expr>".
1414**
1415** If the expression is of the form "X <op> Y" where both X and Y are
1416** columns, then the original expression is unchanged and a new virtual
1417** term of the form "Y <op> X" is added to the WHERE clause and
1418** analyzed separately. The original term is marked with TERM_COPIED
1419** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1420** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1421** is a commuted copy of a prior term.) The original term has nChild=1
1422** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001423*/
drh0fcef5e2005-07-19 17:38:22 +00001424static void exprAnalyze(
1425 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001426 WhereClause *pWC, /* the WHERE clause */
1427 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001428){
drh70d18342013-06-06 19:16:33 +00001429 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001430 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001431 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001432 Expr *pExpr; /* The expression to be analyzed */
1433 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1434 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001435 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001436 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1437 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1438 int noCase = 0; /* LIKE/GLOB distinguishes case */
drh1a58fe02008-12-20 02:06:13 +00001439 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001440 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001441 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001442
drhf998b732007-11-26 13:36:00 +00001443 if( db->mallocFailed ){
1444 return;
1445 }
1446 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001447 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001448 pExpr = pTerm->pExpr;
1449 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001450 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001451 op = pExpr->op;
1452 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001453 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001454 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1455 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1456 }else{
1457 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1458 }
drh50b39962006-10-28 00:28:09 +00001459 }else if( op==TK_ISNULL ){
1460 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001461 }else{
1462 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1463 }
drh22d6a532005-09-19 21:05:48 +00001464 prereqAll = exprTableUsage(pMaskSet, pExpr);
1465 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001466 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1467 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001468 extraRight = x-1; /* ON clause terms may not be used with an index
1469 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001470 }
1471 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001472 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001473 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001474 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001475 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001476 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1477 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001478 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001479 if( pLeft->op==TK_COLUMN ){
1480 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001481 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001482 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001483 }
drh0fcef5e2005-07-19 17:38:22 +00001484 if( pRight && pRight->op==TK_COLUMN ){
1485 WhereTerm *pNew;
1486 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001487 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001488 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001489 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001490 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001491 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001492 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001493 return;
1494 }
drh9eb20282005-08-24 03:52:18 +00001495 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1496 if( idxNew==0 ) return;
1497 pNew = &pWC->a[idxNew];
1498 pNew->iParent = idxTerm;
1499 pTerm = &pWC->a[idxTerm];
drh45b1ee42005-08-02 17:48:22 +00001500 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001501 pTerm->wtFlags |= TERM_COPIED;
drheb5bc922013-01-17 16:43:33 +00001502 if( pExpr->op==TK_EQ
1503 && !ExprHasProperty(pExpr, EP_FromJoin)
1504 && OptimizationEnabled(db, SQLITE_Transitive)
1505 ){
drh7a5bcc02013-01-16 17:08:58 +00001506 pTerm->eOperator |= WO_EQUIV;
1507 eExtraOp = WO_EQUIV;
1508 }
drh0fcef5e2005-07-19 17:38:22 +00001509 }else{
1510 pDup = pExpr;
1511 pNew = pTerm;
1512 }
drh7d10d5a2008-08-20 16:35:10 +00001513 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001514 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001515 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001516 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001517 testcase( (prereqLeft | extraRight) != prereqLeft );
1518 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001519 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001520 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001521 }
1522 }
drhed378002005-07-28 23:12:08 +00001523
drhd2687b72005-08-12 22:56:09 +00001524#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001525 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001526 ** that define the range that the BETWEEN implements. For example:
1527 **
1528 ** a BETWEEN b AND c
1529 **
1530 ** is converted into:
1531 **
1532 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1533 **
1534 ** The two new terms are added onto the end of the WhereClause object.
1535 ** The new terms are "dynamic" and are children of the original BETWEEN
1536 ** term. That means that if the BETWEEN term is coded, the children are
1537 ** skipped. Or, if the children are satisfied by an index, the original
1538 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001539 */
drh29435252008-12-28 18:35:08 +00001540 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001541 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001542 int i;
1543 static const u8 ops[] = {TK_GE, TK_LE};
1544 assert( pList!=0 );
1545 assert( pList->nExpr==2 );
1546 for(i=0; i<2; i++){
1547 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001548 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001549 pNewExpr = sqlite3PExpr(pParse, ops[i],
1550 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001551 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drh9eb20282005-08-24 03:52:18 +00001552 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001553 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001554 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001555 pTerm = &pWC->a[idxTerm];
1556 pWC->a[idxNew].iParent = idxTerm;
drhed378002005-07-28 23:12:08 +00001557 }
drh45b1ee42005-08-02 17:48:22 +00001558 pTerm->nChild = 2;
drhed378002005-07-28 23:12:08 +00001559 }
drhd2687b72005-08-12 22:56:09 +00001560#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001561
danielk19771576cd92006-01-14 08:02:28 +00001562#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001563 /* Analyze a term that is composed of two or more subterms connected by
1564 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001565 */
1566 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001567 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001568 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001569 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001570 }
drhd2687b72005-08-12 22:56:09 +00001571#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1572
1573#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1574 /* Add constraints to reduce the search space on a LIKE or GLOB
1575 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001576 **
1577 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1578 **
1579 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
1580 **
1581 ** The last character of the prefix "abc" is incremented to form the
shane7bc71e52008-05-28 18:01:44 +00001582 ** termination condition "abd".
drhd2687b72005-08-12 22:56:09 +00001583 */
dan937d0de2009-10-15 18:35:38 +00001584 if( pWC->op==TK_AND
1585 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1586 ){
drh1d452e12009-11-01 19:26:59 +00001587 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1588 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1589 Expr *pNewExpr1;
1590 Expr *pNewExpr2;
1591 int idxNew1;
1592 int idxNew2;
drhae80dde2012-12-06 21:16:43 +00001593 Token sCollSeqName; /* Name of collating sequence */
drh9eb20282005-08-24 03:52:18 +00001594
danielk19776ab3a2e2009-02-19 14:39:25 +00001595 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001596 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drhf998b732007-11-26 13:36:00 +00001597 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001598 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001599 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001600 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001601 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001602 /* The point is to increment the last character before the first
1603 ** wildcard. But if we increment '@', that will push it into the
1604 ** alphabetic range where case conversions will mess up the
1605 ** inequality. To avoid this, make sure to also run the full
1606 ** LIKE on all candidate expressions by clearing the isComplete flag
1607 */
drhe9cdcea2010-07-22 22:40:03 +00001608 if( c=='A'-1 ) isComplete = 0; /* EV: R-64339-08207 */
1609
drh254993e2009-06-08 19:44:36 +00001610
drh02a50b72008-05-26 18:33:40 +00001611 c = sqlite3UpperToLower[c];
1612 }
drh9f504ea2008-02-23 21:55:39 +00001613 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001614 }
drhae80dde2012-12-06 21:16:43 +00001615 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1616 sCollSeqName.n = 6;
1617 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001618 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
drh0a8a4062012-12-07 18:38:16 +00001619 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001620 pStr1, 0);
drh9eb20282005-08-24 03:52:18 +00001621 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001622 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001623 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001624 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001625 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
drh0a8a4062012-12-07 18:38:16 +00001626 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001627 pStr2, 0);
drh9eb20282005-08-24 03:52:18 +00001628 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001629 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001630 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001631 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001632 if( isComplete ){
drh9eb20282005-08-24 03:52:18 +00001633 pWC->a[idxNew1].iParent = idxTerm;
1634 pWC->a[idxNew2].iParent = idxTerm;
drhd2687b72005-08-12 22:56:09 +00001635 pTerm->nChild = 2;
1636 }
1637 }
1638#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001639
1640#ifndef SQLITE_OMIT_VIRTUALTABLE
1641 /* Add a WO_MATCH auxiliary term to the constraint set if the
1642 ** current expression is of the form: column MATCH expr.
1643 ** This information is used by the xBestIndex methods of
1644 ** virtual tables. The native query optimizer does not attempt
1645 ** to do anything with MATCH functions.
1646 */
1647 if( isMatchOfColumn(pExpr) ){
1648 int idxNew;
1649 Expr *pRight, *pLeft;
1650 WhereTerm *pNewTerm;
1651 Bitmask prereqColumn, prereqExpr;
1652
danielk19776ab3a2e2009-02-19 14:39:25 +00001653 pRight = pExpr->x.pList->a[0].pExpr;
1654 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001655 prereqExpr = exprTableUsage(pMaskSet, pRight);
1656 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1657 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001658 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001659 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1660 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001661 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001662 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001663 pNewTerm = &pWC->a[idxNew];
1664 pNewTerm->prereqRight = prereqExpr;
1665 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001666 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001667 pNewTerm->eOperator = WO_MATCH;
1668 pNewTerm->iParent = idxTerm;
drhd2ca60d2006-06-27 02:36:58 +00001669 pTerm = &pWC->a[idxTerm];
drh7f375902006-06-13 17:38:59 +00001670 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001671 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001672 pNewTerm->prereqAll = pTerm->prereqAll;
1673 }
1674 }
1675#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001676
drhfaacf172011-08-12 01:51:45 +00001677#ifdef SQLITE_ENABLE_STAT3
drhd3ed7342011-09-21 00:09:41 +00001678 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001679 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1680 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1681 ** virtual term of that form.
1682 **
1683 ** Note that the virtual term must be tagged with TERM_VNULL. This
1684 ** TERM_VNULL tag will suppress the not-null check at the beginning
1685 ** of the loop. Without the TERM_VNULL flag, the not-null check at
1686 ** the start of the loop will prevent any results from being returned.
1687 */
drhea6dc442011-04-08 21:35:26 +00001688 if( pExpr->op==TK_NOTNULL
1689 && pExpr->pLeft->op==TK_COLUMN
1690 && pExpr->pLeft->iColumn>=0
1691 ){
drh534230c2011-01-22 00:10:45 +00001692 Expr *pNewExpr;
1693 Expr *pLeft = pExpr->pLeft;
1694 int idxNew;
1695 WhereTerm *pNewTerm;
1696
1697 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1698 sqlite3ExprDup(db, pLeft, 0),
1699 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1700
1701 idxNew = whereClauseInsert(pWC, pNewExpr,
1702 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001703 if( idxNew ){
1704 pNewTerm = &pWC->a[idxNew];
1705 pNewTerm->prereqRight = 0;
1706 pNewTerm->leftCursor = pLeft->iTable;
1707 pNewTerm->u.leftColumn = pLeft->iColumn;
1708 pNewTerm->eOperator = WO_GT;
1709 pNewTerm->iParent = idxTerm;
1710 pTerm = &pWC->a[idxTerm];
1711 pTerm->nChild = 1;
1712 pTerm->wtFlags |= TERM_COPIED;
1713 pNewTerm->prereqAll = pTerm->prereqAll;
1714 }
drh534230c2011-01-22 00:10:45 +00001715 }
drhfaacf172011-08-12 01:51:45 +00001716#endif /* SQLITE_ENABLE_STAT */
drh534230c2011-01-22 00:10:45 +00001717
drhdafc0ce2008-04-17 19:14:02 +00001718 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1719 ** an index for tables to the left of the join.
1720 */
1721 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001722}
1723
drh7b4fc6a2007-02-06 13:26:32 +00001724/*
dan6f343962011-07-01 18:26:40 +00001725** This function searches the expression list passed as the second argument
1726** for an expression of type TK_COLUMN that refers to the same column and
1727** uses the same collation sequence as the iCol'th column of index pIdx.
1728** Argument iBase is the cursor number used for the table that pIdx refers
1729** to.
1730**
1731** If such an expression is found, its index in pList->a[] is returned. If
1732** no expression is found, -1 is returned.
1733*/
1734static int findIndexCol(
1735 Parse *pParse, /* Parse context */
1736 ExprList *pList, /* Expression list to search */
1737 int iBase, /* Cursor for table associated with pIdx */
1738 Index *pIdx, /* Index to match column of */
1739 int iCol /* Column of index to match */
1740){
1741 int i;
1742 const char *zColl = pIdx->azColl[iCol];
1743
1744 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001745 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001746 if( p->op==TK_COLUMN
1747 && p->iColumn==pIdx->aiColumn[iCol]
1748 && p->iTable==iBase
1749 ){
drh580c8c12012-12-08 03:34:04 +00001750 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001751 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001752 return i;
1753 }
1754 }
1755 }
1756
1757 return -1;
1758}
1759
1760/*
dan6f343962011-07-01 18:26:40 +00001761** Return true if the DISTINCT expression-list passed as the third argument
1762** is redundant. A DISTINCT list is redundant if the database contains a
1763** UNIQUE index that guarantees that the result of the query will be distinct
1764** anyway.
1765*/
1766static int isDistinctRedundant(
1767 Parse *pParse,
1768 SrcList *pTabList,
1769 WhereClause *pWC,
1770 ExprList *pDistinct
1771){
1772 Table *pTab;
1773 Index *pIdx;
1774 int i;
1775 int iBase;
1776
1777 /* If there is more than one table or sub-select in the FROM clause of
1778 ** this query, then it will not be possible to show that the DISTINCT
1779 ** clause is redundant. */
1780 if( pTabList->nSrc!=1 ) return 0;
1781 iBase = pTabList->a[0].iCursor;
1782 pTab = pTabList->a[0].pTab;
1783
dan94e08d92011-07-02 06:44:05 +00001784 /* If any of the expressions is an IPK column on table iBase, then return
1785 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1786 ** current SELECT is a correlated sub-query.
1787 */
dan6f343962011-07-01 18:26:40 +00001788 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001789 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001790 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001791 }
1792
1793 /* Loop through all indices on the table, checking each to see if it makes
1794 ** the DISTINCT qualifier redundant. It does so if:
1795 **
1796 ** 1. The index is itself UNIQUE, and
1797 **
1798 ** 2. All of the columns in the index are either part of the pDistinct
1799 ** list, or else the WHERE clause contains a term of the form "col=X",
1800 ** where X is a constant value. The collation sequences of the
1801 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001802 **
1803 ** 3. All of those index columns for which the WHERE clause does not
1804 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001805 */
1806 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1807 if( pIdx->onError==OE_None ) continue;
1808 for(i=0; i<pIdx->nColumn; i++){
1809 int iCol = pIdx->aiColumn[i];
dan6a36f432012-04-20 16:59:24 +00001810 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1811 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
1812 if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
1813 break;
1814 }
dan6f343962011-07-01 18:26:40 +00001815 }
1816 }
1817 if( i==pIdx->nColumn ){
1818 /* This index implies that the DISTINCT qualifier is redundant. */
1819 return 1;
1820 }
1821 }
1822
1823 return 0;
1824}
drh0fcef5e2005-07-19 17:38:22 +00001825
drh75897232000-05-29 14:26:00 +00001826/*
drhb6fb62d2005-09-20 08:47:20 +00001827** Prepare a crude estimate of the logarithm of the input value.
drh28c4cf42005-07-27 20:41:43 +00001828** The results need not be exact. This is only used for estimating
drh909626d2008-05-30 14:58:37 +00001829** the total cost of performing operations with O(logN) or O(NlogN)
drh28c4cf42005-07-27 20:41:43 +00001830** complexity. Because N is just a guess, it is no great tragedy if
1831** logN is a little off.
drh28c4cf42005-07-27 20:41:43 +00001832*/
drh4efc9292013-06-06 23:02:03 +00001833static WhereCost estLog(WhereCost N){
drh23fec452013-06-07 02:04:19 +00001834 u32 a;
1835 assert( sizeof(WhereCost)==4 ); /* 32-bit float input */
1836 if( N<=0.0 ) return 0.0;
1837 memcpy(&a, &N, 4);
1838 return ((a >>= 23)-127)*0.3;
drh28c4cf42005-07-27 20:41:43 +00001839}
1840
drh6d209d82006-06-27 01:54:26 +00001841/*
1842** Two routines for printing the content of an sqlite3_index_info
1843** structure. Used for testing and debugging only. If neither
1844** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1845** are no-ops.
1846*/
drhd15cb172013-05-21 19:23:10 +00001847#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00001848static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1849 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001850 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001851 for(i=0; i<p->nConstraint; i++){
1852 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1853 i,
1854 p->aConstraint[i].iColumn,
1855 p->aConstraint[i].iTermOffset,
1856 p->aConstraint[i].op,
1857 p->aConstraint[i].usable);
1858 }
1859 for(i=0; i<p->nOrderBy; i++){
1860 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1861 i,
1862 p->aOrderBy[i].iColumn,
1863 p->aOrderBy[i].desc);
1864 }
1865}
1866static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1867 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001868 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001869 for(i=0; i<p->nConstraint; i++){
1870 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1871 i,
1872 p->aConstraintUsage[i].argvIndex,
1873 p->aConstraintUsage[i].omit);
1874 }
1875 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1876 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1877 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1878 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
1879}
1880#else
1881#define TRACE_IDX_INPUTS(A)
1882#define TRACE_IDX_OUTPUTS(A)
1883#endif
1884
drhc6339082010-04-07 16:54:58 +00001885#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001886/*
drh4139c992010-04-07 14:59:45 +00001887** Return TRUE if the WHERE clause term pTerm is of a form where it
1888** could be used with an index to access pSrc, assuming an appropriate
1889** index existed.
1890*/
1891static int termCanDriveIndex(
1892 WhereTerm *pTerm, /* WHERE clause term to check */
1893 struct SrcList_item *pSrc, /* Table we are trying to access */
1894 Bitmask notReady /* Tables in outer loops of the join */
1895){
1896 char aff;
1897 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drh7a5bcc02013-01-16 17:08:58 +00001898 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001899 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00001900 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001901 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1902 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
1903 return 1;
1904}
drhc6339082010-04-07 16:54:58 +00001905#endif
drh4139c992010-04-07 14:59:45 +00001906
drhc6339082010-04-07 16:54:58 +00001907
1908#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001909/*
drhc6339082010-04-07 16:54:58 +00001910** Generate code to construct the Index object for an automatic index
1911** and to set up the WhereLevel object pLevel so that the code generator
1912** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00001913*/
drhc6339082010-04-07 16:54:58 +00001914static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00001915 Parse *pParse, /* The parsing context */
1916 WhereClause *pWC, /* The WHERE clause */
1917 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
1918 Bitmask notReady, /* Mask of cursors that are not available */
1919 WhereLevel *pLevel /* Write new index here */
1920){
1921 int nColumn; /* Number of columns in the constructed index */
1922 WhereTerm *pTerm; /* A single term of the WHERE clause */
1923 WhereTerm *pWCEnd; /* End of pWC->a[] */
1924 int nByte; /* Byte of memory needed for pIdx */
1925 Index *pIdx; /* Object describing the transient index */
1926 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00001927 int addrInit; /* Address of the initialization bypass jump */
1928 Table *pTable; /* The table being indexed */
1929 KeyInfo *pKeyinfo; /* Key information for the index */
1930 int addrTop; /* Top of the index fill loop */
1931 int regRecord; /* Register holding an index record */
1932 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00001933 int i; /* Loop counter */
1934 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00001935 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00001936 WhereLoop *pLoop; /* The Loop object */
drh4139c992010-04-07 14:59:45 +00001937 Bitmask idxCols; /* Bitmap of columns used for indexing */
1938 Bitmask extraCols; /* Bitmap of additional columns */
drh53b52f72013-05-31 11:57:39 +00001939 const int mxConstraint = 10; /* Maximum number of constraints */
drh8b307fb2010-04-06 15:57:05 +00001940
1941 /* Generate code to skip over the creation and initialization of the
1942 ** transient index on 2nd and subsequent iterations of the loop. */
1943 v = pParse->pVdbe;
1944 assert( v!=0 );
dan1d8cb212011-12-09 13:24:16 +00001945 addrInit = sqlite3CodeOnce(pParse);
drh8b307fb2010-04-06 15:57:05 +00001946
drh4139c992010-04-07 14:59:45 +00001947 /* Count the number of columns that will be added to the index
1948 ** and used to match WHERE clause constraints */
drh8b307fb2010-04-06 15:57:05 +00001949 nColumn = 0;
drh424aab82010-04-06 18:28:20 +00001950 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00001951 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00001952 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00001953 idxCols = 0;
drh4efc9292013-06-06 23:02:03 +00001954 for(pTerm=pWC->a; pTerm<pWCEnd && pLoop->nLTerm<mxConstraint; pTerm++){
drh4139c992010-04-07 14:59:45 +00001955 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1956 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001957 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00001958 testcase( iCol==BMS );
1959 testcase( iCol==BMS-1 );
drh0013e722010-04-08 00:40:15 +00001960 if( (idxCols & cMask)==0 ){
drh4efc9292013-06-06 23:02:03 +00001961 if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
1962 pLoop->aLTerm[nColumn++] = pTerm;
drh0013e722010-04-08 00:40:15 +00001963 idxCols |= cMask;
1964 }
drh8b307fb2010-04-06 15:57:05 +00001965 }
1966 }
1967 assert( nColumn>0 );
drh4efc9292013-06-06 23:02:03 +00001968 pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
drh53b52f72013-05-31 11:57:39 +00001969 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
1970 | WHERE_TEMP_INDEX;
drh4139c992010-04-07 14:59:45 +00001971
1972 /* Count the number of additional columns needed to create a
1973 ** covering index. A "covering index" is an index that contains all
1974 ** columns that are needed by the query. With a covering index, the
1975 ** original table never needs to be accessed. Automatic indices must
1976 ** be a covering index because the index will not be updated if the
1977 ** original table changes and the index and table cannot both be used
1978 ** if they go out of sync.
1979 */
drh7699d1c2013-06-04 12:42:29 +00001980 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drh4139c992010-04-07 14:59:45 +00001981 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
drh52ff8ea2010-04-08 14:15:56 +00001982 testcase( pTable->nCol==BMS-1 );
1983 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00001984 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00001985 if( extraCols & MASKBIT(i) ) nColumn++;
drh4139c992010-04-07 14:59:45 +00001986 }
drh7699d1c2013-06-04 12:42:29 +00001987 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00001988 nColumn += pTable->nCol - BMS + 1;
1989 }
drh7ba39a92013-05-30 17:43:19 +00001990 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
drh8b307fb2010-04-06 15:57:05 +00001991
1992 /* Construct the Index object to describe this index */
1993 nByte = sizeof(Index);
1994 nByte += nColumn*sizeof(int); /* Index.aiColumn */
1995 nByte += nColumn*sizeof(char*); /* Index.azColl */
1996 nByte += nColumn; /* Index.aSortOrder */
1997 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
1998 if( pIdx==0 ) return;
drh7ba39a92013-05-30 17:43:19 +00001999 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00002000 pIdx->azColl = (char**)&pIdx[1];
2001 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
2002 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
2003 pIdx->zName = "auto-index";
2004 pIdx->nColumn = nColumn;
drh424aab82010-04-06 18:28:20 +00002005 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00002006 n = 0;
drh0013e722010-04-08 00:40:15 +00002007 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00002008 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00002009 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00002010 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00002011 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh0013e722010-04-08 00:40:15 +00002012 if( (idxCols & cMask)==0 ){
2013 Expr *pX = pTerm->pExpr;
2014 idxCols |= cMask;
2015 pIdx->aiColumn[n] = pTerm->u.leftColumn;
2016 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh6f2e6c02011-02-17 13:33:15 +00002017 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00002018 n++;
2019 }
drh8b307fb2010-04-06 15:57:05 +00002020 }
2021 }
drh7ba39a92013-05-30 17:43:19 +00002022 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00002023
drhc6339082010-04-07 16:54:58 +00002024 /* Add additional columns needed to make the automatic index into
2025 ** a covering index */
drh4139c992010-04-07 14:59:45 +00002026 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00002027 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00002028 pIdx->aiColumn[n] = i;
2029 pIdx->azColl[n] = "BINARY";
2030 n++;
2031 }
2032 }
drh7699d1c2013-06-04 12:42:29 +00002033 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00002034 for(i=BMS-1; i<pTable->nCol; i++){
2035 pIdx->aiColumn[n] = i;
2036 pIdx->azColl[n] = "BINARY";
2037 n++;
2038 }
2039 }
2040 assert( n==nColumn );
drh8b307fb2010-04-06 15:57:05 +00002041
drhc6339082010-04-07 16:54:58 +00002042 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00002043 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
2044 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00002045 pLevel->iIdxCur = pParse->nTab++;
drha21a64d2010-04-06 22:33:55 +00002046 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
drh8b307fb2010-04-06 15:57:05 +00002047 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
drha21a64d2010-04-06 22:33:55 +00002048 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00002049
drhc6339082010-04-07 16:54:58 +00002050 /* Fill the automatic index with content */
drh8b307fb2010-04-06 15:57:05 +00002051 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
2052 regRecord = sqlite3GetTempReg(pParse);
2053 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
2054 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
2055 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2056 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
drha21a64d2010-04-06 22:33:55 +00002057 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00002058 sqlite3VdbeJumpHere(v, addrTop);
2059 sqlite3ReleaseTempReg(pParse, regRecord);
2060
2061 /* Jump here when skipping the initialization */
2062 sqlite3VdbeJumpHere(v, addrInit);
2063}
drhc6339082010-04-07 16:54:58 +00002064#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00002065
drh9eff6162006-06-12 21:59:13 +00002066#ifndef SQLITE_OMIT_VIRTUALTABLE
2067/*
danielk19771d461462009-04-21 09:02:45 +00002068** Allocate and populate an sqlite3_index_info structure. It is the
2069** responsibility of the caller to eventually release the structure
2070** by passing the pointer returned by this function to sqlite3_free().
2071*/
drh5346e952013-05-08 14:14:26 +00002072static sqlite3_index_info *allocateIndexInfo(
2073 Parse *pParse,
2074 WhereClause *pWC,
2075 struct SrcList_item *pSrc,
2076 ExprList *pOrderBy
2077){
danielk19771d461462009-04-21 09:02:45 +00002078 int i, j;
2079 int nTerm;
2080 struct sqlite3_index_constraint *pIdxCons;
2081 struct sqlite3_index_orderby *pIdxOrderBy;
2082 struct sqlite3_index_constraint_usage *pUsage;
2083 WhereTerm *pTerm;
2084 int nOrderBy;
2085 sqlite3_index_info *pIdxInfo;
2086
drhf1b5f5b2013-05-02 00:15:01 +00002087 /*WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));*/
danielk19771d461462009-04-21 09:02:45 +00002088
2089 /* Count the number of possible WHERE clause constraints referring
2090 ** to this virtual table */
2091 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
2092 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00002093 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2094 testcase( pTerm->eOperator & WO_IN );
2095 testcase( pTerm->eOperator & WO_ISNULL );
drh281bbe22012-10-16 23:17:14 +00002096 if( pTerm->eOperator & (WO_ISNULL) ) continue;
drhb4256992011-08-02 01:57:39 +00002097 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00002098 nTerm++;
2099 }
2100
2101 /* If the ORDER BY clause contains only columns in the current
2102 ** virtual table then allocate space for the aOrderBy part of
2103 ** the sqlite3_index_info structure.
2104 */
2105 nOrderBy = 0;
2106 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00002107 int n = pOrderBy->nExpr;
2108 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00002109 Expr *pExpr = pOrderBy->a[i].pExpr;
2110 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
2111 }
drh56f1b992012-09-25 14:29:39 +00002112 if( i==n){
2113 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00002114 }
2115 }
2116
2117 /* Allocate the sqlite3_index_info structure
2118 */
2119 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
2120 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
2121 + sizeof(*pIdxOrderBy)*nOrderBy );
2122 if( pIdxInfo==0 ){
2123 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00002124 return 0;
2125 }
2126
2127 /* Initialize the structure. The sqlite3_index_info structure contains
2128 ** many fields that are declared "const" to prevent xBestIndex from
2129 ** changing them. We have to do some funky casting in order to
2130 ** initialize those fields.
2131 */
2132 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
2133 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
2134 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
2135 *(int*)&pIdxInfo->nConstraint = nTerm;
2136 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
2137 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
2138 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
2139 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
2140 pUsage;
2141
2142 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00002143 u8 op;
danielk19771d461462009-04-21 09:02:45 +00002144 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00002145 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2146 testcase( pTerm->eOperator & WO_IN );
2147 testcase( pTerm->eOperator & WO_ISNULL );
drh281bbe22012-10-16 23:17:14 +00002148 if( pTerm->eOperator & (WO_ISNULL) ) continue;
drhb4256992011-08-02 01:57:39 +00002149 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00002150 pIdxCons[j].iColumn = pTerm->u.leftColumn;
2151 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00002152 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00002153 if( op==WO_IN ) op = WO_EQ;
2154 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00002155 /* The direct assignment in the previous line is possible only because
2156 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
2157 ** following asserts verify this fact. */
2158 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
2159 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
2160 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
2161 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
2162 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
2163 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00002164 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00002165 j++;
2166 }
2167 for(i=0; i<nOrderBy; i++){
2168 Expr *pExpr = pOrderBy->a[i].pExpr;
2169 pIdxOrderBy[i].iColumn = pExpr->iColumn;
2170 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
2171 }
2172
2173 return pIdxInfo;
2174}
2175
2176/*
2177** The table object reference passed as the second argument to this function
2178** must represent a virtual table. This function invokes the xBestIndex()
2179** method of the virtual table with the sqlite3_index_info pointer passed
2180** as the argument.
2181**
2182** If an error occurs, pParse is populated with an error message and a
2183** non-zero value is returned. Otherwise, 0 is returned and the output
2184** part of the sqlite3_index_info structure is left populated.
2185**
2186** Whether or not an error is returned, it is the responsibility of the
2187** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
2188** that this is required.
2189*/
2190static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00002191 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00002192 int i;
2193 int rc;
2194
drhf1b5f5b2013-05-02 00:15:01 +00002195 /*WHERETRACE(("xBestIndex for %s\n", pTab->zName));*/
danielk19771d461462009-04-21 09:02:45 +00002196 TRACE_IDX_INPUTS(p);
2197 rc = pVtab->pModule->xBestIndex(pVtab, p);
2198 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00002199
2200 if( rc!=SQLITE_OK ){
2201 if( rc==SQLITE_NOMEM ){
2202 pParse->db->mallocFailed = 1;
2203 }else if( !pVtab->zErrMsg ){
2204 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
2205 }else{
2206 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
2207 }
2208 }
drhb9755982010-07-24 16:34:37 +00002209 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00002210 pVtab->zErrMsg = 0;
2211
2212 for(i=0; i<p->nConstraint; i++){
2213 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
2214 sqlite3ErrorMsg(pParse,
2215 "table %s: xBestIndex returned an invalid plan", pTab->zName);
2216 }
2217 }
2218
2219 return pParse->nErr;
2220}
drh7ba39a92013-05-30 17:43:19 +00002221#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00002222
2223
drhfaacf172011-08-12 01:51:45 +00002224#ifdef SQLITE_ENABLE_STAT3
drh28c4cf42005-07-27 20:41:43 +00002225/*
drhfaacf172011-08-12 01:51:45 +00002226** Estimate the location of a particular key among all keys in an
2227** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00002228**
drhfaacf172011-08-12 01:51:45 +00002229** aStat[0] Est. number of rows less than pVal
2230** aStat[1] Est. number of rows equal to pVal
dan02fa4692009-08-17 17:06:58 +00002231**
drhfaacf172011-08-12 01:51:45 +00002232** Return SQLITE_OK on success.
dan02fa4692009-08-17 17:06:58 +00002233*/
drhfaacf172011-08-12 01:51:45 +00002234static int whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00002235 Parse *pParse, /* Database connection */
2236 Index *pIdx, /* Index to consider domain of */
2237 sqlite3_value *pVal, /* Value to consider */
drhfaacf172011-08-12 01:51:45 +00002238 int roundUp, /* Round up if true. Round down if false */
2239 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00002240){
drhfaacf172011-08-12 01:51:45 +00002241 tRowcnt n;
2242 IndexSample *aSample;
2243 int i, eType;
2244 int isEq = 0;
drh4e50c5e2011-08-13 19:35:19 +00002245 i64 v;
drh4efc9292013-06-06 23:02:03 +00002246 WhereCost r, rS;
dan02fa4692009-08-17 17:06:58 +00002247
drhfaacf172011-08-12 01:51:45 +00002248 assert( roundUp==0 || roundUp==1 );
drh5c624862011-09-22 18:46:34 +00002249 assert( pIdx->nSample>0 );
drhfaacf172011-08-12 01:51:45 +00002250 if( pVal==0 ) return SQLITE_ERROR;
2251 n = pIdx->aiRowEst[0];
2252 aSample = pIdx->aSample;
drhfaacf172011-08-12 01:51:45 +00002253 eType = sqlite3_value_type(pVal);
2254
2255 if( eType==SQLITE_INTEGER ){
drh4e50c5e2011-08-13 19:35:19 +00002256 v = sqlite3_value_int64(pVal);
2257 r = (i64)v;
drhfaacf172011-08-12 01:51:45 +00002258 for(i=0; i<pIdx->nSample; i++){
2259 if( aSample[i].eType==SQLITE_NULL ) continue;
2260 if( aSample[i].eType>=SQLITE_TEXT ) break;
drh4e50c5e2011-08-13 19:35:19 +00002261 if( aSample[i].eType==SQLITE_INTEGER ){
2262 if( aSample[i].u.i>=v ){
2263 isEq = aSample[i].u.i==v;
2264 break;
2265 }
2266 }else{
2267 assert( aSample[i].eType==SQLITE_FLOAT );
2268 if( aSample[i].u.r>=r ){
2269 isEq = aSample[i].u.r==r;
2270 break;
2271 }
dan02fa4692009-08-17 17:06:58 +00002272 }
drhfaacf172011-08-12 01:51:45 +00002273 }
2274 }else if( eType==SQLITE_FLOAT ){
drh4e50c5e2011-08-13 19:35:19 +00002275 r = sqlite3_value_double(pVal);
drhfaacf172011-08-12 01:51:45 +00002276 for(i=0; i<pIdx->nSample; i++){
2277 if( aSample[i].eType==SQLITE_NULL ) continue;
2278 if( aSample[i].eType>=SQLITE_TEXT ) break;
drh4e50c5e2011-08-13 19:35:19 +00002279 if( aSample[i].eType==SQLITE_FLOAT ){
2280 rS = aSample[i].u.r;
2281 }else{
2282 rS = aSample[i].u.i;
2283 }
2284 if( rS>=r ){
2285 isEq = rS==r;
drhfaacf172011-08-12 01:51:45 +00002286 break;
drh9b3eb0a2011-01-21 14:37:04 +00002287 }
drhfaacf172011-08-12 01:51:45 +00002288 }
2289 }else if( eType==SQLITE_NULL ){
2290 i = 0;
drh5c624862011-09-22 18:46:34 +00002291 if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
drhfaacf172011-08-12 01:51:45 +00002292 }else{
2293 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
2294 for(i=0; i<pIdx->nSample; i++){
2295 if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
2296 break;
2297 }
2298 }
2299 if( i<pIdx->nSample ){
dan02fa4692009-08-17 17:06:58 +00002300 sqlite3 *db = pParse->db;
2301 CollSeq *pColl;
2302 const u8 *z;
dan02fa4692009-08-17 17:06:58 +00002303 if( eType==SQLITE_BLOB ){
2304 z = (const u8 *)sqlite3_value_blob(pVal);
2305 pColl = db->pDfltColl;
dane275dc32009-08-18 16:24:58 +00002306 assert( pColl->enc==SQLITE_UTF8 );
dan02fa4692009-08-17 17:06:58 +00002307 }else{
drh79e72a52012-10-05 14:43:40 +00002308 pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
drh9aeda792009-08-20 02:34:15 +00002309 if( pColl==0 ){
dane275dc32009-08-18 16:24:58 +00002310 return SQLITE_ERROR;
2311 }
dan02fa4692009-08-17 17:06:58 +00002312 z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
dane275dc32009-08-18 16:24:58 +00002313 if( !z ){
2314 return SQLITE_NOMEM;
2315 }
dan02fa4692009-08-17 17:06:58 +00002316 assert( z && pColl && pColl->xCmp );
2317 }
2318 n = sqlite3ValueBytes(pVal, pColl->enc);
drhfaacf172011-08-12 01:51:45 +00002319
2320 for(; i<pIdx->nSample; i++){
drhe847d322011-01-20 02:56:37 +00002321 int c;
dan02fa4692009-08-17 17:06:58 +00002322 int eSampletype = aSample[i].eType;
drhfaacf172011-08-12 01:51:45 +00002323 if( eSampletype<eType ) continue;
2324 if( eSampletype!=eType ) break;
dane83c4f32009-09-21 16:34:24 +00002325#ifndef SQLITE_OMIT_UTF16
2326 if( pColl->enc!=SQLITE_UTF8 ){
dane275dc32009-08-18 16:24:58 +00002327 int nSample;
2328 char *zSample = sqlite3Utf8to16(
dan02fa4692009-08-17 17:06:58 +00002329 db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
2330 );
dane275dc32009-08-18 16:24:58 +00002331 if( !zSample ){
2332 assert( db->mallocFailed );
2333 return SQLITE_NOMEM;
2334 }
drhe847d322011-01-20 02:56:37 +00002335 c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
dane275dc32009-08-18 16:24:58 +00002336 sqlite3DbFree(db, zSample);
dane83c4f32009-09-21 16:34:24 +00002337 }else
2338#endif
2339 {
drhe847d322011-01-20 02:56:37 +00002340 c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
dan02fa4692009-08-17 17:06:58 +00002341 }
drhfaacf172011-08-12 01:51:45 +00002342 if( c>=0 ){
2343 if( c==0 ) isEq = 1;
2344 break;
2345 }
dan02fa4692009-08-17 17:06:58 +00002346 }
2347 }
drhfaacf172011-08-12 01:51:45 +00002348 }
dan02fa4692009-08-17 17:06:58 +00002349
drhfaacf172011-08-12 01:51:45 +00002350 /* At this point, aSample[i] is the first sample that is greater than
2351 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
2352 ** than pVal. If aSample[i]==pVal, then isEq==1.
2353 */
2354 if( isEq ){
2355 assert( i<pIdx->nSample );
2356 aStat[0] = aSample[i].nLt;
2357 aStat[1] = aSample[i].nEq;
2358 }else{
2359 tRowcnt iLower, iUpper, iGap;
2360 if( i==0 ){
2361 iLower = 0;
2362 iUpper = aSample[0].nLt;
drhfaacf172011-08-12 01:51:45 +00002363 }else{
drh4e50c5e2011-08-13 19:35:19 +00002364 iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
drhfaacf172011-08-12 01:51:45 +00002365 iLower = aSample[i-1].nEq + aSample[i-1].nLt;
drhfaacf172011-08-12 01:51:45 +00002366 }
drh4e50c5e2011-08-13 19:35:19 +00002367 aStat[1] = pIdx->avgEq;
drhfaacf172011-08-12 01:51:45 +00002368 if( iLower>=iUpper ){
2369 iGap = 0;
2370 }else{
2371 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00002372 }
2373 if( roundUp ){
2374 iGap = (iGap*2)/3;
2375 }else{
2376 iGap = iGap/3;
2377 }
2378 aStat[0] = iLower + iGap;
dan02fa4692009-08-17 17:06:58 +00002379 }
2380 return SQLITE_OK;
2381}
drhfaacf172011-08-12 01:51:45 +00002382#endif /* SQLITE_ENABLE_STAT3 */
dan02fa4692009-08-17 17:06:58 +00002383
2384/*
dan937d0de2009-10-15 18:35:38 +00002385** If expression pExpr represents a literal value, set *pp to point to
2386** an sqlite3_value structure containing the same value, with affinity
2387** aff applied to it, before returning. It is the responsibility of the
2388** caller to eventually release this structure by passing it to
2389** sqlite3ValueFree().
2390**
2391** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
2392** is an SQL variable that currently has a non-NULL value bound to it,
2393** create an sqlite3_value structure containing this value, again with
2394** affinity aff applied to it, instead.
2395**
2396** If neither of the above apply, set *pp to NULL.
2397**
2398** If an error occurs, return an error code. Otherwise, SQLITE_OK.
2399*/
drhfaacf172011-08-12 01:51:45 +00002400#ifdef SQLITE_ENABLE_STAT3
dan937d0de2009-10-15 18:35:38 +00002401static int valueFromExpr(
2402 Parse *pParse,
2403 Expr *pExpr,
2404 u8 aff,
2405 sqlite3_value **pp
2406){
drh4278d532010-12-16 19:52:52 +00002407 if( pExpr->op==TK_VARIABLE
2408 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
2409 ){
dan937d0de2009-10-15 18:35:38 +00002410 int iVar = pExpr->iColumn;
drhf9b22ca2011-10-21 16:47:31 +00002411 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
dan937d0de2009-10-15 18:35:38 +00002412 *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
2413 return SQLITE_OK;
2414 }
2415 return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
2416}
danf7b0b0a2009-10-19 15:52:32 +00002417#endif
dan937d0de2009-10-15 18:35:38 +00002418
2419/*
dan02fa4692009-08-17 17:06:58 +00002420** This function is used to estimate the number of rows that will be visited
2421** by scanning an index for a range of values. The range may have an upper
2422** bound, a lower bound, or both. The WHERE clause terms that set the upper
2423** and lower bounds are represented by pLower and pUpper respectively. For
2424** example, assuming that index p is on t1(a):
2425**
2426** ... FROM t1 WHERE a > ? AND a < ? ...
2427** |_____| |_____|
2428** | |
2429** pLower pUpper
2430**
drh98cdf622009-08-20 18:14:42 +00002431** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00002432** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00002433**
2434** The nEq parameter is passed the index of the index column subject to the
2435** range constraint. Or, equivalently, the number of equality constraints
2436** optimized by the proposed index scan. For example, assuming index p is
2437** on t1(a, b), and the SQL query is:
2438**
2439** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2440**
2441** then nEq should be passed the value 1 (as the range restricted column,
2442** b, is the second left-most column of the index). Or, if the query is:
2443**
2444** ... FROM t1 WHERE a > ? AND a < ? ...
2445**
2446** then nEq should be passed 0.
2447**
drhfaacf172011-08-12 01:51:45 +00002448** The returned value is an integer divisor to reduce the estimated
2449** search space. A return value of 1 means that range constraints are
2450** no help at all. A return value of 2 means range constraints are
2451** expected to reduce the search space by half. And so forth...
drh98cdf622009-08-20 18:14:42 +00002452**
drhfaacf172011-08-12 01:51:45 +00002453** In the absence of sqlite_stat3 ANALYZE data, each range inequality
2454** reduces the search space by a factor of 4. Hence a single constraint (x>?)
2455** results in a return of 4 and a range constraint (x>? AND x<?) results
2456** in a return of 16.
dan02fa4692009-08-17 17:06:58 +00002457*/
2458static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002459 Parse *pParse, /* Parsing & code generating context */
2460 Index *p, /* The index containing the range-compared column; "x" */
2461 int nEq, /* index into p->aCol[] of the range-compared column */
2462 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2463 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
drh4efc9292013-06-06 23:02:03 +00002464 WhereCost *pRangeDiv /* OUT: Reduce search space by this divisor */
dan02fa4692009-08-17 17:06:58 +00002465){
dan69188d92009-08-19 08:18:32 +00002466 int rc = SQLITE_OK;
2467
drhfaacf172011-08-12 01:51:45 +00002468#ifdef SQLITE_ENABLE_STAT3
dan02fa4692009-08-17 17:06:58 +00002469
drhfaacf172011-08-12 01:51:45 +00002470 if( nEq==0 && p->nSample ){
2471 sqlite3_value *pRangeVal;
2472 tRowcnt iLower = 0;
2473 tRowcnt iUpper = p->aiRowEst[0];
2474 tRowcnt a[2];
dan937d0de2009-10-15 18:35:38 +00002475 u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
drh98cdf622009-08-20 18:14:42 +00002476
dan02fa4692009-08-17 17:06:58 +00002477 if( pLower ){
2478 Expr *pExpr = pLower->pExpr->pRight;
drhfaacf172011-08-12 01:51:45 +00002479 rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
drh7a5bcc02013-01-16 17:08:58 +00002480 assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
drhfaacf172011-08-12 01:51:45 +00002481 if( rc==SQLITE_OK
2482 && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
2483 ){
2484 iLower = a[0];
drh7a5bcc02013-01-16 17:08:58 +00002485 if( (pLower->eOperator & WO_GT)!=0 ) iLower += a[1];
drhfaacf172011-08-12 01:51:45 +00002486 }
2487 sqlite3ValueFree(pRangeVal);
dan02fa4692009-08-17 17:06:58 +00002488 }
drh98cdf622009-08-20 18:14:42 +00002489 if( rc==SQLITE_OK && pUpper ){
dan02fa4692009-08-17 17:06:58 +00002490 Expr *pExpr = pUpper->pExpr->pRight;
drhfaacf172011-08-12 01:51:45 +00002491 rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
drh7a5bcc02013-01-16 17:08:58 +00002492 assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
drhfaacf172011-08-12 01:51:45 +00002493 if( rc==SQLITE_OK
2494 && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
2495 ){
2496 iUpper = a[0];
drh7a5bcc02013-01-16 17:08:58 +00002497 if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
dan02fa4692009-08-17 17:06:58 +00002498 }
drhfaacf172011-08-12 01:51:45 +00002499 sqlite3ValueFree(pRangeVal);
dan02fa4692009-08-17 17:06:58 +00002500 }
drhfaacf172011-08-12 01:51:45 +00002501 if( rc==SQLITE_OK ){
2502 if( iUpper<=iLower ){
drh4efc9292013-06-06 23:02:03 +00002503 *pRangeDiv = (WhereCost)p->aiRowEst[0];
drhfaacf172011-08-12 01:51:45 +00002504 }else{
drh4efc9292013-06-06 23:02:03 +00002505 *pRangeDiv = (WhereCost)p->aiRowEst[0]/(WhereCost)(iUpper - iLower);
drhfaacf172011-08-12 01:51:45 +00002506 }
drhf1b5f5b2013-05-02 00:15:01 +00002507 /*WHERETRACE(("range scan regions: %u..%u div=%g\n",
2508 (u32)iLower, (u32)iUpper, *pRangeDiv));*/
drhfaacf172011-08-12 01:51:45 +00002509 return SQLITE_OK;
drh98cdf622009-08-20 18:14:42 +00002510 }
dan02fa4692009-08-17 17:06:58 +00002511 }
drh3f022182009-09-09 16:10:50 +00002512#else
2513 UNUSED_PARAMETER(pParse);
2514 UNUSED_PARAMETER(p);
2515 UNUSED_PARAMETER(nEq);
dan69188d92009-08-19 08:18:32 +00002516#endif
dan02fa4692009-08-17 17:06:58 +00002517 assert( pLower || pUpper );
drh4efc9292013-06-06 23:02:03 +00002518 *pRangeDiv = (WhereCost)1;
2519 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (WhereCost)4;
2520 if( pUpper ) *pRangeDiv *= (WhereCost)4;
dan02fa4692009-08-17 17:06:58 +00002521 return rc;
2522}
2523
drhfaacf172011-08-12 01:51:45 +00002524#ifdef SQLITE_ENABLE_STAT3
drh82759752011-01-20 16:52:09 +00002525/*
2526** Estimate the number of rows that will be returned based on
2527** an equality constraint x=VALUE and where that VALUE occurs in
2528** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002529** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002530** for that index. When pExpr==NULL that means the constraint is
2531** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002532**
drh0c50fa02011-01-21 16:27:18 +00002533** Write the estimated row count into *pnRow and return SQLITE_OK.
2534** If unable to make an estimate, leave *pnRow unchanged and return
2535** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002536**
2537** This routine can fail if it is unable to load a collating sequence
2538** required for string comparison, or if unable to allocate memory
2539** for a UTF conversion required for comparison. The error is stored
2540** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002541*/
drh041e09f2011-04-07 19:56:21 +00002542static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002543 Parse *pParse, /* Parsing & code generating context */
2544 Index *p, /* The index whose left-most column is pTerm */
drh0c50fa02011-01-21 16:27:18 +00002545 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drh4efc9292013-06-06 23:02:03 +00002546 WhereCost *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002547){
2548 sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
drh82759752011-01-20 16:52:09 +00002549 u8 aff; /* Column affinity */
2550 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002551 tRowcnt a[2]; /* Statistics */
drh82759752011-01-20 16:52:09 +00002552
2553 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002554 assert( p->nSample>0 );
drh82759752011-01-20 16:52:09 +00002555 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
drh1f9c7662011-03-17 01:34:26 +00002556 if( pExpr ){
2557 rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
2558 if( rc ) goto whereEqualScanEst_cancel;
2559 }else{
2560 pRhs = sqlite3ValueNew(pParse->db);
2561 }
drh0c50fa02011-01-21 16:27:18 +00002562 if( pRhs==0 ) return SQLITE_NOTFOUND;
drhfaacf172011-08-12 01:51:45 +00002563 rc = whereKeyStats(pParse, p, pRhs, 0, a);
2564 if( rc==SQLITE_OK ){
drhf1b5f5b2013-05-02 00:15:01 +00002565 /*WHERETRACE(("equality scan regions: %d\n", (int)a[1]));*/
drhfaacf172011-08-12 01:51:45 +00002566 *pnRow = a[1];
drh82759752011-01-20 16:52:09 +00002567 }
drh0c50fa02011-01-21 16:27:18 +00002568whereEqualScanEst_cancel:
drh82759752011-01-20 16:52:09 +00002569 sqlite3ValueFree(pRhs);
drh0c50fa02011-01-21 16:27:18 +00002570 return rc;
2571}
drhfaacf172011-08-12 01:51:45 +00002572#endif /* defined(SQLITE_ENABLE_STAT3) */
drh0c50fa02011-01-21 16:27:18 +00002573
drhfaacf172011-08-12 01:51:45 +00002574#ifdef SQLITE_ENABLE_STAT3
drh0c50fa02011-01-21 16:27:18 +00002575/*
2576** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002577** an IN constraint where the right-hand side of the IN operator
2578** is a list of values. Example:
2579**
2580** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002581**
2582** Write the estimated row count into *pnRow and return SQLITE_OK.
2583** If unable to make an estimate, leave *pnRow unchanged and return
2584** non-zero.
2585**
2586** This routine can fail if it is unable to load a collating sequence
2587** required for string comparison, or if unable to allocate memory
2588** for a UTF conversion required for comparison. The error is stored
2589** in the pParse structure.
2590*/
drh041e09f2011-04-07 19:56:21 +00002591static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002592 Parse *pParse, /* Parsing & code generating context */
2593 Index *p, /* The index whose left-most column is pTerm */
2594 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drh4efc9292013-06-06 23:02:03 +00002595 WhereCost *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002596){
drh68257192011-08-16 17:06:21 +00002597 int rc = SQLITE_OK; /* Subfunction return code */
drh4efc9292013-06-06 23:02:03 +00002598 WhereCost nEst; /* Number of rows for a single term */
2599 WhereCost nRowEst = (WhereCost)0; /* New estimate of the number of rows */
drh68257192011-08-16 17:06:21 +00002600 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002601
2602 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002603 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2604 nEst = p->aiRowEst[0];
2605 rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
2606 nRowEst += nEst;
drh0c50fa02011-01-21 16:27:18 +00002607 }
2608 if( rc==SQLITE_OK ){
drh0c50fa02011-01-21 16:27:18 +00002609 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
2610 *pnRow = nRowEst;
drhf1b5f5b2013-05-02 00:15:01 +00002611 /*WHERETRACE(("IN row estimate: est=%g\n", nRowEst));*/
drh0c50fa02011-01-21 16:27:18 +00002612 }
drh0c50fa02011-01-21 16:27:18 +00002613 return rc;
drh82759752011-01-20 16:52:09 +00002614}
drhfaacf172011-08-12 01:51:45 +00002615#endif /* defined(SQLITE_ENABLE_STAT3) */
drh82759752011-01-20 16:52:09 +00002616
drh46c35f92012-09-26 23:17:01 +00002617/*
drh2ffb1182004-07-19 19:14:01 +00002618** Disable a term in the WHERE clause. Except, do not disable the term
2619** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2620** or USING clause of that join.
2621**
2622** Consider the term t2.z='ok' in the following queries:
2623**
2624** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2625** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2626** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2627**
drh23bf66d2004-12-14 03:34:34 +00002628** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002629** in the ON clause. The term is disabled in (3) because it is not part
2630** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2631**
drhe9cdcea2010-07-22 22:40:03 +00002632** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
2633** completely satisfied by indices.
2634**
drh2ffb1182004-07-19 19:14:01 +00002635** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002636** of the join. Disabling is an optimization. When terms are satisfied
2637** by indices, we disable them to prevent redundant tests in the inner
2638** loop. We would get the correct results if nothing were ever disabled,
2639** but joins might run a little slower. The trick is to disable as much
2640** as we can without disabling too much. If we disabled in (1), we'd get
2641** the wrong answer. See ticket #813.
drh2ffb1182004-07-19 19:14:01 +00002642*/
drh0fcef5e2005-07-19 17:38:22 +00002643static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
2644 if( pTerm
drhbe837bd2010-04-30 21:03:24 +00002645 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002646 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
2647 ){
drh165be382008-12-05 02:36:33 +00002648 pTerm->wtFlags |= TERM_CODED;
drh45b1ee42005-08-02 17:48:22 +00002649 if( pTerm->iParent>=0 ){
2650 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
2651 if( (--pOther->nChild)==0 ){
drhed378002005-07-28 23:12:08 +00002652 disableTerm(pLevel, pOther);
2653 }
drh0fcef5e2005-07-19 17:38:22 +00002654 }
drh2ffb1182004-07-19 19:14:01 +00002655 }
2656}
2657
2658/*
dan69f8bb92009-08-13 19:21:16 +00002659** Code an OP_Affinity opcode to apply the column affinity string zAff
2660** to the n registers starting at base.
2661**
drh039fc322009-11-17 18:31:47 +00002662** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2663** beginning and end of zAff are ignored. If all entries in zAff are
2664** SQLITE_AFF_NONE, then no code gets generated.
2665**
2666** This routine makes its own copy of zAff so that the caller is free
2667** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002668*/
dan69f8bb92009-08-13 19:21:16 +00002669static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2670 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002671 if( zAff==0 ){
2672 assert( pParse->db->mallocFailed );
2673 return;
2674 }
dan69f8bb92009-08-13 19:21:16 +00002675 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002676
2677 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2678 ** and end of the affinity string.
2679 */
2680 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2681 n--;
2682 base++;
2683 zAff++;
2684 }
2685 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2686 n--;
2687 }
2688
2689 /* Code the OP_Affinity opcode if there is anything left to do. */
2690 if( n>0 ){
2691 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2692 sqlite3VdbeChangeP4(v, -1, zAff, n);
2693 sqlite3ExprCacheAffinityChange(pParse, base, n);
2694 }
drh94a11212004-09-25 13:12:14 +00002695}
2696
drhe8b97272005-07-19 22:22:12 +00002697
2698/*
drh51147ba2005-07-23 22:59:55 +00002699** Generate code for a single equality term of the WHERE clause. An equality
2700** term can be either X=expr or X IN (...). pTerm is the term to be
2701** coded.
2702**
drh1db639c2008-01-17 02:36:28 +00002703** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002704**
2705** For a constraint of the form X=expr, the expression is evaluated and its
2706** result is left on the stack. For constraints of the form X IN (...)
2707** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002708*/
drh678ccce2008-03-31 18:19:54 +00002709static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002710 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002711 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh0fe456b2013-03-12 18:34:50 +00002712 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
2713 int iEq, /* Index of the equality term within this level */
drh7ba39a92013-05-30 17:43:19 +00002714 int bRev, /* True for reverse-order IN operations */
drh678ccce2008-03-31 18:19:54 +00002715 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002716){
drh0fcef5e2005-07-19 17:38:22 +00002717 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002718 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002719 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002720
danielk19772d605492008-10-01 08:43:03 +00002721 assert( iTarget>0 );
drh50b39962006-10-28 00:28:09 +00002722 if( pX->op==TK_EQ ){
drh678ccce2008-03-31 18:19:54 +00002723 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002724 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002725 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002726 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002727#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002728 }else{
danielk19779a96b662007-11-29 17:05:18 +00002729 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002730 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002731 struct InLoop *pIn;
drh7ba39a92013-05-30 17:43:19 +00002732 WhereLoop *pLoop = pLevel->pWLoop;
danielk1977b3bce662005-01-29 08:32:43 +00002733
drh7ba39a92013-05-30 17:43:19 +00002734 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
2735 && pLoop->u.btree.pIndex!=0
2736 && pLoop->u.btree.pIndex->aSortOrder[iEq]
drhd3832162013-03-12 18:49:25 +00002737 ){
drh725e1ae2013-03-12 23:58:42 +00002738 testcase( iEq==0 );
2739 testcase( iEq==pLevel->plan.u.pIdx->nColumn-1 );
2740 testcase( iEq>0 && iEq+1<pLevel->plan.u.pIdx->nColumn );
2741 testcase( bRev );
drh1ccce442013-03-12 20:38:51 +00002742 bRev = !bRev;
drh0fe456b2013-03-12 18:34:50 +00002743 }
drh50b39962006-10-28 00:28:09 +00002744 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002745 iReg = iTarget;
danielk19770cdc0222008-06-26 18:04:03 +00002746 eType = sqlite3FindInIndex(pParse, pX, 0);
drh725e1ae2013-03-12 23:58:42 +00002747 if( eType==IN_INDEX_INDEX_DESC ){
2748 testcase( bRev );
2749 bRev = !bRev;
2750 }
danielk1977b3bce662005-01-29 08:32:43 +00002751 iTab = pX->iTable;
drh2d96b932013-02-08 18:48:23 +00002752 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
drh6fa978d2013-05-30 19:29:19 +00002753 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
2754 pLoop->wsFlags |= WHERE_IN_ABLE;
drh111a6a72008-12-21 03:51:16 +00002755 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002756 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00002757 }
drh111a6a72008-12-21 03:51:16 +00002758 pLevel->u.in.nIn++;
2759 pLevel->u.in.aInLoop =
2760 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2761 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2762 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00002763 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00002764 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00002765 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00002766 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00002767 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00002768 }else{
drhb3190c12008-12-08 21:37:14 +00002769 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00002770 }
drh2d96b932013-02-08 18:48:23 +00002771 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
drh1db639c2008-01-17 02:36:28 +00002772 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
drha6110402005-07-28 20:51:19 +00002773 }else{
drh111a6a72008-12-21 03:51:16 +00002774 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00002775 }
danielk1977b3bce662005-01-29 08:32:43 +00002776#endif
drh94a11212004-09-25 13:12:14 +00002777 }
drh0fcef5e2005-07-19 17:38:22 +00002778 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00002779 return iReg;
drh94a11212004-09-25 13:12:14 +00002780}
2781
drh51147ba2005-07-23 22:59:55 +00002782/*
2783** Generate code that will evaluate all == and IN constraints for an
drh039fc322009-11-17 18:31:47 +00002784** index.
drh51147ba2005-07-23 22:59:55 +00002785**
2786** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2787** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
2788** The index has as many as three equality constraints, but in this
2789** example, the third "c" value is an inequality. So only two
2790** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00002791** a==5 and b IN (1,2,3). The current values for a and b will be stored
2792** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00002793**
2794** In the example above nEq==2. But this subroutine works for any value
2795** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00002796** The only thing it does is allocate the pLevel->iMem memory cell and
2797** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00002798**
drh700a2262008-12-17 19:22:15 +00002799** This routine always allocates at least one memory cell and returns
2800** the index of that memory cell. The code that
2801** calls this routine will use that memory cell to store the termination
drh51147ba2005-07-23 22:59:55 +00002802** key value of the loop. If one or more IN operators appear, then
2803** this routine allocates an additional nEq memory cells for internal
2804** use.
dan69f8bb92009-08-13 19:21:16 +00002805**
2806** Before returning, *pzAff is set to point to a buffer containing a
2807** copy of the column affinity string of the index allocated using
2808** sqlite3DbMalloc(). Except, entries in the copy of the string associated
2809** with equality constraints that use NONE affinity are set to
2810** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
2811**
2812** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
2813** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
2814**
2815** In the example above, the index on t1(a) has TEXT affinity. But since
2816** the right hand side of the equality constraint (t2.b) has NONE affinity,
2817** no conversion should be attempted before using a t2.b value as part of
2818** a key to search the index. Hence the first byte in the returned affinity
2819** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00002820*/
drh1db639c2008-01-17 02:36:28 +00002821static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00002822 Parse *pParse, /* Parsing context */
2823 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
2824 WhereClause *pWC, /* The WHERE clause */
drh1db639c2008-01-17 02:36:28 +00002825 Bitmask notReady, /* Which parts of FROM have not yet been coded */
drh7ba39a92013-05-30 17:43:19 +00002826 int bRev, /* Reverse the order of IN operators */
dan69f8bb92009-08-13 19:21:16 +00002827 int nExtraReg, /* Number of extra registers to allocate */
2828 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00002829){
drh7ba39a92013-05-30 17:43:19 +00002830 int nEq; /* The number of == or IN constraints to code */
drh111a6a72008-12-21 03:51:16 +00002831 Vdbe *v = pParse->pVdbe; /* The vm under construction */
2832 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00002833 WhereTerm *pTerm; /* A single constraint term */
drh7ba39a92013-05-30 17:43:19 +00002834 WhereLoop *pLoop; /* The WhereLoop object */
drh51147ba2005-07-23 22:59:55 +00002835 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00002836 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00002837 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00002838 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00002839
drh111a6a72008-12-21 03:51:16 +00002840 /* This module is only called on query plans that use an index. */
drh7ba39a92013-05-30 17:43:19 +00002841 pLoop = pLevel->pWLoop;
2842 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
2843 nEq = pLoop->u.btree.nEq;
2844 pIdx = pLoop->u.btree.pIndex;
2845 assert( pIdx!=0 );
drh111a6a72008-12-21 03:51:16 +00002846
drh51147ba2005-07-23 22:59:55 +00002847 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00002848 */
drh700a2262008-12-17 19:22:15 +00002849 regBase = pParse->nMem + 1;
drh7ba39a92013-05-30 17:43:19 +00002850 nReg = pLoop->u.btree.nEq + nExtraReg;
drh6df2acd2008-12-28 16:55:25 +00002851 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00002852
dan69f8bb92009-08-13 19:21:16 +00002853 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
2854 if( !zAff ){
2855 pParse->db->mallocFailed = 1;
2856 }
2857
drh51147ba2005-07-23 22:59:55 +00002858 /* Evaluate the equality constraints
2859 */
drhc49de5d2007-01-19 01:06:01 +00002860 assert( pIdx->nColumn>=nEq );
2861 for(j=0; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00002862 int r1;
drh4efc9292013-06-06 23:02:03 +00002863 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00002864 assert( pTerm!=0 );
drhbe837bd2010-04-30 21:03:24 +00002865 /* The following true for indices with redundant columns.
2866 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
2867 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drhe9cdcea2010-07-22 22:40:03 +00002868 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh7ba39a92013-05-30 17:43:19 +00002869 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
drh678ccce2008-03-31 18:19:54 +00002870 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00002871 if( nReg==1 ){
2872 sqlite3ReleaseTempReg(pParse, regBase);
2873 regBase = r1;
2874 }else{
2875 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
2876 }
drh678ccce2008-03-31 18:19:54 +00002877 }
drh981642f2008-04-19 14:40:43 +00002878 testcase( pTerm->eOperator & WO_ISNULL );
2879 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00002880 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00002881 Expr *pRight = pTerm->pExpr->pRight;
drh2f2855b2009-11-18 01:25:26 +00002882 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
drh039fc322009-11-17 18:31:47 +00002883 if( zAff ){
2884 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
2885 zAff[j] = SQLITE_AFF_NONE;
2886 }
2887 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
2888 zAff[j] = SQLITE_AFF_NONE;
2889 }
dan69f8bb92009-08-13 19:21:16 +00002890 }
drh51147ba2005-07-23 22:59:55 +00002891 }
2892 }
dan69f8bb92009-08-13 19:21:16 +00002893 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00002894 return regBase;
drh51147ba2005-07-23 22:59:55 +00002895}
2896
dan2ce22452010-11-08 19:01:16 +00002897#ifndef SQLITE_OMIT_EXPLAIN
dan17c0bc02010-11-09 17:35:19 +00002898/*
drh69174c42010-11-12 15:35:59 +00002899** This routine is a helper for explainIndexRange() below
2900**
2901** pStr holds the text of an expression that we are building up one term
2902** at a time. This routine adds a new term to the end of the expression.
2903** Terms are separated by AND so add the "AND" text for second and subsequent
2904** terms only.
2905*/
2906static void explainAppendTerm(
2907 StrAccum *pStr, /* The text expression being built */
2908 int iTerm, /* Index of this term. First is zero */
2909 const char *zColumn, /* Name of the column */
2910 const char *zOp /* Name of the operator */
2911){
2912 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
2913 sqlite3StrAccumAppend(pStr, zColumn, -1);
2914 sqlite3StrAccumAppend(pStr, zOp, 1);
2915 sqlite3StrAccumAppend(pStr, "?", 1);
2916}
2917
2918/*
dan17c0bc02010-11-09 17:35:19 +00002919** Argument pLevel describes a strategy for scanning table pTab. This
2920** function returns a pointer to a string buffer containing a description
2921** of the subset of table rows scanned by the strategy in the form of an
2922** SQL expression. Or, if all rows are scanned, NULL is returned.
2923**
2924** For example, if the query:
2925**
2926** SELECT * FROM t1 WHERE a=1 AND b>2;
2927**
2928** is run and there is an index on (a, b), then this function returns a
2929** string similar to:
2930**
2931** "a=? AND b>?"
2932**
2933** The returned pointer points to memory obtained from sqlite3DbMalloc().
2934** It is the responsibility of the caller to free the buffer when it is
2935** no longer required.
2936*/
drhef866372013-05-22 20:49:02 +00002937static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
2938 Index *pIndex = pLoop->u.btree.pIndex;
2939 int nEq = pLoop->u.btree.nEq;
drh69174c42010-11-12 15:35:59 +00002940 int i, j;
2941 Column *aCol = pTab->aCol;
2942 int *aiColumn = pIndex->aiColumn;
2943 StrAccum txt;
dan2ce22452010-11-08 19:01:16 +00002944
drhef866372013-05-22 20:49:02 +00002945 if( pIndex==0 ) return 0;
2946 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
drh69174c42010-11-12 15:35:59 +00002947 return 0;
2948 }
2949 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
drh03b6df12010-11-15 16:29:30 +00002950 txt.db = db;
drh69174c42010-11-12 15:35:59 +00002951 sqlite3StrAccumAppend(&txt, " (", 2);
dan2ce22452010-11-08 19:01:16 +00002952 for(i=0; i<nEq; i++){
drh69174c42010-11-12 15:35:59 +00002953 explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
dan2ce22452010-11-08 19:01:16 +00002954 }
2955
drh69174c42010-11-12 15:35:59 +00002956 j = i;
drhef866372013-05-22 20:49:02 +00002957 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
dan0c733f62011-11-16 15:27:09 +00002958 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
2959 explainAppendTerm(&txt, i++, z, ">");
dan2ce22452010-11-08 19:01:16 +00002960 }
drhef866372013-05-22 20:49:02 +00002961 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
dan0c733f62011-11-16 15:27:09 +00002962 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
2963 explainAppendTerm(&txt, i, z, "<");
dan2ce22452010-11-08 19:01:16 +00002964 }
drh69174c42010-11-12 15:35:59 +00002965 sqlite3StrAccumAppend(&txt, ")", 1);
2966 return sqlite3StrAccumFinish(&txt);
dan2ce22452010-11-08 19:01:16 +00002967}
2968
dan17c0bc02010-11-09 17:35:19 +00002969/*
2970** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
2971** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
2972** record is added to the output to describe the table scan strategy in
2973** pLevel.
2974*/
2975static void explainOneScan(
dan2ce22452010-11-08 19:01:16 +00002976 Parse *pParse, /* Parse context */
2977 SrcList *pTabList, /* Table list this loop refers to */
2978 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
2979 int iLevel, /* Value for "level" column of output */
dan4a07e3d2010-11-09 14:48:59 +00002980 int iFrom, /* Value for "from" column of output */
2981 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
dan2ce22452010-11-08 19:01:16 +00002982){
2983 if( pParse->explain==2 ){
dan2ce22452010-11-08 19:01:16 +00002984 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
dan17c0bc02010-11-09 17:35:19 +00002985 Vdbe *v = pParse->pVdbe; /* VM being constructed */
2986 sqlite3 *db = pParse->db; /* Database handle */
2987 char *zMsg; /* Text to add to EQP output */
dan4a07e3d2010-11-09 14:48:59 +00002988 sqlite3_int64 nRow; /* Expected number of rows visited by scan */
2989 int iId = pParse->iSelectId; /* Select id (left-most output column) */
dan4bc39fa2010-11-13 16:42:27 +00002990 int isSearch; /* True for a SEARCH. False for SCAN. */
drhef866372013-05-22 20:49:02 +00002991 WhereLoop *pLoop; /* The controlling WhereLoop object */
2992 u32 flags; /* Flags that describe this loop */
dan2ce22452010-11-08 19:01:16 +00002993
drhef866372013-05-22 20:49:02 +00002994 pLoop = pLevel->pWLoop;
2995 flags = pLoop->wsFlags;
dan4a07e3d2010-11-09 14:48:59 +00002996 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
dan2ce22452010-11-08 19:01:16 +00002997
drhef866372013-05-22 20:49:02 +00002998 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
2999 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
3000 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
dan4bc39fa2010-11-13 16:42:27 +00003001
3002 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
dan4a07e3d2010-11-09 14:48:59 +00003003 if( pItem->pSelect ){
dan4bc39fa2010-11-13 16:42:27 +00003004 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
dan4a07e3d2010-11-09 14:48:59 +00003005 }else{
dan4bc39fa2010-11-13 16:42:27 +00003006 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
dan4a07e3d2010-11-09 14:48:59 +00003007 }
3008
dan2ce22452010-11-08 19:01:16 +00003009 if( pItem->zAlias ){
3010 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
3011 }
drhef866372013-05-22 20:49:02 +00003012 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
3013 && pLoop->u.btree.pIndex!=0
3014 ){
3015 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
dan4bc39fa2010-11-13 16:42:27 +00003016 zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
dan2ce22452010-11-08 19:01:16 +00003017 ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
3018 ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
3019 ((flags & WHERE_TEMP_INDEX)?"":" "),
drhef866372013-05-22 20:49:02 +00003020 ((flags & WHERE_TEMP_INDEX)?"": pLoop->u.btree.pIndex->zName),
dan2ce22452010-11-08 19:01:16 +00003021 zWhere
3022 );
3023 sqlite3DbFree(db, zWhere);
drhef71c1f2013-06-04 12:58:02 +00003024 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
dan4bc39fa2010-11-13 16:42:27 +00003025 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
dan2ce22452010-11-08 19:01:16 +00003026
drhef866372013-05-22 20:49:02 +00003027 if( flags&WHERE_COLUMN_EQ ){
dan2ce22452010-11-08 19:01:16 +00003028 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
drh04098e62010-11-15 21:50:19 +00003029 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
dan2ce22452010-11-08 19:01:16 +00003030 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
3031 }else if( flags&WHERE_BTM_LIMIT ){
3032 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
3033 }else if( flags&WHERE_TOP_LIMIT ){
3034 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
3035 }
3036 }
3037#ifndef SQLITE_OMIT_VIRTUALTABLE
3038 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
dan2ce22452010-11-08 19:01:16 +00003039 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
drhef866372013-05-22 20:49:02 +00003040 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
dan2ce22452010-11-08 19:01:16 +00003041 }
3042#endif
dan4a07e3d2010-11-09 14:48:59 +00003043 if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
drh04098e62010-11-15 21:50:19 +00003044 testcase( wctrlFlags & WHERE_ORDERBY_MIN );
dan4a07e3d2010-11-09 14:48:59 +00003045 nRow = 1;
3046 }else{
drhef866372013-05-22 20:49:02 +00003047 nRow = (sqlite3_int64)pLoop->nOut;
dan4a07e3d2010-11-09 14:48:59 +00003048 }
3049 zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
3050 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
dan2ce22452010-11-08 19:01:16 +00003051 }
3052}
3053#else
dan17c0bc02010-11-09 17:35:19 +00003054# define explainOneScan(u,v,w,x,y,z)
dan2ce22452010-11-08 19:01:16 +00003055#endif /* SQLITE_OMIT_EXPLAIN */
3056
3057
drh111a6a72008-12-21 03:51:16 +00003058/*
3059** Generate code for the start of the iLevel-th loop in the WHERE clause
3060** implementation described by pWInfo.
3061*/
3062static Bitmask codeOneLoopStart(
3063 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
3064 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh7a484802012-03-16 00:28:11 +00003065 Bitmask notReady /* Which tables are currently available */
drh111a6a72008-12-21 03:51:16 +00003066){
3067 int j, k; /* Loop counters */
3068 int iCur; /* The VDBE cursor for the table */
3069 int addrNxt; /* Where to jump to continue with the next IN case */
3070 int omitTable; /* True if we use the index only */
3071 int bRev; /* True if we need to scan in reverse order */
3072 WhereLevel *pLevel; /* The where level to be coded */
drh7ba39a92013-05-30 17:43:19 +00003073 WhereLoop *pLoop; /* The WhereLoop object being coded */
drh111a6a72008-12-21 03:51:16 +00003074 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
3075 WhereTerm *pTerm; /* A WHERE clause term */
3076 Parse *pParse; /* Parsing context */
3077 Vdbe *v; /* The prepared stmt under constructions */
3078 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00003079 int addrBrk; /* Jump here to break out of the loop */
3080 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00003081 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
3082 int iReleaseReg = 0; /* Temp register to free before returning */
drh0c41d222013-04-22 02:39:10 +00003083 Bitmask newNotReady; /* Return value */
drh111a6a72008-12-21 03:51:16 +00003084
3085 pParse = pWInfo->pParse;
3086 v = pParse->pVdbe;
drh70d18342013-06-06 19:16:33 +00003087 pWC = &pWInfo->sWC;
drh111a6a72008-12-21 03:51:16 +00003088 pLevel = &pWInfo->a[iLevel];
drh7ba39a92013-05-30 17:43:19 +00003089 pLoop = pLevel->pWLoop;
drh111a6a72008-12-21 03:51:16 +00003090 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
3091 iCur = pTabItem->iCursor;
drh7ba39a92013-05-30 17:43:19 +00003092 bRev = (pWInfo->revMask>>iLevel)&1;
3093 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drh70d18342013-06-06 19:16:33 +00003094 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
drh0c41d222013-04-22 02:39:10 +00003095 VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
drh111a6a72008-12-21 03:51:16 +00003096
3097 /* Create labels for the "break" and "continue" instructions
3098 ** for the current loop. Jump to addrBrk to break out of a loop.
3099 ** Jump to cont to go immediately to the next iteration of the
3100 ** loop.
3101 **
3102 ** When there is an IN operator, we also have a "addrNxt" label that
3103 ** means to continue with the next IN value combination. When
3104 ** there are no IN operators in the constraints, the "addrNxt" label
3105 ** is the same as "addrBrk".
3106 */
3107 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
3108 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
3109
3110 /* If this is the right table of a LEFT OUTER JOIN, allocate and
3111 ** initialize a memory cell that records if this table matches any
3112 ** row of the left table of the join.
3113 */
3114 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
3115 pLevel->iLeftJoin = ++pParse->nMem;
3116 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
3117 VdbeComment((v, "init LEFT JOIN no-match flag"));
3118 }
3119
drh21172c42012-10-30 00:29:07 +00003120 /* Special case of a FROM clause subquery implemented as a co-routine */
3121 if( pTabItem->viaCoroutine ){
3122 int regYield = pTabItem->regReturn;
3123 sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
3124 pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
3125 VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
3126 sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
3127 pLevel->op = OP_Goto;
3128 }else
3129
drh111a6a72008-12-21 03:51:16 +00003130#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00003131 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
3132 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
drh111a6a72008-12-21 03:51:16 +00003133 ** to access the data.
3134 */
3135 int iReg; /* P3 Value for OP_VFilter */
drh281bbe22012-10-16 23:17:14 +00003136 int addrNotFound;
drh4efc9292013-06-06 23:02:03 +00003137 int nConstraint = pLoop->nLTerm;
drh111a6a72008-12-21 03:51:16 +00003138
drha62bb8d2009-11-23 21:23:45 +00003139 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00003140 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh281bbe22012-10-16 23:17:14 +00003141 addrNotFound = pLevel->addrBrk;
drh111a6a72008-12-21 03:51:16 +00003142 for(j=0; j<nConstraint; j++){
drhe2250172013-05-31 18:13:50 +00003143 int iTarget = iReg+j+2;
drh4efc9292013-06-06 23:02:03 +00003144 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00003145 if( pTerm->eOperator & WO_IN ){
3146 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
3147 addrNotFound = pLevel->addrNxt;
3148 }else{
3149 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
3150 }
3151 }
3152 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
drh7e47cb82013-05-31 17:55:27 +00003153 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
drh7ba39a92013-05-30 17:43:19 +00003154 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
3155 pLoop->u.vtab.idxStr,
3156 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
3157 pLoop->u.vtab.needFree = 0;
3158 for(j=0; j<nConstraint && j<16; j++){
3159 if( (pLoop->u.vtab.omitMask>>j)&1 ){
drh4efc9292013-06-06 23:02:03 +00003160 disableTerm(pLevel, pLoop->aLTerm[j]);
drh111a6a72008-12-21 03:51:16 +00003161 }
3162 }
3163 pLevel->op = OP_VNext;
3164 pLevel->p1 = iCur;
3165 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00003166 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drha62bb8d2009-11-23 21:23:45 +00003167 sqlite3ExprCachePop(pParse, 1);
drh111a6a72008-12-21 03:51:16 +00003168 }else
3169#endif /* SQLITE_OMIT_VIRTUALTABLE */
3170
drh7ba39a92013-05-30 17:43:19 +00003171 if( (pLoop->wsFlags & WHERE_IPK)!=0
3172 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
3173 ){
3174 /* Case 2: We can directly reference a single row using an
drh111a6a72008-12-21 03:51:16 +00003175 ** equality comparison against the ROWID field. Or
3176 ** we reference multiple rows using a "rowid IN (...)"
3177 ** construct.
3178 */
drh7ba39a92013-05-30 17:43:19 +00003179 assert( pLoop->u.btree.nEq==1 );
danielk19771d461462009-04-21 09:02:45 +00003180 iReleaseReg = sqlite3GetTempReg(pParse);
drh4efc9292013-06-06 23:02:03 +00003181 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003182 assert( pTerm!=0 );
3183 assert( pTerm->pExpr!=0 );
drh111a6a72008-12-21 03:51:16 +00003184 assert( omitTable==0 );
drhe9cdcea2010-07-22 22:40:03 +00003185 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh7ba39a92013-05-30 17:43:19 +00003186 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00003187 addrNxt = pLevel->addrNxt;
danielk19771d461462009-04-21 09:02:45 +00003188 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
3189 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drh459f63e2013-03-06 01:55:27 +00003190 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
drhceea3322009-04-23 13:22:42 +00003191 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00003192 VdbeComment((v, "pk"));
3193 pLevel->op = OP_Noop;
drh7ba39a92013-05-30 17:43:19 +00003194 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
3195 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
3196 ){
3197 /* Case 3: We have an inequality comparison against the ROWID field.
drh111a6a72008-12-21 03:51:16 +00003198 */
3199 int testOp = OP_Noop;
3200 int start;
3201 int memEndValue = 0;
3202 WhereTerm *pStart, *pEnd;
3203
3204 assert( omitTable==0 );
drh7ba39a92013-05-30 17:43:19 +00003205 j = 0;
3206 pStart = pEnd = 0;
drh4efc9292013-06-06 23:02:03 +00003207 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
3208 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
drh111a6a72008-12-21 03:51:16 +00003209 if( bRev ){
3210 pTerm = pStart;
3211 pStart = pEnd;
3212 pEnd = pTerm;
3213 }
3214 if( pStart ){
3215 Expr *pX; /* The expression that defines the start bound */
3216 int r1, rTemp; /* Registers for holding the start boundary */
3217
3218 /* The following constant maps TK_xx codes into corresponding
3219 ** seek opcodes. It depends on a particular ordering of TK_xx
3220 */
3221 const u8 aMoveOp[] = {
3222 /* TK_GT */ OP_SeekGt,
3223 /* TK_LE */ OP_SeekLe,
3224 /* TK_LT */ OP_SeekLt,
3225 /* TK_GE */ OP_SeekGe
3226 };
3227 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
3228 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
3229 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
3230
drhe9cdcea2010-07-22 22:40:03 +00003231 testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003232 pX = pStart->pExpr;
3233 assert( pX!=0 );
3234 assert( pStart->leftCursor==iCur );
3235 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
3236 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
3237 VdbeComment((v, "pk"));
3238 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
3239 sqlite3ReleaseTempReg(pParse, rTemp);
3240 disableTerm(pLevel, pStart);
3241 }else{
3242 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
3243 }
3244 if( pEnd ){
3245 Expr *pX;
3246 pX = pEnd->pExpr;
3247 assert( pX!=0 );
3248 assert( pEnd->leftCursor==iCur );
drhe9cdcea2010-07-22 22:40:03 +00003249 testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003250 memEndValue = ++pParse->nMem;
3251 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
3252 if( pX->op==TK_LT || pX->op==TK_GT ){
3253 testOp = bRev ? OP_Le : OP_Ge;
3254 }else{
3255 testOp = bRev ? OP_Lt : OP_Gt;
3256 }
3257 disableTerm(pLevel, pEnd);
3258 }
3259 start = sqlite3VdbeCurrentAddr(v);
3260 pLevel->op = bRev ? OP_Prev : OP_Next;
3261 pLevel->p1 = iCur;
3262 pLevel->p2 = start;
drhafc266a2010-03-31 17:47:44 +00003263 if( pStart==0 && pEnd==0 ){
3264 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3265 }else{
3266 assert( pLevel->p5==0 );
3267 }
danielk19771d461462009-04-21 09:02:45 +00003268 if( testOp!=OP_Noop ){
3269 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3270 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003271 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003272 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
3273 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003274 }
drh1b0f0262013-05-30 22:27:09 +00003275 }else if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00003276 /* Case 4: A scan using an index.
drh111a6a72008-12-21 03:51:16 +00003277 **
3278 ** The WHERE clause may contain zero or more equality
3279 ** terms ("==" or "IN" operators) that refer to the N
3280 ** left-most columns of the index. It may also contain
3281 ** inequality constraints (>, <, >= or <=) on the indexed
3282 ** column that immediately follows the N equalities. Only
3283 ** the right-most column can be an inequality - the rest must
3284 ** use the "==" and "IN" operators. For example, if the
3285 ** index is on (x,y,z), then the following clauses are all
3286 ** optimized:
3287 **
3288 ** x=5
3289 ** x=5 AND y=10
3290 ** x=5 AND y<10
3291 ** x=5 AND y>5 AND y<10
3292 ** x=5 AND y=5 AND z<=10
3293 **
3294 ** The z<10 term of the following cannot be used, only
3295 ** the x=5 term:
3296 **
3297 ** x=5 AND z<10
3298 **
3299 ** N may be zero if there are inequality constraints.
3300 ** If there are no inequality constraints, then N is at
3301 ** least one.
3302 **
3303 ** This case is also used when there are no WHERE clause
3304 ** constraints but an index is selected anyway, in order
3305 ** to force the output order to conform to an ORDER BY.
3306 */
drh3bb9b932010-08-06 02:10:00 +00003307 static const u8 aStartOp[] = {
drh111a6a72008-12-21 03:51:16 +00003308 0,
3309 0,
3310 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
3311 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
3312 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
3313 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
3314 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
3315 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
3316 };
drh3bb9b932010-08-06 02:10:00 +00003317 static const u8 aEndOp[] = {
drh111a6a72008-12-21 03:51:16 +00003318 OP_Noop, /* 0: (!end_constraints) */
3319 OP_IdxGE, /* 1: (end_constraints && !bRev) */
3320 OP_IdxLT /* 2: (end_constraints && bRev) */
3321 };
drh7ba39a92013-05-30 17:43:19 +00003322 int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
3323 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
drh111a6a72008-12-21 03:51:16 +00003324 int regBase; /* Base register holding constraint values */
3325 int r1; /* Temp register */
3326 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
3327 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
3328 int startEq; /* True if range start uses ==, >= or <= */
3329 int endEq; /* True if range end uses ==, >= or <= */
3330 int start_constraints; /* Start of range is constrained */
3331 int nConstraint; /* Number of constraint terms */
drh3bb9b932010-08-06 02:10:00 +00003332 Index *pIdx; /* The index we will be using */
3333 int iIdxCur; /* The VDBE cursor for the index */
3334 int nExtraReg = 0; /* Number of extra registers needed */
3335 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00003336 char *zStartAff; /* Affinity for start of range constraint */
3337 char *zEndAff; /* Affinity for end of range constraint */
drh111a6a72008-12-21 03:51:16 +00003338
drh7ba39a92013-05-30 17:43:19 +00003339 pIdx = pLoop->u.btree.pIndex;
drh111a6a72008-12-21 03:51:16 +00003340 iIdxCur = pLevel->iIdxCur;
dan0c733f62011-11-16 15:27:09 +00003341 k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
drh111a6a72008-12-21 03:51:16 +00003342
drh111a6a72008-12-21 03:51:16 +00003343 /* If this loop satisfies a sort order (pOrderBy) request that
3344 ** was passed to this function to implement a "SELECT min(x) ..."
3345 ** query, then the caller will only allow the loop to run for
3346 ** a single iteration. This means that the first row returned
3347 ** should not have a NULL value stored in 'x'. If column 'x' is
3348 ** the first one after the nEq equality constraints in the index,
3349 ** this requires some special handling.
3350 */
drh70d18342013-06-06 19:16:33 +00003351 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
drh7ba39a92013-05-30 17:43:19 +00003352 && (pWInfo->nOBSat>0)
drh111a6a72008-12-21 03:51:16 +00003353 && (pIdx->nColumn>nEq)
3354 ){
3355 /* assert( pOrderBy->nExpr==1 ); */
3356 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
3357 isMinQuery = 1;
drh6df2acd2008-12-28 16:55:25 +00003358 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003359 }
3360
3361 /* Find any inequality constraint terms for the start and end
3362 ** of the range.
3363 */
drh7ba39a92013-05-30 17:43:19 +00003364 j = nEq;
3365 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003366 pRangeStart = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003367 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003368 }
drh7ba39a92013-05-30 17:43:19 +00003369 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003370 pRangeEnd = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003371 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003372 }
3373
drh6df2acd2008-12-28 16:55:25 +00003374 /* Generate code to evaluate all constraint terms using == or IN
3375 ** and store the values of those terms in an array of registers
3376 ** starting at regBase.
3377 */
dan69f8bb92009-08-13 19:21:16 +00003378 regBase = codeAllEqualityTerms(
drh7ba39a92013-05-30 17:43:19 +00003379 pParse, pLevel, pWC, notReady, bRev, nExtraReg, &zStartAff
dan69f8bb92009-08-13 19:21:16 +00003380 );
dan6ac43392010-06-09 15:47:11 +00003381 zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
drh6df2acd2008-12-28 16:55:25 +00003382 addrNxt = pLevel->addrNxt;
3383
drh111a6a72008-12-21 03:51:16 +00003384 /* If we are doing a reverse order scan on an ascending index, or
3385 ** a forward order scan on a descending index, interchange the
3386 ** start and end terms (pRangeStart and pRangeEnd).
3387 */
dan0c733f62011-11-16 15:27:09 +00003388 if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3389 || (bRev && pIdx->nColumn==nEq)
3390 ){
drh111a6a72008-12-21 03:51:16 +00003391 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
3392 }
3393
3394 testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
3395 testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
3396 testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
3397 testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
3398 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3399 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3400 start_constraints = pRangeStart || nEq>0;
3401
3402 /* Seek the index cursor to the start of the range. */
3403 nConstraint = nEq;
3404 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003405 Expr *pRight = pRangeStart->pExpr->pRight;
3406 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003407 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
3408 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3409 }
dan6ac43392010-06-09 15:47:11 +00003410 if( zStartAff ){
3411 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003412 /* Since the comparison is to be performed with no conversions
3413 ** applied to the operands, set the affinity to apply to pRight to
3414 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003415 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003416 }
dan6ac43392010-06-09 15:47:11 +00003417 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3418 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003419 }
3420 }
drh111a6a72008-12-21 03:51:16 +00003421 nConstraint++;
drhe9cdcea2010-07-22 22:40:03 +00003422 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003423 }else if( isMinQuery ){
3424 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3425 nConstraint++;
3426 startEq = 0;
3427 start_constraints = 1;
3428 }
dan6ac43392010-06-09 15:47:11 +00003429 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003430 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3431 assert( op!=0 );
3432 testcase( op==OP_Rewind );
3433 testcase( op==OP_Last );
3434 testcase( op==OP_SeekGt );
3435 testcase( op==OP_SeekGe );
3436 testcase( op==OP_SeekLe );
3437 testcase( op==OP_SeekLt );
drh8cff69d2009-11-12 19:59:44 +00003438 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh111a6a72008-12-21 03:51:16 +00003439
3440 /* Load the value for the inequality constraint at the end of the
3441 ** range (if any).
3442 */
3443 nConstraint = nEq;
3444 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003445 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003446 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003447 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003448 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
3449 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3450 }
dan6ac43392010-06-09 15:47:11 +00003451 if( zEndAff ){
3452 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003453 /* Since the comparison is to be performed with no conversions
3454 ** applied to the operands, set the affinity to apply to pRight to
3455 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003456 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003457 }
dan6ac43392010-06-09 15:47:11 +00003458 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
3459 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003460 }
3461 }
dan6ac43392010-06-09 15:47:11 +00003462 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003463 nConstraint++;
drhe9cdcea2010-07-22 22:40:03 +00003464 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003465 }
dan6ac43392010-06-09 15:47:11 +00003466 sqlite3DbFree(pParse->db, zStartAff);
3467 sqlite3DbFree(pParse->db, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003468
3469 /* Top of the loop body */
3470 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3471
3472 /* Check if the index cursor is past the end of the range. */
3473 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
3474 testcase( op==OP_Noop );
3475 testcase( op==OP_IdxGE );
3476 testcase( op==OP_IdxLT );
drh6df2acd2008-12-28 16:55:25 +00003477 if( op!=OP_Noop ){
drh8cff69d2009-11-12 19:59:44 +00003478 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh6df2acd2008-12-28 16:55:25 +00003479 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
3480 }
drh111a6a72008-12-21 03:51:16 +00003481
3482 /* If there are inequality constraints, check that the value
3483 ** of the table column that the inequality contrains is not NULL.
3484 ** If it is, jump to the next iteration of the loop.
3485 */
3486 r1 = sqlite3GetTempReg(pParse);
3487 testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
3488 testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
drh7ba39a92013-05-30 17:43:19 +00003489 if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
drh111a6a72008-12-21 03:51:16 +00003490 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
3491 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
3492 }
danielk19771d461462009-04-21 09:02:45 +00003493 sqlite3ReleaseTempReg(pParse, r1);
drh111a6a72008-12-21 03:51:16 +00003494
3495 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003496 disableTerm(pLevel, pRangeStart);
3497 disableTerm(pLevel, pRangeEnd);
danielk19771d461462009-04-21 09:02:45 +00003498 if( !omitTable ){
3499 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3500 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003501 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003502 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drh111a6a72008-12-21 03:51:16 +00003503 }
drh111a6a72008-12-21 03:51:16 +00003504
3505 /* Record the instruction used to terminate the loop. Disable
3506 ** WHERE clause terms made redundant by the index range scan.
3507 */
drh7699d1c2013-06-04 12:42:29 +00003508 if( pLoop->wsFlags & WHERE_ONEROW ){
drh95e037b2011-03-09 21:02:31 +00003509 pLevel->op = OP_Noop;
3510 }else if( bRev ){
3511 pLevel->op = OP_Prev;
3512 }else{
3513 pLevel->op = OP_Next;
3514 }
drh111a6a72008-12-21 03:51:16 +00003515 pLevel->p1 = iIdxCur;
drh1b0f0262013-05-30 22:27:09 +00003516 if( (pLoop->wsFlags & (WHERE_COLUMN_EQ | WHERE_COLUMN_RANGE |
3517 WHERE_COLUMN_NULL | WHERE_COLUMN_IN))==0 ){
drh3f4d1d12012-09-15 18:45:54 +00003518 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3519 }else{
3520 assert( pLevel->p5==0 );
3521 }
drhdd5f5a62008-12-23 13:35:23 +00003522 }else
3523
drh23d04d52008-12-23 23:56:22 +00003524#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drh7ba39a92013-05-30 17:43:19 +00003525 if( pLoop->wsFlags & WHERE_MULTI_OR ){
3526 /* Case 5: Two or more separately indexed terms connected by OR
drh111a6a72008-12-21 03:51:16 +00003527 **
3528 ** Example:
3529 **
3530 ** CREATE TABLE t1(a,b,c,d);
3531 ** CREATE INDEX i1 ON t1(a);
3532 ** CREATE INDEX i2 ON t1(b);
3533 ** CREATE INDEX i3 ON t1(c);
3534 **
3535 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3536 **
3537 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003538 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003539 **
drh1b26c7c2009-04-22 02:15:47 +00003540 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003541 **
danielk19771d461462009-04-21 09:02:45 +00003542 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003543 ** RowSetTest are such that the rowid of the current row is inserted
3544 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003545 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003546 **
danielk19771d461462009-04-21 09:02:45 +00003547 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003548 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003549 ** Gosub 2 A
3550 ** sqlite3WhereEnd()
3551 **
3552 ** Following the above, code to terminate the loop. Label A, the target
3553 ** of the Gosub above, jumps to the instruction right after the Goto.
3554 **
drh1b26c7c2009-04-22 02:15:47 +00003555 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003556 ** Goto B # The loop is finished.
3557 **
3558 ** A: <loop body> # Return data, whatever.
3559 **
3560 ** Return 2 # Jump back to the Gosub
3561 **
3562 ** B: <after the loop>
3563 **
drh111a6a72008-12-21 03:51:16 +00003564 */
drh111a6a72008-12-21 03:51:16 +00003565 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
drhc01a3c12009-12-16 22:10:49 +00003566 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
dan0efb72c2012-08-24 18:44:56 +00003567 Index *pCov = 0; /* Potential covering index (or NULL) */
3568 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
danielk19771d461462009-04-21 09:02:45 +00003569
3570 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003571 int regRowset = 0; /* Register for RowSet object */
3572 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003573 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3574 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003575 int untestedTerms = 0; /* Some terms not completely tested */
drh8871ef52011-10-07 13:33:10 +00003576 int ii; /* Loop counter */
3577 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
drh111a6a72008-12-21 03:51:16 +00003578
drh4efc9292013-06-06 23:02:03 +00003579 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003580 assert( pTerm!=0 );
drh7a5bcc02013-01-16 17:08:58 +00003581 assert( pTerm->eOperator & WO_OR );
drh111a6a72008-12-21 03:51:16 +00003582 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3583 pOrWc = &pTerm->u.pOrInfo->wc;
drhc01a3c12009-12-16 22:10:49 +00003584 pLevel->op = OP_Return;
3585 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003586
danbfca6a42012-08-24 10:52:35 +00003587 /* Set up a new SrcList in pOrTab containing the table being scanned
drhc01a3c12009-12-16 22:10:49 +00003588 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3589 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3590 */
3591 if( pWInfo->nLevel>1 ){
3592 int nNotReady; /* The number of notReady tables */
3593 struct SrcList_item *origSrc; /* Original list of tables */
3594 nNotReady = pWInfo->nLevel - iLevel - 1;
3595 pOrTab = sqlite3StackAllocRaw(pParse->db,
3596 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3597 if( pOrTab==0 ) return notReady;
shaneh46aae3c2009-12-31 19:06:23 +00003598 pOrTab->nAlloc = (i16)(nNotReady + 1);
3599 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003600 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3601 origSrc = pWInfo->pTabList->a;
3602 for(k=1; k<=nNotReady; k++){
3603 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3604 }
3605 }else{
3606 pOrTab = pWInfo->pTabList;
3607 }
danielk19771d461462009-04-21 09:02:45 +00003608
drh1b26c7c2009-04-22 02:15:47 +00003609 /* Initialize the rowset register to contain NULL. An SQL NULL is
3610 ** equivalent to an empty rowset.
danielk19771d461462009-04-21 09:02:45 +00003611 **
3612 ** Also initialize regReturn to contain the address of the instruction
3613 ** immediately following the OP_Return at the bottom of the loop. This
3614 ** is required in a few obscure LEFT JOIN cases where control jumps
3615 ** over the top of the loop into the body of it. In this case the
3616 ** correct response for the end-of-loop code (the OP_Return) is to
3617 ** fall through to the next instruction, just as an OP_Next does if
3618 ** called on an uninitialized cursor.
3619 */
drh70d18342013-06-06 19:16:33 +00003620 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003621 regRowset = ++pParse->nMem;
3622 regRowid = ++pParse->nMem;
3623 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3624 }
danielk19771d461462009-04-21 09:02:45 +00003625 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3626
drh8871ef52011-10-07 13:33:10 +00003627 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
3628 ** Then for every term xN, evaluate as the subexpression: xN AND z
3629 ** That way, terms in y that are factored into the disjunction will
3630 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
drh331b67c2012-03-09 22:02:08 +00003631 **
3632 ** Actually, each subexpression is converted to "xN AND w" where w is
3633 ** the "interesting" terms of z - terms that did not originate in the
3634 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3635 ** indices.
drhb3129fa2013-05-09 14:20:11 +00003636 **
3637 ** This optimization also only applies if the (x1 OR x2 OR ...) term
3638 ** is not contained in the ON clause of a LEFT JOIN.
3639 ** See ticket http://www.sqlite.org/src/info/f2369304e4
drh8871ef52011-10-07 13:33:10 +00003640 */
3641 if( pWC->nTerm>1 ){
drh7a484802012-03-16 00:28:11 +00003642 int iTerm;
3643 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3644 Expr *pExpr = pWC->a[iTerm].pExpr;
drh331b67c2012-03-09 22:02:08 +00003645 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drh7a484802012-03-16 00:28:11 +00003646 if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
3647 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
drh331b67c2012-03-09 22:02:08 +00003648 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
3649 pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
3650 }
3651 if( pAndExpr ){
3652 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3653 }
drh8871ef52011-10-07 13:33:10 +00003654 }
3655
danielk19771d461462009-04-21 09:02:45 +00003656 for(ii=0; ii<pOrWc->nTerm; ii++){
3657 WhereTerm *pOrTerm = &pOrWc->a[ii];
drh7a5bcc02013-01-16 17:08:58 +00003658 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
danielk19771d461462009-04-21 09:02:45 +00003659 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
drh8871ef52011-10-07 13:33:10 +00003660 Expr *pOrExpr = pOrTerm->pExpr;
drhb3129fa2013-05-09 14:20:11 +00003661 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
drh8871ef52011-10-07 13:33:10 +00003662 pAndExpr->pLeft = pOrExpr;
3663 pOrExpr = pAndExpr;
3664 }
danielk19771d461462009-04-21 09:02:45 +00003665 /* Loop through table entries that match term pOrTerm. */
drh8871ef52011-10-07 13:33:10 +00003666 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
drh9ef61f42011-10-07 14:40:59 +00003667 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
dan0efb72c2012-08-24 18:44:56 +00003668 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
danbfca6a42012-08-24 10:52:35 +00003669 assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
danielk19771d461462009-04-21 09:02:45 +00003670 if( pSubWInfo ){
drh7ba39a92013-05-30 17:43:19 +00003671 WhereLoop *pSubLoop;
dan17c0bc02010-11-09 17:35:19 +00003672 explainOneScan(
dan4a07e3d2010-11-09 14:48:59 +00003673 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
dan2ce22452010-11-08 19:01:16 +00003674 );
drh70d18342013-06-06 19:16:33 +00003675 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003676 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3677 int r;
3678 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
drha748fdc2012-03-28 01:34:47 +00003679 regRowid, 0);
drh8cff69d2009-11-12 19:59:44 +00003680 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
3681 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
drh336a5302009-04-24 15:46:21 +00003682 }
danielk19771d461462009-04-21 09:02:45 +00003683 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
3684
drhc01a3c12009-12-16 22:10:49 +00003685 /* The pSubWInfo->untestedTerms flag means that this OR term
3686 ** contained one or more AND term from a notReady table. The
3687 ** terms from the notReady table could not be tested and will
3688 ** need to be tested later.
3689 */
3690 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3691
danbfca6a42012-08-24 10:52:35 +00003692 /* If all of the OR-connected terms are optimized using the same
3693 ** index, and the index is opened using the same cursor number
3694 ** by each call to sqlite3WhereBegin() made by this loop, it may
3695 ** be possible to use that index as a covering index.
3696 **
3697 ** If the call to sqlite3WhereBegin() above resulted in a scan that
3698 ** uses an index, and this is either the first OR-connected term
3699 ** processed or the index is the same as that used by all previous
dan0efb72c2012-08-24 18:44:56 +00003700 ** terms, set pCov to the candidate covering index. Otherwise, set
3701 ** pCov to NULL to indicate that no candidate covering index will
3702 ** be available.
danbfca6a42012-08-24 10:52:35 +00003703 */
drh7ba39a92013-05-30 17:43:19 +00003704 pSubLoop = pSubWInfo->a[0].pWLoop;
3705 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
3706 && (pSubLoop->wsFlags & WHERE_TEMP_INDEX)==0
3707 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
danbfca6a42012-08-24 10:52:35 +00003708 ){
drh7ba39a92013-05-30 17:43:19 +00003709 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
drh907717f2013-06-04 18:03:22 +00003710 pCov = pSubLoop->u.btree.pIndex;
danbfca6a42012-08-24 10:52:35 +00003711 }else{
3712 pCov = 0;
3713 }
3714
danielk19771d461462009-04-21 09:02:45 +00003715 /* Finish the loop through table entries that match term pOrTerm. */
3716 sqlite3WhereEnd(pSubWInfo);
3717 }
drhdd5f5a62008-12-23 13:35:23 +00003718 }
3719 }
drhd40e2082012-08-24 23:24:15 +00003720 pLevel->u.pCovidx = pCov;
drh90abfd02012-10-09 21:07:23 +00003721 if( pCov ) pLevel->iIdxCur = iCovCur;
drh331b67c2012-03-09 22:02:08 +00003722 if( pAndExpr ){
3723 pAndExpr->pLeft = 0;
3724 sqlite3ExprDelete(pParse->db, pAndExpr);
3725 }
danielk19771d461462009-04-21 09:02:45 +00003726 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00003727 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
3728 sqlite3VdbeResolveLabel(v, iLoopBody);
3729
drhc01a3c12009-12-16 22:10:49 +00003730 if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
3731 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00003732 }else
drh23d04d52008-12-23 23:56:22 +00003733#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00003734
3735 {
drh7ba39a92013-05-30 17:43:19 +00003736 /* Case 6: There is no usable index. We must do a complete
drh111a6a72008-12-21 03:51:16 +00003737 ** scan of the entire table.
3738 */
drh699b3d42009-02-23 16:52:07 +00003739 static const u8 aStep[] = { OP_Next, OP_Prev };
3740 static const u8 aStart[] = { OP_Rewind, OP_Last };
3741 assert( bRev==0 || bRev==1 );
drh699b3d42009-02-23 16:52:07 +00003742 pLevel->op = aStep[bRev];
drh111a6a72008-12-21 03:51:16 +00003743 pLevel->p1 = iCur;
drh699b3d42009-02-23 16:52:07 +00003744 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh111a6a72008-12-21 03:51:16 +00003745 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3746 }
drh70d18342013-06-06 19:16:33 +00003747 newNotReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
drh111a6a72008-12-21 03:51:16 +00003748
3749 /* Insert code to test every subexpression that can be completely
3750 ** computed using the current set of tables.
drhe9cdcea2010-07-22 22:40:03 +00003751 **
3752 ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
3753 ** the use of indices become tests that are evaluated against each row of
3754 ** the relevant input tables.
drh111a6a72008-12-21 03:51:16 +00003755 */
drh111a6a72008-12-21 03:51:16 +00003756 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3757 Expr *pE;
drhe9cdcea2010-07-22 22:40:03 +00003758 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003759 testcase( pTerm->wtFlags & TERM_CODED );
3760 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0c41d222013-04-22 02:39:10 +00003761 if( (pTerm->prereqAll & newNotReady)!=0 ){
drhc01a3c12009-12-16 22:10:49 +00003762 testcase( pWInfo->untestedTerms==0
3763 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
3764 pWInfo->untestedTerms = 1;
3765 continue;
3766 }
drh111a6a72008-12-21 03:51:16 +00003767 pE = pTerm->pExpr;
3768 assert( pE!=0 );
3769 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
3770 continue;
3771 }
drh111a6a72008-12-21 03:51:16 +00003772 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003773 pTerm->wtFlags |= TERM_CODED;
3774 }
3775
drh0c41d222013-04-22 02:39:10 +00003776 /* Insert code to test for implied constraints based on transitivity
3777 ** of the "==" operator.
3778 **
3779 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
3780 ** and we are coding the t1 loop and the t2 loop has not yet coded,
3781 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
3782 ** the implied "t1.a=123" constraint.
3783 */
3784 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3785 Expr *pE;
3786 WhereTerm *pAlt;
3787 Expr sEq;
3788 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3789 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
3790 if( pTerm->leftCursor!=iCur ) continue;
3791 pE = pTerm->pExpr;
3792 assert( !ExprHasProperty(pE, EP_FromJoin) );
3793 assert( (pTerm->prereqRight & newNotReady)!=0 );
3794 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
3795 if( pAlt==0 ) continue;
drh5c10f3b2013-05-01 17:22:38 +00003796 if( pAlt->wtFlags & (TERM_CODED) ) continue;
drh0c41d222013-04-22 02:39:10 +00003797 VdbeNoopComment((v, "begin transitive constraint"));
3798 sEq = *pAlt->pExpr;
3799 sEq.pLeft = pE->pLeft;
3800 sqlite3ExprIfFalse(pParse, &sEq, addrCont, SQLITE_JUMPIFNULL);
3801 }
3802
drh111a6a72008-12-21 03:51:16 +00003803 /* For a LEFT OUTER JOIN, generate code that will record the fact that
3804 ** at least one row of the right table has matched the left table.
3805 */
3806 if( pLevel->iLeftJoin ){
3807 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
3808 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
3809 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00003810 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00003811 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drhe9cdcea2010-07-22 22:40:03 +00003812 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003813 testcase( pTerm->wtFlags & TERM_CODED );
3814 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0c41d222013-04-22 02:39:10 +00003815 if( (pTerm->prereqAll & newNotReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00003816 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00003817 continue;
3818 }
drh111a6a72008-12-21 03:51:16 +00003819 assert( pTerm->pExpr );
3820 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3821 pTerm->wtFlags |= TERM_CODED;
3822 }
3823 }
danielk19771d461462009-04-21 09:02:45 +00003824 sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh23d04d52008-12-23 23:56:22 +00003825
drh0c41d222013-04-22 02:39:10 +00003826 return newNotReady;
drh111a6a72008-12-21 03:51:16 +00003827}
3828
drhd15cb172013-05-21 19:23:10 +00003829#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00003830/*
3831** Print a WhereLoop object for debugging purposes
3832*/
3833static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
3834 int nb = 2*((pTabList->nSrc+15)/16);
3835 struct SrcList_item *pItem = pTabList->a + p->iTab;
3836 Table *pTab = pItem->pTab;
drhd15cb172013-05-21 19:23:10 +00003837 sqlite3DebugPrintf("%c %2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00003838 p->iTab, nb, p->maskSelf, nb, p->prereq);
3839 sqlite3DebugPrintf(" %8s",
drha18f3d22013-05-08 03:05:41 +00003840 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00003841 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
3842 if( p->u.btree.pIndex ){
drh319f6772013-05-14 15:31:07 +00003843 const char *zName = p->u.btree.pIndex->zName;
drhae70cf12013-05-31 15:18:46 +00003844 if( zName==0 ) zName = "ipk";
drh319f6772013-05-14 15:31:07 +00003845 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
3846 int i = sqlite3Strlen30(zName) - 1;
3847 while( zName[i]!='_' ) i--;
3848 zName += i;
3849 }
3850 sqlite3DebugPrintf(".%-12s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00003851 }else{
3852 sqlite3DebugPrintf("%16s","");
3853 }
drha18f3d22013-05-08 03:05:41 +00003854 }else{
drh5346e952013-05-08 14:14:26 +00003855 char *z;
3856 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00003857 z = sqlite3_mprintf("(%d,\"%s\",%x)",
3858 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003859 }else{
drh3bd26f02013-05-24 14:52:03 +00003860 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003861 }
3862 sqlite3DebugPrintf(" %-15s", z);
3863 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00003864 }
drh4efc9292013-06-06 23:02:03 +00003865 sqlite3DebugPrintf(" fg %05x N %d", p->wsFlags, p->nLTerm);
drhd15cb172013-05-21 19:23:10 +00003866 sqlite3DebugPrintf(" cost %.2g,%.2g,%.2g\n",
drha18f3d22013-05-08 03:05:41 +00003867 p->prereq, p->rSetup, p->rRun, p->nOut);
3868}
3869#endif
3870
drhf1b5f5b2013-05-02 00:15:01 +00003871/*
drh4efc9292013-06-06 23:02:03 +00003872** Convert bulk memory into a valid WhereLoop that can be passed
3873** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00003874*/
drh4efc9292013-06-06 23:02:03 +00003875static void whereLoopInit(WhereLoop *p){
3876 p->aLTerm = p->aLTermSpace;
3877 p->nLTerm = 0;
3878 p->nLSlot = ArraySize(p->aLTermSpace);
3879 p->wsFlags = 0;
3880}
3881
3882/*
3883** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
3884*/
3885static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh13e11b42013-06-06 23:44:25 +00003886 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_TEMP_INDEX) ){
3887 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
3888 sqlite3_free(p->u.vtab.idxStr);
3889 p->u.vtab.needFree = 0;
3890 p->u.vtab.idxStr = 0;
3891 }else if( (p->wsFlags & WHERE_TEMP_INDEX)!=0 && p->u.btree.pIndex!=0 ){
3892 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
3893 sqlite3DbFree(db, p->u.btree.pIndex);
3894 p->u.btree.pIndex = 0;
3895 }
drh5346e952013-05-08 14:14:26 +00003896 }
3897}
3898
drh4efc9292013-06-06 23:02:03 +00003899/*
3900** Deallocate internal memory used by a WhereLoop object
3901*/
3902static void whereLoopClear(sqlite3 *db, WhereLoop *p){
3903 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3904 whereLoopClearUnion(db, p);
3905 whereLoopInit(p);
3906}
3907
3908/*
3909** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
3910*/
3911static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
3912 WhereTerm **paNew;
3913 if( p->nLSlot>=n ) return SQLITE_OK;
3914 n = (n+7)&~7;
3915 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
3916 if( paNew==0 ) return SQLITE_NOMEM;
3917 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
3918 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3919 p->aLTerm = paNew;
3920 p->nLSlot = n;
3921 return SQLITE_OK;
3922}
3923
3924/*
3925** Transfer content from the second pLoop into the first.
3926*/
3927static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
3928 if( whereLoopResize(db, pTo, pFrom->nLTerm) ) return SQLITE_NOMEM;
3929 whereLoopClearUnion(db, pTo);
drha2014152013-06-07 00:29:23 +00003930 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
3931 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00003932 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
3933 pFrom->u.vtab.needFree = 0;
drh13e11b42013-06-06 23:44:25 +00003934 }else if( (pFrom->wsFlags & WHERE_TEMP_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00003935 pFrom->u.btree.pIndex = 0;
3936 }
3937 return SQLITE_OK;
3938}
3939
drh5346e952013-05-08 14:14:26 +00003940/*
drhf1b5f5b2013-05-02 00:15:01 +00003941** Delete a WhereLoop object
3942*/
3943static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00003944 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00003945 sqlite3DbFree(db, p);
3946}
drh84bfda42005-07-15 13:05:21 +00003947
drh9eff6162006-06-12 21:59:13 +00003948/*
3949** Free a WhereInfo structure
3950*/
drh10fe8402008-10-11 16:47:35 +00003951static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00003952 if( ALWAYS(pWInfo) ){
drh70d18342013-06-06 19:16:33 +00003953 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00003954 while( pWInfo->pLoops ){
3955 WhereLoop *p = pWInfo->pLoops;
3956 pWInfo->pLoops = p->pNextLoop;
3957 whereLoopDelete(db, p);
3958 }
drh633e6d52008-07-28 19:34:53 +00003959 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00003960 }
3961}
3962
drhf1b5f5b2013-05-02 00:15:01 +00003963/*
3964** Insert or replace a WhereLoop entry using the template supplied.
3965**
3966** An existing WhereLoop entry might be overwritten if the new template
3967** is better and has fewer dependencies. Or the template will be ignored
3968** and no insert will occur if an existing WhereLoop is faster and has
3969** fewer dependencies than the template. Otherwise a new WhereLoop is
drhd044d202013-05-31 12:43:55 +00003970** added based on the template.
drh23f98da2013-05-21 15:52:07 +00003971**
3972** If pBuilder->pBest is not NULL then we only care about the very
3973** best template and that template should be stored in pBuilder->pBest.
3974** If pBuilder->pBest is NULL then a list of the best templates are stored
3975** in pBuilder->pWInfo->pLoops.
3976**
3977** When accumulating multiple loops (when pBuilder->pBest is NULL) we
3978** still might overwrite similar loops with the new template if the
3979** template is better. Loops may be overwritten if the following
3980** conditions are met:
3981**
3982** (1) They have the same iTab.
3983** (2) They have the same iSortIdx.
3984** (3) The template has same or fewer dependencies than the current loop
3985** (4) The template has the same or lower cost than the current loop
drhd044d202013-05-31 12:43:55 +00003986** (5) The template uses more terms of the same index but has no additional
3987** dependencies
drhf1b5f5b2013-05-02 00:15:01 +00003988*/
drhcf8fa7a2013-05-10 20:26:22 +00003989static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh4efc9292013-06-06 23:02:03 +00003990 WhereLoop **ppPrev, *p, *pNext = 0;
drhcf8fa7a2013-05-10 20:26:22 +00003991 WhereInfo *pWInfo = pBuilder->pWInfo;
drh70d18342013-06-06 19:16:33 +00003992 sqlite3 *db = pWInfo->pParse->db;
drhcf8fa7a2013-05-10 20:26:22 +00003993
drh23f98da2013-05-21 15:52:07 +00003994 /* If pBuilder->pBest is defined, then only keep track of the single
3995 ** best WhereLoop. pBuilder->pBest->maskSelf==0 indicates that no
3996 ** prior WhereLoops have been evaluated and that the current pTemplate
3997 ** is therefore the first and hence the best and should be retained.
3998 */
drhcf8fa7a2013-05-10 20:26:22 +00003999 if( (p = pBuilder->pBest)!=0 ){
4000 if( p->maskSelf!=0 ){
drh4efc9292013-06-06 23:02:03 +00004001 WhereCost rCost = p->rRun + p->rSetup;
4002 WhereCost rTemplate = pTemplate->rRun + pTemplate->rSetup;
4003 if( rCost < rTemplate ){
drhae70cf12013-05-31 15:18:46 +00004004 goto whereLoopInsert_noop;
drhcf8fa7a2013-05-10 20:26:22 +00004005 }
drh4efc9292013-06-06 23:02:03 +00004006 if( rCost == rTemplate && p->prereq <= pTemplate->prereq ){
drhae70cf12013-05-31 15:18:46 +00004007 goto whereLoopInsert_noop;
drhcf8fa7a2013-05-10 20:26:22 +00004008 }
4009 }
drh4efc9292013-06-06 23:02:03 +00004010 whereLoopXfer(db, p, pTemplate);
drhae70cf12013-05-31 15:18:46 +00004011#if WHERETRACE_ENABLED
4012 if( sqlite3WhereTrace & 0x8 ){
4013 sqlite3DebugPrintf("ins-best: ");
drh70d18342013-06-06 19:16:33 +00004014 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004015 }
4016#endif
drhcf8fa7a2013-05-10 20:26:22 +00004017 return SQLITE_OK;
4018 }
drhf1b5f5b2013-05-02 00:15:01 +00004019
4020 /* Search for an existing WhereLoop to overwrite, or which takes
4021 ** priority over pTemplate.
4022 */
4023 for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
drh23f98da2013-05-21 15:52:07 +00004024 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ) continue;
drhf1b5f5b2013-05-02 00:15:01 +00004025 if( (p->prereq & pTemplate->prereq)==p->prereq
drhf1b5f5b2013-05-02 00:15:01 +00004026 && p->rSetup<=pTemplate->rSetup
4027 && p->rRun<=pTemplate->rRun
4028 ){
drhcd0f4072013-06-05 12:47:59 +00004029 /* p is equal or better than pTemplate */
drh4efc9292013-06-06 23:02:03 +00004030 if( p->nLTerm<pTemplate->nLTerm
drhcd0f4072013-06-05 12:47:59 +00004031 && (p->wsFlags & WHERE_INDEXED)!=0
4032 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
4033 && p->u.btree.pIndex==pTemplate->u.btree.pIndex
4034 && p->prereq==pTemplate->prereq
4035 ){
4036 /* Overwrite an existing WhereLoop with an similar one that uses
4037 ** more terms of the index */
4038 pNext = p->pNextLoop;
drhcd0f4072013-06-05 12:47:59 +00004039 break;
4040 }else{
4041 /* pTemplate is not helpful.
4042 ** Return without changing or adding anything */
4043 goto whereLoopInsert_noop;
4044 }
drhf1b5f5b2013-05-02 00:15:01 +00004045 }
4046 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
drhf1b5f5b2013-05-02 00:15:01 +00004047 && p->rSetup>=pTemplate->rSetup
4048 && p->rRun>=pTemplate->rRun
4049 ){
4050 /* Overwrite an existing WhereLoop with a better one */
drh43fe25f2013-05-07 23:06:23 +00004051 pNext = p->pNextLoop;
drhf1b5f5b2013-05-02 00:15:01 +00004052 break;
4053 }
4054 }
4055
4056 /* If we reach this point it means that either p[] should be overwritten
4057 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
4058 ** WhereLoop and insert it.
4059 */
drhae70cf12013-05-31 15:18:46 +00004060#if WHERETRACE_ENABLED
4061 if( sqlite3WhereTrace & 0x8 ){
4062 if( p!=0 ){
4063 sqlite3DebugPrintf("ins-del: ");
drh70d18342013-06-06 19:16:33 +00004064 whereLoopPrint(p, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004065 }
4066 sqlite3DebugPrintf("ins-new: ");
drh70d18342013-06-06 19:16:33 +00004067 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004068 }
4069#endif
drhf1b5f5b2013-05-02 00:15:01 +00004070 if( p==0 ){
drh4efc9292013-06-06 23:02:03 +00004071 p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00004072 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00004073 whereLoopInit(p);
drhf1b5f5b2013-05-02 00:15:01 +00004074 }
drh4efc9292013-06-06 23:02:03 +00004075 whereLoopXfer(db, p, pTemplate);
drh43fe25f2013-05-07 23:06:23 +00004076 p->pNextLoop = pNext;
4077 *ppPrev = p;
drh5346e952013-05-08 14:14:26 +00004078 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00004079 Index *pIndex = p->u.btree.pIndex;
4080 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004081 p->u.btree.pIndex = 0;
4082 }
drh5346e952013-05-08 14:14:26 +00004083 }
drhf1b5f5b2013-05-02 00:15:01 +00004084 return SQLITE_OK;
drhae70cf12013-05-31 15:18:46 +00004085
4086 /* Jump here if the insert is a no-op */
4087whereLoopInsert_noop:
4088#if WHERETRACE_ENABLED
4089 if( sqlite3WhereTrace & 0x8 ){
4090 sqlite3DebugPrintf("ins-noop: ");
drh70d18342013-06-06 19:16:33 +00004091 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004092 }
4093#endif
4094 return SQLITE_OK;
drhf1b5f5b2013-05-02 00:15:01 +00004095}
4096
4097/*
drh5346e952013-05-08 14:14:26 +00004098** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
drh1c8148f2013-05-04 20:25:23 +00004099** Try to match one more.
4100**
4101** If pProbe->tnum==0, that means pIndex is a fake index used for the
4102** INTEGER PRIMARY KEY.
4103*/
drh5346e952013-05-08 14:14:26 +00004104static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00004105 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
4106 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
4107 Index *pProbe, /* An index on pSrc */
4108 int nInMul /* Number of iterations due to IN */
4109){
drh70d18342013-06-06 19:16:33 +00004110 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
4111 Parse *pParse = pWInfo->pParse; /* Parsing context */
4112 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00004113 WhereLoop *pNew; /* Template WhereLoop under construction */
4114 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00004115 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00004116 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00004117 Bitmask saved_prereq; /* Original value of pNew->prereq */
4118 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
4119 int saved_nEq; /* Original value of pNew->u.btree.nEq */
4120 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
4121 WhereCost saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00004122 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00004123 int rc = SQLITE_OK; /* Return code */
drh0f133a42013-05-22 17:01:17 +00004124 tRowcnt iRowEst; /* Estimated index selectivity */
drh4efc9292013-06-06 23:02:03 +00004125 WhereCost rLogSize; /* Logarithm of table size */
drh6f2bfad2013-06-03 17:35:22 +00004126 WhereTerm *pTop, *pBtm; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00004127
drh1c8148f2013-05-04 20:25:23 +00004128 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00004129 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00004130
drh5346e952013-05-08 14:14:26 +00004131 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh0f133a42013-05-22 17:01:17 +00004132 assert( pNew->u.btree.nEq<=pProbe->nColumn );
drh43fe25f2013-05-07 23:06:23 +00004133 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
4134 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
4135 opMask = WO_LT|WO_LE;
4136 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
4137 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004138 }else{
drh43fe25f2013-05-07 23:06:23 +00004139 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004140 }
drhef866372013-05-22 20:49:02 +00004141 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00004142
drh0f133a42013-05-22 17:01:17 +00004143 if( pNew->u.btree.nEq < pProbe->nColumn ){
4144 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
4145 iRowEst = pProbe->aiRowEst[pNew->u.btree.nEq+1];
4146 }else{
4147 iCol = -1;
4148 iRowEst = 1;
4149 }
drha18f3d22013-05-08 03:05:41 +00004150 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00004151 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00004152 saved_nEq = pNew->u.btree.nEq;
4153 saved_nLTerm = pNew->nLTerm;
4154 saved_wsFlags = pNew->wsFlags;
4155 saved_prereq = pNew->prereq;
4156 saved_nOut = pNew->nOut;
4157 pNew->rSetup = (WhereCost)0;
drheb04de32013-05-10 15:16:30 +00004158 rLogSize = estLog(pProbe->aiRowEst[0]);
drh5346e952013-05-08 14:14:26 +00004159 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
drha18f3d22013-05-08 03:05:41 +00004160 int nIn = 1;
drh79a13bf2013-05-31 20:28:28 +00004161 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drh4efc9292013-06-06 23:02:03 +00004162 pNew->wsFlags = saved_wsFlags;
4163 pNew->u.btree.nEq = saved_nEq;
4164 pNew->nLTerm = saved_nLTerm;
4165 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4166 pNew->aLTerm[pNew->nLTerm++] = pTerm;
4167 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00004168 pNew->rRun = rLogSize;
drha18f3d22013-05-08 03:05:41 +00004169 if( pTerm->eOperator & WO_IN ){
4170 Expr *pExpr = pTerm->pExpr;
4171 pNew->wsFlags |= WHERE_COLUMN_IN;
4172 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
4173 /* "x IN (SELECT ...)": Assume the SELECT returns 25 rows */
4174 nIn = 25;
4175 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
4176 /* "x IN (value, value, ...)" */
4177 nIn = pExpr->x.pList->nExpr;
drhf1645f02013-05-07 19:44:38 +00004178 }
drh7699d1c2013-06-04 12:42:29 +00004179 pNew->rRun *= nIn;
drh5346e952013-05-08 14:14:26 +00004180 pNew->u.btree.nEq++;
drh4efc9292013-06-06 23:02:03 +00004181 pNew->nOut = (WhereCost)iRowEst * nInMul * nIn;
drh6fa978d2013-05-30 19:29:19 +00004182 }else if( pTerm->eOperator & (WO_EQ) ){
drh7699d1c2013-06-04 12:42:29 +00004183 assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
4184 || nInMul==1 );
drha18f3d22013-05-08 03:05:41 +00004185 pNew->wsFlags |= WHERE_COLUMN_EQ;
drh7699d1c2013-06-04 12:42:29 +00004186 if( iCol<0
drhee73b872013-06-04 13:37:26 +00004187 || (pProbe->onError!=OE_None && nInMul==1
drh21f7ff72013-06-03 15:07:23 +00004188 && pNew->u.btree.nEq==pProbe->nColumn-1)
4189 ){
drh7699d1c2013-06-04 12:42:29 +00004190 testcase( pNew->wsFlags & WHERE_COLUMN_IN );
4191 pNew->wsFlags |= WHERE_ONEROW;
drh21f7ff72013-06-03 15:07:23 +00004192 }
drh5346e952013-05-08 14:14:26 +00004193 pNew->u.btree.nEq++;
drh4efc9292013-06-06 23:02:03 +00004194 pNew->nOut = (WhereCost)iRowEst * nInMul;
drh6fa978d2013-05-30 19:29:19 +00004195 }else if( pTerm->eOperator & (WO_ISNULL) ){
4196 pNew->wsFlags |= WHERE_COLUMN_NULL;
4197 pNew->u.btree.nEq++;
drh7699d1c2013-06-04 12:42:29 +00004198 nIn = 2; /* Assume IS NULL matches two rows */
drh4efc9292013-06-06 23:02:03 +00004199 pNew->nOut = (WhereCost)iRowEst * nInMul * nIn;
drha18f3d22013-05-08 03:05:41 +00004200 }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
4201 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004202 pBtm = pTerm;
4203 pTop = 0;
drha18f3d22013-05-08 03:05:41 +00004204 }else if( pTerm->eOperator & (WO_LT|WO_LE) ){
4205 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004206 pTop = pTerm;
4207 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00004208 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00004209 }
drh6f2bfad2013-06-03 17:35:22 +00004210 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
4211 /* Adjust nOut and rRun for STAT3 range values */
drh4efc9292013-06-06 23:02:03 +00004212 WhereCost rDiv;
drh70d18342013-06-06 19:16:33 +00004213 whereRangeScanEst(pParse, pProbe, pNew->u.btree.nEq,
drh6f2bfad2013-06-03 17:35:22 +00004214 pBtm, pTop, &rDiv);
drh4efc9292013-06-06 23:02:03 +00004215 pNew->nOut = saved_nOut/rDiv;
drh6f2bfad2013-06-03 17:35:22 +00004216 }
4217#ifdef SQLITE_ENABLE_STAT3
4218 if( pNew->u.btree.nEq==1 && pProbe->nSample ){
4219 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
drh70d18342013-06-06 19:16:33 +00004220 rc = whereEqualScanEst(pParse, pProbe, pTerm->pExpr->pRight,
drh6f2bfad2013-06-03 17:35:22 +00004221 &pNew->nOut);
4222 }else if( (pTerm->eOperator & WO_IN)
4223 && !ExprHasProperty(pTerm->pExpr, EP_xIsSelect) ){
drh70d18342013-06-06 19:16:33 +00004224 rc = whereInScanEst(pParse, pProbe, pTerm->pExpr->x.pList,
drh6f2bfad2013-06-03 17:35:22 +00004225 &pNew->nOut);
4226
4227 }
4228 }
4229#endif
drheb04de32013-05-10 15:16:30 +00004230 if( pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK) ){
4231 pNew->rRun += pNew->nOut; /* Unit step cost to reach each row */
4232 }else{
4233 /* Each row involves a step of the index, then a binary search of
4234 ** the main table */
4235 pNew->rRun += pNew->nOut*(1 + rLogSize);
4236 }
drheb04de32013-05-10 15:16:30 +00004237 /* TBD: Adjust nOut for additional constraints */
drhcf8fa7a2013-05-10 20:26:22 +00004238 rc = whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004239 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
drh0f133a42013-05-22 17:01:17 +00004240 && pNew->u.btree.nEq<=pProbe->nColumn
4241 && pProbe->zName!=0
drh5346e952013-05-08 14:14:26 +00004242 ){
drha18f3d22013-05-08 03:05:41 +00004243 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul*nIn);
4244 }
drh1c8148f2013-05-04 20:25:23 +00004245 }
drh4efc9292013-06-06 23:02:03 +00004246 pNew->prereq = saved_prereq;
4247 pNew->u.btree.nEq = saved_nEq;
4248 pNew->wsFlags = saved_wsFlags;
4249 pNew->nOut = saved_nOut;
4250 pNew->nLTerm = saved_nLTerm;
drh5346e952013-05-08 14:14:26 +00004251 return rc;
drh1c8148f2013-05-04 20:25:23 +00004252}
4253
4254/*
drh23f98da2013-05-21 15:52:07 +00004255** Return True if it is possible that pIndex might be useful in
4256** implementing the ORDER BY clause in pBuilder.
4257**
4258** Return False if pBuilder does not contain an ORDER BY clause or
4259** if there is no way for pIndex to be useful in implementing that
4260** ORDER BY clause.
4261*/
4262static int indexMightHelpWithOrderBy(
4263 WhereLoopBuilder *pBuilder,
4264 Index *pIndex,
4265 int iCursor
4266){
4267 ExprList *pOB;
4268 int iCol;
4269 int ii;
4270
drh70d18342013-06-06 19:16:33 +00004271 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00004272 iCol = pIndex->aiColumn[0];
4273 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00004274 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00004275 if( pExpr->op!=TK_COLUMN ) return 0;
4276 if( pExpr->iTable==iCursor ){
4277 if( pExpr->iColumn==iCol ) return 1;
4278 return 0;
4279 }
4280 }
4281 return 0;
4282}
4283
4284/*
drh0823c892013-05-11 00:06:23 +00004285** Add all WhereLoop objects a single table of the join were the table
4286** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
4287** a b-tree table, not a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004288*/
drh5346e952013-05-08 14:14:26 +00004289static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00004290 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00004291 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00004292){
drh70d18342013-06-06 19:16:33 +00004293 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00004294 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00004295 Index sPk; /* A fake index object for the primary key */
4296 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
4297 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00004298 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00004299 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00004300 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00004301 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00004302 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00004303 int b; /* A boolean value */
drh4efc9292013-06-06 23:02:03 +00004304 WhereCost rSize; /* number of rows in the table */
4305 WhereCost rLogSize; /* Logarithm of the number of rows in the table */
drh23f98da2013-05-21 15:52:07 +00004306
drh1c8148f2013-05-04 20:25:23 +00004307 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004308 pWInfo = pBuilder->pWInfo;
4309 pTabList = pWInfo->pTabList;
4310 pSrc = pTabList->a + pNew->iTab;
drh0823c892013-05-11 00:06:23 +00004311 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00004312
4313 if( pSrc->pIndex ){
4314 /* An INDEXED BY clause specifies a particular index to use */
4315 pProbe = pSrc->pIndex;
4316 }else{
4317 /* There is no INDEXED BY clause. Create a fake Index object in local
4318 ** variable sPk to represent the rowid primary key index. Make this
4319 ** fake index the first in a chain of Index objects with all of the real
4320 ** indices to follow */
4321 Index *pFirst; /* First of real indices on the table */
4322 memset(&sPk, 0, sizeof(Index));
4323 sPk.nColumn = 1;
4324 sPk.aiColumn = &aiColumnPk;
4325 sPk.aiRowEst = aiRowEstPk;
4326 sPk.onError = OE_Replace;
4327 sPk.pTable = pSrc->pTab;
4328 aiRowEstPk[0] = pSrc->pTab->nRowEst;
4329 aiRowEstPk[1] = 1;
4330 pFirst = pSrc->pTab->pIndex;
4331 if( pSrc->notIndexed==0 ){
4332 /* The real indices of the table are only considered if the
4333 ** NOT INDEXED qualifier is omitted from the FROM clause */
4334 sPk.pNext = pFirst;
4335 }
4336 pProbe = &sPk;
4337 }
drh4efc9292013-06-06 23:02:03 +00004338 rSize = (WhereCost)pSrc->pTab->nRowEst;
drheb04de32013-05-10 15:16:30 +00004339 rLogSize = estLog(rSize);
4340
4341 /* Automatic indexes */
drhcf8fa7a2013-05-10 20:26:22 +00004342 if( !pBuilder->pBest
drh70d18342013-06-06 19:16:33 +00004343 && pTabList->nSrc>1
4344 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
drheb04de32013-05-10 15:16:30 +00004345 && !pSrc->viaCoroutine
4346 && !pSrc->notIndexed
4347 && !pSrc->isCorrelated
4348 ){
4349 /* Generate auto-index WhereLoops */
4350 WhereClause *pWC = pBuilder->pWC;
4351 WhereTerm *pTerm;
4352 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
4353 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00004354 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00004355 if( termCanDriveIndex(pTerm, pSrc, 0) ){
4356 pNew->u.btree.nEq = 1;
drhef866372013-05-22 20:49:02 +00004357 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00004358 pNew->nLTerm = 1;
4359 pNew->aLTerm[0] = pTerm;
drhae70cf12013-05-31 15:18:46 +00004360 pNew->rSetup = 20*rLogSize*pSrc->pTab->nRowEst;
drh4efc9292013-06-06 23:02:03 +00004361 pNew->nOut = (WhereCost)10;
drheb04de32013-05-10 15:16:30 +00004362 pNew->rRun = rLogSize + pNew->nOut;
4363 pNew->wsFlags = WHERE_TEMP_INDEX;
4364 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00004365 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00004366 }
4367 }
4368 }
drh1c8148f2013-05-04 20:25:23 +00004369
4370 /* Loop over all indices
4371 */
drh23f98da2013-05-21 15:52:07 +00004372 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh5346e952013-05-08 14:14:26 +00004373 pNew->u.btree.nEq = 0;
drh4efc9292013-06-06 23:02:03 +00004374 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00004375 pNew->iSortIdx = 0;
drh4efc9292013-06-06 23:02:03 +00004376 pNew->rSetup = (WhereCost)0;
drh23f98da2013-05-21 15:52:07 +00004377 pNew->prereq = mExtra;
4378 pNew->u.btree.pIndex = pProbe;
4379 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh43fe25f2013-05-07 23:06:23 +00004380 if( pProbe->tnum<=0 ){
4381 /* Integer primary key index */
4382 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00004383
4384 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00004385 pNew->iSortIdx = b ? iSortIdx : 0;
drh23f98da2013-05-21 15:52:07 +00004386 pNew->nOut = rSize;
4387 pNew->rRun = (rSize + rLogSize)*(3+b); /* 4x penalty for a full-scan */
4388 rc = whereLoopInsert(pBuilder, pNew);
4389 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00004390 }else{
4391 Bitmask m = pSrc->colUsed;
4392 int j;
4393 for(j=pProbe->nColumn-1; j>=0; j--){
4394 int x = pProbe->aiColumn[j];
4395 if( x<BMS-1 ){
drh7699d1c2013-06-04 12:42:29 +00004396 m &= ~MASKBIT(x);
drh43fe25f2013-05-07 23:06:23 +00004397 }
4398 }
drh6fa978d2013-05-30 19:29:19 +00004399 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
drh1c8148f2013-05-04 20:25:23 +00004400
drh23f98da2013-05-21 15:52:07 +00004401 /* Full scan via index */
drhe3b7c922013-06-03 19:17:40 +00004402 if( (m==0 || b)
4403 && pProbe->bUnordered==0
drh70d18342013-06-06 19:16:33 +00004404 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
drhe3b7c922013-06-03 19:17:40 +00004405 && sqlite3GlobalConfig.bUseCis
drh70d18342013-06-06 19:16:33 +00004406 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
drhe3b7c922013-06-03 19:17:40 +00004407 ){
drh23f98da2013-05-21 15:52:07 +00004408 pNew->iSortIdx = b ? iSortIdx : 0;
4409 pNew->nOut = rSize;
4410 pNew->rRun = (m==0) ? (rSize + rLogSize)*(1+b) : (rSize*rLogSize);
4411 rc = whereLoopInsert(pBuilder, pNew);
4412 if( rc ) break;
4413 }
4414 }
drh5346e952013-05-08 14:14:26 +00004415 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 1);
drh1c8148f2013-05-04 20:25:23 +00004416
4417 /* If there was an INDEXED BY clause, then only that one index is
4418 ** considered. */
4419 if( pSrc->pIndex ) break;
4420 }
drh5346e952013-05-08 14:14:26 +00004421 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004422}
4423
4424/*
drh0823c892013-05-11 00:06:23 +00004425** Add all WhereLoop objects for a table of the join identified by
4426** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004427*/
drh5346e952013-05-08 14:14:26 +00004428static int whereLoopAddVirtual(
drh1c8148f2013-05-04 20:25:23 +00004429 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00004430 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00004431){
drh70d18342013-06-06 19:16:33 +00004432 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00004433 Parse *pParse; /* The parsing context */
4434 WhereClause *pWC; /* The WHERE clause */
4435 struct SrcList_item *pSrc; /* The FROM clause term to search */
4436 Table *pTab;
4437 sqlite3 *db;
4438 sqlite3_index_info *pIdxInfo;
4439 struct sqlite3_index_constraint *pIdxCons;
4440 struct sqlite3_index_constraint_usage *pUsage;
4441 WhereTerm *pTerm;
4442 int i, j;
4443 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00004444 int nConstraint;
drh5346e952013-05-08 14:14:26 +00004445 int seenIn = 0; /* True if an IN operator is seen */
4446 int seenVar = 0; /* True if a non-constant constraint is seen */
4447 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
4448 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00004449 int rc = SQLITE_OK;
4450
drh70d18342013-06-06 19:16:33 +00004451 pWInfo = pBuilder->pWInfo;
4452 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00004453 db = pParse->db;
4454 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00004455 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004456 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00004457 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00004458 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00004459 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00004460 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00004461 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00004462 pNew->rSetup = 0;
4463 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00004464 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00004465 pNew->u.vtab.needFree = 0;
4466 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00004467 nConstraint = pIdxInfo->nConstraint;
4468 if( whereLoopResize(db, pNew, nConstraint) ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00004469
drh0823c892013-05-11 00:06:23 +00004470 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00004471 if( !seenIn && (iPhase&1)!=0 ){
4472 iPhase++;
4473 if( iPhase>3 ) break;
4474 }
4475 if( !seenVar && iPhase>1 ) break;
4476 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4477 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
4478 j = pIdxCons->iTermOffset;
4479 pTerm = &pWC->a[j];
4480 switch( iPhase ){
4481 case 0: /* Constants without IN operator */
4482 pIdxCons->usable = 0;
4483 if( (pTerm->eOperator & WO_IN)!=0 ){
4484 seenIn = 1;
4485 }else if( pTerm->prereqRight!=0 ){
4486 seenVar = 1;
4487 }else{
4488 pIdxCons->usable = 1;
4489 }
4490 break;
4491 case 1: /* Constants with IN operators */
4492 assert( seenIn );
4493 pIdxCons->usable = (pTerm->prereqRight==0);
4494 break;
4495 case 2: /* Variables without IN */
4496 assert( seenVar );
4497 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
4498 break;
4499 default: /* Variables with IN */
4500 assert( seenVar && seenIn );
4501 pIdxCons->usable = 1;
4502 break;
4503 }
4504 }
4505 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
4506 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4507 pIdxInfo->idxStr = 0;
4508 pIdxInfo->idxNum = 0;
4509 pIdxInfo->needToFreeIdxStr = 0;
4510 pIdxInfo->orderByConsumed = 0;
drh4efc9292013-06-06 23:02:03 +00004511 /* ((WhereCost)2) In case of SQLITE_OMIT_FLOATING_POINT... */
4512 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((WhereCost)2);
drh5346e952013-05-08 14:14:26 +00004513 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
4514 if( rc ) goto whereLoopAddVtab_exit;
4515 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4516 pNew->prereq = 0;
drhc718f1c2013-05-08 20:05:58 +00004517 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00004518 assert( pNew->nLSlot>=nConstraint );
4519 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00004520 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00004521 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00004522 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4523 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00004524 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00004525 || j<0
4526 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00004527 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00004528 ){
4529 rc = SQLITE_ERROR;
4530 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
4531 goto whereLoopAddVtab_exit;
4532 }
4533 pTerm = &pWC->a[j];
4534 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00004535 assert( iTerm<pNew->nLSlot );
4536 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00004537 if( iTerm>mxTerm ) mxTerm = iTerm;
drh52986302013-06-03 16:03:16 +00004538 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00004539 if( (pTerm->eOperator & WO_IN)!=0 ){
4540 if( pUsage[i].omit==0 ){
4541 /* Do not attempt to use an IN constraint if the virtual table
4542 ** says that the equivalent EQ constraint cannot be safely omitted.
4543 ** If we do attempt to use such a constraint, some rows might be
4544 ** repeated in the output. */
4545 break;
4546 }
4547 /* A virtual table that is constrained by an IN clause may not
4548 ** consume the ORDER BY clause because (1) the order of IN terms
4549 ** is not necessarily related to the order of output terms and
4550 ** (2) Multiple outputs from a single IN value will not merge
4551 ** together. */
4552 pIdxInfo->orderByConsumed = 0;
4553 }
4554 }
4555 }
drh4efc9292013-06-06 23:02:03 +00004556 if( i>=nConstraint ){
4557 pNew->nLTerm = mxTerm+1;
4558 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00004559 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4560 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4561 pIdxInfo->needToFreeIdxStr = 0;
4562 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh3b1d8082013-06-03 16:56:37 +00004563 pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
4564 && pIdxInfo->orderByConsumed);
drh4efc9292013-06-06 23:02:03 +00004565 pNew->rSetup = (WhereCost)0;
drh5346e952013-05-08 14:14:26 +00004566 pNew->rRun = pIdxInfo->estimatedCost;
drh4efc9292013-06-06 23:02:03 +00004567 pNew->nOut = (WhereCost)25;
drhcf8fa7a2013-05-10 20:26:22 +00004568 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004569 if( pNew->u.vtab.needFree ){
4570 sqlite3_free(pNew->u.vtab.idxStr);
4571 pNew->u.vtab.needFree = 0;
4572 }
4573 }
4574 }
4575
4576whereLoopAddVtab_exit:
4577 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4578 sqlite3DbFree(db, pIdxInfo);
4579 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004580}
4581
4582/*
drhcf8fa7a2013-05-10 20:26:22 +00004583** Add WhereLoop entries to handle OR terms. This works for either
4584** btrees or virtual tables.
4585*/
4586static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00004587 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00004588 WhereClause *pWC;
4589 WhereLoop *pNew;
4590 WhereTerm *pTerm, *pWCEnd;
4591 int rc = SQLITE_OK;
4592 int iCur;
4593 WhereClause tempWC;
4594 WhereLoopBuilder sSubBuild;
4595 WhereLoop sBest;
4596 struct SrcList_item *pItem;
4597
drhcf8fa7a2013-05-10 20:26:22 +00004598 pWC = pBuilder->pWC;
drh70d18342013-06-06 19:16:33 +00004599 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
drhcf8fa7a2013-05-10 20:26:22 +00004600 pWCEnd = pWC->a + pWC->nTerm;
4601 pNew = pBuilder->pNew;
drhcf8fa7a2013-05-10 20:26:22 +00004602
4603 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4604 if( (pTerm->eOperator & WO_OR)!=0
4605 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4606 ){
4607 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4608 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4609 WhereTerm *pOrTerm;
drh4efc9292013-06-06 23:02:03 +00004610 WhereCost rTotal = 0;
4611 WhereCost nRow = 0;
drhcf8fa7a2013-05-10 20:26:22 +00004612 Bitmask prereq = mExtra;
drh783dece2013-06-05 17:53:43 +00004613
drh13e11b42013-06-06 23:44:25 +00004614 whereLoopInit(&sBest);
drh70d18342013-06-06 19:16:33 +00004615 pItem = pWInfo->pTabList->a + pNew->iTab;
drh783dece2013-06-05 17:53:43 +00004616 iCur = pItem->iCursor;
4617 sSubBuild = *pBuilder;
4618 sSubBuild.pOrderBy = 0;
4619 sSubBuild.pBest = &sBest;
drhcf8fa7a2013-05-10 20:26:22 +00004620
4621 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00004622 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004623 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4624 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00004625 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00004626 tempWC.pOuter = pWC;
4627 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00004628 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00004629 tempWC.a = pOrTerm;
4630 sSubBuild.pWC = &tempWC;
4631 }else{
4632 continue;
4633 }
4634 sBest.maskSelf = 0;
drh4efc9292013-06-06 23:02:03 +00004635 sBest.rSetup = 0;
4636 sBest.rRun = 0;
drhcf8fa7a2013-05-10 20:26:22 +00004637 if( IsVirtual(pItem->pTab) ){
4638 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
4639 }else{
4640 rc = whereLoopAddBtree(&sSubBuild, mExtra);
4641 }
4642 if( sBest.maskSelf==0 ) break;
drh4efc9292013-06-06 23:02:03 +00004643 assert( sBest.rSetup==(WhereCost)0 );
drhcf8fa7a2013-05-10 20:26:22 +00004644 rTotal += sBest.rRun;
4645 nRow += sBest.nOut;
4646 prereq |= sBest.prereq;
4647 }
drh4efc9292013-06-06 23:02:03 +00004648 assert( pNew->nLSlot>=1 );
4649 pNew->nLTerm = 1;
4650 pNew->aLTerm[0] = pTerm;
drhcf8fa7a2013-05-10 20:26:22 +00004651 pNew->wsFlags = WHERE_MULTI_OR;
drh4efc9292013-06-06 23:02:03 +00004652 pNew->rSetup = (WhereCost)0;
drhcf8fa7a2013-05-10 20:26:22 +00004653 pNew->rRun = rTotal;
4654 pNew->nOut = nRow;
4655 pNew->prereq = prereq;
drh23f98da2013-05-21 15:52:07 +00004656 memset(&pNew->u, 0, sizeof(pNew->u));
drhcf8fa7a2013-05-10 20:26:22 +00004657 rc = whereLoopInsert(pBuilder, pNew);
drh13e11b42013-06-06 23:44:25 +00004658 whereLoopClear(pWInfo->pParse->db, &sBest);
drhcf8fa7a2013-05-10 20:26:22 +00004659 }
4660 }
4661 return rc;
4662}
4663
4664/*
drhf1b5f5b2013-05-02 00:15:01 +00004665** Add all WhereLoop objects for all tables
4666*/
drh5346e952013-05-08 14:14:26 +00004667static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00004668 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00004669 Bitmask mExtra = 0;
4670 Bitmask mPrior = 0;
4671 int iTab;
drh70d18342013-06-06 19:16:33 +00004672 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00004673 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00004674 sqlite3 *db = pWInfo->pParse->db;
4675 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00004676 int rc = SQLITE_OK;
drha2014152013-06-07 00:29:23 +00004677 WhereLoop *pNew, sNew;
drhf1b5f5b2013-05-02 00:15:01 +00004678
4679 /* Loop over the tables in the join, from left to right */
drha2014152013-06-07 00:29:23 +00004680 pBuilder->pNew = pNew = &sNew;
4681 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00004682 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00004683 pNew->iTab = iTab;
drh70d18342013-06-06 19:16:33 +00004684 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
drhf1b5f5b2013-05-02 00:15:01 +00004685 if( (pItem->jointype & (JT_LEFT|JT_CROSS))!=0 ){
4686 mExtra = mPrior;
4687 }
drhb2a90f02013-05-10 03:30:49 +00004688 if( IsVirtual(pItem->pTab) ){
4689 rc = whereLoopAddVirtual(pBuilder, mExtra);
4690 }else{
4691 rc = whereLoopAddBtree(pBuilder, mExtra);
4692 }
drhb2a90f02013-05-10 03:30:49 +00004693 if( rc==SQLITE_OK ){
4694 rc = whereLoopAddOr(pBuilder, mExtra);
4695 }
drhb2a90f02013-05-10 03:30:49 +00004696 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00004697 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00004698 }
drha2014152013-06-07 00:29:23 +00004699 whereLoopClear(db, pNew);
drh1c8148f2013-05-04 20:25:23 +00004700 pBuilder->pNew = 0;
drh5346e952013-05-08 14:14:26 +00004701 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004702}
4703
drha18f3d22013-05-08 03:05:41 +00004704/*
drh7699d1c2013-06-04 12:42:29 +00004705** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00004706** parameters) to see if it outputs rows in the requested ORDER BY
4707** (or GROUP BY) without requiring a separate source operation. Return:
4708**
4709** 0: ORDER BY is not satisfied. Sorting required
4710** 1: ORDER BY is satisfied. Omit sorting
4711** -1: Unknown at this time
4712**
drh6b7157b2013-05-10 02:00:35 +00004713*/
4714static int wherePathSatisfiesOrderBy(
4715 WhereInfo *pWInfo, /* The WHERE clause */
4716 WherePath *pPath, /* The WherePath to check */
4717 int nLoop, /* Number of entries in pPath->aLoop[] */
drh7699d1c2013-06-04 12:42:29 +00004718 int isLastLoop, /* True if pLast is the inner-most loop */
drh319f6772013-05-14 15:31:07 +00004719 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
4720 Bitmask *pRevMask /* Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00004721){
drh88da6442013-05-27 17:59:37 +00004722 u8 revSet; /* True if rev is known */
4723 u8 rev; /* Composite sort order */
4724 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00004725 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
4726 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
4727 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drh7699d1c2013-06-04 12:42:29 +00004728 u16 nColumn; /* Number of columns in pIndex */
4729 u16 nOrderBy; /* Number terms in the ORDER BY clause */
4730 int iLoop; /* Index of WhereLoop in pPath being processed */
4731 int i, j; /* Loop counters */
4732 int iCur; /* Cursor number for current WhereLoop */
4733 int iColumn; /* A column number within table iCur */
4734 WhereLoop *pLoop; /* Current WhereLoop being processed. */
4735 ExprList *pOrderBy = pWInfo->pOrderBy; /* the ORDER BY clause */
4736 WhereTerm *pTerm; /* A single term of the WHERE clause */
4737 Expr *pOBExpr; /* An expression from the ORDER BY clause */
4738 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
4739 Index *pIndex; /* The index associated with pLoop */
4740 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
4741 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
4742 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00004743 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drh7699d1c2013-06-04 12:42:29 +00004744
drh319f6772013-05-14 15:31:07 +00004745
4746 /*
drh7699d1c2013-06-04 12:42:29 +00004747 ** We say the WhereLoop is "one-row" if it generates no more than one
4748 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00004749 ** (a) All index columns match with WHERE_COLUMN_EQ.
4750 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00004751 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
4752 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00004753 **
drhe353ee32013-06-04 23:40:53 +00004754 ** We say the WhereLoop is "order-distinct" if the set of columns from
4755 ** that WhereLoop that are in the ORDER BY clause are different for every
4756 ** row of the WhereLoop. Every one-row WhereLoop is automatically
4757 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
4758 ** is not order-distinct. To be order-distinct is not quite the same as being
4759 ** UNIQUE since a UNIQUE column or index can have multiple rows that
4760 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4761 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4762 **
4763 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4764 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4765 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00004766 */
4767
4768 assert( pOrderBy!=0 );
4769
4770 /* Sortability of virtual tables is determined by the xBestIndex method
4771 ** of the virtual table itself */
4772 if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
drh7699d1c2013-06-04 12:42:29 +00004773 testcase( nLoop>0 ); /* True when outer loops are one-row and match
4774 ** no ORDER BY terms */
drh319f6772013-05-14 15:31:07 +00004775 return pLast->u.vtab.isOrdered;
drh6b7157b2013-05-10 02:00:35 +00004776 }
drh7699d1c2013-06-04 12:42:29 +00004777 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00004778
drh319f6772013-05-14 15:31:07 +00004779 nOrderBy = pOrderBy->nExpr;
drhe353ee32013-06-04 23:40:53 +00004780 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
4781 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00004782 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00004783 orderDistinctMask = 0;
drhe353ee32013-06-04 23:40:53 +00004784 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drh7699d1c2013-06-04 12:42:29 +00004785 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh319f6772013-05-14 15:31:07 +00004786 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh319f6772013-05-14 15:31:07 +00004787 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drh7699d1c2013-06-04 12:42:29 +00004788 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
4789 if( pLoop->wsFlags & WHERE_IPK ){
4790 pIndex = 0;
4791 nColumn = 0;
4792 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00004793 return 0;
drh7699d1c2013-06-04 12:42:29 +00004794 }else{
4795 nColumn = pIndex->nColumn;
drhe353ee32013-06-04 23:40:53 +00004796 isOrderDistinct = pIndex->onError!=OE_None;
drh1b0f0262013-05-30 22:27:09 +00004797 }
drh7699d1c2013-06-04 12:42:29 +00004798
drhe353ee32013-06-04 23:40:53 +00004799 /* For every term of the index that is constrained by == or IS NULL,
drh7699d1c2013-06-04 12:42:29 +00004800 ** mark off corresponding ORDER BY terms wherever they occur
4801 ** in the ORDER BY clause.
4802 */
4803 for(i=0; i<pLoop->u.btree.nEq; i++){
drh4efc9292013-06-06 23:02:03 +00004804 pTerm = pLoop->aLTerm[i];
drh7699d1c2013-06-04 12:42:29 +00004805 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))==0 ) continue;
4806 iColumn = pTerm->u.leftColumn;
4807 for(j=0; j<nOrderBy; j++){
4808 if( MASKBIT(j) & obSat ) continue;
4809 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[j].pExpr);
4810 if( pOBExpr->op!=TK_COLUMN ) continue;
4811 if( pOBExpr->iTable!=iCur ) continue;
4812 if( pOBExpr->iColumn!=iColumn ) continue;
4813 if( iColumn>=0 ){
4814 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[j].pExpr);
4815 if( !pColl ) pColl = db->pDfltColl;
4816 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[i])!=0 ) continue;
4817 }
4818 obSat |= MASKBIT(j);
drhdc3cd4b2013-05-30 23:21:20 +00004819 }
drh7699d1c2013-06-04 12:42:29 +00004820 if( obSat==obDone ) return 1;
drh88da6442013-05-27 17:59:37 +00004821 }
drh7699d1c2013-06-04 12:42:29 +00004822
4823 /* Loop through all columns of the index and deal with the ones
4824 ** that are not constrained by == or IN.
4825 */
4826 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00004827 distinctColumns = 0;
drh7699d1c2013-06-04 12:42:29 +00004828 for(j=0; j<=nColumn; j++){
4829 u8 bOnce; /* True to run the ORDER BY search loop */
4830
drhe353ee32013-06-04 23:40:53 +00004831 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00004832 if( j<pLoop->u.btree.nEq
drh4efc9292013-06-06 23:02:03 +00004833 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
drh7699d1c2013-06-04 12:42:29 +00004834 ){
drhe353ee32013-06-04 23:40:53 +00004835 if( i & WO_ISNULL ) isOrderDistinct = 0;
4836 continue;
drh7699d1c2013-06-04 12:42:29 +00004837 }
4838
drhe353ee32013-06-04 23:40:53 +00004839 /* Get the column number in the table (iColumn) and sort order
4840 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00004841 */
4842 if( j<nColumn ){
4843 /* Normal index columns */
4844 iColumn = pIndex->aiColumn[j];
4845 revIdx = pIndex->aSortOrder[j];
4846 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00004847 }else{
drh7699d1c2013-06-04 12:42:29 +00004848 /* The ROWID column at the end */
4849 iColumn = -1;
4850 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00004851 }
drh7699d1c2013-06-04 12:42:29 +00004852
4853 /* An unconstrained column that might be NULL means that this
4854 ** WhereLoop is not well-ordered
4855 */
drhe353ee32013-06-04 23:40:53 +00004856 if( isOrderDistinct
4857 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00004858 && j>=pLoop->u.btree.nEq
4859 && pIndex->pTable->aCol[iColumn].notNull==0
4860 ){
drhe353ee32013-06-04 23:40:53 +00004861 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00004862 }
4863
4864 /* Find the ORDER BY term that corresponds to the j-th column
4865 ** of the index and and mark that ORDER BY term off
4866 */
4867 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00004868 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00004869 for(i=0; bOnce && i<nOrderBy; i++){
4870 if( MASKBIT(i) & obSat ) continue;
4871 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh7699d1c2013-06-04 12:42:29 +00004872 if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00004873 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00004874 if( pOBExpr->iTable!=iCur ) continue;
4875 if( pOBExpr->iColumn!=iColumn ) continue;
4876 if( iColumn>=0 ){
4877 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4878 if( !pColl ) pColl = db->pDfltColl;
4879 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
4880 }
drhe353ee32013-06-04 23:40:53 +00004881 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00004882 break;
4883 }
drhe353ee32013-06-04 23:40:53 +00004884 if( isMatch ){
4885 if( iColumn<0 ) distinctColumns = 1;
drh7699d1c2013-06-04 12:42:29 +00004886 obSat |= MASKBIT(i);
4887 if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
drhe353ee32013-06-04 23:40:53 +00004888 /* Make sure the sort order is compatible in an ORDER BY clause.
4889 ** Sort order is irrelevant for a GROUP BY clause. */
drh7699d1c2013-06-04 12:42:29 +00004890 if( revSet ){
4891 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
4892 }else{
4893 rev = revIdx ^ pOrderBy->a[i].sortOrder;
4894 if( rev ) *pRevMask |= MASKBIT(iLoop);
4895 revSet = 1;
4896 }
4897 }
4898 }else{
4899 /* No match found */
drhe353ee32013-06-04 23:40:53 +00004900 if( j==0 || j<nColumn ) isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00004901 break;
4902 }
4903 } /* end Loop over all index columns */
drhe353ee32013-06-04 23:40:53 +00004904 if( distinctColumns ) isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00004905 } /* end-if not one-row */
4906
4907 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00004908 if( isOrderDistinct ){
4909 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00004910 for(i=0; i<nOrderBy; i++){
4911 Expr *p;
4912 if( MASKBIT(i) & obSat ) continue;
4913 p = pOrderBy->a[i].pExpr;
drh70d18342013-06-06 19:16:33 +00004914 if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00004915 obSat |= MASKBIT(i);
4916 }
drh0afb4232013-05-31 13:36:32 +00004917 }
drh319f6772013-05-14 15:31:07 +00004918 }
drh319f6772013-05-14 15:31:07 +00004919 }
drh7699d1c2013-06-04 12:42:29 +00004920 if( obSat==obDone ) return 1;
drhe353ee32013-06-04 23:40:53 +00004921 if( !isOrderDistinct ) return 0;
drh7699d1c2013-06-04 12:42:29 +00004922 if( isLastLoop ) return 1;
drh319f6772013-05-14 15:31:07 +00004923 return -1;
drh6b7157b2013-05-10 02:00:35 +00004924}
4925
drhd15cb172013-05-21 19:23:10 +00004926#ifdef WHERETRACE_ENABLED
4927/* For debugging use only: */
4928static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
4929 static char zName[65];
4930 int i;
4931 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
4932 if( pLast ) zName[i++] = pLast->cId;
4933 zName[i] = 0;
4934 return zName;
4935}
4936#endif
4937
drh6b7157b2013-05-10 02:00:35 +00004938
4939/*
drha18f3d22013-05-08 03:05:41 +00004940** Given the list of WhereLoop objects on pWInfo->pLoops, this routine
4941** attempts to find the lowest cost path that visits each WhereLoop
4942** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
4943**
4944** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
4945** error occurs.
4946*/
drh4efc9292013-06-06 23:02:03 +00004947static int wherePathSolver(WhereInfo *pWInfo, WhereCost nRowEst){
drh783dece2013-06-05 17:53:43 +00004948 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00004949 int nLoop; /* Number of terms in the join */
4950 sqlite3 *db; /* The database connection */
4951 int iLoop; /* Loop counter over the terms of the join */
4952 int ii, jj; /* Loop counters */
drh4efc9292013-06-06 23:02:03 +00004953 WhereCost rCost; /* Cost of a path */
4954 WhereCost mxCost; /* Maximum cost of a set of paths */
4955 WhereCost rSortCost; /* Cost to do a sort */
drha18f3d22013-05-08 03:05:41 +00004956 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
4957 WherePath *aFrom; /* All nFrom paths at the previous level */
4958 WherePath *aTo; /* The nTo best paths at the current level */
4959 WherePath *pFrom; /* An element of aFrom[] that we are working on */
4960 WherePath *pTo; /* An element of aTo[] that we are working on */
4961 WhereLoop *pWLoop; /* One of the WhereLoop objects */
4962 WhereLoop **pX; /* Used to divy up the pSpace memory */
4963 char *pSpace; /* Temporary memory used by this routine */
4964
4965 db = pWInfo->pParse->db;
4966 nLoop = pWInfo->nLevel;
drhe9d935a2013-06-05 16:19:59 +00004967 mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00004968 assert( nLoop<=pWInfo->pTabList->nSrc );
drh88da6442013-05-27 17:59:37 +00004969#ifdef WHERETRACE_ENABLED
4970 if( sqlite3WhereTrace>=2 ) sqlite3DebugPrintf("---- begin solver\n");
4971#endif
drha18f3d22013-05-08 03:05:41 +00004972
4973 /* Allocate and initialize space for aTo and aFrom */
4974 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
4975 pSpace = sqlite3DbMallocRaw(db, ii);
4976 if( pSpace==0 ) return SQLITE_NOMEM;
4977 aTo = (WherePath*)pSpace;
4978 aFrom = aTo+mxChoice;
4979 memset(aFrom, 0, sizeof(aFrom[0]));
4980 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00004981 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00004982 pFrom->aLoop = pX;
4983 }
4984
drh6b7157b2013-05-10 02:00:35 +00004985 /* Seed the search with a single WherePath containing zero WhereLoops */
drh4efc9292013-06-06 23:02:03 +00004986 aFrom[0].nRow = (WhereCost)1;
drha18f3d22013-05-08 03:05:41 +00004987 nFrom = 1;
drh6b7157b2013-05-10 02:00:35 +00004988
4989 /* Precompute the cost of sorting the final result set, if the caller
4990 ** to sqlite3WhereBegin() was concerned about sorting */
drh4efc9292013-06-06 23:02:03 +00004991 rSortCost = (WhereCost)0;
drh88da6442013-05-27 17:59:37 +00004992 if( pWInfo->pOrderBy==0 || nRowEst<=0.0 ){
drh6b7157b2013-05-10 02:00:35 +00004993 aFrom[0].isOrderedValid = 1;
4994 }else{
4995 /* Compute an estimate on the cost to sort the entire result set */
drha50ef112013-05-22 02:06:59 +00004996 rSortCost = nRowEst*estLog(nRowEst);
drha50ef112013-05-22 02:06:59 +00004997#ifdef WHERETRACE_ENABLED
4998 if( sqlite3WhereTrace>=2 ){
drh88da6442013-05-27 17:59:37 +00004999 sqlite3DebugPrintf("---- sort cost=%-7.2g\n", rSortCost);
drha50ef112013-05-22 02:06:59 +00005000 }
5001#endif
drh6b7157b2013-05-10 02:00:35 +00005002 }
5003
5004 /* Compute successively longer WherePaths using the previous generation
5005 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5006 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00005007 for(iLoop=0; iLoop<nLoop; iLoop++){
5008 nTo = 0;
5009 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
5010 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
5011 Bitmask maskNew;
drh319f6772013-05-14 15:31:07 +00005012 Bitmask revMask = 0;
drh6b7157b2013-05-10 02:00:35 +00005013 u8 isOrderedValid = pFrom->isOrderedValid;
5014 u8 isOrdered = pFrom->isOrdered;
drha18f3d22013-05-08 03:05:41 +00005015 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5016 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00005017 /* At this point, pWLoop is a candidate to be the next loop.
5018 ** Compute its cost */
drha18f3d22013-05-08 03:05:41 +00005019 rCost = pWLoop->rSetup + pWLoop->rRun*pFrom->nRow + pFrom->rCost;
5020 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh6b7157b2013-05-10 02:00:35 +00005021 if( !isOrderedValid ){
drh0afb4232013-05-31 13:36:32 +00005022 switch( wherePathSatisfiesOrderBy(pWInfo, pFrom, iLoop, iLoop==nLoop-1,
drh319f6772013-05-14 15:31:07 +00005023 pWLoop, &revMask) ){
drh6b7157b2013-05-10 02:00:35 +00005024 case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
5025 isOrdered = 1;
5026 isOrderedValid = 1;
5027 break;
5028 case 0: /* No. pFrom+pWLoop will require a separate sort */
5029 isOrdered = 0;
5030 isOrderedValid = 1;
5031 rCost += rSortCost;
5032 break;
5033 default: /* Cannot tell yet. Try again on the next iteration */
5034 break;
5035 }
drh3a5ba8b2013-06-03 15:34:48 +00005036 }else{
5037 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00005038 }
5039 /* Check to see if pWLoop should be added to the mxChoice best so far */
5040 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
5041 if( pTo->maskLoop==maskNew && pTo->isOrderedValid==isOrderedValid ){
5042 break;
5043 }
5044 }
drha18f3d22013-05-08 03:05:41 +00005045 if( jj>=nTo ){
drhd15cb172013-05-21 19:23:10 +00005046 if( nTo>=mxChoice && rCost>=mxCost ){
drhae70cf12013-05-31 15:18:46 +00005047#ifdef WHERETRACE_ENABLED
5048 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005049 sqlite3DebugPrintf("Skip %s cost=%-7.2g order=%c\n",
5050 wherePathName(pFrom, iLoop, pWLoop), rCost,
5051 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5052 }
5053#endif
5054 continue;
5055 }
5056 /* Add a new Path to the aTo[] set */
drha18f3d22013-05-08 03:05:41 +00005057 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00005058 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00005059 jj = nTo++;
5060 }else{
drhd15cb172013-05-21 19:23:10 +00005061 /* New path replaces the prior worst to keep count below mxChoice */
drhc718f1c2013-05-08 20:05:58 +00005062 for(jj=nTo-1; aTo[jj].rCost<mxCost; jj--){ assert(jj>0); }
drha18f3d22013-05-08 03:05:41 +00005063 }
5064 pTo = &aTo[jj];
drhd15cb172013-05-21 19:23:10 +00005065#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005066 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005067 sqlite3DebugPrintf("New %s cost=%-7.2g order=%c\n",
5068 wherePathName(pFrom, iLoop, pWLoop), rCost,
5069 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5070 }
5071#endif
drhf204dac2013-05-08 03:22:07 +00005072 }else{
drhd15cb172013-05-21 19:23:10 +00005073 if( pTo->rCost<=rCost ){
5074#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005075 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005076 sqlite3DebugPrintf(
5077 "Skip %s cost=%-7.2g order=%c",
5078 wherePathName(pFrom, iLoop, pWLoop), rCost,
5079 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5080 sqlite3DebugPrintf(" vs %s cost=%-7.2g order=%c\n",
5081 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
5082 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5083 }
5084#endif
5085 continue;
5086 }
5087 /* A new and better score for a previously created equivalent path */
5088#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005089 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005090 sqlite3DebugPrintf(
5091 "Update %s cost=%-7.2g order=%c",
5092 wherePathName(pFrom, iLoop, pWLoop), rCost,
5093 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5094 sqlite3DebugPrintf(" was %s cost=%-7.2g order=%c\n",
5095 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
5096 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5097 }
5098#endif
drha18f3d22013-05-08 03:05:41 +00005099 }
drh6b7157b2013-05-10 02:00:35 +00005100 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00005101 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00005102 pTo->revLoop = revMask;
drha18f3d22013-05-08 03:05:41 +00005103 pTo->nRow = pFrom->nRow * pWLoop->nOut;
5104 pTo->rCost = rCost;
drh6b7157b2013-05-10 02:00:35 +00005105 pTo->isOrderedValid = isOrderedValid;
5106 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00005107 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5108 pTo->aLoop[iLoop] = pWLoop;
5109 if( nTo>=mxChoice ){
5110 mxCost = aTo[0].rCost;
5111 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
5112 if( pTo->rCost>mxCost ) mxCost = pTo->rCost;
5113 }
5114 }
5115 }
5116 }
5117
drhd15cb172013-05-21 19:23:10 +00005118#ifdef WHERETRACE_ENABLED
5119 if( sqlite3WhereTrace>=2 ){
drha50ef112013-05-22 02:06:59 +00005120 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00005121 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drh88da6442013-05-27 17:59:37 +00005122 sqlite3DebugPrintf(" %s cost=%-7.2g nrow=%-7.2g order=%c",
drha50ef112013-05-22 02:06:59 +00005123 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00005124 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
drh88da6442013-05-27 17:59:37 +00005125 if( pTo->isOrderedValid && pTo->isOrdered ){
5126 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5127 }else{
5128 sqlite3DebugPrintf("\n");
5129 }
drhf204dac2013-05-08 03:22:07 +00005130 }
5131 }
5132#endif
5133
drh6b7157b2013-05-10 02:00:35 +00005134 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00005135 pFrom = aTo;
5136 aTo = aFrom;
5137 aFrom = pFrom;
5138 nFrom = nTo;
5139 }
5140
drh75b93402013-05-31 20:43:57 +00005141 if( nFrom==0 ){
5142 sqlite3ErrorMsg(pWInfo->pParse, "no query solution");
5143 sqlite3DbFree(db, pSpace);
5144 return SQLITE_ERROR;
5145 }
drha18f3d22013-05-08 03:05:41 +00005146
drh6b7157b2013-05-10 02:00:35 +00005147 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00005148 pFrom = aFrom;
5149 for(ii=1; ii<nFrom; ii++){
5150 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5151 }
5152 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00005153 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00005154 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00005155 WhereLevel *pLevel = pWInfo->a + iLoop;
5156 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
5157 pLevel->iFrom = pWLoop->iTab; /* FIXME: Omit the iFrom field */
5158 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00005159 }
drh6b7157b2013-05-10 02:00:35 +00005160 if( pFrom->isOrdered ){
5161 pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
drh88da6442013-05-27 17:59:37 +00005162 pWInfo->revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00005163 }
drha50ef112013-05-22 02:06:59 +00005164 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00005165
5166 /* Free temporary memory and return success */
5167 sqlite3DbFree(db, pSpace);
5168 return SQLITE_OK;
5169}
drh94a11212004-09-25 13:12:14 +00005170
5171/*
drh60c96cd2013-06-09 17:21:25 +00005172** Most queries use only a single table (they are not joins) and have
5173** simple == constraints against indexed fields. This routine attempts
5174** to plan those simple cases using much less ceremony than the
5175** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5176** times for the common case.
5177**
5178** Return non-zero on success, if this query can be handled by this
5179** no-frills query planner. Return zero if this query needs the
5180** general-purpose query planner.
5181*/
5182static int whereSimpleFastCase(WhereLoopBuilder *pBuilder){
5183 WhereInfo *pWInfo;
5184 struct SrcList_item *pItem;
5185 WhereClause *pWC;
5186 WhereTerm *pTerm;
5187 WhereLoop *pLoop;
5188 int iCur;
5189 int i, j;
5190 int nOrderBy;
5191 Table *pTab;
5192 Index *pIdx;
5193
5194 pWInfo = pBuilder->pWInfo;
5195 assert( pWInfo->pTabList->nSrc>=1 );
5196 pItem = pWInfo->pTabList->a;
5197 pTab = pItem->pTab;
5198 if( IsVirtual(pTab) ) return 0;
5199 if( pItem->zIndex ) return 0;
5200 iCur = pItem->iCursor;
5201 pWC = &pWInfo->sWC;
5202 pLoop = pBuilder->pNew;
5203 pWInfo->a[0].pWLoop = pLoop;
5204 pLoop->wsFlags = 0;
5205 nOrderBy = pWInfo->pOrderBy ? pWInfo->pOrderBy->nExpr : 0;
5206 pTerm = findTerm(pWC, iCur, -1, 1, WO_EQ, 0);
5207 if( pTerm ){
5208 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5209 pLoop->aLTerm[0] = pTerm;
5210 pLoop->nLTerm = 1;
5211 pLoop->u.btree.nEq = 1;
5212 pLoop->rRun = (WhereCost)10;
5213 pLoop->nOut = (WhereCost)1;
5214 pWInfo->nRowOut = 1;
5215 pWInfo->nOBSat = nOrderBy;
5216 }else{
5217 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5218 if( pIdx->onError==OE_None ) continue;
5219 for(j=0; j<pIdx->nColumn; j++){
5220 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 1, WO_EQ, pIdx);
5221 if( pTerm==0 ) break;
5222 whereLoopResize(pWInfo->pParse->db, pLoop, j);
5223 pLoop->aLTerm[j] = pTerm;
5224 }
5225 if( j!=pIdx->nColumn ) continue;
5226 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW;
5227 pLoop->nLTerm = j;
5228 pLoop->u.btree.nEq = j;
5229 pLoop->u.btree.pIndex = pIdx;
5230 pLoop->rRun = (WhereCost)15;
5231 pLoop->nOut = (WhereCost)1;
5232 pWInfo->nRowOut = 1;
5233 pWInfo->nOBSat = nOrderBy;
5234 break;
5235 }
5236 }
5237 return pLoop->wsFlags!=0;
5238}
5239
5240/*
drhe3184742002-06-19 14:27:05 +00005241** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00005242** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00005243** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00005244** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00005245** in order to complete the WHERE clause processing.
5246**
5247** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00005248**
5249** The basic idea is to do a nested loop, one loop for each table in
5250** the FROM clause of a select. (INSERT and UPDATE statements are the
5251** same as a SELECT with only a single table in the FROM clause.) For
5252** example, if the SQL is this:
5253**
5254** SELECT * FROM t1, t2, t3 WHERE ...;
5255**
5256** Then the code generated is conceptually like the following:
5257**
5258** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005259** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00005260** foreach row3 in t3 do /
5261** ...
5262** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005263** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00005264** end /
5265**
drh29dda4a2005-07-21 18:23:20 +00005266** Note that the loops might not be nested in the order in which they
5267** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00005268** use of indices. Note also that when the IN operator appears in
5269** the WHERE clause, it might result in additional nested loops for
5270** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00005271**
drhc27a1ce2002-06-14 20:58:45 +00005272** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00005273** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5274** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00005275** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00005276**
drhe6f85e72004-12-25 01:03:13 +00005277** The code that sqlite3WhereBegin() generates leaves the cursors named
5278** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00005279** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00005280** data from the various tables of the loop.
5281**
drhc27a1ce2002-06-14 20:58:45 +00005282** If the WHERE clause is empty, the foreach loops must each scan their
5283** entire tables. Thus a three-way join is an O(N^3) operation. But if
5284** the tables have indices and there are terms in the WHERE clause that
5285** refer to those indices, a complete table scan can be avoided and the
5286** code will run much faster. Most of the work of this routine is checking
5287** to see if there are indices that can be used to speed up the loop.
5288**
5289** Terms of the WHERE clause are also used to limit which rows actually
5290** make it to the "..." in the middle of the loop. After each "foreach",
5291** terms of the WHERE clause that use only terms in that loop and outer
5292** loops are evaluated and if false a jump is made around all subsequent
5293** inner loops (or around the "..." if the test occurs within the inner-
5294** most loop)
5295**
5296** OUTER JOINS
5297**
5298** An outer join of tables t1 and t2 is conceptally coded as follows:
5299**
5300** foreach row1 in t1 do
5301** flag = 0
5302** foreach row2 in t2 do
5303** start:
5304** ...
5305** flag = 1
5306** end
drhe3184742002-06-19 14:27:05 +00005307** if flag==0 then
5308** move the row2 cursor to a null row
5309** goto start
5310** fi
drhc27a1ce2002-06-14 20:58:45 +00005311** end
5312**
drhe3184742002-06-19 14:27:05 +00005313** ORDER BY CLAUSE PROCESSING
5314**
drh46ec5b62012-09-24 15:30:54 +00005315** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
drhe3184742002-06-19 14:27:05 +00005316** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00005317** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drhe3184742002-06-19 14:27:05 +00005318**
5319** If an index can be used so that the natural output order of the table
5320** scan is correct for the ORDER BY clause, then that index is used and
drh46ec5b62012-09-24 15:30:54 +00005321** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr. This
5322** is an optimization that prevents an unnecessary sort of the result set
5323** if an index appropriate for the ORDER BY clause already exists.
drhe3184742002-06-19 14:27:05 +00005324**
5325** If the where clause loops cannot be arranged to provide the correct
drh46ec5b62012-09-24 15:30:54 +00005326** output order, then WhereInfo.nOBSat is 0.
drh75897232000-05-29 14:26:00 +00005327*/
danielk19774adee202004-05-08 08:23:19 +00005328WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00005329 Parse *pParse, /* The parser context */
5330 SrcList *pTabList, /* A list of all tables to be scanned */
5331 Expr *pWhere, /* The WHERE clause */
drh46ec5b62012-09-24 15:30:54 +00005332 ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
dan38cc40c2011-06-30 20:17:15 +00005333 ExprList *pDistinct, /* The select-list for DISTINCT queries - or NULL */
dan0efb72c2012-08-24 18:44:56 +00005334 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
5335 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00005336){
danielk1977be229652009-03-20 14:18:51 +00005337 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00005338 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00005339 WhereInfo *pWInfo; /* Will become the return value of this function */
5340 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00005341 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00005342 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00005343 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00005344 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drh9cd1c992012-09-25 20:43:35 +00005345 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00005346 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00005347 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00005348
drh56f1b992012-09-25 14:29:39 +00005349
5350 /* Variable initialization */
drh1c8148f2013-05-04 20:25:23 +00005351 memset(&sWLB, 0, sizeof(sWLB));
drh1c8148f2013-05-04 20:25:23 +00005352 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00005353
drh29dda4a2005-07-21 18:23:20 +00005354 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00005355 ** bits in a Bitmask
5356 */
drh67ae0cb2010-04-08 14:38:51 +00005357 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00005358 if( pTabList->nSrc>BMS ){
5359 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00005360 return 0;
5361 }
5362
drhc01a3c12009-12-16 22:10:49 +00005363 /* This function normally generates a nested loop for all tables in
5364 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
5365 ** only generate code for the first table in pTabList and assume that
5366 ** any cursors associated with subsequent tables are uninitialized.
5367 */
5368 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
5369
drh75897232000-05-29 14:26:00 +00005370 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00005371 ** return value. A single allocation is used to store the WhereInfo
5372 ** struct, the contents of WhereInfo.a[], the WhereClause structure
5373 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5374 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5375 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00005376 */
drh17435752007-08-16 04:30:38 +00005377 db = pParse->db;
drhc01a3c12009-12-16 22:10:49 +00005378 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00005379 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00005380 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00005381 sqlite3DbFree(db, pWInfo);
5382 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00005383 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00005384 }
drhc01a3c12009-12-16 22:10:49 +00005385 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00005386 pWInfo->pParse = pParse;
5387 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00005388 pWInfo->pOrderBy = pOrderBy;
5389 pWInfo->pDistinct = pDistinct;
danielk19774adee202004-05-08 08:23:19 +00005390 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00005391 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00005392 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00005393 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00005394 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00005395 sWLB.pWC = &pWInfo->sWC;
drh60c96cd2013-06-09 17:21:25 +00005396 sWLB.pNew = (WhereLoop*)&pWInfo->a[nTabList];
5397 whereLoopInit(sWLB.pNew);
drh08192d52002-04-30 19:20:28 +00005398
drha9b1b912011-07-08 13:07:02 +00005399 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
5400 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
drh7e5418e2012-09-27 15:05:54 +00005401 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
drha9b1b912011-07-08 13:07:02 +00005402
drh111a6a72008-12-21 03:51:16 +00005403 /* Split the WHERE clause into separate subexpressions where each
5404 ** subexpression is separated by an AND operator.
5405 */
5406 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00005407 whereClauseInit(&pWInfo->sWC, pWInfo);
drh111a6a72008-12-21 03:51:16 +00005408 sqlite3ExprCodeConstants(pParse, pWhere);
drh70d18342013-06-06 19:16:33 +00005409 whereSplit(&pWInfo->sWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
drh111a6a72008-12-21 03:51:16 +00005410
drh08192d52002-04-30 19:20:28 +00005411 /* Special case: a WHERE clause that is constant. Evaluate the
5412 ** expression and either jump over all of the code or fall thru.
5413 */
drhc01a3c12009-12-16 22:10:49 +00005414 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
drh35573352008-01-08 23:54:25 +00005415 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
drhdf199a22002-06-14 22:38:41 +00005416 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00005417 }
drh75897232000-05-29 14:26:00 +00005418
drh42165be2008-03-26 14:56:34 +00005419 /* Assign a bit from the bitmask to every term in the FROM clause.
5420 **
5421 ** When assigning bitmask values to FROM clause cursors, it must be
5422 ** the case that if X is the bitmask for the N-th FROM clause term then
5423 ** the bitmask for all FROM clause terms to the left of the N-th term
5424 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
5425 ** its Expr.iRightJoinTable value to find the bitmask of the right table
5426 ** of the join. Subtracting one from the right table bitmask gives a
5427 ** bitmask for all tables to the left of the join. Knowing the bitmask
5428 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00005429 **
drhc01a3c12009-12-16 22:10:49 +00005430 ** Note that bitmasks are created for all pTabList->nSrc tables in
5431 ** pTabList, not just the first nTabList tables. nTabList is normally
5432 ** equal to pTabList->nSrc but might be shortened to 1 if the
5433 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00005434 */
drh9cd1c992012-09-25 20:43:35 +00005435 for(ii=0; ii<pTabList->nSrc; ii++){
5436 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005437 }
5438#ifndef NDEBUG
5439 {
5440 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00005441 for(ii=0; ii<pTabList->nSrc; ii++){
5442 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005443 assert( (m-1)==toTheLeft );
5444 toTheLeft |= m;
5445 }
5446 }
5447#endif
5448
drh29dda4a2005-07-21 18:23:20 +00005449 /* Analyze all of the subexpressions. Note that exprAnalyze() might
5450 ** add new virtual terms onto the end of the WHERE clause. We do not
5451 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00005452 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00005453 */
drh70d18342013-06-06 19:16:33 +00005454 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drh17435752007-08-16 04:30:38 +00005455 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00005456 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00005457 }
drh75897232000-05-29 14:26:00 +00005458
dan38cc40c2011-06-30 20:17:15 +00005459 /* Check if the DISTINCT qualifier, if there is one, is redundant.
5460 ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
5461 ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
5462 */
drh70d18342013-06-06 19:16:33 +00005463 if( pDistinct && isDistinctRedundant(pParse,pTabList,&pWInfo->sWC,pDistinct) ){
dan38cc40c2011-06-30 20:17:15 +00005464 pDistinct = 0;
5465 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5466 }
5467
drhf1b5f5b2013-05-02 00:15:01 +00005468 /* Construct the WhereLoop objects */
5469 WHERETRACE(("*** Optimizer Start ***\n"));
drh60c96cd2013-06-09 17:21:25 +00005470 if( nTabList!=1 || whereSimpleFastCase(&sWLB)==0 ){
5471 rc = whereLoopAddAll(&sWLB);
5472 if( rc ) goto whereBeginError;
5473
5474 /* Display all of the WhereLoop objects if wheretrace is enabled */
drhd15cb172013-05-21 19:23:10 +00005475#ifdef WHERETRACE_ENABLED
drh60c96cd2013-06-09 17:21:25 +00005476 if( sqlite3WhereTrace ){
5477 WhereLoop *p;
5478 int i = 0;
5479 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5480 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
5481 for(p=pWInfo->pLoops; p; p=p->pNextLoop){
5482 p->cId = zLabel[(i++)%sizeof(zLabel)];
5483 whereLoopPrint(p, pTabList);
5484 }
5485 }
5486#endif
5487
5488 wherePathSolver(pWInfo, -1);
5489 if( db->mallocFailed ) goto whereBeginError;
5490 if( pWInfo->pOrderBy ){
5491 wherePathSolver(pWInfo, pWInfo->nRowOut);
5492 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00005493 }
5494 }
drh60c96cd2013-06-09 17:21:25 +00005495 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00005496 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00005497 }
drh75b93402013-05-31 20:43:57 +00005498 if( pParse->nErr || db->mallocFailed ){
5499 goto whereBeginError;
5500 }
drhd15cb172013-05-21 19:23:10 +00005501#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00005502 if( sqlite3WhereTrace ){
5503 int ii;
drh88da6442013-05-27 17:59:37 +00005504 sqlite3DebugPrintf("---- Solution");
drh319f6772013-05-14 15:31:07 +00005505 if( pWInfo->nOBSat ){
drh88da6442013-05-27 17:59:37 +00005506 sqlite3DebugPrintf(" ORDER BY omitted rev=0x%llx\n", pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00005507 }else{
5508 sqlite3DebugPrintf("\n");
5509 }
drha18f3d22013-05-08 03:05:41 +00005510 for(ii=0; ii<nTabList; ii++){
5511 whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
drhf1b5f5b2013-05-02 00:15:01 +00005512 }
5513 }
5514#endif
drh0edc94d2013-05-31 19:14:56 +00005515 WHERETRACE(("*** Optimizer Finished ***\n"));
drhf1b5f5b2013-05-02 00:15:01 +00005516
drh7ba39a92013-05-30 17:43:19 +00005517#if 0 /* FIXME: Add this back in? */
drh08c88eb2008-04-10 13:33:18 +00005518 /* If the caller is an UPDATE or DELETE statement that is requesting
5519 ** to use a one-pass algorithm, determine if this is appropriate.
5520 ** The one-pass algorithm only works if the WHERE clause constraints
5521 ** the statement to update a single row.
5522 */
drh165be382008-12-05 02:36:33 +00005523 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh7699d1c2013-06-04 12:42:29 +00005524 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00005525 pWInfo->okOnePass = 1;
drh111a6a72008-12-21 03:51:16 +00005526 pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
drh08c88eb2008-04-10 13:33:18 +00005527 }
drheb04de32013-05-10 15:16:30 +00005528#endif
5529
drh9012bcb2004-12-19 00:11:35 +00005530 /* Open all tables in the pTabList and any indices selected for
5531 ** searching those tables.
5532 */
5533 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
drh8b307fb2010-04-06 15:57:05 +00005534 notReady = ~(Bitmask)0;
drh4efc9292013-06-06 23:02:03 +00005535 pWInfo->nRowOut = (WhereCost)1;
drh9cd1c992012-09-25 20:43:35 +00005536 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00005537 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00005538 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00005539 struct SrcList_item *pTabItem;
drh7ba39a92013-05-30 17:43:19 +00005540 WhereLoop *pLoop;
drh9012bcb2004-12-19 00:11:35 +00005541
drh29dda4a2005-07-21 18:23:20 +00005542 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005543 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00005544 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00005545 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00005546 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00005547 /* Do nothing */
5548 }else
drh9eff6162006-06-12 21:59:13 +00005549#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00005550 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00005551 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00005552 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00005553 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00005554 }else if( IsVirtual(pTab) ){
5555 /* noop */
drh9eff6162006-06-12 21:59:13 +00005556 }else
5557#endif
drh7ba39a92013-05-30 17:43:19 +00005558 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00005559 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drh08c88eb2008-04-10 13:33:18 +00005560 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
5561 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drh67ae0cb2010-04-08 14:38:51 +00005562 testcase( pTab->nCol==BMS-1 );
5563 testcase( pTab->nCol==BMS );
danielk197723432972008-11-17 16:42:00 +00005564 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
danielk19779792eef2006-01-13 15:58:43 +00005565 Bitmask b = pTabItem->colUsed;
5566 int n = 0;
drh74161702006-02-24 02:53:49 +00005567 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00005568 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
5569 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00005570 assert( n<=pTab->nCol );
5571 }
danielk1977c00da102006-01-07 13:21:04 +00005572 }else{
5573 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00005574 }
drhc6339082010-04-07 16:54:58 +00005575#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh7ba39a92013-05-30 17:43:19 +00005576 if( (pLoop->wsFlags & WHERE_TEMP_INDEX)!=0 ){
drh70d18342013-06-06 19:16:33 +00005577 constructAutomaticIndex(pParse, &pWInfo->sWC, pTabItem, notReady, pLevel);
drhc6339082010-04-07 16:54:58 +00005578 }else
5579#endif
drh7e47cb82013-05-31 17:55:27 +00005580 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00005581 Index *pIx = pLoop->u.btree.pIndex;
danielk1977b3bf5562006-01-10 17:58:23 +00005582 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
drhae70cf12013-05-31 15:18:46 +00005583 /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
5584 int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
danielk1977da184232006-01-05 11:34:32 +00005585 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00005586 assert( iIndexCur>=0 );
5587 sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00005588 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00005589 VdbeComment((v, "%s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00005590 }
danielk1977da184232006-01-05 11:34:32 +00005591 sqlite3CodeVerifySchema(pParse, iDb);
drh70d18342013-06-06 19:16:33 +00005592 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00005593 }
5594 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00005595 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00005596
drh29dda4a2005-07-21 18:23:20 +00005597 /* Generate the code to do the search. Each iteration of the for
5598 ** loop below generates code for a single nested loop of the VM
5599 ** program.
drh75897232000-05-29 14:26:00 +00005600 */
drhfe05af82005-07-21 03:14:59 +00005601 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00005602 for(ii=0; ii<nTabList; ii++){
5603 pLevel = &pWInfo->a[ii];
5604 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
drh70d18342013-06-06 19:16:33 +00005605 notReady = codeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00005606 pWInfo->iContinue = pLevel->addrCont;
drh75897232000-05-29 14:26:00 +00005607 }
drh7ec764a2005-07-21 03:48:20 +00005608
drh6fa978d2013-05-30 19:29:19 +00005609 /* Done. */
drh75897232000-05-29 14:26:00 +00005610 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00005611
5612 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00005613whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00005614 if( pWInfo ){
5615 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5616 whereInfoFree(db, pWInfo);
5617 }
drhe23399f2005-07-22 00:31:39 +00005618 return 0;
drh75897232000-05-29 14:26:00 +00005619}
5620
5621/*
drhc27a1ce2002-06-14 20:58:45 +00005622** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00005623** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00005624*/
danielk19774adee202004-05-08 08:23:19 +00005625void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00005626 Parse *pParse = pWInfo->pParse;
5627 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00005628 int i;
drh6b563442001-11-07 16:48:26 +00005629 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00005630 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00005631 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00005632 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00005633
drh9012bcb2004-12-19 00:11:35 +00005634 /* Generate loop termination code.
5635 */
drhceea3322009-04-23 13:22:42 +00005636 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00005637 for(i=pWInfo->nLevel-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00005638 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00005639 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00005640 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00005641 if( pLevel->op!=OP_Noop ){
drh66a51672008-01-03 00:01:23 +00005642 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
drhd1d38482008-10-07 23:46:38 +00005643 sqlite3VdbeChangeP5(v, pLevel->p5);
drh19a775c2000-06-05 18:54:46 +00005644 }
drh7ba39a92013-05-30 17:43:19 +00005645 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00005646 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00005647 int j;
drhb3190c12008-12-08 21:37:14 +00005648 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00005649 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00005650 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00005651 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drhb3190c12008-12-08 21:37:14 +00005652 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00005653 }
drh111a6a72008-12-21 03:51:16 +00005654 sqlite3DbFree(db, pLevel->u.in.aInLoop);
drhd99f7062002-06-08 23:25:08 +00005655 }
drhb3190c12008-12-08 21:37:14 +00005656 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhad2d8302002-05-24 20:31:36 +00005657 if( pLevel->iLeftJoin ){
5658 int addr;
drh3c84ddf2008-01-09 02:15:38 +00005659 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
drh7ba39a92013-05-30 17:43:19 +00005660 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
5661 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
5662 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00005663 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
5664 }
drh76f4cfb2013-05-31 18:20:52 +00005665 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00005666 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00005667 }
drh336a5302009-04-24 15:46:21 +00005668 if( pLevel->op==OP_Return ){
5669 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
5670 }else{
5671 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
5672 }
drhd654be82005-09-20 17:42:23 +00005673 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00005674 }
drh19a775c2000-06-05 18:54:46 +00005675 }
drh9012bcb2004-12-19 00:11:35 +00005676
5677 /* The "break" point is here, just past the end of the outer loop.
5678 ** Set it.
5679 */
danielk19774adee202004-05-08 08:23:19 +00005680 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00005681
drh29dda4a2005-07-21 18:23:20 +00005682 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00005683 */
drhc01a3c12009-12-16 22:10:49 +00005684 assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
5685 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
danbfca6a42012-08-24 10:52:35 +00005686 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00005687 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005688 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00005689 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00005690 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00005691 if( (pTab->tabFlags & TF_Ephemeral)==0
5692 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00005693 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00005694 ){
drh7ba39a92013-05-30 17:43:19 +00005695 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00005696 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00005697 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
5698 }
drh7ba39a92013-05-30 17:43:19 +00005699 if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_TEMP_INDEX))==0 ){
drh6df2acd2008-12-28 16:55:25 +00005700 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
5701 }
drh9012bcb2004-12-19 00:11:35 +00005702 }
5703
danielk197721de2e72007-11-29 17:43:27 +00005704 /* If this scan uses an index, make code substitutions to read data
5705 ** from the index in preference to the table. Sometimes, this means
5706 ** the table need never be read from. This is a performance boost,
5707 ** as the vdbe level waits until the table is read before actually
5708 ** seeking the table cursor to the record corresponding to the current
5709 ** position in the index.
drh9012bcb2004-12-19 00:11:35 +00005710 **
5711 ** Calls to the code generator in between sqlite3WhereBegin and
5712 ** sqlite3WhereEnd will have created code that references the table
5713 ** directly. This loop scans all that code looking for opcodes
5714 ** that reference the table and converts them into opcodes that
5715 ** reference the index.
5716 */
drh7ba39a92013-05-30 17:43:19 +00005717 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
5718 pIdx = pLoop->u.btree.pIndex;
5719 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00005720 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00005721 }
drh7ba39a92013-05-30 17:43:19 +00005722 if( pIdx && !db->mallocFailed ){
danielk1977f0113002006-01-24 12:09:17 +00005723 int k, j, last;
drh9012bcb2004-12-19 00:11:35 +00005724 VdbeOp *pOp;
drh9012bcb2004-12-19 00:11:35 +00005725
drh9012bcb2004-12-19 00:11:35 +00005726 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
5727 last = sqlite3VdbeCurrentAddr(v);
danielk1977f0113002006-01-24 12:09:17 +00005728 for(k=pWInfo->iTop; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00005729 if( pOp->p1!=pLevel->iTabCur ) continue;
5730 if( pOp->opcode==OP_Column ){
drh9012bcb2004-12-19 00:11:35 +00005731 for(j=0; j<pIdx->nColumn; j++){
5732 if( pOp->p2==pIdx->aiColumn[j] ){
5733 pOp->p2 = j;
danielk197721de2e72007-11-29 17:43:27 +00005734 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00005735 break;
5736 }
5737 }
drh7ba39a92013-05-30 17:43:19 +00005738 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
drhf0863fe2005-06-12 21:35:51 +00005739 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00005740 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00005741 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00005742 }
5743 }
drh6b563442001-11-07 16:48:26 +00005744 }
drh19a775c2000-06-05 18:54:46 +00005745 }
drh9012bcb2004-12-19 00:11:35 +00005746
5747 /* Final cleanup
5748 */
drhf12cde52010-04-08 17:28:00 +00005749 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5750 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00005751 return;
5752}