blob: b6b80c5390960d3b8e0a859475ba44e97e3c05dc [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
drh51669862004-12-18 18:40:26 +000013** the WHERE clause of SQL statements. This module is reponsible for
14** 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**
drh6c30be82005-07-29 15:10:17 +000019** $Id: where.c,v 1.157 2005/07/29 15:10:18 drh Exp $
drh75897232000-05-29 14:26:00 +000020*/
21#include "sqliteInt.h"
22
23/*
drh0aa74ed2005-07-16 13:33:20 +000024** The number of bits in a Bitmask. "BMS" means "BitMask Size".
25*/
drh29dda4a2005-07-21 18:23:20 +000026#define BMS (sizeof(Bitmask)*8)
drh0aa74ed2005-07-16 13:33:20 +000027
28/*
29** Determine the number of elements in an array.
30*/
31#define ARRAYSIZE(X) (sizeof(X)/sizeof(X[0]))
32
drh51147ba2005-07-23 22:59:55 +000033/*
34** Trace output macros
35*/
36#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
37int sqlite3_where_trace = 0;
38# define TRACE(X) if(sqlite3_where_trace) sqlite3DebugPrintf X
39#else
40# define TRACE(X)
41#endif
42
drh0fcef5e2005-07-19 17:38:22 +000043/* Forward reference
44*/
45typedef struct WhereClause WhereClause;
drh0aa74ed2005-07-16 13:33:20 +000046
47/*
drh75897232000-05-29 14:26:00 +000048** The query generator uses an array of instances of this structure to
49** help it analyze the subexpressions of the WHERE clause. Each WHERE
50** clause subexpression is separated from the others by an AND operator.
drh51669862004-12-18 18:40:26 +000051**
drh0fcef5e2005-07-19 17:38:22 +000052** All WhereTerms are collected into a single WhereClause structure.
53** The following identity holds:
drh51669862004-12-18 18:40:26 +000054**
drh0fcef5e2005-07-19 17:38:22 +000055** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
drh51669862004-12-18 18:40:26 +000056**
drh0fcef5e2005-07-19 17:38:22 +000057** When a term is of the form:
58**
59** X <op> <expr>
60**
61** where X is a column name and <op> is one of certain operators,
62** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
drh51147ba2005-07-23 22:59:55 +000063** cursor number and column number for X. WhereTerm.operator records
64** the <op> using a bitmask encoding defined by WO_xxx below. The
65** use of a bitmask encoding for the operator allows us to search
66** quickly for terms that match any of several different operators.
drh0fcef5e2005-07-19 17:38:22 +000067**
68** prereqRight and prereqAll record sets of cursor numbers,
drh51669862004-12-18 18:40:26 +000069** but they do so indirectly. A single ExprMaskSet structure translates
70** cursor number into bits and the translated bit is stored in the prereq
71** fields. The translation is used in order to maximize the number of
72** bits that will fit in a Bitmask. The VDBE cursor numbers might be
73** spread out over the non-negative integers. For example, the cursor
74** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The ExprMaskSet
75** translates these sparse cursor numbers into consecutive integers
76** beginning with 0 in order to make the best possible use of the available
77** bits in the Bitmask. So, in the example above, the cursor numbers
78** would be mapped into integers 0 through 7.
drh75897232000-05-29 14:26:00 +000079*/
drh0aa74ed2005-07-16 13:33:20 +000080typedef struct WhereTerm WhereTerm;
81struct WhereTerm {
drh0fcef5e2005-07-19 17:38:22 +000082 Expr *pExpr; /* Pointer to the subexpression */
83 u16 idx; /* Index of this term in pWC->a[] */
84 i16 iPartner; /* Disable pWC->a[iPartner] when this term disabled */
drh0fcef5e2005-07-19 17:38:22 +000085 i16 leftCursor; /* Cursor number of X in "X <op> <expr>" */
86 i16 leftColumn; /* Column number of X in "X <op> <expr>" */
drh51147ba2005-07-23 22:59:55 +000087 u16 operator; /* A WO_xx value describing <op> */
drh6c30be82005-07-29 15:10:17 +000088 u8 flags; /* Bit flags. See below */
drhed378002005-07-28 23:12:08 +000089 u8 nPartner; /* Number of partners that must disable us */
drh0fcef5e2005-07-19 17:38:22 +000090 WhereClause *pWC; /* The clause this term is part of */
91 Bitmask prereqRight; /* Bitmask of tables used by pRight */
drh51669862004-12-18 18:40:26 +000092 Bitmask prereqAll; /* Bitmask of tables referenced by p */
drh75897232000-05-29 14:26:00 +000093};
94
95/*
drh0aa74ed2005-07-16 13:33:20 +000096** Allowed values of WhereTerm.flags
97*/
drh6c30be82005-07-29 15:10:17 +000098#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(pExpr) */
99#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
100#define TERM_CODED 0x04 /* This term is already coded */
101#define TERM_PARTNERED 0x08 /* Has a virtual partner */
102#define TERM_OR_OK 0x10 /* Used during OR-clause processing */
drh0aa74ed2005-07-16 13:33:20 +0000103
104/*
105** An instance of the following structure holds all information about a
106** WHERE clause. Mostly this is a container for one or more WhereTerms.
107*/
drh0aa74ed2005-07-16 13:33:20 +0000108struct WhereClause {
drhfe05af82005-07-21 03:14:59 +0000109 Parse *pParse; /* The parser context */
drh0aa74ed2005-07-16 13:33:20 +0000110 int nTerm; /* Number of terms */
111 int nSlot; /* Number of entries in a[] */
drh51147ba2005-07-23 22:59:55 +0000112 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
113 WhereTerm aStatic[10]; /* Initial static space for a[] */
drhe23399f2005-07-22 00:31:39 +0000114};
115
116/*
drh6a3ea0e2003-05-02 14:32:12 +0000117** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000118** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000119**
120** The VDBE cursor numbers are small integers contained in
121** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
122** clause, the cursor numbers might not begin with 0 and they might
123** contain gaps in the numbering sequence. But we want to make maximum
124** use of the bits in our bitmasks. This structure provides a mapping
125** from the sparse cursor numbers into consecutive integers beginning
126** with 0.
127**
128** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
129** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
130**
131** For example, if the WHERE clause expression used these VDBE
132** cursors: 4, 5, 8, 29, 57, 73. Then the ExprMaskSet structure
133** would map those cursor numbers into bits 0 through 5.
134**
135** Note that the mapping is not necessarily ordered. In the example
136** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
137** 57->5, 73->4. Or one of 719 other combinations might be used. It
138** does not really matter. What is important is that sparse cursor
139** numbers all get mapped into bit numbers that begin with 0 and contain
140** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000141*/
142typedef struct ExprMaskSet ExprMaskSet;
143struct ExprMaskSet {
drh1398ad32005-01-19 23:24:50 +0000144 int n; /* Number of assigned cursor values */
145 int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000146};
147
drh0aa74ed2005-07-16 13:33:20 +0000148
drh6a3ea0e2003-05-02 14:32:12 +0000149/*
drh51147ba2005-07-23 22:59:55 +0000150** Bitmasks for the operators that indices are able to exploit. An
151** OR-ed combination of these values can be used when searching for
152** terms in the where clause.
153*/
154#define WO_IN 1
drha6110402005-07-28 20:51:19 +0000155#define WO_EQ 2
drh51147ba2005-07-23 22:59:55 +0000156#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
157#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
158#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
159#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
160
161/*
162** Value for flags returned by bestIndex()
163*/
164#define WHERE_ROWID_EQ 0x0001 /* rowid=EXPR or rowid IN (...) */
165#define WHERE_ROWID_RANGE 0x0002 /* rowid<EXPR and/or rowid>EXPR */
166#define WHERE_COLUMN_EQ 0x0010 /* x=EXPR or x IN (...) */
167#define WHERE_COLUMN_RANGE 0x0020 /* x<EXPR and/or x>EXPR */
168#define WHERE_COLUMN_IN 0x0040 /* x IN (...) */
169#define WHERE_TOP_LIMIT 0x0100 /* x<EXPR or x<=EXPR constraint */
170#define WHERE_BTM_LIMIT 0x0200 /* x>EXPR or x>=EXPR constraint */
171#define WHERE_IDX_ONLY 0x0800 /* Use index only - omit table */
172#define WHERE_ORDERBY 0x1000 /* Output will appear in correct order */
173#define WHERE_REVERSE 0x2000 /* Scan in reverse order */
174
175/*
drh0aa74ed2005-07-16 13:33:20 +0000176** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000177*/
drhfe05af82005-07-21 03:14:59 +0000178static void whereClauseInit(WhereClause *pWC, Parse *pParse){
179 pWC->pParse = pParse;
drh0aa74ed2005-07-16 13:33:20 +0000180 pWC->nTerm = 0;
181 pWC->nSlot = ARRAYSIZE(pWC->aStatic);
182 pWC->a = pWC->aStatic;
183}
184
185/*
186** Deallocate a WhereClause structure. The WhereClause structure
187** itself is not freed. This routine is the inverse of whereClauseInit().
188*/
189static void whereClauseClear(WhereClause *pWC){
190 int i;
191 WhereTerm *a;
192 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
193 if( a->flags & TERM_DYNAMIC ){
drh0fcef5e2005-07-19 17:38:22 +0000194 sqlite3ExprDelete(a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000195 }
196 }
197 if( pWC->a!=pWC->aStatic ){
198 sqliteFree(pWC->a);
199 }
200}
201
202/*
203** Add a new entries to the WhereClause structure. Increase the allocated
204** space as necessary.
205*/
drh0fcef5e2005-07-19 17:38:22 +0000206static WhereTerm *whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
drh0aa74ed2005-07-16 13:33:20 +0000207 WhereTerm *pTerm;
208 if( pWC->nTerm>=pWC->nSlot ){
209 WhereTerm *pOld = pWC->a;
210 pWC->a = sqliteMalloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
drh0fcef5e2005-07-19 17:38:22 +0000211 if( pWC->a==0 ) return 0;
drh0aa74ed2005-07-16 13:33:20 +0000212 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
213 if( pOld!=pWC->aStatic ){
214 sqliteFree(pOld);
215 }
216 pWC->nSlot *= 2;
217 }
drh0fcef5e2005-07-19 17:38:22 +0000218 pTerm = &pWC->a[pWC->nTerm];
219 pTerm->idx = pWC->nTerm;
220 pWC->nTerm++;
221 pTerm->pExpr = p;
drh0aa74ed2005-07-16 13:33:20 +0000222 pTerm->flags = flags;
drh0fcef5e2005-07-19 17:38:22 +0000223 pTerm->pWC = pWC;
224 pTerm->iPartner = -1;
225 return pTerm;
drh0aa74ed2005-07-16 13:33:20 +0000226}
drh75897232000-05-29 14:26:00 +0000227
228/*
drh51669862004-12-18 18:40:26 +0000229** This routine identifies subexpressions in the WHERE clause where
drh6c30be82005-07-29 15:10:17 +0000230** each subexpression is separate by the AND operator or some other
231** operator specified in the op parameter. The WhereClause structure
232** is filled with pointers to subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000233**
drh51669862004-12-18 18:40:26 +0000234** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
235** \________/ \_______________/ \________________/
236** slot[0] slot[1] slot[2]
237**
238** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000239** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000240**
drh51147ba2005-07-23 22:59:55 +0000241** In the previous sentence and in the diagram, "slot[]" refers to
242** the WhereClause.a[] array. This array grows as needed to contain
243** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000244*/
drh6c30be82005-07-29 15:10:17 +0000245static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
drh0aa74ed2005-07-16 13:33:20 +0000246 if( pExpr==0 ) return;
drh6c30be82005-07-29 15:10:17 +0000247 if( pExpr->op!=op ){
drh0aa74ed2005-07-16 13:33:20 +0000248 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000249 }else{
drh6c30be82005-07-29 15:10:17 +0000250 whereSplit(pWC, pExpr->pLeft, op);
251 whereSplit(pWC, pExpr->pRight, op);
drh75897232000-05-29 14:26:00 +0000252 }
drh75897232000-05-29 14:26:00 +0000253}
254
255/*
drh6a3ea0e2003-05-02 14:32:12 +0000256** Initialize an expression mask set
257*/
258#define initMaskSet(P) memset(P, 0, sizeof(*P))
259
260/*
drh1398ad32005-01-19 23:24:50 +0000261** Return the bitmask for the given cursor number. Return 0 if
262** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000263*/
drh51669862004-12-18 18:40:26 +0000264static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000265 int i;
266 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000267 if( pMaskSet->ix[i]==iCursor ){
268 return ((Bitmask)1)<<i;
269 }
drh6a3ea0e2003-05-02 14:32:12 +0000270 }
drh6a3ea0e2003-05-02 14:32:12 +0000271 return 0;
272}
273
274/*
drh1398ad32005-01-19 23:24:50 +0000275** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000276**
277** There is one cursor per table in the FROM clause. The number of
278** tables in the FROM clause is limited by a test early in the
279** sqlite3WhereBegin() routien. So we know that the pMaskSet->ix[]
280** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000281*/
282static void createMask(ExprMaskSet *pMaskSet, int iCursor){
drh0fcef5e2005-07-19 17:38:22 +0000283 assert( pMaskSet->n < ARRAYSIZE(pMaskSet->ix) );
284 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000285}
286
287/*
drh75897232000-05-29 14:26:00 +0000288** This routine walks (recursively) an expression tree and generates
289** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000290** tree.
drh75897232000-05-29 14:26:00 +0000291**
292** In order for this routine to work, the calling function must have
drh626a8792005-01-17 22:08:19 +0000293** previously invoked sqlite3ExprResolveNames() on the expression. See
drh75897232000-05-29 14:26:00 +0000294** the header comment on that routine for additional information.
drh626a8792005-01-17 22:08:19 +0000295** The sqlite3ExprResolveNames() routines looks for column names and
drh6a3ea0e2003-05-02 14:32:12 +0000296** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
drh51147ba2005-07-23 22:59:55 +0000297** the VDBE cursor number of the table. This routine just has to
298** translate the cursor numbers into bitmask values and OR all
299** the bitmasks together.
drh75897232000-05-29 14:26:00 +0000300*/
danielk1977b3bce662005-01-29 08:32:43 +0000301static Bitmask exprListTableUsage(ExprMaskSet *, ExprList *);
drh51669862004-12-18 18:40:26 +0000302static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
303 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000304 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000305 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000306 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000307 return mask;
drh75897232000-05-29 14:26:00 +0000308 }
danielk1977b3bce662005-01-29 08:32:43 +0000309 mask = exprTableUsage(pMaskSet, p->pRight);
310 mask |= exprTableUsage(pMaskSet, p->pLeft);
311 mask |= exprListTableUsage(pMaskSet, p->pList);
312 if( p->pSelect ){
313 Select *pS = p->pSelect;
314 mask |= exprListTableUsage(pMaskSet, pS->pEList);
315 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
316 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
317 mask |= exprTableUsage(pMaskSet, pS->pWhere);
318 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drh75897232000-05-29 14:26:00 +0000319 }
danielk1977b3bce662005-01-29 08:32:43 +0000320 return mask;
321}
322static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
323 int i;
324 Bitmask mask = 0;
325 if( pList ){
326 for(i=0; i<pList->nExpr; i++){
327 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000328 }
329 }
drh75897232000-05-29 14:26:00 +0000330 return mask;
331}
332
333/*
drh487ab3c2001-11-08 00:45:21 +0000334** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000335** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000336** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000337*/
338static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000339 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
340 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
341 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
342 assert( TK_GE==TK_EQ+4 );
drh9a432672004-10-04 13:38:09 +0000343 return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
drh487ab3c2001-11-08 00:45:21 +0000344}
345
346/*
drh51669862004-12-18 18:40:26 +0000347** Swap two objects of type T.
drh193bd772004-07-20 18:23:14 +0000348*/
349#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
350
351/*
drh0fcef5e2005-07-19 17:38:22 +0000352** Commute a comparision operator. Expressions of the form "X op Y"
353** are converted into "Y op X".
drh193bd772004-07-20 18:23:14 +0000354*/
drh0fcef5e2005-07-19 17:38:22 +0000355static void exprCommute(Expr *pExpr){
drhfe05af82005-07-21 03:14:59 +0000356 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drh0fcef5e2005-07-19 17:38:22 +0000357 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
358 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
359 if( pExpr->op>=TK_GT ){
360 assert( TK_LT==TK_GT+2 );
361 assert( TK_GE==TK_LE+2 );
362 assert( TK_GT>TK_EQ );
363 assert( TK_GT<TK_LE );
364 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
365 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000366 }
drh193bd772004-07-20 18:23:14 +0000367}
368
369/*
drhfe05af82005-07-21 03:14:59 +0000370** Translate from TK_xx operator to WO_xx bitmask.
371*/
372static int operatorMask(int op){
drh51147ba2005-07-23 22:59:55 +0000373 int c;
drhfe05af82005-07-21 03:14:59 +0000374 assert( allowedOp(op) );
375 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000376 c = WO_IN;
drhfe05af82005-07-21 03:14:59 +0000377 }else{
drh51147ba2005-07-23 22:59:55 +0000378 c = WO_EQ<<(op-TK_EQ);
drhfe05af82005-07-21 03:14:59 +0000379 }
drh51147ba2005-07-23 22:59:55 +0000380 assert( op!=TK_IN || c==WO_IN );
381 assert( op!=TK_EQ || c==WO_EQ );
382 assert( op!=TK_LT || c==WO_LT );
383 assert( op!=TK_LE || c==WO_LE );
384 assert( op!=TK_GT || c==WO_GT );
385 assert( op!=TK_GE || c==WO_GE );
386 return c;
drhfe05af82005-07-21 03:14:59 +0000387}
388
389/*
390** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
391** where X is a reference to the iColumn of table iCur and <op> is one of
392** the WO_xx operator codes specified by the op parameter.
393** Return a pointer to the term. Return 0 if not found.
394*/
395static WhereTerm *findTerm(
396 WhereClause *pWC, /* The WHERE clause to be searched */
397 int iCur, /* Cursor number of LHS */
398 int iColumn, /* Column number of LHS */
399 Bitmask notReady, /* RHS must not overlap with this mask */
drh51147ba2005-07-23 22:59:55 +0000400 u16 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000401 Index *pIdx /* Must be compatible with this index, if not NULL */
402){
403 WhereTerm *pTerm;
404 int k;
405 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
406 if( pTerm->leftCursor==iCur
407 && (pTerm->prereqRight & notReady)==0
408 && pTerm->leftColumn==iColumn
409 && (pTerm->operator & op)!=0
410 ){
411 if( iCur>=0 && pIdx ){
412 Expr *pX = pTerm->pExpr;
413 CollSeq *pColl;
414 char idxaff;
415 int k;
416 Parse *pParse = pWC->pParse;
417
418 idxaff = pIdx->pTable->aCol[iColumn].affinity;
419 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
420 pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
421 if( !pColl ){
422 if( pX->pRight ){
423 pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
424 }
425 if( !pColl ){
426 pColl = pParse->db->pDfltColl;
427 }
428 }
429 for(k=0; k<pIdx->nColumn && pIdx->aiColumn[k]!=iColumn; k++){}
430 assert( k<pIdx->nColumn );
431 if( pColl!=pIdx->keyInfo.aColl[k] ) continue;
432 }
433 return pTerm;
434 }
435 }
436 return 0;
437}
438
drh6c30be82005-07-29 15:10:17 +0000439/* Forward reference */
440static void exprAnalyze(SrcList*, ExprMaskSet*, WhereTerm*);
441
442/*
443** Call exprAnalyze on all terms in a WHERE clause.
444**
445**
446*/
447static void exprAnalyzeAll(
448 SrcList *pTabList, /* the FROM clause */
449 ExprMaskSet *pMaskSet, /* table masks */
450 WhereClause *pWC /* the WHERE clause to be analyzed */
451){
452 WhereTerm *pTerm;
453 int i;
454 for(i=pWC->nTerm-1, pTerm=pWC->a; i>=0; i--, pTerm++){
455 exprAnalyze(pTabList, pMaskSet, pTerm);
456 }
457}
458
drhfe05af82005-07-21 03:14:59 +0000459/*
drh0aa74ed2005-07-16 13:33:20 +0000460** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +0000461** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +0000462** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +0000463** structure.
drh51147ba2005-07-23 22:59:55 +0000464**
465** If the expression is of the form "<expr> <op> X" it gets commuted
466** to the standard form of "X <op> <expr>". If the expression is of
467** the form "X <op> Y" where both X and Y are columns, then the original
468** expression is unchanged and a new virtual expression of the form
469** "Y <op> X" is added to the WHERE clause.
drh75897232000-05-29 14:26:00 +0000470*/
drh0fcef5e2005-07-19 17:38:22 +0000471static void exprAnalyze(
472 SrcList *pSrc, /* the FROM clause */
473 ExprMaskSet *pMaskSet, /* table masks */
474 WhereTerm *pTerm /* the WHERE clause term to be analyzed */
475){
476 Expr *pExpr = pTerm->pExpr;
477 Bitmask prereqLeft;
478 Bitmask prereqAll;
479 int idxRight;
480
481 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
482 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
483 pTerm->prereqAll = prereqAll = exprTableUsage(pMaskSet, pExpr);
484 pTerm->leftCursor = -1;
485 pTerm->iPartner = -1;
drhfe05af82005-07-21 03:14:59 +0000486 pTerm->operator = 0;
drh0fcef5e2005-07-19 17:38:22 +0000487 idxRight = -1;
488 if( allowedOp(pExpr->op) && (pTerm->prereqRight & prereqLeft)==0 ){
489 Expr *pLeft = pExpr->pLeft;
490 Expr *pRight = pExpr->pRight;
491 if( pLeft->op==TK_COLUMN ){
492 pTerm->leftCursor = pLeft->iTable;
493 pTerm->leftColumn = pLeft->iColumn;
drhfe05af82005-07-21 03:14:59 +0000494 pTerm->operator = operatorMask(pExpr->op);
drh75897232000-05-29 14:26:00 +0000495 }
drh0fcef5e2005-07-19 17:38:22 +0000496 if( pRight && pRight->op==TK_COLUMN ){
497 WhereTerm *pNew;
498 Expr *pDup;
499 if( pTerm->leftCursor>=0 ){
500 pDup = sqlite3ExprDup(pExpr);
501 pNew = whereClauseInsert(pTerm->pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
502 if( pNew==0 ) return;
503 pNew->iPartner = pTerm->idx;
drhed378002005-07-28 23:12:08 +0000504 pTerm->nPartner = 1;
drh6c30be82005-07-29 15:10:17 +0000505 pTerm->flags |= TERM_PARTNERED;
drh0fcef5e2005-07-19 17:38:22 +0000506 }else{
507 pDup = pExpr;
508 pNew = pTerm;
509 }
510 exprCommute(pDup);
511 pLeft = pDup->pLeft;
512 pNew->leftCursor = pLeft->iTable;
513 pNew->leftColumn = pLeft->iColumn;
514 pNew->prereqRight = prereqLeft;
515 pNew->prereqAll = prereqAll;
drhfe05af82005-07-21 03:14:59 +0000516 pNew->operator = operatorMask(pDup->op);
drh75897232000-05-29 14:26:00 +0000517 }
518 }
drhed378002005-07-28 23:12:08 +0000519
520 /* If a term is the BETWEEN operator, create two new virtual terms
521 ** that define the range that the BETWEEN implements.
522 */
523 else if( pExpr->op==TK_BETWEEN ){
524 ExprList *pList = pExpr->pList;
525 int i;
526 static const u8 ops[] = {TK_GE, TK_LE};
527 assert( pList!=0 );
528 assert( pList->nExpr==2 );
529 for(i=0; i<2; i++){
530 Expr *pNewExpr;
531 WhereTerm *pNewTerm;
532 pNewExpr = sqlite3Expr(ops[i], sqlite3ExprDup(pExpr->pLeft),
533 sqlite3ExprDup(pList->a[i].pExpr), 0);
534 pNewTerm = whereClauseInsert(pTerm->pWC, pNewExpr,
535 TERM_VIRTUAL|TERM_DYNAMIC);
536 exprAnalyze(pSrc, pMaskSet, pNewTerm);
537 pNewTerm->iPartner = pTerm->idx;
538 }
539 pTerm->nPartner = 2;
540 }
541
drh6c30be82005-07-29 15:10:17 +0000542 /* Attempt to convert OR-connected terms into an IN operator so that
543 ** they can make use of indices.
544 */
545 else if( pExpr->op==TK_OR ){
546 int ok;
547 int i, j;
548 int iColumn, iCursor;
549 WhereClause sOr;
550 WhereTerm *pOrTerm;
551
552 assert( (pTerm->flags & TERM_DYNAMIC)==0 );
553 whereClauseInit(&sOr, pTerm->pWC->pParse);
554 whereSplit(&sOr, pExpr, TK_OR);
555 exprAnalyzeAll(pSrc, pMaskSet, &sOr);
556 assert( sOr.nTerm>0 );
557 j = 0;
558 do{
559 iColumn = sOr.a[j].leftColumn;
560 iCursor = sOr.a[j].leftCursor;
561 ok = iCursor>=0;
562 for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
563 if( pOrTerm->operator!=WO_EQ ){
564 goto or_not_possible;
565 }
566 if( pOrTerm->leftCursor==iCursor && pOrTerm->leftColumn==iColumn ){
567 pOrTerm->flags |= TERM_OR_OK;
568 }else if( (pOrTerm->flags & TERM_PARTNERED)!=0 ||
569 ((pOrTerm->flags & TERM_VIRTUAL)!=0 &&
570 (sOr.a[pOrTerm->iPartner].flags & TERM_OR_OK)!=0) ){
571 pOrTerm->flags &= ~TERM_OR_OK;
572 }else{
573 ok = 0;
574 }
575 }
576 }while( !ok && (sOr.a[j++].flags & TERM_PARTNERED)!=0 && j<sOr.nTerm );
577 if( ok ){
578 ExprList *pList = 0;
579 Expr *pNew, *pDup;
580 for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
581 if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
582 pDup = sqlite3ExprDup(pOrTerm->pExpr->pRight);
583 pList = sqlite3ExprListAppend(pList, pDup, 0);
584 }
585 pDup = sqlite3Expr(TK_COLUMN, 0, 0, 0);
586 if( pDup ){
587 pDup->iTable = iCursor;
588 pDup->iColumn = iColumn;
589 }
590 pNew = sqlite3Expr(TK_IN, pDup, 0, 0);
591 if( pNew ) pNew->pList = pList;
592 pTerm->pExpr = pNew;
593 pTerm->flags |= TERM_DYNAMIC;
594 exprAnalyze(pSrc, pMaskSet, pTerm);
595 }
596or_not_possible:
597 whereClauseClear(&sOr);
598 }
drh75897232000-05-29 14:26:00 +0000599}
600
drh0fcef5e2005-07-19 17:38:22 +0000601
drh75897232000-05-29 14:26:00 +0000602/*
drh51669862004-12-18 18:40:26 +0000603** This routine decides if pIdx can be used to satisfy the ORDER BY
604** clause. If it can, it returns 1. If pIdx cannot satisfy the
605** ORDER BY clause, this routine returns 0.
606**
607** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
608** left-most table in the FROM clause of that same SELECT statement and
609** the table has a cursor number of "base". pIdx is an index on pTab.
610**
611** nEqCol is the number of columns of pIdx that are used as equality
612** constraints. Any of these columns may be missing from the ORDER BY
613** clause and the match can still be a success.
614**
615** If the index is UNIQUE, then the ORDER BY clause is allowed to have
616** additional terms past the end of the index and the match will still
617** be a success.
618**
619** All terms of the ORDER BY that match against the index must be either
620** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
621** index do not need to satisfy this constraint.) The *pbRev value is
622** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
623** the ORDER BY clause is all ASC.
624*/
625static int isSortingIndex(
626 Parse *pParse, /* Parsing context */
627 Index *pIdx, /* The index we are testing */
628 Table *pTab, /* The table to be sorted */
629 int base, /* Cursor number for pTab */
630 ExprList *pOrderBy, /* The ORDER BY clause */
631 int nEqCol, /* Number of index columns with == constraints */
632 int *pbRev /* Set to 1 if ORDER BY is DESC */
633){
634 int i, j; /* Loop counters */
635 int sortOrder; /* Which direction we are sorting */
636 int nTerm; /* Number of ORDER BY terms */
637 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
638 sqlite3 *db = pParse->db;
639
640 assert( pOrderBy!=0 );
641 nTerm = pOrderBy->nExpr;
642 assert( nTerm>0 );
643
drh28c4cf42005-07-27 20:41:43 +0000644 /* A UNIQUE index that is fully specified is always a sorting
645 ** index.
646 */
647 if( pIdx->onError!=OE_None && nEqCol==pIdx->nColumn ){
648 *pbRev = 0;
649 return 1;
650 }
651
drh51669862004-12-18 18:40:26 +0000652 /* Match terms of the ORDER BY clause against columns of
653 ** the index.
654 */
655 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
656 Expr *pExpr; /* The expression of the ORDER BY pTerm */
657 CollSeq *pColl; /* The collating sequence of pExpr */
658
659 pExpr = pTerm->pExpr;
660 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
661 /* Can not use an index sort on anything that is not a column in the
662 ** left-most table of the FROM clause */
663 return 0;
664 }
665 pColl = sqlite3ExprCollSeq(pParse, pExpr);
666 if( !pColl ) pColl = db->pDfltColl;
drh9012bcb2004-12-19 00:11:35 +0000667 if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
668 /* Term j of the ORDER BY clause does not match column i of the index */
669 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +0000670 /* If an index column that is constrained by == fails to match an
671 ** ORDER BY term, that is OK. Just ignore that column of the index
672 */
673 continue;
674 }else{
675 /* If an index column fails to match and is not constrained by ==
676 ** then the index cannot satisfy the ORDER BY constraint.
677 */
678 return 0;
679 }
680 }
681 if( i>nEqCol ){
682 if( pTerm->sortOrder!=sortOrder ){
683 /* Indices can only be used if all ORDER BY terms past the
684 ** equality constraints are all either DESC or ASC. */
685 return 0;
686 }
687 }else{
688 sortOrder = pTerm->sortOrder;
689 }
690 j++;
691 pTerm++;
692 }
693
694 /* The index can be used for sorting if all terms of the ORDER BY clause
695 ** or covered or if we ran out of index columns and the it is a UNIQUE
696 ** index.
697 */
698 if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
699 *pbRev = sortOrder==SQLITE_SO_DESC;
700 return 1;
701 }
702 return 0;
703}
704
705/*
drhb6c29892004-11-22 19:12:19 +0000706** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
707** by sorting in order of ROWID. Return true if so and set *pbRev to be
708** true for reverse ROWID and false for forward ROWID order.
709*/
710static int sortableByRowid(
711 int base, /* Cursor number for table to be sorted */
712 ExprList *pOrderBy, /* The ORDER BY clause */
713 int *pbRev /* Set to 1 if ORDER BY is DESC */
714){
715 Expr *p;
716
717 assert( pOrderBy!=0 );
718 assert( pOrderBy->nExpr>0 );
719 p = pOrderBy->a[0].pExpr;
720 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
721 *pbRev = pOrderBy->a[0].sortOrder;
722 return 1;
723 }
724 return 0;
725}
726
drhfe05af82005-07-21 03:14:59 +0000727/*
drh28c4cf42005-07-27 20:41:43 +0000728** Prepare a crude estimate of the logorithm of the input value.
729** The results need not be exact. This is only used for estimating
730** the total cost of performing operatings with O(logN) or O(NlogN)
731** complexity. Because N is just a guess, it is no great tragedy if
732** logN is a little off.
733**
734** We can assume N>=1.0;
735*/
736static double estLog(double N){
737 double logN = 1.0;
738 double x = 10.0;
739 while( N>x ){
740 logN = logN+1.0;
741 x *= 10;
742 }
743 return logN;
744}
745
746/*
drh51147ba2005-07-23 22:59:55 +0000747** Find the best index for accessing a particular table. Return a pointer
748** to the index, flags that describe how the index should be used, the
drha6110402005-07-28 20:51:19 +0000749** number of equality constraints, and the "cost" for this index.
drh51147ba2005-07-23 22:59:55 +0000750**
751** The lowest cost index wins. The cost is an estimate of the amount of
752** CPU and disk I/O need to process the request using the selected index.
753** Factors that influence cost include:
754**
755** * The estimated number of rows that will be retrieved. (The
756** fewer the better.)
757**
758** * Whether or not sorting must occur.
759**
760** * Whether or not there must be separate lookups in the
761** index and in the main table.
762**
drhfe05af82005-07-21 03:14:59 +0000763*/
764static double bestIndex(
765 Parse *pParse, /* The parsing context */
766 WhereClause *pWC, /* The WHERE clause */
767 struct SrcList_item *pSrc, /* The FROM clause term to search */
768 Bitmask notReady, /* Mask of cursors that are not available */
769 ExprList *pOrderBy, /* The order by clause */
770 Index **ppIndex, /* Make *ppIndex point to the best index */
drh51147ba2005-07-23 22:59:55 +0000771 int *pFlags, /* Put flags describing this choice in *pFlags */
772 int *pnEq /* Put the number of == or IN constraints here */
drhfe05af82005-07-21 03:14:59 +0000773){
774 WhereTerm *pTerm;
drh51147ba2005-07-23 22:59:55 +0000775 Index *bestIdx = 0; /* Index that gives the lowest cost */
776 double lowestCost = 1.0e99; /* The cost of using bestIdx */
777 int bestFlags = 0; /* Flags associated with bestIdx */
778 int bestNEq = 0; /* Best value for nEq */
779 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
780 Index *pProbe; /* An index we are evaluating */
781 int rev; /* True to scan in reverse order */
782 int flags; /* Flags associated with pProbe */
783 int nEq; /* Number of == or IN constraints */
784 double cost; /* Cost of using pProbe */
drhfe05af82005-07-21 03:14:59 +0000785
drh51147ba2005-07-23 22:59:55 +0000786 TRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
787
788 /* Check for a rowid=EXPR or rowid IN (...) constraints
drhfe05af82005-07-21 03:14:59 +0000789 */
790 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
791 if( pTerm ){
drha6110402005-07-28 20:51:19 +0000792 Expr *pExpr;
drhfe05af82005-07-21 03:14:59 +0000793 *ppIndex = 0;
drh51147ba2005-07-23 22:59:55 +0000794 bestFlags = WHERE_ROWID_EQ;
drhfe05af82005-07-21 03:14:59 +0000795 if( pTerm->operator & WO_EQ ){
drh28c4cf42005-07-27 20:41:43 +0000796 /* Rowid== is always the best pick. Look no further. Because only
797 ** a single row is generated, output is always in sorted order */
drhfe05af82005-07-21 03:14:59 +0000798 *pFlags = WHERE_ROWID_EQ;
drh51147ba2005-07-23 22:59:55 +0000799 *pnEq = 1;
drhfe05af82005-07-21 03:14:59 +0000800 if( pOrderBy ) *pFlags |= WHERE_ORDERBY;
drh51147ba2005-07-23 22:59:55 +0000801 TRACE(("... best is rowid\n"));
802 return 0.0;
drha6110402005-07-28 20:51:19 +0000803 }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
drh28c4cf42005-07-27 20:41:43 +0000804 /* Rowid IN (LIST): cost is NlogN where N is the number of list
805 ** elements. */
drha6110402005-07-28 20:51:19 +0000806 lowestCost = pExpr->pList->nExpr;
drh28c4cf42005-07-27 20:41:43 +0000807 lowestCost *= estLog(lowestCost);
drhfe05af82005-07-21 03:14:59 +0000808 }else{
drh28c4cf42005-07-27 20:41:43 +0000809 /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
810 ** in the result of the inner select. We have no way to estimate
811 ** that value so make a wild guess. */
812 lowestCost = 200.0;
drhfe05af82005-07-21 03:14:59 +0000813 }
drh3adc9ce2005-07-28 16:51:51 +0000814 TRACE(("... rowid IN cost: %.9g\n", lowestCost));
drhfe05af82005-07-21 03:14:59 +0000815 }
816
drh28c4cf42005-07-27 20:41:43 +0000817 /* Estimate the cost of a table scan. If we do not know how many
818 ** entries are in the table, use 1 million as a guess.
drhfe05af82005-07-21 03:14:59 +0000819 */
drh51147ba2005-07-23 22:59:55 +0000820 pProbe = pSrc->pTab->pIndex;
drh28c4cf42005-07-27 20:41:43 +0000821 cost = pProbe ? pProbe->aiRowEst[0] : 1000000.0;
drh3adc9ce2005-07-28 16:51:51 +0000822 TRACE(("... table scan base cost: %.9g\n", cost));
drh28c4cf42005-07-27 20:41:43 +0000823 flags = WHERE_ROWID_RANGE;
824
825 /* Check for constraints on a range of rowids in a table scan.
826 */
drhfe05af82005-07-21 03:14:59 +0000827 pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
828 if( pTerm ){
drh51147ba2005-07-23 22:59:55 +0000829 if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
830 flags |= WHERE_TOP_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000831 cost *= 0.333; /* Guess that rowid<EXPR eliminates two-thirds or rows */
drhfe05af82005-07-21 03:14:59 +0000832 }
drh51147ba2005-07-23 22:59:55 +0000833 if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
834 flags |= WHERE_BTM_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000835 cost *= 0.333; /* Guess that rowid>EXPR eliminates two-thirds of rows */
drhfe05af82005-07-21 03:14:59 +0000836 }
drh3adc9ce2005-07-28 16:51:51 +0000837 TRACE(("... rowid range reduces cost to %.9g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000838 }else{
839 flags = 0;
840 }
drh28c4cf42005-07-27 20:41:43 +0000841
842 /* If the table scan does not satisfy the ORDER BY clause, increase
843 ** the cost by NlogN to cover the expense of sorting. */
844 if( pOrderBy ){
845 if( sortableByRowid(iCur, pOrderBy, &rev) ){
846 flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
847 if( rev ){
848 flags |= WHERE_REVERSE;
849 }
850 }else{
851 cost += cost*estLog(cost);
drh3adc9ce2005-07-28 16:51:51 +0000852 TRACE(("... sorting increases cost to %.9g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000853 }
drh51147ba2005-07-23 22:59:55 +0000854 }
855 if( cost<lowestCost ){
856 lowestCost = cost;
drhfe05af82005-07-21 03:14:59 +0000857 bestFlags = flags;
858 }
859
860 /* Look at each index.
861 */
drh51147ba2005-07-23 22:59:55 +0000862 for(; pProbe; pProbe=pProbe->pNext){
863 int i; /* Loop counter */
drh28c4cf42005-07-27 20:41:43 +0000864 double inMultiplier = 1.0;
drh51147ba2005-07-23 22:59:55 +0000865
866 TRACE(("... index %s:\n", pProbe->zName));
drhfe05af82005-07-21 03:14:59 +0000867
868 /* Count the number of columns in the index that are satisfied
869 ** by x=EXPR constraints or x IN (...) constraints.
870 */
drh51147ba2005-07-23 22:59:55 +0000871 flags = 0;
drhfe05af82005-07-21 03:14:59 +0000872 for(i=0; i<pProbe->nColumn; i++){
873 int j = pProbe->aiColumn[i];
874 pTerm = findTerm(pWC, iCur, j, notReady, WO_EQ|WO_IN, pProbe);
875 if( pTerm==0 ) break;
drh51147ba2005-07-23 22:59:55 +0000876 flags |= WHERE_COLUMN_EQ;
877 if( pTerm->operator & WO_IN ){
drha6110402005-07-28 20:51:19 +0000878 Expr *pExpr = pTerm->pExpr;
drh51147ba2005-07-23 22:59:55 +0000879 flags |= WHERE_COLUMN_IN;
drha6110402005-07-28 20:51:19 +0000880 if( pExpr->pSelect!=0 ){
drh51147ba2005-07-23 22:59:55 +0000881 inMultiplier *= 100.0;
drha6110402005-07-28 20:51:19 +0000882 }else if( pExpr->pList!=0 ){
883 inMultiplier *= pExpr->pList->nExpr + 1.0;
drhfe05af82005-07-21 03:14:59 +0000884 }
885 }
886 }
drh28c4cf42005-07-27 20:41:43 +0000887 cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
drh51147ba2005-07-23 22:59:55 +0000888 nEq = i;
drh3adc9ce2005-07-28 16:51:51 +0000889 TRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n", nEq, inMultiplier, cost));
drhfe05af82005-07-21 03:14:59 +0000890
drh51147ba2005-07-23 22:59:55 +0000891 /* Look for range constraints
drhfe05af82005-07-21 03:14:59 +0000892 */
drh51147ba2005-07-23 22:59:55 +0000893 if( nEq<pProbe->nColumn ){
894 int j = pProbe->aiColumn[nEq];
895 pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
896 if( pTerm ){
drha6110402005-07-28 20:51:19 +0000897 flags |= WHERE_COLUMN_RANGE;
drh51147ba2005-07-23 22:59:55 +0000898 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
899 flags |= WHERE_TOP_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000900 cost *= 0.333;
drh51147ba2005-07-23 22:59:55 +0000901 }
902 if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
903 flags |= WHERE_BTM_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000904 cost *= 0.333;
drh51147ba2005-07-23 22:59:55 +0000905 }
drh3adc9ce2005-07-28 16:51:51 +0000906 TRACE(("...... range reduces cost to %.9g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000907 }
908 }
909
drh28c4cf42005-07-27 20:41:43 +0000910 /* Add the additional cost of sorting if that is a factor.
drh51147ba2005-07-23 22:59:55 +0000911 */
drh28c4cf42005-07-27 20:41:43 +0000912 if( pOrderBy ){
913 if( (flags & WHERE_COLUMN_IN)==0 &&
drhfe05af82005-07-21 03:14:59 +0000914 isSortingIndex(pParse, pProbe, pSrc->pTab, iCur, pOrderBy, nEq, &rev) ){
drh28c4cf42005-07-27 20:41:43 +0000915 if( flags==0 ){
916 flags = WHERE_COLUMN_RANGE;
917 }
918 flags |= WHERE_ORDERBY;
919 if( rev ){
920 flags |= WHERE_REVERSE;
921 }
922 }else{
923 cost += cost*estLog(cost);
drh3adc9ce2005-07-28 16:51:51 +0000924 TRACE(("...... orderby increases cost to %.9g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000925 }
drhfe05af82005-07-21 03:14:59 +0000926 }
927
928 /* Check to see if we can get away with using just the index without
drh51147ba2005-07-23 22:59:55 +0000929 ** ever reading the table. If that is the case, then halve the
930 ** cost of this index.
drhfe05af82005-07-21 03:14:59 +0000931 */
drh51147ba2005-07-23 22:59:55 +0000932 if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
drhfe05af82005-07-21 03:14:59 +0000933 Bitmask m = pSrc->colUsed;
934 int j;
935 for(j=0; j<pProbe->nColumn; j++){
936 int x = pProbe->aiColumn[j];
937 if( x<BMS-1 ){
938 m &= ~(((Bitmask)1)<<x);
939 }
940 }
941 if( m==0 ){
942 flags |= WHERE_IDX_ONLY;
drh51147ba2005-07-23 22:59:55 +0000943 cost *= 0.5;
drh3adc9ce2005-07-28 16:51:51 +0000944 TRACE(("...... idx-only reduces cost to %.9g\n", cost));
drhfe05af82005-07-21 03:14:59 +0000945 }
946 }
947
drh51147ba2005-07-23 22:59:55 +0000948 /* If this index has achieved the lowest cost so far, then use it.
drhfe05af82005-07-21 03:14:59 +0000949 */
drh51147ba2005-07-23 22:59:55 +0000950 if( cost < lowestCost ){
drhfe05af82005-07-21 03:14:59 +0000951 bestIdx = pProbe;
drh51147ba2005-07-23 22:59:55 +0000952 lowestCost = cost;
drha6110402005-07-28 20:51:19 +0000953 assert( flags!=0 );
drhfe05af82005-07-21 03:14:59 +0000954 bestFlags = flags;
drh51147ba2005-07-23 22:59:55 +0000955 bestNEq = nEq;
drhfe05af82005-07-21 03:14:59 +0000956 }
957 }
958
drhfe05af82005-07-21 03:14:59 +0000959 /* Report the best result
960 */
961 *ppIndex = bestIdx;
drh3adc9ce2005-07-28 16:51:51 +0000962 TRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
drh51147ba2005-07-23 22:59:55 +0000963 bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
drhfe05af82005-07-21 03:14:59 +0000964 *pFlags = bestFlags;
drh51147ba2005-07-23 22:59:55 +0000965 *pnEq = bestNEq;
966 return lowestCost;
drhfe05af82005-07-21 03:14:59 +0000967}
968
drhb6c29892004-11-22 19:12:19 +0000969
970/*
drh2ffb1182004-07-19 19:14:01 +0000971** Disable a term in the WHERE clause. Except, do not disable the term
972** if it controls a LEFT OUTER JOIN and it did not originate in the ON
973** or USING clause of that join.
974**
975** Consider the term t2.z='ok' in the following queries:
976**
977** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
978** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
979** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
980**
drh23bf66d2004-12-14 03:34:34 +0000981** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +0000982** in the ON clause. The term is disabled in (3) because it is not part
983** of a LEFT OUTER JOIN. In (1), the term is not disabled.
984**
985** Disabling a term causes that term to not be tested in the inner loop
986** of the join. Disabling is an optimization. We would get the correct
987** results if nothing were ever disabled, but joins might run a little
988** slower. The trick is to disable as much as we can without disabling
989** too much. If we disabled in (1), we'd get the wrong answer.
990** See ticket #813.
991*/
drh0fcef5e2005-07-19 17:38:22 +0000992static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
993 if( pTerm
994 && (pTerm->flags & TERM_CODED)==0
995 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
996 ){
997 pTerm->flags |= TERM_CODED;
998 if( pTerm->iPartner>=0 ){
drhed378002005-07-28 23:12:08 +0000999 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iPartner];
1000 if( (--pOther->nPartner)<=0 ){
1001 disableTerm(pLevel, pOther);
1002 }
drh0fcef5e2005-07-19 17:38:22 +00001003 }
drh2ffb1182004-07-19 19:14:01 +00001004 }
1005}
1006
1007/*
drh94a11212004-09-25 13:12:14 +00001008** Generate code that builds a probe for an index. Details:
1009**
1010** * Check the top nColumn entries on the stack. If any
1011** of those entries are NULL, jump immediately to brk,
1012** which is the loop exit, since no index entry will match
1013** if any part of the key is NULL.
1014**
1015** * Construct a probe entry from the top nColumn entries in
1016** the stack with affinities appropriate for index pIdx.
1017*/
1018static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
1019 sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
1020 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
1021 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
1022 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
1023 sqlite3IndexAffinityStr(v, pIdx);
1024}
1025
drhe8b97272005-07-19 22:22:12 +00001026
1027/*
drh51147ba2005-07-23 22:59:55 +00001028** Generate code for a single equality term of the WHERE clause. An equality
1029** term can be either X=expr or X IN (...). pTerm is the term to be
1030** coded.
1031**
1032** The current value for the constraint is left on the top of the stack.
1033**
1034** For a constraint of the form X=expr, the expression is evaluated and its
1035** result is left on the stack. For constraints of the form X IN (...)
1036** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00001037*/
1038static void codeEqualityTerm(
1039 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00001040 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh94a11212004-09-25 13:12:14 +00001041 int brk, /* Jump here to abandon the loop */
1042 WhereLevel *pLevel /* When level of the FROM clause we are working on */
1043){
drh0fcef5e2005-07-19 17:38:22 +00001044 Expr *pX = pTerm->pExpr;
drh94a11212004-09-25 13:12:14 +00001045 if( pX->op!=TK_IN ){
1046 assert( pX->op==TK_EQ );
1047 sqlite3ExprCode(pParse, pX->pRight);
danielk1977b3bce662005-01-29 08:32:43 +00001048#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00001049 }else{
danielk1977b3bce662005-01-29 08:32:43 +00001050 int iTab;
drhe23399f2005-07-22 00:31:39 +00001051 int *aIn;
drh94a11212004-09-25 13:12:14 +00001052 Vdbe *v = pParse->pVdbe;
danielk1977b3bce662005-01-29 08:32:43 +00001053
1054 sqlite3CodeSubselect(pParse, pX);
1055 iTab = pX->iTable;
drh94a11212004-09-25 13:12:14 +00001056 sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
danielk1977b3bce662005-01-29 08:32:43 +00001057 VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
drhe23399f2005-07-22 00:31:39 +00001058 pLevel->nIn++;
1059 pLevel->aInLoop = aIn = sqliteRealloc(pLevel->aInLoop,
1060 sizeof(pLevel->aInLoop[0])*3*pLevel->nIn);
1061 if( aIn ){
1062 aIn += pLevel->nIn*3 - 3;
1063 aIn[0] = OP_Next;
1064 aIn[1] = iTab;
1065 aIn[2] = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
drha6110402005-07-28 20:51:19 +00001066 }else{
1067 pLevel->nIn = 0;
drhe23399f2005-07-22 00:31:39 +00001068 }
danielk1977b3bce662005-01-29 08:32:43 +00001069#endif
drh94a11212004-09-25 13:12:14 +00001070 }
drh0fcef5e2005-07-19 17:38:22 +00001071 disableTerm(pLevel, pTerm);
drh94a11212004-09-25 13:12:14 +00001072}
1073
drh51147ba2005-07-23 22:59:55 +00001074/*
1075** Generate code that will evaluate all == and IN constraints for an
1076** index. The values for all constraints are left on the stack.
1077**
1078** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
1079** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
1080** The index has as many as three equality constraints, but in this
1081** example, the third "c" value is an inequality. So only two
1082** constraints are coded. This routine will generate code to evaluate
1083** a==5 and b IN (1,2,3). The current values for a and b will be left
1084** on the stack - a is the deepest and b the shallowest.
1085**
1086** In the example above nEq==2. But this subroutine works for any value
1087** of nEq including 0. If nEq==0, this routine is nearly a no-op.
1088** The only thing it does is allocate the pLevel->iMem memory cell.
1089**
1090** This routine always allocates at least one memory cell and puts
1091** the address of that memory cell in pLevel->iMem. The code that
1092** calls this routine will use pLevel->iMem to store the termination
1093** key value of the loop. If one or more IN operators appear, then
1094** this routine allocates an additional nEq memory cells for internal
1095** use.
1096*/
1097static void codeAllEqualityTerms(
1098 Parse *pParse, /* Parsing context */
1099 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
1100 WhereClause *pWC, /* The WHERE clause */
1101 Bitmask notReady, /* Which parts of FROM have not yet been coded */
1102 int brk /* Jump here to end the loop */
1103){
1104 int nEq = pLevel->nEq; /* The number of == or IN constraints to code */
1105 int termsInMem = 0; /* If true, store value in mem[] cells */
1106 Vdbe *v = pParse->pVdbe; /* The virtual machine under construction */
1107 Index *pIdx = pLevel->pIdx; /* The index being used for this loop */
1108 int iCur = pLevel->iTabCur; /* The cursor of the table */
1109 WhereTerm *pTerm; /* A single constraint term */
1110 int j; /* Loop counter */
1111
1112 /* Figure out how many memory cells we will need then allocate them.
1113 ** We always need at least one used to store the loop terminator
1114 ** value. If there are IN operators we'll need one for each == or
1115 ** IN constraint.
1116 */
1117 pLevel->iMem = pParse->nMem++;
1118 if( pLevel->flags & WHERE_COLUMN_IN ){
1119 pParse->nMem += pLevel->nEq;
1120 termsInMem = 1;
1121 }
1122
1123 /* Evaluate the equality constraints
1124 */
1125 for(j=0; 1; j++){
1126 int k = pIdx->aiColumn[j];
1127 pTerm = findTerm(pWC, iCur, k, notReady, WO_EQ|WO_IN, pIdx);
1128 if( pTerm==0 ) break;
1129 assert( (pTerm->flags & TERM_CODED)==0 );
1130 codeEqualityTerm(pParse, pTerm, brk, pLevel);
1131 if( termsInMem ){
1132 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1);
1133 }
1134 }
1135 assert( j==nEq );
1136
1137 /* Make sure all the constraint values are on the top of the stack
1138 */
1139 if( termsInMem ){
1140 for(j=0; j<nEq; j++){
1141 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem+j+1, 0);
1142 }
1143 }
1144}
1145
drh84bfda42005-07-15 13:05:21 +00001146#ifdef SQLITE_TEST
1147/*
1148** The following variable holds a text description of query plan generated
1149** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
1150** overwrites the previous. This information is used for testing and
1151** analysis only.
1152*/
1153char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
1154static int nQPlan = 0; /* Next free slow in _query_plan[] */
1155
1156#endif /* SQLITE_TEST */
1157
1158
drh94a11212004-09-25 13:12:14 +00001159
1160/*
drhe3184742002-06-19 14:27:05 +00001161** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00001162** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00001163** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00001164** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00001165** in order to complete the WHERE clause processing.
1166**
1167** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00001168**
1169** The basic idea is to do a nested loop, one loop for each table in
1170** the FROM clause of a select. (INSERT and UPDATE statements are the
1171** same as a SELECT with only a single table in the FROM clause.) For
1172** example, if the SQL is this:
1173**
1174** SELECT * FROM t1, t2, t3 WHERE ...;
1175**
1176** Then the code generated is conceptually like the following:
1177**
1178** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00001179** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00001180** foreach row3 in t3 do /
1181** ...
1182** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00001183** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00001184** end /
1185**
drh29dda4a2005-07-21 18:23:20 +00001186** Note that the loops might not be nested in the order in which they
1187** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00001188** use of indices. Note also that when the IN operator appears in
1189** the WHERE clause, it might result in additional nested loops for
1190** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00001191**
drhc27a1ce2002-06-14 20:58:45 +00001192** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00001193** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
1194** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00001195** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00001196**
drhe6f85e72004-12-25 01:03:13 +00001197** The code that sqlite3WhereBegin() generates leaves the cursors named
1198** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00001199** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00001200** data from the various tables of the loop.
1201**
drhc27a1ce2002-06-14 20:58:45 +00001202** If the WHERE clause is empty, the foreach loops must each scan their
1203** entire tables. Thus a three-way join is an O(N^3) operation. But if
1204** the tables have indices and there are terms in the WHERE clause that
1205** refer to those indices, a complete table scan can be avoided and the
1206** code will run much faster. Most of the work of this routine is checking
1207** to see if there are indices that can be used to speed up the loop.
1208**
1209** Terms of the WHERE clause are also used to limit which rows actually
1210** make it to the "..." in the middle of the loop. After each "foreach",
1211** terms of the WHERE clause that use only terms in that loop and outer
1212** loops are evaluated and if false a jump is made around all subsequent
1213** inner loops (or around the "..." if the test occurs within the inner-
1214** most loop)
1215**
1216** OUTER JOINS
1217**
1218** An outer join of tables t1 and t2 is conceptally coded as follows:
1219**
1220** foreach row1 in t1 do
1221** flag = 0
1222** foreach row2 in t2 do
1223** start:
1224** ...
1225** flag = 1
1226** end
drhe3184742002-06-19 14:27:05 +00001227** if flag==0 then
1228** move the row2 cursor to a null row
1229** goto start
1230** fi
drhc27a1ce2002-06-14 20:58:45 +00001231** end
1232**
drhe3184742002-06-19 14:27:05 +00001233** ORDER BY CLAUSE PROCESSING
1234**
1235** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
1236** if there is one. If there is no ORDER BY clause or if this routine
1237** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
1238**
1239** If an index can be used so that the natural output order of the table
1240** scan is correct for the ORDER BY clause, then that index is used and
1241** *ppOrderBy is set to NULL. This is an optimization that prevents an
1242** unnecessary sort of the result set if an index appropriate for the
1243** ORDER BY clause already exists.
1244**
1245** If the where clause loops cannot be arranged to provide the correct
1246** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +00001247*/
danielk19774adee202004-05-08 08:23:19 +00001248WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00001249 Parse *pParse, /* The parser context */
1250 SrcList *pTabList, /* A list of all tables to be scanned */
1251 Expr *pWhere, /* The WHERE clause */
drhf8db1bc2005-04-22 02:38:37 +00001252 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +00001253){
1254 int i; /* Loop counter */
1255 WhereInfo *pWInfo; /* Will become the return value of this function */
1256 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhd4f5ee22003-07-16 00:54:31 +00001257 int brk, cont = 0; /* Addresses used during code generation */
drhfe05af82005-07-21 03:14:59 +00001258 Bitmask notReady; /* Cursors that are not yet positioned */
drh0aa74ed2005-07-16 13:33:20 +00001259 WhereTerm *pTerm; /* A single term in the WHERE clause */
1260 ExprMaskSet maskSet; /* The expression mask set */
drh0aa74ed2005-07-16 13:33:20 +00001261 WhereClause wc; /* The WHERE clause is divided into these terms */
drh9012bcb2004-12-19 00:11:35 +00001262 struct SrcList_item *pTabItem; /* A single entry from pTabList */
1263 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh29dda4a2005-07-21 18:23:20 +00001264 int iFrom; /* First unused FROM clause element */
drh75897232000-05-29 14:26:00 +00001265
drh29dda4a2005-07-21 18:23:20 +00001266 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00001267 ** bits in a Bitmask
1268 */
drh29dda4a2005-07-21 18:23:20 +00001269 if( pTabList->nSrc>BMS ){
1270 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00001271 return 0;
1272 }
1273
drh83dcb1a2002-06-28 01:02:38 +00001274 /* Split the WHERE clause into separate subexpressions where each
drh29dda4a2005-07-21 18:23:20 +00001275 ** subexpression is separated by an AND operator.
drh83dcb1a2002-06-28 01:02:38 +00001276 */
drh6a3ea0e2003-05-02 14:32:12 +00001277 initMaskSet(&maskSet);
drhfe05af82005-07-21 03:14:59 +00001278 whereClauseInit(&wc, pParse);
drh6c30be82005-07-29 15:10:17 +00001279 whereSplit(&wc, pWhere, TK_AND);
drh1398ad32005-01-19 23:24:50 +00001280
drh75897232000-05-29 14:26:00 +00001281 /* Allocate and initialize the WhereInfo structure that will become the
1282 ** return value.
1283 */
drhad3cab52002-05-24 02:04:32 +00001284 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
danielk1977132872b2004-05-10 10:37:18 +00001285 if( sqlite3_malloc_failed ){
drhe23399f2005-07-22 00:31:39 +00001286 goto whereBeginNoMem;
drh75897232000-05-29 14:26:00 +00001287 }
1288 pWInfo->pParse = pParse;
1289 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +00001290 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh08192d52002-04-30 19:20:28 +00001291
1292 /* Special case: a WHERE clause that is constant. Evaluate the
1293 ** expression and either jump over all of the code or fall thru.
1294 */
danielk19774adee202004-05-08 08:23:19 +00001295 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
1296 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +00001297 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00001298 }
drh75897232000-05-29 14:26:00 +00001299
drh29dda4a2005-07-21 18:23:20 +00001300 /* Analyze all of the subexpressions. Note that exprAnalyze() might
1301 ** add new virtual terms onto the end of the WHERE clause. We do not
1302 ** want to analyze these virtual terms, so start analyzing at the end
1303 ** and work forward so that they added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00001304 */
drh1398ad32005-01-19 23:24:50 +00001305 for(i=0; i<pTabList->nSrc; i++){
1306 createMask(&maskSet, pTabList->a[i].iCursor);
1307 }
drh6c30be82005-07-29 15:10:17 +00001308 exprAnalyzeAll(pTabList, &maskSet, &wc);
drh75897232000-05-29 14:26:00 +00001309
drh29dda4a2005-07-21 18:23:20 +00001310 /* Chose the best index to use for each table in the FROM clause.
1311 **
drh51147ba2005-07-23 22:59:55 +00001312 ** This loop fills in the following fields:
1313 **
1314 ** pWInfo->a[].pIdx The index to use for this level of the loop.
1315 ** pWInfo->a[].flags WHERE_xxx flags associated with pIdx
1316 ** pWInfo->a[].nEq The number of == and IN constraints
1317 ** pWInfo->a[].iFrom When term of the FROM clause is being coded
1318 ** pWInfo->a[].iTabCur The VDBE cursor for the database table
1319 ** pWInfo->a[].iIdxCur The VDBE cursor for the index
1320 **
1321 ** This loop also figures out the nesting order of tables in the FROM
1322 ** clause.
drh75897232000-05-29 14:26:00 +00001323 */
drhfe05af82005-07-21 03:14:59 +00001324 notReady = ~(Bitmask)0;
drh9012bcb2004-12-19 00:11:35 +00001325 pTabItem = pTabList->a;
1326 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001327 for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1328 Index *pIdx; /* Index for FROM table at pTabItem */
1329 int flags; /* Flags asssociated with pIdx */
drh51147ba2005-07-23 22:59:55 +00001330 int nEq; /* Number of == or IN constraints */
1331 double cost; /* The cost for pIdx */
drh29dda4a2005-07-21 18:23:20 +00001332 int j; /* For looping over FROM tables */
1333 Index *pBest = 0; /* The best index seen so far */
1334 int bestFlags = 0; /* Flags associated with pBest */
drh51147ba2005-07-23 22:59:55 +00001335 int bestNEq = 0; /* nEq associated with pBest */
1336 double lowestCost = 1.0e99; /* Cost of the pBest */
drh29dda4a2005-07-21 18:23:20 +00001337 int bestJ; /* The value of j */
1338 Bitmask m; /* Bitmask value for j or bestJ */
1339
1340 for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
1341 m = getMask(&maskSet, pTabItem->iCursor);
1342 if( (m & notReady)==0 ){
1343 if( j==iFrom ) iFrom++;
1344 continue;
1345 }
drh51147ba2005-07-23 22:59:55 +00001346 cost = bestIndex(pParse, &wc, pTabItem, notReady,
1347 (j==0 && ppOrderBy) ? *ppOrderBy : 0,
1348 &pIdx, &flags, &nEq);
1349 if( cost<lowestCost ){
1350 lowestCost = cost;
drh29dda4a2005-07-21 18:23:20 +00001351 pBest = pIdx;
1352 bestFlags = flags;
drh51147ba2005-07-23 22:59:55 +00001353 bestNEq = nEq;
drh29dda4a2005-07-21 18:23:20 +00001354 bestJ = j;
1355 }
1356 if( (pTabItem->jointype & JT_LEFT)!=0
1357 || (j>0 && (pTabItem[-1].jointype & JT_LEFT)!=0)
1358 ){
1359 break;
1360 }
1361 }
1362 if( bestFlags & WHERE_ORDERBY ){
drhfe05af82005-07-21 03:14:59 +00001363 *ppOrderBy = 0;
drhc4a3c772001-04-04 11:48:57 +00001364 }
drh29dda4a2005-07-21 18:23:20 +00001365 pLevel->flags = bestFlags;
drhfe05af82005-07-21 03:14:59 +00001366 pLevel->pIdx = pBest;
drh51147ba2005-07-23 22:59:55 +00001367 pLevel->nEq = bestNEq;
drhe23399f2005-07-22 00:31:39 +00001368 pLevel->aInLoop = 0;
1369 pLevel->nIn = 0;
drhfe05af82005-07-21 03:14:59 +00001370 if( pBest ){
drh9012bcb2004-12-19 00:11:35 +00001371 pLevel->iIdxCur = pParse->nTab++;
drhfe05af82005-07-21 03:14:59 +00001372 }else{
1373 pLevel->iIdxCur = -1;
drh6b563442001-11-07 16:48:26 +00001374 }
drh29dda4a2005-07-21 18:23:20 +00001375 notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
1376 pLevel->iFrom = bestJ;
drh75897232000-05-29 14:26:00 +00001377 }
1378
drh9012bcb2004-12-19 00:11:35 +00001379 /* Open all tables in the pTabList and any indices selected for
1380 ** searching those tables.
1381 */
1382 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
1383 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001384 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drh9012bcb2004-12-19 00:11:35 +00001385 Table *pTab;
1386 Index *pIx;
1387 int iIdxCur = pLevel->iIdxCur;
1388
drh29dda4a2005-07-21 18:23:20 +00001389 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001390 pTab = pTabItem->pTab;
1391 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001392 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001393 sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
1394 }
1395 pLevel->iTabCur = pTabItem->iCursor;
1396 if( (pIx = pLevel->pIdx)!=0 ){
1397 sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
drh29dda4a2005-07-21 18:23:20 +00001398 VdbeComment((v, "# %s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00001399 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
1400 (char*)&pIx->keyInfo, P3_KEYINFO);
1401 }
drhfe05af82005-07-21 03:14:59 +00001402 if( (pLevel->flags & WHERE_IDX_ONLY)!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001403 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
1404 }
1405 sqlite3CodeVerifySchema(pParse, pTab->iDb);
1406 }
1407 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
1408
drh29dda4a2005-07-21 18:23:20 +00001409 /* Generate the code to do the search. Each iteration of the for
1410 ** loop below generates code for a single nested loop of the VM
1411 ** program.
drh75897232000-05-29 14:26:00 +00001412 */
drhfe05af82005-07-21 03:14:59 +00001413 notReady = ~(Bitmask)0;
drh29dda4a2005-07-21 18:23:20 +00001414 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drhfe05af82005-07-21 03:14:59 +00001415 int j;
drh9012bcb2004-12-19 00:11:35 +00001416 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
1417 Index *pIdx; /* The index we will be using */
1418 int iIdxCur; /* The VDBE cursor for the index */
1419 int omitTable; /* True if we use the index only */
drh29dda4a2005-07-21 18:23:20 +00001420 int bRev; /* True if we need to scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001421
drh29dda4a2005-07-21 18:23:20 +00001422 pTabItem = &pTabList->a[pLevel->iFrom];
1423 iCur = pTabItem->iCursor;
drh9012bcb2004-12-19 00:11:35 +00001424 pIdx = pLevel->pIdx;
1425 iIdxCur = pLevel->iIdxCur;
drh29dda4a2005-07-21 18:23:20 +00001426 bRev = (pLevel->flags & WHERE_REVERSE)!=0;
drhfe05af82005-07-21 03:14:59 +00001427 omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
drh75897232000-05-29 14:26:00 +00001428
drh29dda4a2005-07-21 18:23:20 +00001429 /* Create labels for the "break" and "continue" instructions
1430 ** for the current loop. Jump to brk to break out of a loop.
1431 ** Jump to cont to go immediately to the next iteration of the
1432 ** loop.
1433 */
1434 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1435 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1436
drhad2d8302002-05-24 20:31:36 +00001437 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +00001438 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +00001439 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +00001440 */
drh29dda4a2005-07-21 18:23:20 +00001441 if( pLevel->iFrom>0 && (pTabItem[-1].jointype & JT_LEFT)!=0 ){
drhad2d8302002-05-24 20:31:36 +00001442 if( !pParse->nMem ) pParse->nMem++;
1443 pLevel->iLeftJoin = pParse->nMem++;
drhf0863fe2005-06-12 21:35:51 +00001444 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001445 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001446 VdbeComment((v, "# init LEFT JOIN no-match flag"));
drhad2d8302002-05-24 20:31:36 +00001447 }
1448
drhfe05af82005-07-21 03:14:59 +00001449 if( pLevel->flags & WHERE_ROWID_EQ ){
drh8aff1012001-12-22 14:49:24 +00001450 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +00001451 ** equality comparison against the ROWID field. Or
1452 ** we reference multiple rows using a "rowid IN (...)"
1453 ** construct.
drhc4a3c772001-04-04 11:48:57 +00001454 */
drhfe05af82005-07-21 03:14:59 +00001455 pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1456 assert( pTerm!=0 );
drh0fcef5e2005-07-19 17:38:22 +00001457 assert( pTerm->pExpr!=0 );
1458 assert( pTerm->leftCursor==iCur );
drh9012bcb2004-12-19 00:11:35 +00001459 assert( omitTable==0 );
drh94a11212004-09-25 13:12:14 +00001460 codeEqualityTerm(pParse, pTerm, brk, pLevel);
danielk19774adee202004-05-08 08:23:19 +00001461 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
danielk19774adee202004-05-08 08:23:19 +00001462 sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001463 VdbeComment((v, "pk"));
drh6b563442001-11-07 16:48:26 +00001464 pLevel->op = OP_Noop;
drhfe05af82005-07-21 03:14:59 +00001465 }else if( pLevel->flags & WHERE_ROWID_RANGE ){
drh51147ba2005-07-23 22:59:55 +00001466 /* Case 2: We have an inequality comparison against the ROWID field.
drh8aff1012001-12-22 14:49:24 +00001467 */
1468 int testOp = OP_Noop;
1469 int start;
drhfe05af82005-07-21 03:14:59 +00001470 WhereTerm *pStart, *pEnd;
drh8aff1012001-12-22 14:49:24 +00001471
drh9012bcb2004-12-19 00:11:35 +00001472 assert( omitTable==0 );
drha6110402005-07-28 20:51:19 +00001473 pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
1474 pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
drhfe05af82005-07-21 03:14:59 +00001475 if( bRev ){
1476 pTerm = pStart;
1477 pStart = pEnd;
1478 pEnd = pTerm;
1479 }
1480 if( pStart ){
drh94a11212004-09-25 13:12:14 +00001481 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001482 pX = pStart->pExpr;
drh94a11212004-09-25 13:12:14 +00001483 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001484 assert( pStart->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001485 sqlite3ExprCode(pParse, pX->pRight);
danielk1977d0a69322005-02-02 01:10:44 +00001486 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
drhb6c29892004-11-22 19:12:19 +00001487 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001488 VdbeComment((v, "pk"));
drhfe05af82005-07-21 03:14:59 +00001489 disableTerm(pLevel, pStart);
drh8aff1012001-12-22 14:49:24 +00001490 }else{
drhb6c29892004-11-22 19:12:19 +00001491 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
drh8aff1012001-12-22 14:49:24 +00001492 }
drhfe05af82005-07-21 03:14:59 +00001493 if( pEnd ){
drh94a11212004-09-25 13:12:14 +00001494 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001495 pX = pEnd->pExpr;
drh94a11212004-09-25 13:12:14 +00001496 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001497 assert( pEnd->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001498 sqlite3ExprCode(pParse, pX->pRight);
drh8aff1012001-12-22 14:49:24 +00001499 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001500 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drh94a11212004-09-25 13:12:14 +00001501 if( pX->op==TK_LT || pX->op==TK_GT ){
drhb6c29892004-11-22 19:12:19 +00001502 testOp = bRev ? OP_Le : OP_Ge;
drh8aff1012001-12-22 14:49:24 +00001503 }else{
drhb6c29892004-11-22 19:12:19 +00001504 testOp = bRev ? OP_Lt : OP_Gt;
drh8aff1012001-12-22 14:49:24 +00001505 }
drhfe05af82005-07-21 03:14:59 +00001506 disableTerm(pLevel, pEnd);
drh8aff1012001-12-22 14:49:24 +00001507 }
danielk19774adee202004-05-08 08:23:19 +00001508 start = sqlite3VdbeCurrentAddr(v);
drhb6c29892004-11-22 19:12:19 +00001509 pLevel->op = bRev ? OP_Prev : OP_Next;
drh6a3ea0e2003-05-02 14:32:12 +00001510 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001511 pLevel->p2 = start;
1512 if( testOp!=OP_Noop ){
drhf0863fe2005-06-12 21:35:51 +00001513 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001514 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drhf0863fe2005-06-12 21:35:51 +00001515 sqlite3VdbeAddOp(v, testOp, 'n', brk);
drh8aff1012001-12-22 14:49:24 +00001516 }
drhfe05af82005-07-21 03:14:59 +00001517 }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
drh51147ba2005-07-23 22:59:55 +00001518 /* Case 3: The WHERE clause term that refers to the right-most
drhc27a1ce2002-06-14 20:58:45 +00001519 ** column of the index is an inequality. For example, if
1520 ** the index is on (x,y,z) and the WHERE clause is of the
1521 ** form "x=5 AND y<10" then this case is used. Only the
1522 ** right-most column can be an inequality - the rest must
drh51147ba2005-07-23 22:59:55 +00001523 ** use the "==" and "IN" operators.
drhe3184742002-06-19 14:27:05 +00001524 **
1525 ** This case is also used when there are no WHERE clause
1526 ** constraints but an index is selected anyway, in order
1527 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +00001528 */
drh487ab3c2001-11-08 00:45:21 +00001529 int start;
drh51147ba2005-07-23 22:59:55 +00001530 int nEq = pLevel->nEq;
danielk1977f7df9cc2004-06-16 12:02:47 +00001531 int leFlag=0, geFlag=0;
drh487ab3c2001-11-08 00:45:21 +00001532 int testOp;
drhfe05af82005-07-21 03:14:59 +00001533 int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
1534 int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
drh487ab3c2001-11-08 00:45:21 +00001535
drh51147ba2005-07-23 22:59:55 +00001536 /* Generate code to evaluate all constraint terms using == or IN
1537 ** and level the values of those terms on the stack.
drh487ab3c2001-11-08 00:45:21 +00001538 */
drh51147ba2005-07-23 22:59:55 +00001539 codeAllEqualityTerms(pParse, pLevel, &wc, notReady, brk);
drh487ab3c2001-11-08 00:45:21 +00001540
drhc27a1ce2002-06-14 20:58:45 +00001541 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +00001542 ** used twice: once to make the termination key and once to make the
1543 ** start key.
1544 */
drh51147ba2005-07-23 22:59:55 +00001545 for(j=0; j<nEq; j++){
1546 sqlite3VdbeAddOp(v, OP_Dup, nEq-1, 0);
drh487ab3c2001-11-08 00:45:21 +00001547 }
1548
1549 /* Generate the termination key. This is the key value that
1550 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +00001551 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +00001552 **
1553 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1554 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +00001555 */
drhfe05af82005-07-21 03:14:59 +00001556 if( topLimit ){
drhe8b97272005-07-19 22:22:12 +00001557 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001558 int k = pIdx->aiColumn[j];
1559 pTerm = findTerm(&wc, iCur, k, notReady, WO_LT|WO_LE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001560 assert( pTerm!=0 );
1561 pX = pTerm->pExpr;
1562 assert( (pTerm->flags & TERM_CODED)==0 );
1563 sqlite3ExprCode(pParse, pX->pRight);
1564 leFlag = pX->op==TK_LE;
1565 disableTerm(pLevel, pTerm);
drh487ab3c2001-11-08 00:45:21 +00001566 testOp = OP_IdxGE;
1567 }else{
drh51147ba2005-07-23 22:59:55 +00001568 testOp = nEq>0 ? OP_IdxGE : OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001569 leFlag = 1;
1570 }
1571 if( testOp!=OP_Noop ){
drh51147ba2005-07-23 22:59:55 +00001572 int nCol = nEq + topLimit;
drh487ab3c2001-11-08 00:45:21 +00001573 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001574 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001575 if( bRev ){
drh7cf6e4d2004-05-19 14:56:55 +00001576 int op = leFlag ? OP_MoveLe : OP_MoveLt;
drh9012bcb2004-12-19 00:11:35 +00001577 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001578 }else{
danielk19774adee202004-05-08 08:23:19 +00001579 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001580 }
drhfe05af82005-07-21 03:14:59 +00001581 }else if( bRev ){
drh9012bcb2004-12-19 00:11:35 +00001582 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001583 }
1584
1585 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001586 ** bound on the search. There is no start key if there are no
1587 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001588 ** that case, generate a "Rewind" instruction in place of the
1589 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001590 **
1591 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1592 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001593 */
drhfe05af82005-07-21 03:14:59 +00001594 if( btmLimit ){
drhe8b97272005-07-19 22:22:12 +00001595 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001596 int k = pIdx->aiColumn[j];
1597 pTerm = findTerm(&wc, iCur, k, notReady, WO_GT|WO_GE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001598 assert( pTerm!=0 );
1599 pX = pTerm->pExpr;
1600 assert( (pTerm->flags & TERM_CODED)==0 );
1601 sqlite3ExprCode(pParse, pX->pRight);
1602 geFlag = pX->op==TK_GE;
1603 disableTerm(pLevel, pTerm);
drh7900ead2001-11-12 13:51:43 +00001604 }else{
1605 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001606 }
drh51147ba2005-07-23 22:59:55 +00001607 if( nEq>0 || btmLimit ){
1608 int nCol = nEq + btmLimit;
drh94a11212004-09-25 13:12:14 +00001609 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001610 if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001611 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001612 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001613 testOp = OP_IdxLT;
1614 }else{
drh7cf6e4d2004-05-19 14:56:55 +00001615 int op = geFlag ? OP_MoveGe : OP_MoveGt;
drh9012bcb2004-12-19 00:11:35 +00001616 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001617 }
drhfe05af82005-07-21 03:14:59 +00001618 }else if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001619 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001620 }else{
drh9012bcb2004-12-19 00:11:35 +00001621 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001622 }
1623
1624 /* Generate the the top of the loop. If there is a termination
1625 ** key we have to test for that key and abort at the top of the
1626 ** loop.
1627 */
danielk19774adee202004-05-08 08:23:19 +00001628 start = sqlite3VdbeCurrentAddr(v);
drh487ab3c2001-11-08 00:45:21 +00001629 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001630 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001631 sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
drhfe05af82005-07-21 03:14:59 +00001632 if( (leFlag && !bRev) || (!geFlag && bRev) ){
danielk19773d1bfea2004-05-14 11:00:53 +00001633 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
1634 }
drh487ab3c2001-11-08 00:45:21 +00001635 }
drh9012bcb2004-12-19 00:11:35 +00001636 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
drh51147ba2005-07-23 22:59:55 +00001637 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEq + topLimit, cont);
drhe6f85e72004-12-25 01:03:13 +00001638 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001639 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001640 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh487ab3c2001-11-08 00:45:21 +00001641 }
1642
1643 /* Record the instruction used to terminate the loop.
1644 */
drhfe05af82005-07-21 03:14:59 +00001645 pLevel->op = bRev ? OP_Prev : OP_Next;
drh9012bcb2004-12-19 00:11:35 +00001646 pLevel->p1 = iIdxCur;
drh487ab3c2001-11-08 00:45:21 +00001647 pLevel->p2 = start;
drh51147ba2005-07-23 22:59:55 +00001648 }else if( pLevel->flags & WHERE_COLUMN_EQ ){
1649 /* Case 4: There is an index and all terms of the WHERE clause that
1650 ** refer to the index using the "==" or "IN" operators.
1651 */
1652 int start;
1653 int nEq = pLevel->nEq;
1654
1655 /* Generate code to evaluate all constraint terms using == or IN
1656 ** and level the values of those terms on the stack.
1657 */
1658 codeAllEqualityTerms(pParse, pLevel, &wc, notReady, brk);
1659
1660 /* Generate a single key that will be used to both start and terminate
1661 ** the search
1662 */
1663 buildIndexProbe(v, nEq, brk, pIdx);
1664 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
1665
1666 /* Generate code (1) to move to the first matching element of the table.
1667 ** Then generate code (2) that jumps to "brk" after the cursor is past
1668 ** the last matching element of the table. The code (1) is executed
1669 ** once to initialize the search, the code (2) is executed before each
1670 ** iteration of the scan to see if the scan has finished. */
1671 if( bRev ){
1672 /* Scan in reverse order */
1673 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
1674 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1675 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
1676 pLevel->op = OP_Prev;
1677 }else{
1678 /* Scan in the forward order */
1679 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
1680 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1681 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
1682 pLevel->op = OP_Next;
1683 }
1684 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
1685 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEq, cont);
1686 if( !omitTable ){
1687 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
1688 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
1689 }
1690 pLevel->p1 = iIdxCur;
1691 pLevel->p2 = start;
drhfe05af82005-07-21 03:14:59 +00001692 }else{
1693 /* Case 5: There is no usable index. We must do a complete
1694 ** scan of the entire table.
1695 */
drhfe05af82005-07-21 03:14:59 +00001696 assert( omitTable==0 );
drha6110402005-07-28 20:51:19 +00001697 assert( bRev==0 );
1698 pLevel->op = OP_Next;
drhfe05af82005-07-21 03:14:59 +00001699 pLevel->p1 = iCur;
drha6110402005-07-28 20:51:19 +00001700 pLevel->p2 = 1 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, brk);
drh75897232000-05-29 14:26:00 +00001701 }
drhfe05af82005-07-21 03:14:59 +00001702 notReady &= ~getMask(&maskSet, iCur);
drh75897232000-05-29 14:26:00 +00001703
1704 /* Insert code to test every subexpression that can be completely
1705 ** computed using the current set of tables.
1706 */
drh0fcef5e2005-07-19 17:38:22 +00001707 for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
1708 Expr *pE;
1709 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001710 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001711 pE = pTerm->pExpr;
1712 assert( pE!=0 );
drh392e5972005-07-08 14:14:22 +00001713 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
drh1f162302002-10-27 19:35:33 +00001714 continue;
1715 }
drh392e5972005-07-08 14:14:22 +00001716 sqlite3ExprIfFalse(pParse, pE, cont, 1);
drh0fcef5e2005-07-19 17:38:22 +00001717 pTerm->flags |= TERM_CODED;
drh75897232000-05-29 14:26:00 +00001718 }
drhad2d8302002-05-24 20:31:36 +00001719
1720 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1721 ** at least one row of the right table has matched the left table.
1722 */
1723 if( pLevel->iLeftJoin ){
danielk19774adee202004-05-08 08:23:19 +00001724 pLevel->top = sqlite3VdbeCurrentAddr(v);
1725 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1726 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001727 VdbeComment((v, "# record LEFT JOIN hit"));
drh0aa74ed2005-07-16 13:33:20 +00001728 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
drh0fcef5e2005-07-19 17:38:22 +00001729 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001730 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001731 assert( pTerm->pExpr );
1732 sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
1733 pTerm->flags |= TERM_CODED;
drh1cc093c2002-06-24 22:01:57 +00001734 }
drhad2d8302002-05-24 20:31:36 +00001735 }
drh75897232000-05-29 14:26:00 +00001736 }
drh7ec764a2005-07-21 03:48:20 +00001737
1738#ifdef SQLITE_TEST /* For testing and debugging use only */
1739 /* Record in the query plan information about the current table
1740 ** and the index used to access it (if any). If the table itself
1741 ** is not used, its name is just '{}'. If no index is used
1742 ** the index is listed as "{}". If the primary key is used the
1743 ** index name is '*'.
1744 */
1745 for(i=0; i<pTabList->nSrc; i++){
1746 char *z;
1747 int n;
drh7ec764a2005-07-21 03:48:20 +00001748 pLevel = &pWInfo->a[i];
drh29dda4a2005-07-21 18:23:20 +00001749 pTabItem = &pTabList->a[pLevel->iFrom];
drh7ec764a2005-07-21 03:48:20 +00001750 z = pTabItem->zAlias;
1751 if( z==0 ) z = pTabItem->pTab->zName;
1752 n = strlen(z);
1753 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
1754 if( pLevel->flags & WHERE_IDX_ONLY ){
1755 strcpy(&sqlite3_query_plan[nQPlan], "{}");
1756 nQPlan += 2;
1757 }else{
1758 strcpy(&sqlite3_query_plan[nQPlan], z);
1759 nQPlan += n;
1760 }
1761 sqlite3_query_plan[nQPlan++] = ' ';
1762 }
1763 if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
1764 strcpy(&sqlite3_query_plan[nQPlan], "* ");
1765 nQPlan += 2;
1766 }else if( pLevel->pIdx==0 ){
1767 strcpy(&sqlite3_query_plan[nQPlan], "{} ");
1768 nQPlan += 3;
1769 }else{
1770 n = strlen(pLevel->pIdx->zName);
1771 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
1772 strcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName);
1773 nQPlan += n;
1774 sqlite3_query_plan[nQPlan++] = ' ';
1775 }
1776 }
1777 }
1778 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
1779 sqlite3_query_plan[--nQPlan] = 0;
1780 }
1781 sqlite3_query_plan[nQPlan] = 0;
1782 nQPlan = 0;
1783#endif /* SQLITE_TEST // Testing and debugging use only */
1784
drh29dda4a2005-07-21 18:23:20 +00001785 /* Record the continuation address in the WhereInfo structure. Then
1786 ** clean up and return.
1787 */
drh75897232000-05-29 14:26:00 +00001788 pWInfo->iContinue = cont;
drh0aa74ed2005-07-16 13:33:20 +00001789 whereClauseClear(&wc);
drh75897232000-05-29 14:26:00 +00001790 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00001791
1792 /* Jump here if malloc fails */
1793whereBeginNoMem:
1794 whereClauseClear(&wc);
1795 sqliteFree(pWInfo);
1796 return 0;
drh75897232000-05-29 14:26:00 +00001797}
1798
1799/*
drhc27a1ce2002-06-14 20:58:45 +00001800** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00001801** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001802*/
danielk19774adee202004-05-08 08:23:19 +00001803void sqlite3WhereEnd(WhereInfo *pWInfo){
drh75897232000-05-29 14:26:00 +00001804 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001805 int i;
drh6b563442001-11-07 16:48:26 +00001806 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001807 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001808
drh9012bcb2004-12-19 00:11:35 +00001809 /* Generate loop termination code.
1810 */
drhad3cab52002-05-24 02:04:32 +00001811 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001812 pLevel = &pWInfo->a[i];
danielk19774adee202004-05-08 08:23:19 +00001813 sqlite3VdbeResolveLabel(v, pLevel->cont);
drh6b563442001-11-07 16:48:26 +00001814 if( pLevel->op!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001815 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001816 }
danielk19774adee202004-05-08 08:23:19 +00001817 sqlite3VdbeResolveLabel(v, pLevel->brk);
drhe23399f2005-07-22 00:31:39 +00001818 if( pLevel->nIn ){
1819 int *a;
1820 int j;
1821 for(j=pLevel->nIn, a=&pLevel->aInLoop[j*3-3]; j>0; j--, a-=3){
1822 sqlite3VdbeAddOp(v, a[0], a[1], a[2]);
1823 }
1824 sqliteFree(pLevel->aInLoop);
drhd99f7062002-06-08 23:25:08 +00001825 }
drhad2d8302002-05-24 20:31:36 +00001826 if( pLevel->iLeftJoin ){
1827 int addr;
danielk19774adee202004-05-08 08:23:19 +00001828 addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh9012bcb2004-12-19 00:11:35 +00001829 sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
danielk19774adee202004-05-08 08:23:19 +00001830 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
drh9012bcb2004-12-19 00:11:35 +00001831 if( pLevel->iIdxCur>=0 ){
1832 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
drh7f09b3e2002-08-13 13:15:49 +00001833 }
danielk19774adee202004-05-08 08:23:19 +00001834 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
drhad2d8302002-05-24 20:31:36 +00001835 }
drh19a775c2000-06-05 18:54:46 +00001836 }
drh9012bcb2004-12-19 00:11:35 +00001837
1838 /* The "break" point is here, just past the end of the outer loop.
1839 ** Set it.
1840 */
danielk19774adee202004-05-08 08:23:19 +00001841 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00001842
drh29dda4a2005-07-21 18:23:20 +00001843 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00001844 */
drh29dda4a2005-07-21 18:23:20 +00001845 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1846 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001847 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00001848 assert( pTab!=0 );
1849 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001850 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001851 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
1852 }
drh6b563442001-11-07 16:48:26 +00001853 if( pLevel->pIdx!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001854 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
1855 }
1856
drhacf3b982005-01-03 01:27:18 +00001857 /* Make cursor substitutions for cases where we want to use
drh9012bcb2004-12-19 00:11:35 +00001858 ** just the index and never reference the table.
1859 **
1860 ** Calls to the code generator in between sqlite3WhereBegin and
1861 ** sqlite3WhereEnd will have created code that references the table
1862 ** directly. This loop scans all that code looking for opcodes
1863 ** that reference the table and converts them into opcodes that
1864 ** reference the index.
1865 */
drhfe05af82005-07-21 03:14:59 +00001866 if( pLevel->flags & WHERE_IDX_ONLY ){
drh9012bcb2004-12-19 00:11:35 +00001867 int i, j, last;
1868 VdbeOp *pOp;
1869 Index *pIdx = pLevel->pIdx;
1870
1871 assert( pIdx!=0 );
1872 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1873 last = sqlite3VdbeCurrentAddr(v);
1874 for(i=pWInfo->iTop; i<last; i++, pOp++){
1875 if( pOp->p1!=pLevel->iTabCur ) continue;
1876 if( pOp->opcode==OP_Column ){
1877 pOp->p1 = pLevel->iIdxCur;
1878 for(j=0; j<pIdx->nColumn; j++){
1879 if( pOp->p2==pIdx->aiColumn[j] ){
1880 pOp->p2 = j;
1881 break;
1882 }
1883 }
drhf0863fe2005-06-12 21:35:51 +00001884 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00001885 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00001886 pOp->opcode = OP_IdxRowid;
danielk19776c18b6e2005-01-30 09:17:58 +00001887 }else if( pOp->opcode==OP_NullRow ){
1888 pOp->opcode = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001889 }
1890 }
drh6b563442001-11-07 16:48:26 +00001891 }
drh19a775c2000-06-05 18:54:46 +00001892 }
drh9012bcb2004-12-19 00:11:35 +00001893
1894 /* Final cleanup
1895 */
drh75897232000-05-29 14:26:00 +00001896 sqliteFree(pWInfo);
1897 return;
1898}