blob: e98d6542cb72e714493d5ae9911130024c2fcebc [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**
drhed378002005-07-28 23:12:08 +000019** $Id: where.c,v 1.156 2005/07/28 23:12:08 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 */
drh0aa74ed2005-07-16 13:33:20 +000085 u16 flags; /* Bit flags. See below */
drh0fcef5e2005-07-19 17:38:22 +000086 i16 leftCursor; /* Cursor number of X in "X <op> <expr>" */
87 i16 leftColumn; /* Column number of X in "X <op> <expr>" */
drh51147ba2005-07-23 22:59:55 +000088 u16 operator; /* A WO_xx value describing <op> */
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*/
drh51147ba2005-07-23 22:59:55 +000098#define TERM_DYNAMIC 0x0001 /* Need to call sqlite3ExprDelete(pExpr) */
drh0aa74ed2005-07-16 13:33:20 +000099#define TERM_VIRTUAL 0x0002 /* Added by the optimizer. Do not code */
drh0fcef5e2005-07-19 17:38:22 +0000100#define TERM_CODED 0x0004 /* This term is already coded */
drh0aa74ed2005-07-16 13:33:20 +0000101
102/*
103** An instance of the following structure holds all information about a
104** WHERE clause. Mostly this is a container for one or more WhereTerms.
105*/
drh0aa74ed2005-07-16 13:33:20 +0000106struct WhereClause {
drhfe05af82005-07-21 03:14:59 +0000107 Parse *pParse; /* The parser context */
drh0aa74ed2005-07-16 13:33:20 +0000108 int nTerm; /* Number of terms */
109 int nSlot; /* Number of entries in a[] */
drh51147ba2005-07-23 22:59:55 +0000110 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
111 WhereTerm aStatic[10]; /* Initial static space for a[] */
drhe23399f2005-07-22 00:31:39 +0000112};
113
114/*
drh6a3ea0e2003-05-02 14:32:12 +0000115** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000116** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000117**
118** The VDBE cursor numbers are small integers contained in
119** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
120** clause, the cursor numbers might not begin with 0 and they might
121** contain gaps in the numbering sequence. But we want to make maximum
122** use of the bits in our bitmasks. This structure provides a mapping
123** from the sparse cursor numbers into consecutive integers beginning
124** with 0.
125**
126** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
127** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
128**
129** For example, if the WHERE clause expression used these VDBE
130** cursors: 4, 5, 8, 29, 57, 73. Then the ExprMaskSet structure
131** would map those cursor numbers into bits 0 through 5.
132**
133** Note that the mapping is not necessarily ordered. In the example
134** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
135** 57->5, 73->4. Or one of 719 other combinations might be used. It
136** does not really matter. What is important is that sparse cursor
137** numbers all get mapped into bit numbers that begin with 0 and contain
138** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000139*/
140typedef struct ExprMaskSet ExprMaskSet;
141struct ExprMaskSet {
drh1398ad32005-01-19 23:24:50 +0000142 int n; /* Number of assigned cursor values */
143 int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000144};
145
drh0aa74ed2005-07-16 13:33:20 +0000146
drh6a3ea0e2003-05-02 14:32:12 +0000147/*
drh51147ba2005-07-23 22:59:55 +0000148** Bitmasks for the operators that indices are able to exploit. An
149** OR-ed combination of these values can be used when searching for
150** terms in the where clause.
151*/
152#define WO_IN 1
drha6110402005-07-28 20:51:19 +0000153#define WO_EQ 2
drh51147ba2005-07-23 22:59:55 +0000154#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
155#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
156#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
157#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
158
159/*
160** Value for flags returned by bestIndex()
161*/
162#define WHERE_ROWID_EQ 0x0001 /* rowid=EXPR or rowid IN (...) */
163#define WHERE_ROWID_RANGE 0x0002 /* rowid<EXPR and/or rowid>EXPR */
164#define WHERE_COLUMN_EQ 0x0010 /* x=EXPR or x IN (...) */
165#define WHERE_COLUMN_RANGE 0x0020 /* x<EXPR and/or x>EXPR */
166#define WHERE_COLUMN_IN 0x0040 /* x IN (...) */
167#define WHERE_TOP_LIMIT 0x0100 /* x<EXPR or x<=EXPR constraint */
168#define WHERE_BTM_LIMIT 0x0200 /* x>EXPR or x>=EXPR constraint */
169#define WHERE_IDX_ONLY 0x0800 /* Use index only - omit table */
170#define WHERE_ORDERBY 0x1000 /* Output will appear in correct order */
171#define WHERE_REVERSE 0x2000 /* Scan in reverse order */
172
173/*
drh0aa74ed2005-07-16 13:33:20 +0000174** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000175*/
drhfe05af82005-07-21 03:14:59 +0000176static void whereClauseInit(WhereClause *pWC, Parse *pParse){
177 pWC->pParse = pParse;
drh0aa74ed2005-07-16 13:33:20 +0000178 pWC->nTerm = 0;
179 pWC->nSlot = ARRAYSIZE(pWC->aStatic);
180 pWC->a = pWC->aStatic;
181}
182
183/*
184** Deallocate a WhereClause structure. The WhereClause structure
185** itself is not freed. This routine is the inverse of whereClauseInit().
186*/
187static void whereClauseClear(WhereClause *pWC){
188 int i;
189 WhereTerm *a;
190 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
191 if( a->flags & TERM_DYNAMIC ){
drh0fcef5e2005-07-19 17:38:22 +0000192 sqlite3ExprDelete(a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000193 }
194 }
195 if( pWC->a!=pWC->aStatic ){
196 sqliteFree(pWC->a);
197 }
198}
199
200/*
201** Add a new entries to the WhereClause structure. Increase the allocated
202** space as necessary.
203*/
drh0fcef5e2005-07-19 17:38:22 +0000204static WhereTerm *whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
drh0aa74ed2005-07-16 13:33:20 +0000205 WhereTerm *pTerm;
206 if( pWC->nTerm>=pWC->nSlot ){
207 WhereTerm *pOld = pWC->a;
208 pWC->a = sqliteMalloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
drh0fcef5e2005-07-19 17:38:22 +0000209 if( pWC->a==0 ) return 0;
drh0aa74ed2005-07-16 13:33:20 +0000210 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
211 if( pOld!=pWC->aStatic ){
212 sqliteFree(pOld);
213 }
214 pWC->nSlot *= 2;
215 }
drh0fcef5e2005-07-19 17:38:22 +0000216 pTerm = &pWC->a[pWC->nTerm];
217 pTerm->idx = pWC->nTerm;
218 pWC->nTerm++;
219 pTerm->pExpr = p;
drh0aa74ed2005-07-16 13:33:20 +0000220 pTerm->flags = flags;
drh0fcef5e2005-07-19 17:38:22 +0000221 pTerm->pWC = pWC;
222 pTerm->iPartner = -1;
223 return pTerm;
drh0aa74ed2005-07-16 13:33:20 +0000224}
drh75897232000-05-29 14:26:00 +0000225
226/*
drh51669862004-12-18 18:40:26 +0000227** This routine identifies subexpressions in the WHERE clause where
228** each subexpression is separate by the AND operator. aSlot is
229** filled with pointers to the subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000230**
drh51669862004-12-18 18:40:26 +0000231** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
232** \________/ \_______________/ \________________/
233** slot[0] slot[1] slot[2]
234**
235** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000236** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000237**
drh51147ba2005-07-23 22:59:55 +0000238** In the previous sentence and in the diagram, "slot[]" refers to
239** the WhereClause.a[] array. This array grows as needed to contain
240** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000241*/
drh0aa74ed2005-07-16 13:33:20 +0000242static void whereSplit(WhereClause *pWC, Expr *pExpr){
243 if( pExpr==0 ) return;
244 if( pExpr->op!=TK_AND ){
245 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000246 }else{
drh0aa74ed2005-07-16 13:33:20 +0000247 whereSplit(pWC, pExpr->pLeft);
248 whereSplit(pWC, pExpr->pRight);
drh75897232000-05-29 14:26:00 +0000249 }
drh75897232000-05-29 14:26:00 +0000250}
251
252/*
drh6a3ea0e2003-05-02 14:32:12 +0000253** Initialize an expression mask set
254*/
255#define initMaskSet(P) memset(P, 0, sizeof(*P))
256
257/*
drh1398ad32005-01-19 23:24:50 +0000258** Return the bitmask for the given cursor number. Return 0 if
259** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000260*/
drh51669862004-12-18 18:40:26 +0000261static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000262 int i;
263 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000264 if( pMaskSet->ix[i]==iCursor ){
265 return ((Bitmask)1)<<i;
266 }
drh6a3ea0e2003-05-02 14:32:12 +0000267 }
drh6a3ea0e2003-05-02 14:32:12 +0000268 return 0;
269}
270
271/*
drh1398ad32005-01-19 23:24:50 +0000272** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000273**
274** There is one cursor per table in the FROM clause. The number of
275** tables in the FROM clause is limited by a test early in the
276** sqlite3WhereBegin() routien. So we know that the pMaskSet->ix[]
277** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000278*/
279static void createMask(ExprMaskSet *pMaskSet, int iCursor){
drh0fcef5e2005-07-19 17:38:22 +0000280 assert( pMaskSet->n < ARRAYSIZE(pMaskSet->ix) );
281 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000282}
283
284/*
drh75897232000-05-29 14:26:00 +0000285** This routine walks (recursively) an expression tree and generates
286** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000287** tree.
drh75897232000-05-29 14:26:00 +0000288**
289** In order for this routine to work, the calling function must have
drh626a8792005-01-17 22:08:19 +0000290** previously invoked sqlite3ExprResolveNames() on the expression. See
drh75897232000-05-29 14:26:00 +0000291** the header comment on that routine for additional information.
drh626a8792005-01-17 22:08:19 +0000292** The sqlite3ExprResolveNames() routines looks for column names and
drh6a3ea0e2003-05-02 14:32:12 +0000293** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
drh51147ba2005-07-23 22:59:55 +0000294** the VDBE cursor number of the table. This routine just has to
295** translate the cursor numbers into bitmask values and OR all
296** the bitmasks together.
drh75897232000-05-29 14:26:00 +0000297*/
danielk1977b3bce662005-01-29 08:32:43 +0000298static Bitmask exprListTableUsage(ExprMaskSet *, ExprList *);
drh51669862004-12-18 18:40:26 +0000299static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
300 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000301 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000302 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000303 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000304 return mask;
drh75897232000-05-29 14:26:00 +0000305 }
danielk1977b3bce662005-01-29 08:32:43 +0000306 mask = exprTableUsage(pMaskSet, p->pRight);
307 mask |= exprTableUsage(pMaskSet, p->pLeft);
308 mask |= exprListTableUsage(pMaskSet, p->pList);
309 if( p->pSelect ){
310 Select *pS = p->pSelect;
311 mask |= exprListTableUsage(pMaskSet, pS->pEList);
312 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
313 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
314 mask |= exprTableUsage(pMaskSet, pS->pWhere);
315 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drh75897232000-05-29 14:26:00 +0000316 }
danielk1977b3bce662005-01-29 08:32:43 +0000317 return mask;
318}
319static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
320 int i;
321 Bitmask mask = 0;
322 if( pList ){
323 for(i=0; i<pList->nExpr; i++){
324 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000325 }
326 }
drh75897232000-05-29 14:26:00 +0000327 return mask;
328}
329
330/*
drh487ab3c2001-11-08 00:45:21 +0000331** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000332** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000333** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000334*/
335static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000336 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
337 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
338 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
339 assert( TK_GE==TK_EQ+4 );
drh9a432672004-10-04 13:38:09 +0000340 return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
drh487ab3c2001-11-08 00:45:21 +0000341}
342
343/*
drh51669862004-12-18 18:40:26 +0000344** Swap two objects of type T.
drh193bd772004-07-20 18:23:14 +0000345*/
346#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
347
348/*
drh0fcef5e2005-07-19 17:38:22 +0000349** Commute a comparision operator. Expressions of the form "X op Y"
350** are converted into "Y op X".
drh193bd772004-07-20 18:23:14 +0000351*/
drh0fcef5e2005-07-19 17:38:22 +0000352static void exprCommute(Expr *pExpr){
drhfe05af82005-07-21 03:14:59 +0000353 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drh0fcef5e2005-07-19 17:38:22 +0000354 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
355 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
356 if( pExpr->op>=TK_GT ){
357 assert( TK_LT==TK_GT+2 );
358 assert( TK_GE==TK_LE+2 );
359 assert( TK_GT>TK_EQ );
360 assert( TK_GT<TK_LE );
361 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
362 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000363 }
drh193bd772004-07-20 18:23:14 +0000364}
365
366/*
drhfe05af82005-07-21 03:14:59 +0000367** Translate from TK_xx operator to WO_xx bitmask.
368*/
369static int operatorMask(int op){
drh51147ba2005-07-23 22:59:55 +0000370 int c;
drhfe05af82005-07-21 03:14:59 +0000371 assert( allowedOp(op) );
372 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000373 c = WO_IN;
drhfe05af82005-07-21 03:14:59 +0000374 }else{
drh51147ba2005-07-23 22:59:55 +0000375 c = WO_EQ<<(op-TK_EQ);
drhfe05af82005-07-21 03:14:59 +0000376 }
drh51147ba2005-07-23 22:59:55 +0000377 assert( op!=TK_IN || c==WO_IN );
378 assert( op!=TK_EQ || c==WO_EQ );
379 assert( op!=TK_LT || c==WO_LT );
380 assert( op!=TK_LE || c==WO_LE );
381 assert( op!=TK_GT || c==WO_GT );
382 assert( op!=TK_GE || c==WO_GE );
383 return c;
drhfe05af82005-07-21 03:14:59 +0000384}
385
386/*
387** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
388** where X is a reference to the iColumn of table iCur and <op> is one of
389** the WO_xx operator codes specified by the op parameter.
390** Return a pointer to the term. Return 0 if not found.
391*/
392static WhereTerm *findTerm(
393 WhereClause *pWC, /* The WHERE clause to be searched */
394 int iCur, /* Cursor number of LHS */
395 int iColumn, /* Column number of LHS */
396 Bitmask notReady, /* RHS must not overlap with this mask */
drh51147ba2005-07-23 22:59:55 +0000397 u16 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000398 Index *pIdx /* Must be compatible with this index, if not NULL */
399){
400 WhereTerm *pTerm;
401 int k;
402 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
403 if( pTerm->leftCursor==iCur
404 && (pTerm->prereqRight & notReady)==0
405 && pTerm->leftColumn==iColumn
406 && (pTerm->operator & op)!=0
407 ){
408 if( iCur>=0 && pIdx ){
409 Expr *pX = pTerm->pExpr;
410 CollSeq *pColl;
411 char idxaff;
412 int k;
413 Parse *pParse = pWC->pParse;
414
415 idxaff = pIdx->pTable->aCol[iColumn].affinity;
416 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
417 pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
418 if( !pColl ){
419 if( pX->pRight ){
420 pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
421 }
422 if( !pColl ){
423 pColl = pParse->db->pDfltColl;
424 }
425 }
426 for(k=0; k<pIdx->nColumn && pIdx->aiColumn[k]!=iColumn; k++){}
427 assert( k<pIdx->nColumn );
428 if( pColl!=pIdx->keyInfo.aColl[k] ) continue;
429 }
430 return pTerm;
431 }
432 }
433 return 0;
434}
435
436/*
drh0aa74ed2005-07-16 13:33:20 +0000437** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +0000438** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +0000439** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +0000440** structure.
drh51147ba2005-07-23 22:59:55 +0000441**
442** If the expression is of the form "<expr> <op> X" it gets commuted
443** to the standard form of "X <op> <expr>". If the expression is of
444** the form "X <op> Y" where both X and Y are columns, then the original
445** expression is unchanged and a new virtual expression of the form
446** "Y <op> X" is added to the WHERE clause.
drh75897232000-05-29 14:26:00 +0000447*/
drh0fcef5e2005-07-19 17:38:22 +0000448static void exprAnalyze(
449 SrcList *pSrc, /* the FROM clause */
450 ExprMaskSet *pMaskSet, /* table masks */
451 WhereTerm *pTerm /* the WHERE clause term to be analyzed */
452){
453 Expr *pExpr = pTerm->pExpr;
454 Bitmask prereqLeft;
455 Bitmask prereqAll;
456 int idxRight;
457
458 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
459 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
460 pTerm->prereqAll = prereqAll = exprTableUsage(pMaskSet, pExpr);
461 pTerm->leftCursor = -1;
462 pTerm->iPartner = -1;
drhfe05af82005-07-21 03:14:59 +0000463 pTerm->operator = 0;
drh0fcef5e2005-07-19 17:38:22 +0000464 idxRight = -1;
465 if( allowedOp(pExpr->op) && (pTerm->prereqRight & prereqLeft)==0 ){
466 Expr *pLeft = pExpr->pLeft;
467 Expr *pRight = pExpr->pRight;
468 if( pLeft->op==TK_COLUMN ){
469 pTerm->leftCursor = pLeft->iTable;
470 pTerm->leftColumn = pLeft->iColumn;
drhfe05af82005-07-21 03:14:59 +0000471 pTerm->operator = operatorMask(pExpr->op);
drh75897232000-05-29 14:26:00 +0000472 }
drh0fcef5e2005-07-19 17:38:22 +0000473 if( pRight && pRight->op==TK_COLUMN ){
474 WhereTerm *pNew;
475 Expr *pDup;
476 if( pTerm->leftCursor>=0 ){
477 pDup = sqlite3ExprDup(pExpr);
478 pNew = whereClauseInsert(pTerm->pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
479 if( pNew==0 ) return;
480 pNew->iPartner = pTerm->idx;
drhed378002005-07-28 23:12:08 +0000481 pTerm->nPartner = 1;
drh0fcef5e2005-07-19 17:38:22 +0000482 }else{
483 pDup = pExpr;
484 pNew = pTerm;
485 }
486 exprCommute(pDup);
487 pLeft = pDup->pLeft;
488 pNew->leftCursor = pLeft->iTable;
489 pNew->leftColumn = pLeft->iColumn;
490 pNew->prereqRight = prereqLeft;
491 pNew->prereqAll = prereqAll;
drhfe05af82005-07-21 03:14:59 +0000492 pNew->operator = operatorMask(pDup->op);
drh75897232000-05-29 14:26:00 +0000493 }
494 }
drhed378002005-07-28 23:12:08 +0000495
496 /* If a term is the BETWEEN operator, create two new virtual terms
497 ** that define the range that the BETWEEN implements.
498 */
499 else if( pExpr->op==TK_BETWEEN ){
500 ExprList *pList = pExpr->pList;
501 int i;
502 static const u8 ops[] = {TK_GE, TK_LE};
503 assert( pList!=0 );
504 assert( pList->nExpr==2 );
505 for(i=0; i<2; i++){
506 Expr *pNewExpr;
507 WhereTerm *pNewTerm;
508 pNewExpr = sqlite3Expr(ops[i], sqlite3ExprDup(pExpr->pLeft),
509 sqlite3ExprDup(pList->a[i].pExpr), 0);
510 pNewTerm = whereClauseInsert(pTerm->pWC, pNewExpr,
511 TERM_VIRTUAL|TERM_DYNAMIC);
512 exprAnalyze(pSrc, pMaskSet, pNewTerm);
513 pNewTerm->iPartner = pTerm->idx;
514 }
515 pTerm->nPartner = 2;
516 }
517
518
drh75897232000-05-29 14:26:00 +0000519}
520
drh0fcef5e2005-07-19 17:38:22 +0000521
drh75897232000-05-29 14:26:00 +0000522/*
drh51669862004-12-18 18:40:26 +0000523** This routine decides if pIdx can be used to satisfy the ORDER BY
524** clause. If it can, it returns 1. If pIdx cannot satisfy the
525** ORDER BY clause, this routine returns 0.
526**
527** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
528** left-most table in the FROM clause of that same SELECT statement and
529** the table has a cursor number of "base". pIdx is an index on pTab.
530**
531** nEqCol is the number of columns of pIdx that are used as equality
532** constraints. Any of these columns may be missing from the ORDER BY
533** clause and the match can still be a success.
534**
535** If the index is UNIQUE, then the ORDER BY clause is allowed to have
536** additional terms past the end of the index and the match will still
537** be a success.
538**
539** All terms of the ORDER BY that match against the index must be either
540** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
541** index do not need to satisfy this constraint.) The *pbRev value is
542** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
543** the ORDER BY clause is all ASC.
544*/
545static int isSortingIndex(
546 Parse *pParse, /* Parsing context */
547 Index *pIdx, /* The index we are testing */
548 Table *pTab, /* The table to be sorted */
549 int base, /* Cursor number for pTab */
550 ExprList *pOrderBy, /* The ORDER BY clause */
551 int nEqCol, /* Number of index columns with == constraints */
552 int *pbRev /* Set to 1 if ORDER BY is DESC */
553){
554 int i, j; /* Loop counters */
555 int sortOrder; /* Which direction we are sorting */
556 int nTerm; /* Number of ORDER BY terms */
557 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
558 sqlite3 *db = pParse->db;
559
560 assert( pOrderBy!=0 );
561 nTerm = pOrderBy->nExpr;
562 assert( nTerm>0 );
563
drh28c4cf42005-07-27 20:41:43 +0000564 /* A UNIQUE index that is fully specified is always a sorting
565 ** index.
566 */
567 if( pIdx->onError!=OE_None && nEqCol==pIdx->nColumn ){
568 *pbRev = 0;
569 return 1;
570 }
571
drh51669862004-12-18 18:40:26 +0000572 /* Match terms of the ORDER BY clause against columns of
573 ** the index.
574 */
575 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
576 Expr *pExpr; /* The expression of the ORDER BY pTerm */
577 CollSeq *pColl; /* The collating sequence of pExpr */
578
579 pExpr = pTerm->pExpr;
580 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
581 /* Can not use an index sort on anything that is not a column in the
582 ** left-most table of the FROM clause */
583 return 0;
584 }
585 pColl = sqlite3ExprCollSeq(pParse, pExpr);
586 if( !pColl ) pColl = db->pDfltColl;
drh9012bcb2004-12-19 00:11:35 +0000587 if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
588 /* Term j of the ORDER BY clause does not match column i of the index */
589 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +0000590 /* If an index column that is constrained by == fails to match an
591 ** ORDER BY term, that is OK. Just ignore that column of the index
592 */
593 continue;
594 }else{
595 /* If an index column fails to match and is not constrained by ==
596 ** then the index cannot satisfy the ORDER BY constraint.
597 */
598 return 0;
599 }
600 }
601 if( i>nEqCol ){
602 if( pTerm->sortOrder!=sortOrder ){
603 /* Indices can only be used if all ORDER BY terms past the
604 ** equality constraints are all either DESC or ASC. */
605 return 0;
606 }
607 }else{
608 sortOrder = pTerm->sortOrder;
609 }
610 j++;
611 pTerm++;
612 }
613
614 /* The index can be used for sorting if all terms of the ORDER BY clause
615 ** or covered or if we ran out of index columns and the it is a UNIQUE
616 ** index.
617 */
618 if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
619 *pbRev = sortOrder==SQLITE_SO_DESC;
620 return 1;
621 }
622 return 0;
623}
624
625/*
drhb6c29892004-11-22 19:12:19 +0000626** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
627** by sorting in order of ROWID. Return true if so and set *pbRev to be
628** true for reverse ROWID and false for forward ROWID order.
629*/
630static int sortableByRowid(
631 int base, /* Cursor number for table to be sorted */
632 ExprList *pOrderBy, /* The ORDER BY clause */
633 int *pbRev /* Set to 1 if ORDER BY is DESC */
634){
635 Expr *p;
636
637 assert( pOrderBy!=0 );
638 assert( pOrderBy->nExpr>0 );
639 p = pOrderBy->a[0].pExpr;
640 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
641 *pbRev = pOrderBy->a[0].sortOrder;
642 return 1;
643 }
644 return 0;
645}
646
drhfe05af82005-07-21 03:14:59 +0000647/*
drh28c4cf42005-07-27 20:41:43 +0000648** Prepare a crude estimate of the logorithm of the input value.
649** The results need not be exact. This is only used for estimating
650** the total cost of performing operatings with O(logN) or O(NlogN)
651** complexity. Because N is just a guess, it is no great tragedy if
652** logN is a little off.
653**
654** We can assume N>=1.0;
655*/
656static double estLog(double N){
657 double logN = 1.0;
658 double x = 10.0;
659 while( N>x ){
660 logN = logN+1.0;
661 x *= 10;
662 }
663 return logN;
664}
665
666/*
drh51147ba2005-07-23 22:59:55 +0000667** Find the best index for accessing a particular table. Return a pointer
668** to the index, flags that describe how the index should be used, the
drha6110402005-07-28 20:51:19 +0000669** number of equality constraints, and the "cost" for this index.
drh51147ba2005-07-23 22:59:55 +0000670**
671** The lowest cost index wins. The cost is an estimate of the amount of
672** CPU and disk I/O need to process the request using the selected index.
673** Factors that influence cost include:
674**
675** * The estimated number of rows that will be retrieved. (The
676** fewer the better.)
677**
678** * Whether or not sorting must occur.
679**
680** * Whether or not there must be separate lookups in the
681** index and in the main table.
682**
drhfe05af82005-07-21 03:14:59 +0000683*/
684static double bestIndex(
685 Parse *pParse, /* The parsing context */
686 WhereClause *pWC, /* The WHERE clause */
687 struct SrcList_item *pSrc, /* The FROM clause term to search */
688 Bitmask notReady, /* Mask of cursors that are not available */
689 ExprList *pOrderBy, /* The order by clause */
690 Index **ppIndex, /* Make *ppIndex point to the best index */
drh51147ba2005-07-23 22:59:55 +0000691 int *pFlags, /* Put flags describing this choice in *pFlags */
692 int *pnEq /* Put the number of == or IN constraints here */
drhfe05af82005-07-21 03:14:59 +0000693){
694 WhereTerm *pTerm;
drh51147ba2005-07-23 22:59:55 +0000695 Index *bestIdx = 0; /* Index that gives the lowest cost */
696 double lowestCost = 1.0e99; /* The cost of using bestIdx */
697 int bestFlags = 0; /* Flags associated with bestIdx */
698 int bestNEq = 0; /* Best value for nEq */
699 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
700 Index *pProbe; /* An index we are evaluating */
701 int rev; /* True to scan in reverse order */
702 int flags; /* Flags associated with pProbe */
703 int nEq; /* Number of == or IN constraints */
704 double cost; /* Cost of using pProbe */
drhfe05af82005-07-21 03:14:59 +0000705
drh51147ba2005-07-23 22:59:55 +0000706 TRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
707
708 /* Check for a rowid=EXPR or rowid IN (...) constraints
drhfe05af82005-07-21 03:14:59 +0000709 */
710 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
711 if( pTerm ){
drha6110402005-07-28 20:51:19 +0000712 Expr *pExpr;
drhfe05af82005-07-21 03:14:59 +0000713 *ppIndex = 0;
drh51147ba2005-07-23 22:59:55 +0000714 bestFlags = WHERE_ROWID_EQ;
drhfe05af82005-07-21 03:14:59 +0000715 if( pTerm->operator & WO_EQ ){
drh28c4cf42005-07-27 20:41:43 +0000716 /* Rowid== is always the best pick. Look no further. Because only
717 ** a single row is generated, output is always in sorted order */
drhfe05af82005-07-21 03:14:59 +0000718 *pFlags = WHERE_ROWID_EQ;
drh51147ba2005-07-23 22:59:55 +0000719 *pnEq = 1;
drhfe05af82005-07-21 03:14:59 +0000720 if( pOrderBy ) *pFlags |= WHERE_ORDERBY;
drh51147ba2005-07-23 22:59:55 +0000721 TRACE(("... best is rowid\n"));
722 return 0.0;
drha6110402005-07-28 20:51:19 +0000723 }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
drh28c4cf42005-07-27 20:41:43 +0000724 /* Rowid IN (LIST): cost is NlogN where N is the number of list
725 ** elements. */
drha6110402005-07-28 20:51:19 +0000726 lowestCost = pExpr->pList->nExpr;
drh28c4cf42005-07-27 20:41:43 +0000727 lowestCost *= estLog(lowestCost);
drhfe05af82005-07-21 03:14:59 +0000728 }else{
drh28c4cf42005-07-27 20:41:43 +0000729 /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
730 ** in the result of the inner select. We have no way to estimate
731 ** that value so make a wild guess. */
732 lowestCost = 200.0;
drhfe05af82005-07-21 03:14:59 +0000733 }
drh3adc9ce2005-07-28 16:51:51 +0000734 TRACE(("... rowid IN cost: %.9g\n", lowestCost));
drhfe05af82005-07-21 03:14:59 +0000735 }
736
drh28c4cf42005-07-27 20:41:43 +0000737 /* Estimate the cost of a table scan. If we do not know how many
738 ** entries are in the table, use 1 million as a guess.
drhfe05af82005-07-21 03:14:59 +0000739 */
drh51147ba2005-07-23 22:59:55 +0000740 pProbe = pSrc->pTab->pIndex;
drh28c4cf42005-07-27 20:41:43 +0000741 cost = pProbe ? pProbe->aiRowEst[0] : 1000000.0;
drh3adc9ce2005-07-28 16:51:51 +0000742 TRACE(("... table scan base cost: %.9g\n", cost));
drh28c4cf42005-07-27 20:41:43 +0000743 flags = WHERE_ROWID_RANGE;
744
745 /* Check for constraints on a range of rowids in a table scan.
746 */
drhfe05af82005-07-21 03:14:59 +0000747 pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
748 if( pTerm ){
drh51147ba2005-07-23 22:59:55 +0000749 if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
750 flags |= WHERE_TOP_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000751 cost *= 0.333; /* Guess that rowid<EXPR eliminates two-thirds or rows */
drhfe05af82005-07-21 03:14:59 +0000752 }
drh51147ba2005-07-23 22:59:55 +0000753 if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
754 flags |= WHERE_BTM_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000755 cost *= 0.333; /* Guess that rowid>EXPR eliminates two-thirds of rows */
drhfe05af82005-07-21 03:14:59 +0000756 }
drh3adc9ce2005-07-28 16:51:51 +0000757 TRACE(("... rowid range reduces cost to %.9g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000758 }else{
759 flags = 0;
760 }
drh28c4cf42005-07-27 20:41:43 +0000761
762 /* If the table scan does not satisfy the ORDER BY clause, increase
763 ** the cost by NlogN to cover the expense of sorting. */
764 if( pOrderBy ){
765 if( sortableByRowid(iCur, pOrderBy, &rev) ){
766 flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
767 if( rev ){
768 flags |= WHERE_REVERSE;
769 }
770 }else{
771 cost += cost*estLog(cost);
drh3adc9ce2005-07-28 16:51:51 +0000772 TRACE(("... sorting increases cost to %.9g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000773 }
drh51147ba2005-07-23 22:59:55 +0000774 }
775 if( cost<lowestCost ){
776 lowestCost = cost;
drhfe05af82005-07-21 03:14:59 +0000777 bestFlags = flags;
778 }
779
780 /* Look at each index.
781 */
drh51147ba2005-07-23 22:59:55 +0000782 for(; pProbe; pProbe=pProbe->pNext){
783 int i; /* Loop counter */
drh28c4cf42005-07-27 20:41:43 +0000784 double inMultiplier = 1.0;
drh51147ba2005-07-23 22:59:55 +0000785
786 TRACE(("... index %s:\n", pProbe->zName));
drhfe05af82005-07-21 03:14:59 +0000787
788 /* Count the number of columns in the index that are satisfied
789 ** by x=EXPR constraints or x IN (...) constraints.
790 */
drh51147ba2005-07-23 22:59:55 +0000791 flags = 0;
drhfe05af82005-07-21 03:14:59 +0000792 for(i=0; i<pProbe->nColumn; i++){
793 int j = pProbe->aiColumn[i];
794 pTerm = findTerm(pWC, iCur, j, notReady, WO_EQ|WO_IN, pProbe);
795 if( pTerm==0 ) break;
drh51147ba2005-07-23 22:59:55 +0000796 flags |= WHERE_COLUMN_EQ;
797 if( pTerm->operator & WO_IN ){
drha6110402005-07-28 20:51:19 +0000798 Expr *pExpr = pTerm->pExpr;
drh51147ba2005-07-23 22:59:55 +0000799 flags |= WHERE_COLUMN_IN;
drha6110402005-07-28 20:51:19 +0000800 if( pExpr->pSelect!=0 ){
drh51147ba2005-07-23 22:59:55 +0000801 inMultiplier *= 100.0;
drha6110402005-07-28 20:51:19 +0000802 }else if( pExpr->pList!=0 ){
803 inMultiplier *= pExpr->pList->nExpr + 1.0;
drhfe05af82005-07-21 03:14:59 +0000804 }
805 }
806 }
drh28c4cf42005-07-27 20:41:43 +0000807 cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
drh51147ba2005-07-23 22:59:55 +0000808 nEq = i;
drh3adc9ce2005-07-28 16:51:51 +0000809 TRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n", nEq, inMultiplier, cost));
drhfe05af82005-07-21 03:14:59 +0000810
drh51147ba2005-07-23 22:59:55 +0000811 /* Look for range constraints
drhfe05af82005-07-21 03:14:59 +0000812 */
drh51147ba2005-07-23 22:59:55 +0000813 if( nEq<pProbe->nColumn ){
814 int j = pProbe->aiColumn[nEq];
815 pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
816 if( pTerm ){
drha6110402005-07-28 20:51:19 +0000817 flags |= WHERE_COLUMN_RANGE;
drh51147ba2005-07-23 22:59:55 +0000818 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
819 flags |= WHERE_TOP_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000820 cost *= 0.333;
drh51147ba2005-07-23 22:59:55 +0000821 }
822 if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
823 flags |= WHERE_BTM_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000824 cost *= 0.333;
drh51147ba2005-07-23 22:59:55 +0000825 }
drh3adc9ce2005-07-28 16:51:51 +0000826 TRACE(("...... range reduces cost to %.9g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000827 }
828 }
829
drh28c4cf42005-07-27 20:41:43 +0000830 /* Add the additional cost of sorting if that is a factor.
drh51147ba2005-07-23 22:59:55 +0000831 */
drh28c4cf42005-07-27 20:41:43 +0000832 if( pOrderBy ){
833 if( (flags & WHERE_COLUMN_IN)==0 &&
drhfe05af82005-07-21 03:14:59 +0000834 isSortingIndex(pParse, pProbe, pSrc->pTab, iCur, pOrderBy, nEq, &rev) ){
drh28c4cf42005-07-27 20:41:43 +0000835 if( flags==0 ){
836 flags = WHERE_COLUMN_RANGE;
837 }
838 flags |= WHERE_ORDERBY;
839 if( rev ){
840 flags |= WHERE_REVERSE;
841 }
842 }else{
843 cost += cost*estLog(cost);
drh3adc9ce2005-07-28 16:51:51 +0000844 TRACE(("...... orderby increases cost to %.9g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000845 }
drhfe05af82005-07-21 03:14:59 +0000846 }
847
848 /* Check to see if we can get away with using just the index without
drh51147ba2005-07-23 22:59:55 +0000849 ** ever reading the table. If that is the case, then halve the
850 ** cost of this index.
drhfe05af82005-07-21 03:14:59 +0000851 */
drh51147ba2005-07-23 22:59:55 +0000852 if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
drhfe05af82005-07-21 03:14:59 +0000853 Bitmask m = pSrc->colUsed;
854 int j;
855 for(j=0; j<pProbe->nColumn; j++){
856 int x = pProbe->aiColumn[j];
857 if( x<BMS-1 ){
858 m &= ~(((Bitmask)1)<<x);
859 }
860 }
861 if( m==0 ){
862 flags |= WHERE_IDX_ONLY;
drh51147ba2005-07-23 22:59:55 +0000863 cost *= 0.5;
drh3adc9ce2005-07-28 16:51:51 +0000864 TRACE(("...... idx-only reduces cost to %.9g\n", cost));
drhfe05af82005-07-21 03:14:59 +0000865 }
866 }
867
drh51147ba2005-07-23 22:59:55 +0000868 /* If this index has achieved the lowest cost so far, then use it.
drhfe05af82005-07-21 03:14:59 +0000869 */
drh51147ba2005-07-23 22:59:55 +0000870 if( cost < lowestCost ){
drhfe05af82005-07-21 03:14:59 +0000871 bestIdx = pProbe;
drh51147ba2005-07-23 22:59:55 +0000872 lowestCost = cost;
drha6110402005-07-28 20:51:19 +0000873 assert( flags!=0 );
drhfe05af82005-07-21 03:14:59 +0000874 bestFlags = flags;
drh51147ba2005-07-23 22:59:55 +0000875 bestNEq = nEq;
drhfe05af82005-07-21 03:14:59 +0000876 }
877 }
878
drhfe05af82005-07-21 03:14:59 +0000879 /* Report the best result
880 */
881 *ppIndex = bestIdx;
drh3adc9ce2005-07-28 16:51:51 +0000882 TRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
drh51147ba2005-07-23 22:59:55 +0000883 bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
drhfe05af82005-07-21 03:14:59 +0000884 *pFlags = bestFlags;
drh51147ba2005-07-23 22:59:55 +0000885 *pnEq = bestNEq;
886 return lowestCost;
drhfe05af82005-07-21 03:14:59 +0000887}
888
drhb6c29892004-11-22 19:12:19 +0000889
890/*
drh2ffb1182004-07-19 19:14:01 +0000891** Disable a term in the WHERE clause. Except, do not disable the term
892** if it controls a LEFT OUTER JOIN and it did not originate in the ON
893** or USING clause of that join.
894**
895** Consider the term t2.z='ok' in the following queries:
896**
897** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
898** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
899** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
900**
drh23bf66d2004-12-14 03:34:34 +0000901** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +0000902** in the ON clause. The term is disabled in (3) because it is not part
903** of a LEFT OUTER JOIN. In (1), the term is not disabled.
904**
905** Disabling a term causes that term to not be tested in the inner loop
906** of the join. Disabling is an optimization. We would get the correct
907** results if nothing were ever disabled, but joins might run a little
908** slower. The trick is to disable as much as we can without disabling
909** too much. If we disabled in (1), we'd get the wrong answer.
910** See ticket #813.
911*/
drh0fcef5e2005-07-19 17:38:22 +0000912static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
913 if( pTerm
914 && (pTerm->flags & TERM_CODED)==0
915 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
916 ){
917 pTerm->flags |= TERM_CODED;
918 if( pTerm->iPartner>=0 ){
drhed378002005-07-28 23:12:08 +0000919 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iPartner];
920 if( (--pOther->nPartner)<=0 ){
921 disableTerm(pLevel, pOther);
922 }
drh0fcef5e2005-07-19 17:38:22 +0000923 }
drh2ffb1182004-07-19 19:14:01 +0000924 }
925}
926
927/*
drh94a11212004-09-25 13:12:14 +0000928** Generate code that builds a probe for an index. Details:
929**
930** * Check the top nColumn entries on the stack. If any
931** of those entries are NULL, jump immediately to brk,
932** which is the loop exit, since no index entry will match
933** if any part of the key is NULL.
934**
935** * Construct a probe entry from the top nColumn entries in
936** the stack with affinities appropriate for index pIdx.
937*/
938static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
939 sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
940 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
941 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
942 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
943 sqlite3IndexAffinityStr(v, pIdx);
944}
945
drhe8b97272005-07-19 22:22:12 +0000946
947/*
drh51147ba2005-07-23 22:59:55 +0000948** Generate code for a single equality term of the WHERE clause. An equality
949** term can be either X=expr or X IN (...). pTerm is the term to be
950** coded.
951**
952** The current value for the constraint is left on the top of the stack.
953**
954** For a constraint of the form X=expr, the expression is evaluated and its
955** result is left on the stack. For constraints of the form X IN (...)
956** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +0000957*/
958static void codeEqualityTerm(
959 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +0000960 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh94a11212004-09-25 13:12:14 +0000961 int brk, /* Jump here to abandon the loop */
962 WhereLevel *pLevel /* When level of the FROM clause we are working on */
963){
drh0fcef5e2005-07-19 17:38:22 +0000964 Expr *pX = pTerm->pExpr;
drh94a11212004-09-25 13:12:14 +0000965 if( pX->op!=TK_IN ){
966 assert( pX->op==TK_EQ );
967 sqlite3ExprCode(pParse, pX->pRight);
danielk1977b3bce662005-01-29 08:32:43 +0000968#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +0000969 }else{
danielk1977b3bce662005-01-29 08:32:43 +0000970 int iTab;
drhe23399f2005-07-22 00:31:39 +0000971 int *aIn;
drh94a11212004-09-25 13:12:14 +0000972 Vdbe *v = pParse->pVdbe;
danielk1977b3bce662005-01-29 08:32:43 +0000973
974 sqlite3CodeSubselect(pParse, pX);
975 iTab = pX->iTable;
drh94a11212004-09-25 13:12:14 +0000976 sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
danielk1977b3bce662005-01-29 08:32:43 +0000977 VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
drhe23399f2005-07-22 00:31:39 +0000978 pLevel->nIn++;
979 pLevel->aInLoop = aIn = sqliteRealloc(pLevel->aInLoop,
980 sizeof(pLevel->aInLoop[0])*3*pLevel->nIn);
981 if( aIn ){
982 aIn += pLevel->nIn*3 - 3;
983 aIn[0] = OP_Next;
984 aIn[1] = iTab;
985 aIn[2] = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
drha6110402005-07-28 20:51:19 +0000986 }else{
987 pLevel->nIn = 0;
drhe23399f2005-07-22 00:31:39 +0000988 }
danielk1977b3bce662005-01-29 08:32:43 +0000989#endif
drh94a11212004-09-25 13:12:14 +0000990 }
drh0fcef5e2005-07-19 17:38:22 +0000991 disableTerm(pLevel, pTerm);
drh94a11212004-09-25 13:12:14 +0000992}
993
drh51147ba2005-07-23 22:59:55 +0000994/*
995** Generate code that will evaluate all == and IN constraints for an
996** index. The values for all constraints are left on the stack.
997**
998** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
999** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
1000** The index has as many as three equality constraints, but in this
1001** example, the third "c" value is an inequality. So only two
1002** constraints are coded. This routine will generate code to evaluate
1003** a==5 and b IN (1,2,3). The current values for a and b will be left
1004** on the stack - a is the deepest and b the shallowest.
1005**
1006** In the example above nEq==2. But this subroutine works for any value
1007** of nEq including 0. If nEq==0, this routine is nearly a no-op.
1008** The only thing it does is allocate the pLevel->iMem memory cell.
1009**
1010** This routine always allocates at least one memory cell and puts
1011** the address of that memory cell in pLevel->iMem. The code that
1012** calls this routine will use pLevel->iMem to store the termination
1013** key value of the loop. If one or more IN operators appear, then
1014** this routine allocates an additional nEq memory cells for internal
1015** use.
1016*/
1017static void codeAllEqualityTerms(
1018 Parse *pParse, /* Parsing context */
1019 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
1020 WhereClause *pWC, /* The WHERE clause */
1021 Bitmask notReady, /* Which parts of FROM have not yet been coded */
1022 int brk /* Jump here to end the loop */
1023){
1024 int nEq = pLevel->nEq; /* The number of == or IN constraints to code */
1025 int termsInMem = 0; /* If true, store value in mem[] cells */
1026 Vdbe *v = pParse->pVdbe; /* The virtual machine under construction */
1027 Index *pIdx = pLevel->pIdx; /* The index being used for this loop */
1028 int iCur = pLevel->iTabCur; /* The cursor of the table */
1029 WhereTerm *pTerm; /* A single constraint term */
1030 int j; /* Loop counter */
1031
1032 /* Figure out how many memory cells we will need then allocate them.
1033 ** We always need at least one used to store the loop terminator
1034 ** value. If there are IN operators we'll need one for each == or
1035 ** IN constraint.
1036 */
1037 pLevel->iMem = pParse->nMem++;
1038 if( pLevel->flags & WHERE_COLUMN_IN ){
1039 pParse->nMem += pLevel->nEq;
1040 termsInMem = 1;
1041 }
1042
1043 /* Evaluate the equality constraints
1044 */
1045 for(j=0; 1; j++){
1046 int k = pIdx->aiColumn[j];
1047 pTerm = findTerm(pWC, iCur, k, notReady, WO_EQ|WO_IN, pIdx);
1048 if( pTerm==0 ) break;
1049 assert( (pTerm->flags & TERM_CODED)==0 );
1050 codeEqualityTerm(pParse, pTerm, brk, pLevel);
1051 if( termsInMem ){
1052 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1);
1053 }
1054 }
1055 assert( j==nEq );
1056
1057 /* Make sure all the constraint values are on the top of the stack
1058 */
1059 if( termsInMem ){
1060 for(j=0; j<nEq; j++){
1061 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem+j+1, 0);
1062 }
1063 }
1064}
1065
drh84bfda42005-07-15 13:05:21 +00001066#ifdef SQLITE_TEST
1067/*
1068** The following variable holds a text description of query plan generated
1069** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
1070** overwrites the previous. This information is used for testing and
1071** analysis only.
1072*/
1073char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
1074static int nQPlan = 0; /* Next free slow in _query_plan[] */
1075
1076#endif /* SQLITE_TEST */
1077
1078
drh94a11212004-09-25 13:12:14 +00001079
1080/*
drhe3184742002-06-19 14:27:05 +00001081** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00001082** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00001083** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00001084** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00001085** in order to complete the WHERE clause processing.
1086**
1087** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00001088**
1089** The basic idea is to do a nested loop, one loop for each table in
1090** the FROM clause of a select. (INSERT and UPDATE statements are the
1091** same as a SELECT with only a single table in the FROM clause.) For
1092** example, if the SQL is this:
1093**
1094** SELECT * FROM t1, t2, t3 WHERE ...;
1095**
1096** Then the code generated is conceptually like the following:
1097**
1098** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00001099** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00001100** foreach row3 in t3 do /
1101** ...
1102** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00001103** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00001104** end /
1105**
drh29dda4a2005-07-21 18:23:20 +00001106** Note that the loops might not be nested in the order in which they
1107** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00001108** use of indices. Note also that when the IN operator appears in
1109** the WHERE clause, it might result in additional nested loops for
1110** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00001111**
drhc27a1ce2002-06-14 20:58:45 +00001112** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00001113** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
1114** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00001115** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00001116**
drhe6f85e72004-12-25 01:03:13 +00001117** The code that sqlite3WhereBegin() generates leaves the cursors named
1118** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00001119** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00001120** data from the various tables of the loop.
1121**
drhc27a1ce2002-06-14 20:58:45 +00001122** If the WHERE clause is empty, the foreach loops must each scan their
1123** entire tables. Thus a three-way join is an O(N^3) operation. But if
1124** the tables have indices and there are terms in the WHERE clause that
1125** refer to those indices, a complete table scan can be avoided and the
1126** code will run much faster. Most of the work of this routine is checking
1127** to see if there are indices that can be used to speed up the loop.
1128**
1129** Terms of the WHERE clause are also used to limit which rows actually
1130** make it to the "..." in the middle of the loop. After each "foreach",
1131** terms of the WHERE clause that use only terms in that loop and outer
1132** loops are evaluated and if false a jump is made around all subsequent
1133** inner loops (or around the "..." if the test occurs within the inner-
1134** most loop)
1135**
1136** OUTER JOINS
1137**
1138** An outer join of tables t1 and t2 is conceptally coded as follows:
1139**
1140** foreach row1 in t1 do
1141** flag = 0
1142** foreach row2 in t2 do
1143** start:
1144** ...
1145** flag = 1
1146** end
drhe3184742002-06-19 14:27:05 +00001147** if flag==0 then
1148** move the row2 cursor to a null row
1149** goto start
1150** fi
drhc27a1ce2002-06-14 20:58:45 +00001151** end
1152**
drhe3184742002-06-19 14:27:05 +00001153** ORDER BY CLAUSE PROCESSING
1154**
1155** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
1156** if there is one. If there is no ORDER BY clause or if this routine
1157** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
1158**
1159** If an index can be used so that the natural output order of the table
1160** scan is correct for the ORDER BY clause, then that index is used and
1161** *ppOrderBy is set to NULL. This is an optimization that prevents an
1162** unnecessary sort of the result set if an index appropriate for the
1163** ORDER BY clause already exists.
1164**
1165** If the where clause loops cannot be arranged to provide the correct
1166** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +00001167*/
danielk19774adee202004-05-08 08:23:19 +00001168WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00001169 Parse *pParse, /* The parser context */
1170 SrcList *pTabList, /* A list of all tables to be scanned */
1171 Expr *pWhere, /* The WHERE clause */
drhf8db1bc2005-04-22 02:38:37 +00001172 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +00001173){
1174 int i; /* Loop counter */
1175 WhereInfo *pWInfo; /* Will become the return value of this function */
1176 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhd4f5ee22003-07-16 00:54:31 +00001177 int brk, cont = 0; /* Addresses used during code generation */
drhfe05af82005-07-21 03:14:59 +00001178 Bitmask notReady; /* Cursors that are not yet positioned */
drh0aa74ed2005-07-16 13:33:20 +00001179 WhereTerm *pTerm; /* A single term in the WHERE clause */
1180 ExprMaskSet maskSet; /* The expression mask set */
drh0aa74ed2005-07-16 13:33:20 +00001181 WhereClause wc; /* The WHERE clause is divided into these terms */
drh9012bcb2004-12-19 00:11:35 +00001182 struct SrcList_item *pTabItem; /* A single entry from pTabList */
1183 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh29dda4a2005-07-21 18:23:20 +00001184 int iFrom; /* First unused FROM clause element */
drh75897232000-05-29 14:26:00 +00001185
drh29dda4a2005-07-21 18:23:20 +00001186 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00001187 ** bits in a Bitmask
1188 */
drh29dda4a2005-07-21 18:23:20 +00001189 if( pTabList->nSrc>BMS ){
1190 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00001191 return 0;
1192 }
1193
drh83dcb1a2002-06-28 01:02:38 +00001194 /* Split the WHERE clause into separate subexpressions where each
drh29dda4a2005-07-21 18:23:20 +00001195 ** subexpression is separated by an AND operator.
drh83dcb1a2002-06-28 01:02:38 +00001196 */
drh6a3ea0e2003-05-02 14:32:12 +00001197 initMaskSet(&maskSet);
drhfe05af82005-07-21 03:14:59 +00001198 whereClauseInit(&wc, pParse);
drh0aa74ed2005-07-16 13:33:20 +00001199 whereSplit(&wc, pWhere);
drh1398ad32005-01-19 23:24:50 +00001200
drh75897232000-05-29 14:26:00 +00001201 /* Allocate and initialize the WhereInfo structure that will become the
1202 ** return value.
1203 */
drhad3cab52002-05-24 02:04:32 +00001204 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
danielk1977132872b2004-05-10 10:37:18 +00001205 if( sqlite3_malloc_failed ){
drhe23399f2005-07-22 00:31:39 +00001206 goto whereBeginNoMem;
drh75897232000-05-29 14:26:00 +00001207 }
1208 pWInfo->pParse = pParse;
1209 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +00001210 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh08192d52002-04-30 19:20:28 +00001211
1212 /* Special case: a WHERE clause that is constant. Evaluate the
1213 ** expression and either jump over all of the code or fall thru.
1214 */
danielk19774adee202004-05-08 08:23:19 +00001215 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
1216 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +00001217 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00001218 }
drh75897232000-05-29 14:26:00 +00001219
drh29dda4a2005-07-21 18:23:20 +00001220 /* Analyze all of the subexpressions. Note that exprAnalyze() might
1221 ** add new virtual terms onto the end of the WHERE clause. We do not
1222 ** want to analyze these virtual terms, so start analyzing at the end
1223 ** and work forward so that they added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00001224 */
drh1398ad32005-01-19 23:24:50 +00001225 for(i=0; i<pTabList->nSrc; i++){
1226 createMask(&maskSet, pTabList->a[i].iCursor);
1227 }
drh0fcef5e2005-07-19 17:38:22 +00001228 for(i=wc.nTerm-1; i>=0; i--){
1229 exprAnalyze(pTabList, &maskSet, &wc.a[i]);
drh75897232000-05-29 14:26:00 +00001230 }
1231
drh29dda4a2005-07-21 18:23:20 +00001232 /* Chose the best index to use for each table in the FROM clause.
1233 **
drh51147ba2005-07-23 22:59:55 +00001234 ** This loop fills in the following fields:
1235 **
1236 ** pWInfo->a[].pIdx The index to use for this level of the loop.
1237 ** pWInfo->a[].flags WHERE_xxx flags associated with pIdx
1238 ** pWInfo->a[].nEq The number of == and IN constraints
1239 ** pWInfo->a[].iFrom When term of the FROM clause is being coded
1240 ** pWInfo->a[].iTabCur The VDBE cursor for the database table
1241 ** pWInfo->a[].iIdxCur The VDBE cursor for the index
1242 **
1243 ** This loop also figures out the nesting order of tables in the FROM
1244 ** clause.
drh75897232000-05-29 14:26:00 +00001245 */
drhfe05af82005-07-21 03:14:59 +00001246 notReady = ~(Bitmask)0;
drh9012bcb2004-12-19 00:11:35 +00001247 pTabItem = pTabList->a;
1248 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001249 for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1250 Index *pIdx; /* Index for FROM table at pTabItem */
1251 int flags; /* Flags asssociated with pIdx */
drh51147ba2005-07-23 22:59:55 +00001252 int nEq; /* Number of == or IN constraints */
1253 double cost; /* The cost for pIdx */
drh29dda4a2005-07-21 18:23:20 +00001254 int j; /* For looping over FROM tables */
1255 Index *pBest = 0; /* The best index seen so far */
1256 int bestFlags = 0; /* Flags associated with pBest */
drh51147ba2005-07-23 22:59:55 +00001257 int bestNEq = 0; /* nEq associated with pBest */
1258 double lowestCost = 1.0e99; /* Cost of the pBest */
drh29dda4a2005-07-21 18:23:20 +00001259 int bestJ; /* The value of j */
1260 Bitmask m; /* Bitmask value for j or bestJ */
1261
1262 for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
1263 m = getMask(&maskSet, pTabItem->iCursor);
1264 if( (m & notReady)==0 ){
1265 if( j==iFrom ) iFrom++;
1266 continue;
1267 }
drh51147ba2005-07-23 22:59:55 +00001268 cost = bestIndex(pParse, &wc, pTabItem, notReady,
1269 (j==0 && ppOrderBy) ? *ppOrderBy : 0,
1270 &pIdx, &flags, &nEq);
1271 if( cost<lowestCost ){
1272 lowestCost = cost;
drh29dda4a2005-07-21 18:23:20 +00001273 pBest = pIdx;
1274 bestFlags = flags;
drh51147ba2005-07-23 22:59:55 +00001275 bestNEq = nEq;
drh29dda4a2005-07-21 18:23:20 +00001276 bestJ = j;
1277 }
1278 if( (pTabItem->jointype & JT_LEFT)!=0
1279 || (j>0 && (pTabItem[-1].jointype & JT_LEFT)!=0)
1280 ){
1281 break;
1282 }
1283 }
1284 if( bestFlags & WHERE_ORDERBY ){
drhfe05af82005-07-21 03:14:59 +00001285 *ppOrderBy = 0;
drhc4a3c772001-04-04 11:48:57 +00001286 }
drh29dda4a2005-07-21 18:23:20 +00001287 pLevel->flags = bestFlags;
drhfe05af82005-07-21 03:14:59 +00001288 pLevel->pIdx = pBest;
drh51147ba2005-07-23 22:59:55 +00001289 pLevel->nEq = bestNEq;
drhe23399f2005-07-22 00:31:39 +00001290 pLevel->aInLoop = 0;
1291 pLevel->nIn = 0;
drhfe05af82005-07-21 03:14:59 +00001292 if( pBest ){
drh9012bcb2004-12-19 00:11:35 +00001293 pLevel->iIdxCur = pParse->nTab++;
drhfe05af82005-07-21 03:14:59 +00001294 }else{
1295 pLevel->iIdxCur = -1;
drh6b563442001-11-07 16:48:26 +00001296 }
drh29dda4a2005-07-21 18:23:20 +00001297 notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
1298 pLevel->iFrom = bestJ;
drh75897232000-05-29 14:26:00 +00001299 }
1300
drh9012bcb2004-12-19 00:11:35 +00001301 /* Open all tables in the pTabList and any indices selected for
1302 ** searching those tables.
1303 */
1304 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
1305 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001306 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drh9012bcb2004-12-19 00:11:35 +00001307 Table *pTab;
1308 Index *pIx;
1309 int iIdxCur = pLevel->iIdxCur;
1310
drh29dda4a2005-07-21 18:23:20 +00001311 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001312 pTab = pTabItem->pTab;
1313 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001314 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001315 sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
1316 }
1317 pLevel->iTabCur = pTabItem->iCursor;
1318 if( (pIx = pLevel->pIdx)!=0 ){
1319 sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
drh29dda4a2005-07-21 18:23:20 +00001320 VdbeComment((v, "# %s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00001321 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
1322 (char*)&pIx->keyInfo, P3_KEYINFO);
1323 }
drhfe05af82005-07-21 03:14:59 +00001324 if( (pLevel->flags & WHERE_IDX_ONLY)!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001325 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
1326 }
1327 sqlite3CodeVerifySchema(pParse, pTab->iDb);
1328 }
1329 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
1330
drh29dda4a2005-07-21 18:23:20 +00001331 /* Generate the code to do the search. Each iteration of the for
1332 ** loop below generates code for a single nested loop of the VM
1333 ** program.
drh75897232000-05-29 14:26:00 +00001334 */
drhfe05af82005-07-21 03:14:59 +00001335 notReady = ~(Bitmask)0;
drh29dda4a2005-07-21 18:23:20 +00001336 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drhfe05af82005-07-21 03:14:59 +00001337 int j;
drh9012bcb2004-12-19 00:11:35 +00001338 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
1339 Index *pIdx; /* The index we will be using */
1340 int iIdxCur; /* The VDBE cursor for the index */
1341 int omitTable; /* True if we use the index only */
drh29dda4a2005-07-21 18:23:20 +00001342 int bRev; /* True if we need to scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001343
drh29dda4a2005-07-21 18:23:20 +00001344 pTabItem = &pTabList->a[pLevel->iFrom];
1345 iCur = pTabItem->iCursor;
drh9012bcb2004-12-19 00:11:35 +00001346 pIdx = pLevel->pIdx;
1347 iIdxCur = pLevel->iIdxCur;
drh29dda4a2005-07-21 18:23:20 +00001348 bRev = (pLevel->flags & WHERE_REVERSE)!=0;
drhfe05af82005-07-21 03:14:59 +00001349 omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
drh75897232000-05-29 14:26:00 +00001350
drh29dda4a2005-07-21 18:23:20 +00001351 /* Create labels for the "break" and "continue" instructions
1352 ** for the current loop. Jump to brk to break out of a loop.
1353 ** Jump to cont to go immediately to the next iteration of the
1354 ** loop.
1355 */
1356 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1357 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1358
drhad2d8302002-05-24 20:31:36 +00001359 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +00001360 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +00001361 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +00001362 */
drh29dda4a2005-07-21 18:23:20 +00001363 if( pLevel->iFrom>0 && (pTabItem[-1].jointype & JT_LEFT)!=0 ){
drhad2d8302002-05-24 20:31:36 +00001364 if( !pParse->nMem ) pParse->nMem++;
1365 pLevel->iLeftJoin = pParse->nMem++;
drhf0863fe2005-06-12 21:35:51 +00001366 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001367 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001368 VdbeComment((v, "# init LEFT JOIN no-match flag"));
drhad2d8302002-05-24 20:31:36 +00001369 }
1370
drhfe05af82005-07-21 03:14:59 +00001371 if( pLevel->flags & WHERE_ROWID_EQ ){
drh8aff1012001-12-22 14:49:24 +00001372 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +00001373 ** equality comparison against the ROWID field. Or
1374 ** we reference multiple rows using a "rowid IN (...)"
1375 ** construct.
drhc4a3c772001-04-04 11:48:57 +00001376 */
drhfe05af82005-07-21 03:14:59 +00001377 pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1378 assert( pTerm!=0 );
drh0fcef5e2005-07-19 17:38:22 +00001379 assert( pTerm->pExpr!=0 );
1380 assert( pTerm->leftCursor==iCur );
drh9012bcb2004-12-19 00:11:35 +00001381 assert( omitTable==0 );
drh94a11212004-09-25 13:12:14 +00001382 codeEqualityTerm(pParse, pTerm, brk, pLevel);
danielk19774adee202004-05-08 08:23:19 +00001383 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
danielk19774adee202004-05-08 08:23:19 +00001384 sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001385 VdbeComment((v, "pk"));
drh6b563442001-11-07 16:48:26 +00001386 pLevel->op = OP_Noop;
drhfe05af82005-07-21 03:14:59 +00001387 }else if( pLevel->flags & WHERE_ROWID_RANGE ){
drh51147ba2005-07-23 22:59:55 +00001388 /* Case 2: We have an inequality comparison against the ROWID field.
drh8aff1012001-12-22 14:49:24 +00001389 */
1390 int testOp = OP_Noop;
1391 int start;
drhfe05af82005-07-21 03:14:59 +00001392 WhereTerm *pStart, *pEnd;
drh8aff1012001-12-22 14:49:24 +00001393
drh9012bcb2004-12-19 00:11:35 +00001394 assert( omitTable==0 );
drha6110402005-07-28 20:51:19 +00001395 pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
1396 pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
drhfe05af82005-07-21 03:14:59 +00001397 if( bRev ){
1398 pTerm = pStart;
1399 pStart = pEnd;
1400 pEnd = pTerm;
1401 }
1402 if( pStart ){
drh94a11212004-09-25 13:12:14 +00001403 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001404 pX = pStart->pExpr;
drh94a11212004-09-25 13:12:14 +00001405 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001406 assert( pStart->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001407 sqlite3ExprCode(pParse, pX->pRight);
danielk1977d0a69322005-02-02 01:10:44 +00001408 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
drhb6c29892004-11-22 19:12:19 +00001409 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001410 VdbeComment((v, "pk"));
drhfe05af82005-07-21 03:14:59 +00001411 disableTerm(pLevel, pStart);
drh8aff1012001-12-22 14:49:24 +00001412 }else{
drhb6c29892004-11-22 19:12:19 +00001413 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
drh8aff1012001-12-22 14:49:24 +00001414 }
drhfe05af82005-07-21 03:14:59 +00001415 if( pEnd ){
drh94a11212004-09-25 13:12:14 +00001416 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001417 pX = pEnd->pExpr;
drh94a11212004-09-25 13:12:14 +00001418 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001419 assert( pEnd->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001420 sqlite3ExprCode(pParse, pX->pRight);
drh8aff1012001-12-22 14:49:24 +00001421 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001422 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drh94a11212004-09-25 13:12:14 +00001423 if( pX->op==TK_LT || pX->op==TK_GT ){
drhb6c29892004-11-22 19:12:19 +00001424 testOp = bRev ? OP_Le : OP_Ge;
drh8aff1012001-12-22 14:49:24 +00001425 }else{
drhb6c29892004-11-22 19:12:19 +00001426 testOp = bRev ? OP_Lt : OP_Gt;
drh8aff1012001-12-22 14:49:24 +00001427 }
drhfe05af82005-07-21 03:14:59 +00001428 disableTerm(pLevel, pEnd);
drh8aff1012001-12-22 14:49:24 +00001429 }
danielk19774adee202004-05-08 08:23:19 +00001430 start = sqlite3VdbeCurrentAddr(v);
drhb6c29892004-11-22 19:12:19 +00001431 pLevel->op = bRev ? OP_Prev : OP_Next;
drh6a3ea0e2003-05-02 14:32:12 +00001432 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001433 pLevel->p2 = start;
1434 if( testOp!=OP_Noop ){
drhf0863fe2005-06-12 21:35:51 +00001435 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001436 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drhf0863fe2005-06-12 21:35:51 +00001437 sqlite3VdbeAddOp(v, testOp, 'n', brk);
drh8aff1012001-12-22 14:49:24 +00001438 }
drhfe05af82005-07-21 03:14:59 +00001439 }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
drh51147ba2005-07-23 22:59:55 +00001440 /* Case 3: The WHERE clause term that refers to the right-most
drhc27a1ce2002-06-14 20:58:45 +00001441 ** column of the index is an inequality. For example, if
1442 ** the index is on (x,y,z) and the WHERE clause is of the
1443 ** form "x=5 AND y<10" then this case is used. Only the
1444 ** right-most column can be an inequality - the rest must
drh51147ba2005-07-23 22:59:55 +00001445 ** use the "==" and "IN" operators.
drhe3184742002-06-19 14:27:05 +00001446 **
1447 ** This case is also used when there are no WHERE clause
1448 ** constraints but an index is selected anyway, in order
1449 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +00001450 */
drh487ab3c2001-11-08 00:45:21 +00001451 int start;
drh51147ba2005-07-23 22:59:55 +00001452 int nEq = pLevel->nEq;
danielk1977f7df9cc2004-06-16 12:02:47 +00001453 int leFlag=0, geFlag=0;
drh487ab3c2001-11-08 00:45:21 +00001454 int testOp;
drhfe05af82005-07-21 03:14:59 +00001455 int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
1456 int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
drh487ab3c2001-11-08 00:45:21 +00001457
drh51147ba2005-07-23 22:59:55 +00001458 /* Generate code to evaluate all constraint terms using == or IN
1459 ** and level the values of those terms on the stack.
drh487ab3c2001-11-08 00:45:21 +00001460 */
drh51147ba2005-07-23 22:59:55 +00001461 codeAllEqualityTerms(pParse, pLevel, &wc, notReady, brk);
drh487ab3c2001-11-08 00:45:21 +00001462
drhc27a1ce2002-06-14 20:58:45 +00001463 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +00001464 ** used twice: once to make the termination key and once to make the
1465 ** start key.
1466 */
drh51147ba2005-07-23 22:59:55 +00001467 for(j=0; j<nEq; j++){
1468 sqlite3VdbeAddOp(v, OP_Dup, nEq-1, 0);
drh487ab3c2001-11-08 00:45:21 +00001469 }
1470
1471 /* Generate the termination key. This is the key value that
1472 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +00001473 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +00001474 **
1475 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1476 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +00001477 */
drhfe05af82005-07-21 03:14:59 +00001478 if( topLimit ){
drhe8b97272005-07-19 22:22:12 +00001479 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001480 int k = pIdx->aiColumn[j];
1481 pTerm = findTerm(&wc, iCur, k, notReady, WO_LT|WO_LE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001482 assert( pTerm!=0 );
1483 pX = pTerm->pExpr;
1484 assert( (pTerm->flags & TERM_CODED)==0 );
1485 sqlite3ExprCode(pParse, pX->pRight);
1486 leFlag = pX->op==TK_LE;
1487 disableTerm(pLevel, pTerm);
drh487ab3c2001-11-08 00:45:21 +00001488 testOp = OP_IdxGE;
1489 }else{
drh51147ba2005-07-23 22:59:55 +00001490 testOp = nEq>0 ? OP_IdxGE : OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001491 leFlag = 1;
1492 }
1493 if( testOp!=OP_Noop ){
drh51147ba2005-07-23 22:59:55 +00001494 int nCol = nEq + topLimit;
drh487ab3c2001-11-08 00:45:21 +00001495 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001496 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001497 if( bRev ){
drh7cf6e4d2004-05-19 14:56:55 +00001498 int op = leFlag ? OP_MoveLe : OP_MoveLt;
drh9012bcb2004-12-19 00:11:35 +00001499 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001500 }else{
danielk19774adee202004-05-08 08:23:19 +00001501 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001502 }
drhfe05af82005-07-21 03:14:59 +00001503 }else if( bRev ){
drh9012bcb2004-12-19 00:11:35 +00001504 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001505 }
1506
1507 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001508 ** bound on the search. There is no start key if there are no
1509 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001510 ** that case, generate a "Rewind" instruction in place of the
1511 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001512 **
1513 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1514 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001515 */
drhfe05af82005-07-21 03:14:59 +00001516 if( btmLimit ){
drhe8b97272005-07-19 22:22:12 +00001517 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001518 int k = pIdx->aiColumn[j];
1519 pTerm = findTerm(&wc, iCur, k, notReady, WO_GT|WO_GE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001520 assert( pTerm!=0 );
1521 pX = pTerm->pExpr;
1522 assert( (pTerm->flags & TERM_CODED)==0 );
1523 sqlite3ExprCode(pParse, pX->pRight);
1524 geFlag = pX->op==TK_GE;
1525 disableTerm(pLevel, pTerm);
drh7900ead2001-11-12 13:51:43 +00001526 }else{
1527 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001528 }
drh51147ba2005-07-23 22:59:55 +00001529 if( nEq>0 || btmLimit ){
1530 int nCol = nEq + btmLimit;
drh94a11212004-09-25 13:12:14 +00001531 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001532 if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001533 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001534 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001535 testOp = OP_IdxLT;
1536 }else{
drh7cf6e4d2004-05-19 14:56:55 +00001537 int op = geFlag ? OP_MoveGe : OP_MoveGt;
drh9012bcb2004-12-19 00:11:35 +00001538 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001539 }
drhfe05af82005-07-21 03:14:59 +00001540 }else if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001541 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001542 }else{
drh9012bcb2004-12-19 00:11:35 +00001543 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001544 }
1545
1546 /* Generate the the top of the loop. If there is a termination
1547 ** key we have to test for that key and abort at the top of the
1548 ** loop.
1549 */
danielk19774adee202004-05-08 08:23:19 +00001550 start = sqlite3VdbeCurrentAddr(v);
drh487ab3c2001-11-08 00:45:21 +00001551 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001552 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001553 sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
drhfe05af82005-07-21 03:14:59 +00001554 if( (leFlag && !bRev) || (!geFlag && bRev) ){
danielk19773d1bfea2004-05-14 11:00:53 +00001555 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
1556 }
drh487ab3c2001-11-08 00:45:21 +00001557 }
drh9012bcb2004-12-19 00:11:35 +00001558 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
drh51147ba2005-07-23 22:59:55 +00001559 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEq + topLimit, cont);
drhe6f85e72004-12-25 01:03:13 +00001560 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001561 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001562 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh487ab3c2001-11-08 00:45:21 +00001563 }
1564
1565 /* Record the instruction used to terminate the loop.
1566 */
drhfe05af82005-07-21 03:14:59 +00001567 pLevel->op = bRev ? OP_Prev : OP_Next;
drh9012bcb2004-12-19 00:11:35 +00001568 pLevel->p1 = iIdxCur;
drh487ab3c2001-11-08 00:45:21 +00001569 pLevel->p2 = start;
drh51147ba2005-07-23 22:59:55 +00001570 }else if( pLevel->flags & WHERE_COLUMN_EQ ){
1571 /* Case 4: There is an index and all terms of the WHERE clause that
1572 ** refer to the index using the "==" or "IN" operators.
1573 */
1574 int start;
1575 int nEq = pLevel->nEq;
1576
1577 /* Generate code to evaluate all constraint terms using == or IN
1578 ** and level the values of those terms on the stack.
1579 */
1580 codeAllEqualityTerms(pParse, pLevel, &wc, notReady, brk);
1581
1582 /* Generate a single key that will be used to both start and terminate
1583 ** the search
1584 */
1585 buildIndexProbe(v, nEq, brk, pIdx);
1586 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
1587
1588 /* Generate code (1) to move to the first matching element of the table.
1589 ** Then generate code (2) that jumps to "brk" after the cursor is past
1590 ** the last matching element of the table. The code (1) is executed
1591 ** once to initialize the search, the code (2) is executed before each
1592 ** iteration of the scan to see if the scan has finished. */
1593 if( bRev ){
1594 /* Scan in reverse order */
1595 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
1596 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1597 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
1598 pLevel->op = OP_Prev;
1599 }else{
1600 /* Scan in the forward order */
1601 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
1602 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1603 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
1604 pLevel->op = OP_Next;
1605 }
1606 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
1607 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEq, cont);
1608 if( !omitTable ){
1609 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
1610 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
1611 }
1612 pLevel->p1 = iIdxCur;
1613 pLevel->p2 = start;
drhfe05af82005-07-21 03:14:59 +00001614 }else{
1615 /* Case 5: There is no usable index. We must do a complete
1616 ** scan of the entire table.
1617 */
drhfe05af82005-07-21 03:14:59 +00001618 assert( omitTable==0 );
drha6110402005-07-28 20:51:19 +00001619 assert( bRev==0 );
1620 pLevel->op = OP_Next;
drhfe05af82005-07-21 03:14:59 +00001621 pLevel->p1 = iCur;
drha6110402005-07-28 20:51:19 +00001622 pLevel->p2 = 1 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, brk);
drh75897232000-05-29 14:26:00 +00001623 }
drhfe05af82005-07-21 03:14:59 +00001624 notReady &= ~getMask(&maskSet, iCur);
drh75897232000-05-29 14:26:00 +00001625
1626 /* Insert code to test every subexpression that can be completely
1627 ** computed using the current set of tables.
1628 */
drh0fcef5e2005-07-19 17:38:22 +00001629 for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
1630 Expr *pE;
1631 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001632 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001633 pE = pTerm->pExpr;
1634 assert( pE!=0 );
drh392e5972005-07-08 14:14:22 +00001635 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
drh1f162302002-10-27 19:35:33 +00001636 continue;
1637 }
drh392e5972005-07-08 14:14:22 +00001638 sqlite3ExprIfFalse(pParse, pE, cont, 1);
drh0fcef5e2005-07-19 17:38:22 +00001639 pTerm->flags |= TERM_CODED;
drh75897232000-05-29 14:26:00 +00001640 }
drhad2d8302002-05-24 20:31:36 +00001641
1642 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1643 ** at least one row of the right table has matched the left table.
1644 */
1645 if( pLevel->iLeftJoin ){
danielk19774adee202004-05-08 08:23:19 +00001646 pLevel->top = sqlite3VdbeCurrentAddr(v);
1647 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1648 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001649 VdbeComment((v, "# record LEFT JOIN hit"));
drh0aa74ed2005-07-16 13:33:20 +00001650 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
drh0fcef5e2005-07-19 17:38:22 +00001651 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001652 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001653 assert( pTerm->pExpr );
1654 sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
1655 pTerm->flags |= TERM_CODED;
drh1cc093c2002-06-24 22:01:57 +00001656 }
drhad2d8302002-05-24 20:31:36 +00001657 }
drh75897232000-05-29 14:26:00 +00001658 }
drh7ec764a2005-07-21 03:48:20 +00001659
1660#ifdef SQLITE_TEST /* For testing and debugging use only */
1661 /* Record in the query plan information about the current table
1662 ** and the index used to access it (if any). If the table itself
1663 ** is not used, its name is just '{}'. If no index is used
1664 ** the index is listed as "{}". If the primary key is used the
1665 ** index name is '*'.
1666 */
1667 for(i=0; i<pTabList->nSrc; i++){
1668 char *z;
1669 int n;
drh7ec764a2005-07-21 03:48:20 +00001670 pLevel = &pWInfo->a[i];
drh29dda4a2005-07-21 18:23:20 +00001671 pTabItem = &pTabList->a[pLevel->iFrom];
drh7ec764a2005-07-21 03:48:20 +00001672 z = pTabItem->zAlias;
1673 if( z==0 ) z = pTabItem->pTab->zName;
1674 n = strlen(z);
1675 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
1676 if( pLevel->flags & WHERE_IDX_ONLY ){
1677 strcpy(&sqlite3_query_plan[nQPlan], "{}");
1678 nQPlan += 2;
1679 }else{
1680 strcpy(&sqlite3_query_plan[nQPlan], z);
1681 nQPlan += n;
1682 }
1683 sqlite3_query_plan[nQPlan++] = ' ';
1684 }
1685 if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
1686 strcpy(&sqlite3_query_plan[nQPlan], "* ");
1687 nQPlan += 2;
1688 }else if( pLevel->pIdx==0 ){
1689 strcpy(&sqlite3_query_plan[nQPlan], "{} ");
1690 nQPlan += 3;
1691 }else{
1692 n = strlen(pLevel->pIdx->zName);
1693 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
1694 strcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName);
1695 nQPlan += n;
1696 sqlite3_query_plan[nQPlan++] = ' ';
1697 }
1698 }
1699 }
1700 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
1701 sqlite3_query_plan[--nQPlan] = 0;
1702 }
1703 sqlite3_query_plan[nQPlan] = 0;
1704 nQPlan = 0;
1705#endif /* SQLITE_TEST // Testing and debugging use only */
1706
drh29dda4a2005-07-21 18:23:20 +00001707 /* Record the continuation address in the WhereInfo structure. Then
1708 ** clean up and return.
1709 */
drh75897232000-05-29 14:26:00 +00001710 pWInfo->iContinue = cont;
drh0aa74ed2005-07-16 13:33:20 +00001711 whereClauseClear(&wc);
drh75897232000-05-29 14:26:00 +00001712 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00001713
1714 /* Jump here if malloc fails */
1715whereBeginNoMem:
1716 whereClauseClear(&wc);
1717 sqliteFree(pWInfo);
1718 return 0;
drh75897232000-05-29 14:26:00 +00001719}
1720
1721/*
drhc27a1ce2002-06-14 20:58:45 +00001722** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00001723** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001724*/
danielk19774adee202004-05-08 08:23:19 +00001725void sqlite3WhereEnd(WhereInfo *pWInfo){
drh75897232000-05-29 14:26:00 +00001726 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001727 int i;
drh6b563442001-11-07 16:48:26 +00001728 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001729 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001730
drh9012bcb2004-12-19 00:11:35 +00001731 /* Generate loop termination code.
1732 */
drhad3cab52002-05-24 02:04:32 +00001733 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001734 pLevel = &pWInfo->a[i];
danielk19774adee202004-05-08 08:23:19 +00001735 sqlite3VdbeResolveLabel(v, pLevel->cont);
drh6b563442001-11-07 16:48:26 +00001736 if( pLevel->op!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001737 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001738 }
danielk19774adee202004-05-08 08:23:19 +00001739 sqlite3VdbeResolveLabel(v, pLevel->brk);
drhe23399f2005-07-22 00:31:39 +00001740 if( pLevel->nIn ){
1741 int *a;
1742 int j;
1743 for(j=pLevel->nIn, a=&pLevel->aInLoop[j*3-3]; j>0; j--, a-=3){
1744 sqlite3VdbeAddOp(v, a[0], a[1], a[2]);
1745 }
1746 sqliteFree(pLevel->aInLoop);
drhd99f7062002-06-08 23:25:08 +00001747 }
drhad2d8302002-05-24 20:31:36 +00001748 if( pLevel->iLeftJoin ){
1749 int addr;
danielk19774adee202004-05-08 08:23:19 +00001750 addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh9012bcb2004-12-19 00:11:35 +00001751 sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
danielk19774adee202004-05-08 08:23:19 +00001752 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
drh9012bcb2004-12-19 00:11:35 +00001753 if( pLevel->iIdxCur>=0 ){
1754 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
drh7f09b3e2002-08-13 13:15:49 +00001755 }
danielk19774adee202004-05-08 08:23:19 +00001756 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
drhad2d8302002-05-24 20:31:36 +00001757 }
drh19a775c2000-06-05 18:54:46 +00001758 }
drh9012bcb2004-12-19 00:11:35 +00001759
1760 /* The "break" point is here, just past the end of the outer loop.
1761 ** Set it.
1762 */
danielk19774adee202004-05-08 08:23:19 +00001763 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00001764
drh29dda4a2005-07-21 18:23:20 +00001765 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00001766 */
drh29dda4a2005-07-21 18:23:20 +00001767 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1768 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001769 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00001770 assert( pTab!=0 );
1771 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001772 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001773 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
1774 }
drh6b563442001-11-07 16:48:26 +00001775 if( pLevel->pIdx!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001776 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
1777 }
1778
drhacf3b982005-01-03 01:27:18 +00001779 /* Make cursor substitutions for cases where we want to use
drh9012bcb2004-12-19 00:11:35 +00001780 ** just the index and never reference the table.
1781 **
1782 ** Calls to the code generator in between sqlite3WhereBegin and
1783 ** sqlite3WhereEnd will have created code that references the table
1784 ** directly. This loop scans all that code looking for opcodes
1785 ** that reference the table and converts them into opcodes that
1786 ** reference the index.
1787 */
drhfe05af82005-07-21 03:14:59 +00001788 if( pLevel->flags & WHERE_IDX_ONLY ){
drh9012bcb2004-12-19 00:11:35 +00001789 int i, j, last;
1790 VdbeOp *pOp;
1791 Index *pIdx = pLevel->pIdx;
1792
1793 assert( pIdx!=0 );
1794 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1795 last = sqlite3VdbeCurrentAddr(v);
1796 for(i=pWInfo->iTop; i<last; i++, pOp++){
1797 if( pOp->p1!=pLevel->iTabCur ) continue;
1798 if( pOp->opcode==OP_Column ){
1799 pOp->p1 = pLevel->iIdxCur;
1800 for(j=0; j<pIdx->nColumn; j++){
1801 if( pOp->p2==pIdx->aiColumn[j] ){
1802 pOp->p2 = j;
1803 break;
1804 }
1805 }
drhf0863fe2005-06-12 21:35:51 +00001806 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00001807 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00001808 pOp->opcode = OP_IdxRowid;
danielk19776c18b6e2005-01-30 09:17:58 +00001809 }else if( pOp->opcode==OP_NullRow ){
1810 pOp->opcode = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001811 }
1812 }
drh6b563442001-11-07 16:48:26 +00001813 }
drh19a775c2000-06-05 18:54:46 +00001814 }
drh9012bcb2004-12-19 00:11:35 +00001815
1816 /* Final cleanup
1817 */
drh75897232000-05-29 14:26:00 +00001818 sqliteFree(pWInfo);
1819 return;
1820}