blob: 28380844fd2dd95f40adeb712cad962119923045 [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**
drh28c4cf42005-07-27 20:41:43 +000019** $Id: where.c,v 1.153 2005/07/27 20:41:44 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> */
drh0fcef5e2005-07-19 17:38:22 +000089 WhereClause *pWC; /* The clause this term is part of */
90 Bitmask prereqRight; /* Bitmask of tables used by pRight */
drh51669862004-12-18 18:40:26 +000091 Bitmask prereqAll; /* Bitmask of tables referenced by p */
drh75897232000-05-29 14:26:00 +000092};
93
94/*
drh0aa74ed2005-07-16 13:33:20 +000095** Allowed values of WhereTerm.flags
96*/
drh51147ba2005-07-23 22:59:55 +000097#define TERM_DYNAMIC 0x0001 /* Need to call sqlite3ExprDelete(pExpr) */
drh0aa74ed2005-07-16 13:33:20 +000098#define TERM_VIRTUAL 0x0002 /* Added by the optimizer. Do not code */
drh0fcef5e2005-07-19 17:38:22 +000099#define TERM_CODED 0x0004 /* This term is already coded */
drh0aa74ed2005-07-16 13:33:20 +0000100
101/*
102** An instance of the following structure holds all information about a
103** WHERE clause. Mostly this is a container for one or more WhereTerms.
104*/
drh0aa74ed2005-07-16 13:33:20 +0000105struct WhereClause {
drhfe05af82005-07-21 03:14:59 +0000106 Parse *pParse; /* The parser context */
drh0aa74ed2005-07-16 13:33:20 +0000107 int nTerm; /* Number of terms */
108 int nSlot; /* Number of entries in a[] */
drh51147ba2005-07-23 22:59:55 +0000109 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
110 WhereTerm aStatic[10]; /* Initial static space for a[] */
drhe23399f2005-07-22 00:31:39 +0000111};
112
113/*
drh6a3ea0e2003-05-02 14:32:12 +0000114** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000115** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000116**
117** The VDBE cursor numbers are small integers contained in
118** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
119** clause, the cursor numbers might not begin with 0 and they might
120** contain gaps in the numbering sequence. But we want to make maximum
121** use of the bits in our bitmasks. This structure provides a mapping
122** from the sparse cursor numbers into consecutive integers beginning
123** with 0.
124**
125** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
126** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
127**
128** For example, if the WHERE clause expression used these VDBE
129** cursors: 4, 5, 8, 29, 57, 73. Then the ExprMaskSet structure
130** would map those cursor numbers into bits 0 through 5.
131**
132** Note that the mapping is not necessarily ordered. In the example
133** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
134** 57->5, 73->4. Or one of 719 other combinations might be used. It
135** does not really matter. What is important is that sparse cursor
136** numbers all get mapped into bit numbers that begin with 0 and contain
137** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000138*/
139typedef struct ExprMaskSet ExprMaskSet;
140struct ExprMaskSet {
drh1398ad32005-01-19 23:24:50 +0000141 int n; /* Number of assigned cursor values */
142 int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000143};
144
drh0aa74ed2005-07-16 13:33:20 +0000145
drh6a3ea0e2003-05-02 14:32:12 +0000146/*
drh51147ba2005-07-23 22:59:55 +0000147** Bitmasks for the operators that indices are able to exploit. An
148** OR-ed combination of these values can be used when searching for
149** terms in the where clause.
150*/
151#define WO_IN 1
152#define WO_LIST 2
153#define WO_SELECT 4
154#define WO_EQ 8
155#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
156#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
157#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
158#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
159
160/*
161** Value for flags returned by bestIndex()
162*/
163#define WHERE_ROWID_EQ 0x0001 /* rowid=EXPR or rowid IN (...) */
164#define WHERE_ROWID_RANGE 0x0002 /* rowid<EXPR and/or rowid>EXPR */
165#define WHERE_COLUMN_EQ 0x0010 /* x=EXPR or x IN (...) */
166#define WHERE_COLUMN_RANGE 0x0020 /* x<EXPR and/or x>EXPR */
167#define WHERE_COLUMN_IN 0x0040 /* x IN (...) */
168#define WHERE_TOP_LIMIT 0x0100 /* x<EXPR or x<=EXPR constraint */
169#define WHERE_BTM_LIMIT 0x0200 /* x>EXPR or x>=EXPR constraint */
170#define WHERE_IDX_ONLY 0x0800 /* Use index only - omit table */
171#define WHERE_ORDERBY 0x1000 /* Output will appear in correct order */
172#define WHERE_REVERSE 0x2000 /* Scan in reverse order */
173
174/*
drh0aa74ed2005-07-16 13:33:20 +0000175** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000176*/
drhfe05af82005-07-21 03:14:59 +0000177static void whereClauseInit(WhereClause *pWC, Parse *pParse){
178 pWC->pParse = pParse;
drh0aa74ed2005-07-16 13:33:20 +0000179 pWC->nTerm = 0;
180 pWC->nSlot = ARRAYSIZE(pWC->aStatic);
181 pWC->a = pWC->aStatic;
182}
183
184/*
185** Deallocate a WhereClause structure. The WhereClause structure
186** itself is not freed. This routine is the inverse of whereClauseInit().
187*/
188static void whereClauseClear(WhereClause *pWC){
189 int i;
190 WhereTerm *a;
191 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
192 if( a->flags & TERM_DYNAMIC ){
drh0fcef5e2005-07-19 17:38:22 +0000193 sqlite3ExprDelete(a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000194 }
195 }
196 if( pWC->a!=pWC->aStatic ){
197 sqliteFree(pWC->a);
198 }
199}
200
201/*
202** Add a new entries to the WhereClause structure. Increase the allocated
203** space as necessary.
204*/
drh0fcef5e2005-07-19 17:38:22 +0000205static WhereTerm *whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
drh0aa74ed2005-07-16 13:33:20 +0000206 WhereTerm *pTerm;
207 if( pWC->nTerm>=pWC->nSlot ){
208 WhereTerm *pOld = pWC->a;
209 pWC->a = sqliteMalloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
drh0fcef5e2005-07-19 17:38:22 +0000210 if( pWC->a==0 ) return 0;
drh0aa74ed2005-07-16 13:33:20 +0000211 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
212 if( pOld!=pWC->aStatic ){
213 sqliteFree(pOld);
214 }
215 pWC->nSlot *= 2;
216 }
drh0fcef5e2005-07-19 17:38:22 +0000217 pTerm = &pWC->a[pWC->nTerm];
218 pTerm->idx = pWC->nTerm;
219 pWC->nTerm++;
220 pTerm->pExpr = p;
drh0aa74ed2005-07-16 13:33:20 +0000221 pTerm->flags = flags;
drh0fcef5e2005-07-19 17:38:22 +0000222 pTerm->pWC = pWC;
223 pTerm->iPartner = -1;
224 return pTerm;
drh0aa74ed2005-07-16 13:33:20 +0000225}
drh75897232000-05-29 14:26:00 +0000226
227/*
drh51669862004-12-18 18:40:26 +0000228** This routine identifies subexpressions in the WHERE clause where
229** each subexpression is separate by the AND operator. aSlot is
230** filled with pointers to the subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000231**
drh51669862004-12-18 18:40:26 +0000232** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
233** \________/ \_______________/ \________________/
234** slot[0] slot[1] slot[2]
235**
236** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000237** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000238**
drh51147ba2005-07-23 22:59:55 +0000239** In the previous sentence and in the diagram, "slot[]" refers to
240** the WhereClause.a[] array. This array grows as needed to contain
241** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000242*/
drh0aa74ed2005-07-16 13:33:20 +0000243static void whereSplit(WhereClause *pWC, Expr *pExpr){
244 if( pExpr==0 ) return;
245 if( pExpr->op!=TK_AND ){
246 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000247 }else{
drh0aa74ed2005-07-16 13:33:20 +0000248 whereSplit(pWC, pExpr->pLeft);
249 whereSplit(pWC, pExpr->pRight);
drh75897232000-05-29 14:26:00 +0000250 }
drh75897232000-05-29 14:26:00 +0000251}
252
253/*
drh6a3ea0e2003-05-02 14:32:12 +0000254** Initialize an expression mask set
255*/
256#define initMaskSet(P) memset(P, 0, sizeof(*P))
257
258/*
drh1398ad32005-01-19 23:24:50 +0000259** Return the bitmask for the given cursor number. Return 0 if
260** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000261*/
drh51669862004-12-18 18:40:26 +0000262static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000263 int i;
264 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000265 if( pMaskSet->ix[i]==iCursor ){
266 return ((Bitmask)1)<<i;
267 }
drh6a3ea0e2003-05-02 14:32:12 +0000268 }
drh6a3ea0e2003-05-02 14:32:12 +0000269 return 0;
270}
271
272/*
drh1398ad32005-01-19 23:24:50 +0000273** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000274**
275** There is one cursor per table in the FROM clause. The number of
276** tables in the FROM clause is limited by a test early in the
277** sqlite3WhereBegin() routien. So we know that the pMaskSet->ix[]
278** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000279*/
280static void createMask(ExprMaskSet *pMaskSet, int iCursor){
drh0fcef5e2005-07-19 17:38:22 +0000281 assert( pMaskSet->n < ARRAYSIZE(pMaskSet->ix) );
282 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000283}
284
285/*
drh75897232000-05-29 14:26:00 +0000286** This routine walks (recursively) an expression tree and generates
287** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000288** tree.
drh75897232000-05-29 14:26:00 +0000289**
290** In order for this routine to work, the calling function must have
drh626a8792005-01-17 22:08:19 +0000291** previously invoked sqlite3ExprResolveNames() on the expression. See
drh75897232000-05-29 14:26:00 +0000292** the header comment on that routine for additional information.
drh626a8792005-01-17 22:08:19 +0000293** The sqlite3ExprResolveNames() routines looks for column names and
drh6a3ea0e2003-05-02 14:32:12 +0000294** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
drh51147ba2005-07-23 22:59:55 +0000295** the VDBE cursor number of the table. This routine just has to
296** translate the cursor numbers into bitmask values and OR all
297** the bitmasks together.
drh75897232000-05-29 14:26:00 +0000298*/
danielk1977b3bce662005-01-29 08:32:43 +0000299static Bitmask exprListTableUsage(ExprMaskSet *, ExprList *);
drh51669862004-12-18 18:40:26 +0000300static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
301 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000302 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000303 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000304 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000305 return mask;
drh75897232000-05-29 14:26:00 +0000306 }
danielk1977b3bce662005-01-29 08:32:43 +0000307 mask = exprTableUsage(pMaskSet, p->pRight);
308 mask |= exprTableUsage(pMaskSet, p->pLeft);
309 mask |= exprListTableUsage(pMaskSet, p->pList);
310 if( p->pSelect ){
311 Select *pS = p->pSelect;
312 mask |= exprListTableUsage(pMaskSet, pS->pEList);
313 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
314 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
315 mask |= exprTableUsage(pMaskSet, pS->pWhere);
316 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drh75897232000-05-29 14:26:00 +0000317 }
danielk1977b3bce662005-01-29 08:32:43 +0000318 return mask;
319}
320static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
321 int i;
322 Bitmask mask = 0;
323 if( pList ){
324 for(i=0; i<pList->nExpr; i++){
325 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000326 }
327 }
drh75897232000-05-29 14:26:00 +0000328 return mask;
329}
330
331/*
drh487ab3c2001-11-08 00:45:21 +0000332** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000333** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000334** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000335*/
336static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000337 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
338 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
339 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
340 assert( TK_GE==TK_EQ+4 );
drh9a432672004-10-04 13:38:09 +0000341 return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
drh487ab3c2001-11-08 00:45:21 +0000342}
343
344/*
drh51669862004-12-18 18:40:26 +0000345** Swap two objects of type T.
drh193bd772004-07-20 18:23:14 +0000346*/
347#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
348
349/*
drh0fcef5e2005-07-19 17:38:22 +0000350** Commute a comparision operator. Expressions of the form "X op Y"
351** are converted into "Y op X".
drh193bd772004-07-20 18:23:14 +0000352*/
drh0fcef5e2005-07-19 17:38:22 +0000353static void exprCommute(Expr *pExpr){
drhfe05af82005-07-21 03:14:59 +0000354 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drh0fcef5e2005-07-19 17:38:22 +0000355 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
356 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
357 if( pExpr->op>=TK_GT ){
358 assert( TK_LT==TK_GT+2 );
359 assert( TK_GE==TK_LE+2 );
360 assert( TK_GT>TK_EQ );
361 assert( TK_GT<TK_LE );
362 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
363 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000364 }
drh193bd772004-07-20 18:23:14 +0000365}
366
367/*
drhfe05af82005-07-21 03:14:59 +0000368** Translate from TK_xx operator to WO_xx bitmask.
369*/
370static int operatorMask(int op){
drh51147ba2005-07-23 22:59:55 +0000371 int c;
drhfe05af82005-07-21 03:14:59 +0000372 assert( allowedOp(op) );
373 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000374 c = WO_IN;
drhfe05af82005-07-21 03:14:59 +0000375 }else{
drh51147ba2005-07-23 22:59:55 +0000376 c = WO_EQ<<(op-TK_EQ);
drhfe05af82005-07-21 03:14:59 +0000377 }
drh51147ba2005-07-23 22:59:55 +0000378 assert( op!=TK_IN || c==WO_IN );
379 assert( op!=TK_EQ || c==WO_EQ );
380 assert( op!=TK_LT || c==WO_LT );
381 assert( op!=TK_LE || c==WO_LE );
382 assert( op!=TK_GT || c==WO_GT );
383 assert( op!=TK_GE || c==WO_GE );
384 return c;
drhfe05af82005-07-21 03:14:59 +0000385}
386
387/*
388** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
389** where X is a reference to the iColumn of table iCur and <op> is one of
390** the WO_xx operator codes specified by the op parameter.
391** Return a pointer to the term. Return 0 if not found.
392*/
393static WhereTerm *findTerm(
394 WhereClause *pWC, /* The WHERE clause to be searched */
395 int iCur, /* Cursor number of LHS */
396 int iColumn, /* Column number of LHS */
397 Bitmask notReady, /* RHS must not overlap with this mask */
drh51147ba2005-07-23 22:59:55 +0000398 u16 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000399 Index *pIdx /* Must be compatible with this index, if not NULL */
400){
401 WhereTerm *pTerm;
402 int k;
403 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
404 if( pTerm->leftCursor==iCur
405 && (pTerm->prereqRight & notReady)==0
406 && pTerm->leftColumn==iColumn
407 && (pTerm->operator & op)!=0
408 ){
409 if( iCur>=0 && pIdx ){
410 Expr *pX = pTerm->pExpr;
411 CollSeq *pColl;
412 char idxaff;
413 int k;
414 Parse *pParse = pWC->pParse;
415
416 idxaff = pIdx->pTable->aCol[iColumn].affinity;
417 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
418 pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
419 if( !pColl ){
420 if( pX->pRight ){
421 pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
422 }
423 if( !pColl ){
424 pColl = pParse->db->pDfltColl;
425 }
426 }
427 for(k=0; k<pIdx->nColumn && pIdx->aiColumn[k]!=iColumn; k++){}
428 assert( k<pIdx->nColumn );
429 if( pColl!=pIdx->keyInfo.aColl[k] ) continue;
430 }
431 return pTerm;
432 }
433 }
434 return 0;
435}
436
437/*
drh0aa74ed2005-07-16 13:33:20 +0000438** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +0000439** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +0000440** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +0000441** structure.
drh51147ba2005-07-23 22:59:55 +0000442**
443** If the expression is of the form "<expr> <op> X" it gets commuted
444** to the standard form of "X <op> <expr>". If the expression is of
445** the form "X <op> Y" where both X and Y are columns, then the original
446** expression is unchanged and a new virtual expression of the form
447** "Y <op> X" is added to the WHERE clause.
drh75897232000-05-29 14:26:00 +0000448*/
drh0fcef5e2005-07-19 17:38:22 +0000449static void exprAnalyze(
450 SrcList *pSrc, /* the FROM clause */
451 ExprMaskSet *pMaskSet, /* table masks */
452 WhereTerm *pTerm /* the WHERE clause term to be analyzed */
453){
454 Expr *pExpr = pTerm->pExpr;
455 Bitmask prereqLeft;
456 Bitmask prereqAll;
457 int idxRight;
458
459 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
460 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
461 pTerm->prereqAll = prereqAll = exprTableUsage(pMaskSet, pExpr);
462 pTerm->leftCursor = -1;
463 pTerm->iPartner = -1;
drhfe05af82005-07-21 03:14:59 +0000464 pTerm->operator = 0;
drh0fcef5e2005-07-19 17:38:22 +0000465 idxRight = -1;
466 if( allowedOp(pExpr->op) && (pTerm->prereqRight & prereqLeft)==0 ){
467 Expr *pLeft = pExpr->pLeft;
468 Expr *pRight = pExpr->pRight;
469 if( pLeft->op==TK_COLUMN ){
470 pTerm->leftCursor = pLeft->iTable;
471 pTerm->leftColumn = pLeft->iColumn;
drhfe05af82005-07-21 03:14:59 +0000472 pTerm->operator = operatorMask(pExpr->op);
drh51147ba2005-07-23 22:59:55 +0000473 if( pTerm->operator==WO_IN ){
474 if( pExpr->pSelect ){
475 pTerm->operator |= WO_SELECT;
476 }else if( pExpr->pList ){
477 pTerm->operator |= WO_LIST;
478 }
479 }
drh75897232000-05-29 14:26:00 +0000480 }
drh0fcef5e2005-07-19 17:38:22 +0000481 if( pRight && pRight->op==TK_COLUMN ){
482 WhereTerm *pNew;
483 Expr *pDup;
484 if( pTerm->leftCursor>=0 ){
485 pDup = sqlite3ExprDup(pExpr);
486 pNew = whereClauseInsert(pTerm->pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
487 if( pNew==0 ) return;
488 pNew->iPartner = pTerm->idx;
489 }else{
490 pDup = pExpr;
491 pNew = pTerm;
492 }
493 exprCommute(pDup);
494 pLeft = pDup->pLeft;
495 pNew->leftCursor = pLeft->iTable;
496 pNew->leftColumn = pLeft->iColumn;
497 pNew->prereqRight = prereqLeft;
498 pNew->prereqAll = prereqAll;
drhfe05af82005-07-21 03:14:59 +0000499 pNew->operator = operatorMask(pDup->op);
drh75897232000-05-29 14:26:00 +0000500 }
501 }
502}
503
drh0fcef5e2005-07-19 17:38:22 +0000504
drh75897232000-05-29 14:26:00 +0000505/*
drh51669862004-12-18 18:40:26 +0000506** This routine decides if pIdx can be used to satisfy the ORDER BY
507** clause. If it can, it returns 1. If pIdx cannot satisfy the
508** ORDER BY clause, this routine returns 0.
509**
510** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
511** left-most table in the FROM clause of that same SELECT statement and
512** the table has a cursor number of "base". pIdx is an index on pTab.
513**
514** nEqCol is the number of columns of pIdx that are used as equality
515** constraints. Any of these columns may be missing from the ORDER BY
516** clause and the match can still be a success.
517**
518** If the index is UNIQUE, then the ORDER BY clause is allowed to have
519** additional terms past the end of the index and the match will still
520** be a success.
521**
522** All terms of the ORDER BY that match against the index must be either
523** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
524** index do not need to satisfy this constraint.) The *pbRev value is
525** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
526** the ORDER BY clause is all ASC.
527*/
528static int isSortingIndex(
529 Parse *pParse, /* Parsing context */
530 Index *pIdx, /* The index we are testing */
531 Table *pTab, /* The table to be sorted */
532 int base, /* Cursor number for pTab */
533 ExprList *pOrderBy, /* The ORDER BY clause */
534 int nEqCol, /* Number of index columns with == constraints */
535 int *pbRev /* Set to 1 if ORDER BY is DESC */
536){
537 int i, j; /* Loop counters */
538 int sortOrder; /* Which direction we are sorting */
539 int nTerm; /* Number of ORDER BY terms */
540 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
541 sqlite3 *db = pParse->db;
542
543 assert( pOrderBy!=0 );
544 nTerm = pOrderBy->nExpr;
545 assert( nTerm>0 );
546
drh28c4cf42005-07-27 20:41:43 +0000547 /* A UNIQUE index that is fully specified is always a sorting
548 ** index.
549 */
550 if( pIdx->onError!=OE_None && nEqCol==pIdx->nColumn ){
551 *pbRev = 0;
552 return 1;
553 }
554
drh51669862004-12-18 18:40:26 +0000555 /* Match terms of the ORDER BY clause against columns of
556 ** the index.
557 */
558 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
559 Expr *pExpr; /* The expression of the ORDER BY pTerm */
560 CollSeq *pColl; /* The collating sequence of pExpr */
561
562 pExpr = pTerm->pExpr;
563 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
564 /* Can not use an index sort on anything that is not a column in the
565 ** left-most table of the FROM clause */
566 return 0;
567 }
568 pColl = sqlite3ExprCollSeq(pParse, pExpr);
569 if( !pColl ) pColl = db->pDfltColl;
drh9012bcb2004-12-19 00:11:35 +0000570 if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
571 /* Term j of the ORDER BY clause does not match column i of the index */
572 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +0000573 /* If an index column that is constrained by == fails to match an
574 ** ORDER BY term, that is OK. Just ignore that column of the index
575 */
576 continue;
577 }else{
578 /* If an index column fails to match and is not constrained by ==
579 ** then the index cannot satisfy the ORDER BY constraint.
580 */
581 return 0;
582 }
583 }
584 if( i>nEqCol ){
585 if( pTerm->sortOrder!=sortOrder ){
586 /* Indices can only be used if all ORDER BY terms past the
587 ** equality constraints are all either DESC or ASC. */
588 return 0;
589 }
590 }else{
591 sortOrder = pTerm->sortOrder;
592 }
593 j++;
594 pTerm++;
595 }
596
597 /* The index can be used for sorting if all terms of the ORDER BY clause
598 ** or covered or if we ran out of index columns and the it is a UNIQUE
599 ** index.
600 */
601 if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
602 *pbRev = sortOrder==SQLITE_SO_DESC;
603 return 1;
604 }
605 return 0;
606}
607
608/*
drhb6c29892004-11-22 19:12:19 +0000609** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
610** by sorting in order of ROWID. Return true if so and set *pbRev to be
611** true for reverse ROWID and false for forward ROWID order.
612*/
613static int sortableByRowid(
614 int base, /* Cursor number for table to be sorted */
615 ExprList *pOrderBy, /* The ORDER BY clause */
616 int *pbRev /* Set to 1 if ORDER BY is DESC */
617){
618 Expr *p;
619
620 assert( pOrderBy!=0 );
621 assert( pOrderBy->nExpr>0 );
622 p = pOrderBy->a[0].pExpr;
623 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
624 *pbRev = pOrderBy->a[0].sortOrder;
625 return 1;
626 }
627 return 0;
628}
629
drhfe05af82005-07-21 03:14:59 +0000630/*
drh28c4cf42005-07-27 20:41:43 +0000631** Prepare a crude estimate of the logorithm of the input value.
632** The results need not be exact. This is only used for estimating
633** the total cost of performing operatings with O(logN) or O(NlogN)
634** complexity. Because N is just a guess, it is no great tragedy if
635** logN is a little off.
636**
637** We can assume N>=1.0;
638*/
639static double estLog(double N){
640 double logN = 1.0;
641 double x = 10.0;
642 while( N>x ){
643 logN = logN+1.0;
644 x *= 10;
645 }
646 return logN;
647}
648
649/*
drh51147ba2005-07-23 22:59:55 +0000650** Find the best index for accessing a particular table. Return a pointer
651** to the index, flags that describe how the index should be used, the
652** number of equality constraints and the "cost" for this index.
653**
654** The lowest cost index wins. The cost is an estimate of the amount of
655** CPU and disk I/O need to process the request using the selected index.
656** Factors that influence cost include:
657**
658** * The estimated number of rows that will be retrieved. (The
659** fewer the better.)
660**
661** * Whether or not sorting must occur.
662**
663** * Whether or not there must be separate lookups in the
664** index and in the main table.
665**
drhfe05af82005-07-21 03:14:59 +0000666*/
667static double bestIndex(
668 Parse *pParse, /* The parsing context */
669 WhereClause *pWC, /* The WHERE clause */
670 struct SrcList_item *pSrc, /* The FROM clause term to search */
671 Bitmask notReady, /* Mask of cursors that are not available */
672 ExprList *pOrderBy, /* The order by clause */
673 Index **ppIndex, /* Make *ppIndex point to the best index */
drh51147ba2005-07-23 22:59:55 +0000674 int *pFlags, /* Put flags describing this choice in *pFlags */
675 int *pnEq /* Put the number of == or IN constraints here */
drhfe05af82005-07-21 03:14:59 +0000676){
677 WhereTerm *pTerm;
drh51147ba2005-07-23 22:59:55 +0000678 Index *bestIdx = 0; /* Index that gives the lowest cost */
679 double lowestCost = 1.0e99; /* The cost of using bestIdx */
680 int bestFlags = 0; /* Flags associated with bestIdx */
681 int bestNEq = 0; /* Best value for nEq */
682 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
683 Index *pProbe; /* An index we are evaluating */
684 int rev; /* True to scan in reverse order */
685 int flags; /* Flags associated with pProbe */
686 int nEq; /* Number of == or IN constraints */
687 double cost; /* Cost of using pProbe */
drhfe05af82005-07-21 03:14:59 +0000688
drh51147ba2005-07-23 22:59:55 +0000689 TRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
690
691 /* Check for a rowid=EXPR or rowid IN (...) constraints
drhfe05af82005-07-21 03:14:59 +0000692 */
693 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
694 if( pTerm ){
695 *ppIndex = 0;
drh51147ba2005-07-23 22:59:55 +0000696 bestFlags = WHERE_ROWID_EQ;
drhfe05af82005-07-21 03:14:59 +0000697 if( pTerm->operator & WO_EQ ){
drh28c4cf42005-07-27 20:41:43 +0000698 /* Rowid== is always the best pick. Look no further. Because only
699 ** a single row is generated, output is always in sorted order */
drhfe05af82005-07-21 03:14:59 +0000700 *pFlags = WHERE_ROWID_EQ;
drh51147ba2005-07-23 22:59:55 +0000701 *pnEq = 1;
drhfe05af82005-07-21 03:14:59 +0000702 if( pOrderBy ) *pFlags |= WHERE_ORDERBY;
drh51147ba2005-07-23 22:59:55 +0000703 TRACE(("... best is rowid\n"));
704 return 0.0;
705 }else if( pTerm->operator & WO_LIST ){
drh28c4cf42005-07-27 20:41:43 +0000706 /* Rowid IN (LIST): cost is NlogN where N is the number of list
707 ** elements. */
drh51147ba2005-07-23 22:59:55 +0000708 lowestCost = pTerm->pExpr->pList->nExpr;
drh28c4cf42005-07-27 20:41:43 +0000709 lowestCost *= estLog(lowestCost);
drhfe05af82005-07-21 03:14:59 +0000710 }else{
drh28c4cf42005-07-27 20:41:43 +0000711 /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
712 ** in the result of the inner select. We have no way to estimate
713 ** that value so make a wild guess. */
714 lowestCost = 200.0;
drhfe05af82005-07-21 03:14:59 +0000715 }
drh51147ba2005-07-23 22:59:55 +0000716 TRACE(("... rowid IN cost: %g\n", lowestCost));
drhfe05af82005-07-21 03:14:59 +0000717 }
718
drh28c4cf42005-07-27 20:41:43 +0000719 /* Estimate the cost of a table scan. If we do not know how many
720 ** entries are in the table, use 1 million as a guess.
drhfe05af82005-07-21 03:14:59 +0000721 */
drh51147ba2005-07-23 22:59:55 +0000722 pProbe = pSrc->pTab->pIndex;
drh28c4cf42005-07-27 20:41:43 +0000723 cost = pProbe ? pProbe->aiRowEst[0] : 1000000.0;
724 TRACE(("... table scan base cost: %g\n", cost));
725 flags = WHERE_ROWID_RANGE;
726
727 /* Check for constraints on a range of rowids in a table scan.
728 */
drhfe05af82005-07-21 03:14:59 +0000729 pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
730 if( pTerm ){
drh51147ba2005-07-23 22:59:55 +0000731 if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
732 flags |= WHERE_TOP_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000733 cost *= 0.333; /* Guess that rowid<EXPR eliminates two-thirds or rows */
drhfe05af82005-07-21 03:14:59 +0000734 }
drh51147ba2005-07-23 22:59:55 +0000735 if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
736 flags |= WHERE_BTM_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000737 cost *= 0.333; /* Guess that rowid>EXPR eliminates two-thirds of rows */
drhfe05af82005-07-21 03:14:59 +0000738 }
drh28c4cf42005-07-27 20:41:43 +0000739 TRACE(("... rowid range reduces cost to %g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000740 }else{
741 flags = 0;
742 }
drh28c4cf42005-07-27 20:41:43 +0000743
744 /* If the table scan does not satisfy the ORDER BY clause, increase
745 ** the cost by NlogN to cover the expense of sorting. */
746 if( pOrderBy ){
747 if( sortableByRowid(iCur, pOrderBy, &rev) ){
748 flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
749 if( rev ){
750 flags |= WHERE_REVERSE;
751 }
752 }else{
753 cost += cost*estLog(cost);
754 TRACE(("... sorting increases cost to %g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000755 }
drh51147ba2005-07-23 22:59:55 +0000756 }
757 if( cost<lowestCost ){
758 lowestCost = cost;
drhfe05af82005-07-21 03:14:59 +0000759 bestFlags = flags;
760 }
761
762 /* Look at each index.
763 */
drh51147ba2005-07-23 22:59:55 +0000764 for(; pProbe; pProbe=pProbe->pNext){
765 int i; /* Loop counter */
drh28c4cf42005-07-27 20:41:43 +0000766 double inMultiplier = 1.0;
drh51147ba2005-07-23 22:59:55 +0000767
768 TRACE(("... index %s:\n", pProbe->zName));
drhfe05af82005-07-21 03:14:59 +0000769
770 /* Count the number of columns in the index that are satisfied
771 ** by x=EXPR constraints or x IN (...) constraints.
772 */
drh51147ba2005-07-23 22:59:55 +0000773 flags = 0;
drhfe05af82005-07-21 03:14:59 +0000774 for(i=0; i<pProbe->nColumn; i++){
775 int j = pProbe->aiColumn[i];
776 pTerm = findTerm(pWC, iCur, j, notReady, WO_EQ|WO_IN, pProbe);
777 if( pTerm==0 ) break;
drh51147ba2005-07-23 22:59:55 +0000778 flags |= WHERE_COLUMN_EQ;
779 if( pTerm->operator & WO_IN ){
780 flags |= WHERE_COLUMN_IN;
781 if( pTerm->operator & WO_SELECT ){
782 inMultiplier *= 100.0;
783 }else if( pTerm->operator & WO_LIST ){
784 inMultiplier *= pTerm->pExpr->pList->nExpr + 1.0;
drhfe05af82005-07-21 03:14:59 +0000785 }
786 }
787 }
drh28c4cf42005-07-27 20:41:43 +0000788 cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
drh51147ba2005-07-23 22:59:55 +0000789 nEq = i;
790 TRACE(("...... nEq=%d inMult=%g cost=%g\n", nEq, inMultiplier, cost));
drhfe05af82005-07-21 03:14:59 +0000791
drh51147ba2005-07-23 22:59:55 +0000792 /* Look for range constraints
drhfe05af82005-07-21 03:14:59 +0000793 */
drh51147ba2005-07-23 22:59:55 +0000794 if( nEq<pProbe->nColumn ){
795 int j = pProbe->aiColumn[nEq];
796 pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
797 if( pTerm ){
798 flags = WHERE_COLUMN_RANGE;
799 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
800 flags |= WHERE_TOP_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000801 cost *= 0.333;
drh51147ba2005-07-23 22:59:55 +0000802 }
803 if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
804 flags |= WHERE_BTM_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000805 cost *= 0.333;
drh51147ba2005-07-23 22:59:55 +0000806 }
807 TRACE(("...... range reduces cost to %g\n", cost));
808 }
809 }
810
drh28c4cf42005-07-27 20:41:43 +0000811 /* Add the additional cost of sorting if that is a factor.
drh51147ba2005-07-23 22:59:55 +0000812 */
drh28c4cf42005-07-27 20:41:43 +0000813 if( pOrderBy ){
814 if( (flags & WHERE_COLUMN_IN)==0 &&
drhfe05af82005-07-21 03:14:59 +0000815 isSortingIndex(pParse, pProbe, pSrc->pTab, iCur, pOrderBy, nEq, &rev) ){
drh28c4cf42005-07-27 20:41:43 +0000816 if( flags==0 ){
817 flags = WHERE_COLUMN_RANGE;
818 }
819 flags |= WHERE_ORDERBY;
820 if( rev ){
821 flags |= WHERE_REVERSE;
822 }
823 }else{
824 cost += cost*estLog(cost);
825 TRACE(("...... orderby reduces cost to %g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000826 }
drhfe05af82005-07-21 03:14:59 +0000827 }
828
829 /* Check to see if we can get away with using just the index without
drh51147ba2005-07-23 22:59:55 +0000830 ** ever reading the table. If that is the case, then halve the
831 ** cost of this index.
drhfe05af82005-07-21 03:14:59 +0000832 */
drh51147ba2005-07-23 22:59:55 +0000833 if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
drhfe05af82005-07-21 03:14:59 +0000834 Bitmask m = pSrc->colUsed;
835 int j;
836 for(j=0; j<pProbe->nColumn; j++){
837 int x = pProbe->aiColumn[j];
838 if( x<BMS-1 ){
839 m &= ~(((Bitmask)1)<<x);
840 }
841 }
842 if( m==0 ){
843 flags |= WHERE_IDX_ONLY;
drh51147ba2005-07-23 22:59:55 +0000844 cost *= 0.5;
845 TRACE(("...... idx-only reduces cost to %g\n", cost));
drhfe05af82005-07-21 03:14:59 +0000846 }
847 }
848
drh51147ba2005-07-23 22:59:55 +0000849 /* If this index has achieved the lowest cost so far, then use it.
drhfe05af82005-07-21 03:14:59 +0000850 */
drh51147ba2005-07-23 22:59:55 +0000851 if( cost < lowestCost ){
drhfe05af82005-07-21 03:14:59 +0000852 bestIdx = pProbe;
drh51147ba2005-07-23 22:59:55 +0000853 lowestCost = cost;
854 if( flags==0 ){
855 flags = WHERE_COLUMN_RANGE;
856 }
drhfe05af82005-07-21 03:14:59 +0000857 bestFlags = flags;
drh51147ba2005-07-23 22:59:55 +0000858 bestNEq = nEq;
drhfe05af82005-07-21 03:14:59 +0000859 }
860 }
861
drhfe05af82005-07-21 03:14:59 +0000862 /* Report the best result
863 */
864 *ppIndex = bestIdx;
drh51147ba2005-07-23 22:59:55 +0000865 TRACE(("best index is %s, cost=%g, flags=%x, nEq=%d\n",
866 bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
drhfe05af82005-07-21 03:14:59 +0000867 *pFlags = bestFlags;
drh51147ba2005-07-23 22:59:55 +0000868 *pnEq = bestNEq;
869 return lowestCost;
drhfe05af82005-07-21 03:14:59 +0000870}
871
drhb6c29892004-11-22 19:12:19 +0000872
873/*
drh2ffb1182004-07-19 19:14:01 +0000874** Disable a term in the WHERE clause. Except, do not disable the term
875** if it controls a LEFT OUTER JOIN and it did not originate in the ON
876** or USING clause of that join.
877**
878** Consider the term t2.z='ok' in the following queries:
879**
880** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
881** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
882** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
883**
drh23bf66d2004-12-14 03:34:34 +0000884** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +0000885** in the ON clause. The term is disabled in (3) because it is not part
886** of a LEFT OUTER JOIN. In (1), the term is not disabled.
887**
888** Disabling a term causes that term to not be tested in the inner loop
889** of the join. Disabling is an optimization. We would get the correct
890** results if nothing were ever disabled, but joins might run a little
891** slower. The trick is to disable as much as we can without disabling
892** too much. If we disabled in (1), we'd get the wrong answer.
893** See ticket #813.
894*/
drh0fcef5e2005-07-19 17:38:22 +0000895static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
896 if( pTerm
897 && (pTerm->flags & TERM_CODED)==0
898 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
899 ){
900 pTerm->flags |= TERM_CODED;
901 if( pTerm->iPartner>=0 ){
902 disableTerm(pLevel, &pTerm->pWC->a[pTerm->iPartner]);
903 }
drh2ffb1182004-07-19 19:14:01 +0000904 }
905}
906
907/*
drh94a11212004-09-25 13:12:14 +0000908** Generate code that builds a probe for an index. Details:
909**
910** * Check the top nColumn entries on the stack. If any
911** of those entries are NULL, jump immediately to brk,
912** which is the loop exit, since no index entry will match
913** if any part of the key is NULL.
914**
915** * Construct a probe entry from the top nColumn entries in
916** the stack with affinities appropriate for index pIdx.
917*/
918static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
919 sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
920 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
921 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
922 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
923 sqlite3IndexAffinityStr(v, pIdx);
924}
925
drhe8b97272005-07-19 22:22:12 +0000926
927/*
drh51147ba2005-07-23 22:59:55 +0000928** Generate code for a single equality term of the WHERE clause. An equality
929** term can be either X=expr or X IN (...). pTerm is the term to be
930** coded.
931**
932** The current value for the constraint is left on the top of the stack.
933**
934** For a constraint of the form X=expr, the expression is evaluated and its
935** result is left on the stack. For constraints of the form X IN (...)
936** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +0000937*/
938static void codeEqualityTerm(
939 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +0000940 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh94a11212004-09-25 13:12:14 +0000941 int brk, /* Jump here to abandon the loop */
942 WhereLevel *pLevel /* When level of the FROM clause we are working on */
943){
drh0fcef5e2005-07-19 17:38:22 +0000944 Expr *pX = pTerm->pExpr;
drh94a11212004-09-25 13:12:14 +0000945 if( pX->op!=TK_IN ){
946 assert( pX->op==TK_EQ );
947 sqlite3ExprCode(pParse, pX->pRight);
danielk1977b3bce662005-01-29 08:32:43 +0000948#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +0000949 }else{
danielk1977b3bce662005-01-29 08:32:43 +0000950 int iTab;
drhe23399f2005-07-22 00:31:39 +0000951 int *aIn;
drh94a11212004-09-25 13:12:14 +0000952 Vdbe *v = pParse->pVdbe;
danielk1977b3bce662005-01-29 08:32:43 +0000953
954 sqlite3CodeSubselect(pParse, pX);
955 iTab = pX->iTable;
drh94a11212004-09-25 13:12:14 +0000956 sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
danielk1977b3bce662005-01-29 08:32:43 +0000957 VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
drhe23399f2005-07-22 00:31:39 +0000958 pLevel->nIn++;
959 pLevel->aInLoop = aIn = sqliteRealloc(pLevel->aInLoop,
960 sizeof(pLevel->aInLoop[0])*3*pLevel->nIn);
961 if( aIn ){
962 aIn += pLevel->nIn*3 - 3;
963 aIn[0] = OP_Next;
964 aIn[1] = iTab;
965 aIn[2] = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
966 }
danielk1977b3bce662005-01-29 08:32:43 +0000967#endif
drh94a11212004-09-25 13:12:14 +0000968 }
drh0fcef5e2005-07-19 17:38:22 +0000969 disableTerm(pLevel, pTerm);
drh94a11212004-09-25 13:12:14 +0000970}
971
drh51147ba2005-07-23 22:59:55 +0000972/*
973** Generate code that will evaluate all == and IN constraints for an
974** index. The values for all constraints are left on the stack.
975**
976** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
977** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
978** The index has as many as three equality constraints, but in this
979** example, the third "c" value is an inequality. So only two
980** constraints are coded. This routine will generate code to evaluate
981** a==5 and b IN (1,2,3). The current values for a and b will be left
982** on the stack - a is the deepest and b the shallowest.
983**
984** In the example above nEq==2. But this subroutine works for any value
985** of nEq including 0. If nEq==0, this routine is nearly a no-op.
986** The only thing it does is allocate the pLevel->iMem memory cell.
987**
988** This routine always allocates at least one memory cell and puts
989** the address of that memory cell in pLevel->iMem. The code that
990** calls this routine will use pLevel->iMem to store the termination
991** key value of the loop. If one or more IN operators appear, then
992** this routine allocates an additional nEq memory cells for internal
993** use.
994*/
995static void codeAllEqualityTerms(
996 Parse *pParse, /* Parsing context */
997 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
998 WhereClause *pWC, /* The WHERE clause */
999 Bitmask notReady, /* Which parts of FROM have not yet been coded */
1000 int brk /* Jump here to end the loop */
1001){
1002 int nEq = pLevel->nEq; /* The number of == or IN constraints to code */
1003 int termsInMem = 0; /* If true, store value in mem[] cells */
1004 Vdbe *v = pParse->pVdbe; /* The virtual machine under construction */
1005 Index *pIdx = pLevel->pIdx; /* The index being used for this loop */
1006 int iCur = pLevel->iTabCur; /* The cursor of the table */
1007 WhereTerm *pTerm; /* A single constraint term */
1008 int j; /* Loop counter */
1009
1010 /* Figure out how many memory cells we will need then allocate them.
1011 ** We always need at least one used to store the loop terminator
1012 ** value. If there are IN operators we'll need one for each == or
1013 ** IN constraint.
1014 */
1015 pLevel->iMem = pParse->nMem++;
1016 if( pLevel->flags & WHERE_COLUMN_IN ){
1017 pParse->nMem += pLevel->nEq;
1018 termsInMem = 1;
1019 }
1020
1021 /* Evaluate the equality constraints
1022 */
1023 for(j=0; 1; j++){
1024 int k = pIdx->aiColumn[j];
1025 pTerm = findTerm(pWC, iCur, k, notReady, WO_EQ|WO_IN, pIdx);
1026 if( pTerm==0 ) break;
1027 assert( (pTerm->flags & TERM_CODED)==0 );
1028 codeEqualityTerm(pParse, pTerm, brk, pLevel);
1029 if( termsInMem ){
1030 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1);
1031 }
1032 }
1033 assert( j==nEq );
1034
1035 /* Make sure all the constraint values are on the top of the stack
1036 */
1037 if( termsInMem ){
1038 for(j=0; j<nEq; j++){
1039 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem+j+1, 0);
1040 }
1041 }
1042}
1043
drh84bfda42005-07-15 13:05:21 +00001044#ifdef SQLITE_TEST
1045/*
1046** The following variable holds a text description of query plan generated
1047** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
1048** overwrites the previous. This information is used for testing and
1049** analysis only.
1050*/
1051char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
1052static int nQPlan = 0; /* Next free slow in _query_plan[] */
1053
1054#endif /* SQLITE_TEST */
1055
1056
drh94a11212004-09-25 13:12:14 +00001057
1058/*
drhe3184742002-06-19 14:27:05 +00001059** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00001060** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00001061** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00001062** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00001063** in order to complete the WHERE clause processing.
1064**
1065** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00001066**
1067** The basic idea is to do a nested loop, one loop for each table in
1068** the FROM clause of a select. (INSERT and UPDATE statements are the
1069** same as a SELECT with only a single table in the FROM clause.) For
1070** example, if the SQL is this:
1071**
1072** SELECT * FROM t1, t2, t3 WHERE ...;
1073**
1074** Then the code generated is conceptually like the following:
1075**
1076** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00001077** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00001078** foreach row3 in t3 do /
1079** ...
1080** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00001081** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00001082** end /
1083**
drh29dda4a2005-07-21 18:23:20 +00001084** Note that the loops might not be nested in the order in which they
1085** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00001086** use of indices. Note also that when the IN operator appears in
1087** the WHERE clause, it might result in additional nested loops for
1088** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00001089**
drhc27a1ce2002-06-14 20:58:45 +00001090** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00001091** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
1092** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00001093** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00001094**
drhe6f85e72004-12-25 01:03:13 +00001095** The code that sqlite3WhereBegin() generates leaves the cursors named
1096** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00001097** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00001098** data from the various tables of the loop.
1099**
drhc27a1ce2002-06-14 20:58:45 +00001100** If the WHERE clause is empty, the foreach loops must each scan their
1101** entire tables. Thus a three-way join is an O(N^3) operation. But if
1102** the tables have indices and there are terms in the WHERE clause that
1103** refer to those indices, a complete table scan can be avoided and the
1104** code will run much faster. Most of the work of this routine is checking
1105** to see if there are indices that can be used to speed up the loop.
1106**
1107** Terms of the WHERE clause are also used to limit which rows actually
1108** make it to the "..." in the middle of the loop. After each "foreach",
1109** terms of the WHERE clause that use only terms in that loop and outer
1110** loops are evaluated and if false a jump is made around all subsequent
1111** inner loops (or around the "..." if the test occurs within the inner-
1112** most loop)
1113**
1114** OUTER JOINS
1115**
1116** An outer join of tables t1 and t2 is conceptally coded as follows:
1117**
1118** foreach row1 in t1 do
1119** flag = 0
1120** foreach row2 in t2 do
1121** start:
1122** ...
1123** flag = 1
1124** end
drhe3184742002-06-19 14:27:05 +00001125** if flag==0 then
1126** move the row2 cursor to a null row
1127** goto start
1128** fi
drhc27a1ce2002-06-14 20:58:45 +00001129** end
1130**
drhe3184742002-06-19 14:27:05 +00001131** ORDER BY CLAUSE PROCESSING
1132**
1133** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
1134** if there is one. If there is no ORDER BY clause or if this routine
1135** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
1136**
1137** If an index can be used so that the natural output order of the table
1138** scan is correct for the ORDER BY clause, then that index is used and
1139** *ppOrderBy is set to NULL. This is an optimization that prevents an
1140** unnecessary sort of the result set if an index appropriate for the
1141** ORDER BY clause already exists.
1142**
1143** If the where clause loops cannot be arranged to provide the correct
1144** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +00001145*/
danielk19774adee202004-05-08 08:23:19 +00001146WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00001147 Parse *pParse, /* The parser context */
1148 SrcList *pTabList, /* A list of all tables to be scanned */
1149 Expr *pWhere, /* The WHERE clause */
drhf8db1bc2005-04-22 02:38:37 +00001150 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +00001151){
1152 int i; /* Loop counter */
1153 WhereInfo *pWInfo; /* Will become the return value of this function */
1154 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhd4f5ee22003-07-16 00:54:31 +00001155 int brk, cont = 0; /* Addresses used during code generation */
drhfe05af82005-07-21 03:14:59 +00001156 Bitmask notReady; /* Cursors that are not yet positioned */
drh0aa74ed2005-07-16 13:33:20 +00001157 WhereTerm *pTerm; /* A single term in the WHERE clause */
1158 ExprMaskSet maskSet; /* The expression mask set */
drh0aa74ed2005-07-16 13:33:20 +00001159 WhereClause wc; /* The WHERE clause is divided into these terms */
drh9012bcb2004-12-19 00:11:35 +00001160 struct SrcList_item *pTabItem; /* A single entry from pTabList */
1161 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh29dda4a2005-07-21 18:23:20 +00001162 int iFrom; /* First unused FROM clause element */
drh75897232000-05-29 14:26:00 +00001163
drh29dda4a2005-07-21 18:23:20 +00001164 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00001165 ** bits in a Bitmask
1166 */
drh29dda4a2005-07-21 18:23:20 +00001167 if( pTabList->nSrc>BMS ){
1168 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00001169 return 0;
1170 }
1171
drh83dcb1a2002-06-28 01:02:38 +00001172 /* Split the WHERE clause into separate subexpressions where each
drh29dda4a2005-07-21 18:23:20 +00001173 ** subexpression is separated by an AND operator.
drh83dcb1a2002-06-28 01:02:38 +00001174 */
drh6a3ea0e2003-05-02 14:32:12 +00001175 initMaskSet(&maskSet);
drhfe05af82005-07-21 03:14:59 +00001176 whereClauseInit(&wc, pParse);
drh0aa74ed2005-07-16 13:33:20 +00001177 whereSplit(&wc, pWhere);
drh1398ad32005-01-19 23:24:50 +00001178
drh75897232000-05-29 14:26:00 +00001179 /* Allocate and initialize the WhereInfo structure that will become the
1180 ** return value.
1181 */
drhad3cab52002-05-24 02:04:32 +00001182 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
danielk1977132872b2004-05-10 10:37:18 +00001183 if( sqlite3_malloc_failed ){
drhe23399f2005-07-22 00:31:39 +00001184 goto whereBeginNoMem;
drh75897232000-05-29 14:26:00 +00001185 }
1186 pWInfo->pParse = pParse;
1187 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +00001188 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh08192d52002-04-30 19:20:28 +00001189
1190 /* Special case: a WHERE clause that is constant. Evaluate the
1191 ** expression and either jump over all of the code or fall thru.
1192 */
danielk19774adee202004-05-08 08:23:19 +00001193 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
1194 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +00001195 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00001196 }
drh75897232000-05-29 14:26:00 +00001197
drh29dda4a2005-07-21 18:23:20 +00001198 /* Analyze all of the subexpressions. Note that exprAnalyze() might
1199 ** add new virtual terms onto the end of the WHERE clause. We do not
1200 ** want to analyze these virtual terms, so start analyzing at the end
1201 ** and work forward so that they added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00001202 */
drh1398ad32005-01-19 23:24:50 +00001203 for(i=0; i<pTabList->nSrc; i++){
1204 createMask(&maskSet, pTabList->a[i].iCursor);
1205 }
drh0fcef5e2005-07-19 17:38:22 +00001206 for(i=wc.nTerm-1; i>=0; i--){
1207 exprAnalyze(pTabList, &maskSet, &wc.a[i]);
drh75897232000-05-29 14:26:00 +00001208 }
1209
drh29dda4a2005-07-21 18:23:20 +00001210 /* Chose the best index to use for each table in the FROM clause.
1211 **
drh51147ba2005-07-23 22:59:55 +00001212 ** This loop fills in the following fields:
1213 **
1214 ** pWInfo->a[].pIdx The index to use for this level of the loop.
1215 ** pWInfo->a[].flags WHERE_xxx flags associated with pIdx
1216 ** pWInfo->a[].nEq The number of == and IN constraints
1217 ** pWInfo->a[].iFrom When term of the FROM clause is being coded
1218 ** pWInfo->a[].iTabCur The VDBE cursor for the database table
1219 ** pWInfo->a[].iIdxCur The VDBE cursor for the index
1220 **
1221 ** This loop also figures out the nesting order of tables in the FROM
1222 ** clause.
drh75897232000-05-29 14:26:00 +00001223 */
drhfe05af82005-07-21 03:14:59 +00001224 notReady = ~(Bitmask)0;
drh9012bcb2004-12-19 00:11:35 +00001225 pTabItem = pTabList->a;
1226 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001227 for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1228 Index *pIdx; /* Index for FROM table at pTabItem */
1229 int flags; /* Flags asssociated with pIdx */
drh51147ba2005-07-23 22:59:55 +00001230 int nEq; /* Number of == or IN constraints */
1231 double cost; /* The cost for pIdx */
drh29dda4a2005-07-21 18:23:20 +00001232 int j; /* For looping over FROM tables */
1233 Index *pBest = 0; /* The best index seen so far */
1234 int bestFlags = 0; /* Flags associated with pBest */
drh51147ba2005-07-23 22:59:55 +00001235 int bestNEq = 0; /* nEq associated with pBest */
1236 double lowestCost = 1.0e99; /* Cost of the pBest */
drh29dda4a2005-07-21 18:23:20 +00001237 int bestJ; /* The value of j */
1238 Bitmask m; /* Bitmask value for j or bestJ */
1239
1240 for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
1241 m = getMask(&maskSet, pTabItem->iCursor);
1242 if( (m & notReady)==0 ){
1243 if( j==iFrom ) iFrom++;
1244 continue;
1245 }
drh51147ba2005-07-23 22:59:55 +00001246 cost = bestIndex(pParse, &wc, pTabItem, notReady,
1247 (j==0 && ppOrderBy) ? *ppOrderBy : 0,
1248 &pIdx, &flags, &nEq);
1249 if( cost<lowestCost ){
1250 lowestCost = cost;
drh29dda4a2005-07-21 18:23:20 +00001251 pBest = pIdx;
1252 bestFlags = flags;
drh51147ba2005-07-23 22:59:55 +00001253 bestNEq = nEq;
drh29dda4a2005-07-21 18:23:20 +00001254 bestJ = j;
1255 }
1256 if( (pTabItem->jointype & JT_LEFT)!=0
1257 || (j>0 && (pTabItem[-1].jointype & JT_LEFT)!=0)
1258 ){
1259 break;
1260 }
1261 }
1262 if( bestFlags & WHERE_ORDERBY ){
drhfe05af82005-07-21 03:14:59 +00001263 *ppOrderBy = 0;
drhc4a3c772001-04-04 11:48:57 +00001264 }
drh29dda4a2005-07-21 18:23:20 +00001265 pLevel->flags = bestFlags;
drhfe05af82005-07-21 03:14:59 +00001266 pLevel->pIdx = pBest;
drh51147ba2005-07-23 22:59:55 +00001267 pLevel->nEq = bestNEq;
drhe23399f2005-07-22 00:31:39 +00001268 pLevel->aInLoop = 0;
1269 pLevel->nIn = 0;
drhfe05af82005-07-21 03:14:59 +00001270 if( pBest ){
drh9012bcb2004-12-19 00:11:35 +00001271 pLevel->iIdxCur = pParse->nTab++;
drhfe05af82005-07-21 03:14:59 +00001272 }else{
1273 pLevel->iIdxCur = -1;
drh6b563442001-11-07 16:48:26 +00001274 }
drh29dda4a2005-07-21 18:23:20 +00001275 notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
1276 pLevel->iFrom = bestJ;
drh75897232000-05-29 14:26:00 +00001277 }
1278
drh9012bcb2004-12-19 00:11:35 +00001279 /* Open all tables in the pTabList and any indices selected for
1280 ** searching those tables.
1281 */
1282 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
1283 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001284 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drh9012bcb2004-12-19 00:11:35 +00001285 Table *pTab;
1286 Index *pIx;
1287 int iIdxCur = pLevel->iIdxCur;
1288
drh29dda4a2005-07-21 18:23:20 +00001289 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001290 pTab = pTabItem->pTab;
1291 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001292 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001293 sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
1294 }
1295 pLevel->iTabCur = pTabItem->iCursor;
1296 if( (pIx = pLevel->pIdx)!=0 ){
1297 sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
drh29dda4a2005-07-21 18:23:20 +00001298 VdbeComment((v, "# %s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00001299 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
1300 (char*)&pIx->keyInfo, P3_KEYINFO);
1301 }
drhfe05af82005-07-21 03:14:59 +00001302 if( (pLevel->flags & WHERE_IDX_ONLY)!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001303 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
1304 }
1305 sqlite3CodeVerifySchema(pParse, pTab->iDb);
1306 }
1307 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
1308
drh29dda4a2005-07-21 18:23:20 +00001309 /* Generate the code to do the search. Each iteration of the for
1310 ** loop below generates code for a single nested loop of the VM
1311 ** program.
drh75897232000-05-29 14:26:00 +00001312 */
drhfe05af82005-07-21 03:14:59 +00001313 notReady = ~(Bitmask)0;
drh29dda4a2005-07-21 18:23:20 +00001314 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drhfe05af82005-07-21 03:14:59 +00001315 int j;
drh9012bcb2004-12-19 00:11:35 +00001316 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
1317 Index *pIdx; /* The index we will be using */
1318 int iIdxCur; /* The VDBE cursor for the index */
1319 int omitTable; /* True if we use the index only */
drh29dda4a2005-07-21 18:23:20 +00001320 int bRev; /* True if we need to scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001321
drh29dda4a2005-07-21 18:23:20 +00001322 pTabItem = &pTabList->a[pLevel->iFrom];
1323 iCur = pTabItem->iCursor;
drh9012bcb2004-12-19 00:11:35 +00001324 pIdx = pLevel->pIdx;
1325 iIdxCur = pLevel->iIdxCur;
drh29dda4a2005-07-21 18:23:20 +00001326 bRev = (pLevel->flags & WHERE_REVERSE)!=0;
drhfe05af82005-07-21 03:14:59 +00001327 omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
drh75897232000-05-29 14:26:00 +00001328
drh29dda4a2005-07-21 18:23:20 +00001329 /* Create labels for the "break" and "continue" instructions
1330 ** for the current loop. Jump to brk to break out of a loop.
1331 ** Jump to cont to go immediately to the next iteration of the
1332 ** loop.
1333 */
1334 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1335 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1336
drhad2d8302002-05-24 20:31:36 +00001337 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +00001338 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +00001339 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +00001340 */
drh29dda4a2005-07-21 18:23:20 +00001341 if( pLevel->iFrom>0 && (pTabItem[-1].jointype & JT_LEFT)!=0 ){
drhad2d8302002-05-24 20:31:36 +00001342 if( !pParse->nMem ) pParse->nMem++;
1343 pLevel->iLeftJoin = pParse->nMem++;
drhf0863fe2005-06-12 21:35:51 +00001344 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001345 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001346 VdbeComment((v, "# init LEFT JOIN no-match flag"));
drhad2d8302002-05-24 20:31:36 +00001347 }
1348
drhfe05af82005-07-21 03:14:59 +00001349 if( pLevel->flags & WHERE_ROWID_EQ ){
drh8aff1012001-12-22 14:49:24 +00001350 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +00001351 ** equality comparison against the ROWID field. Or
1352 ** we reference multiple rows using a "rowid IN (...)"
1353 ** construct.
drhc4a3c772001-04-04 11:48:57 +00001354 */
drhfe05af82005-07-21 03:14:59 +00001355 pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1356 assert( pTerm!=0 );
drh0fcef5e2005-07-19 17:38:22 +00001357 assert( pTerm->pExpr!=0 );
1358 assert( pTerm->leftCursor==iCur );
drh9012bcb2004-12-19 00:11:35 +00001359 assert( omitTable==0 );
drh94a11212004-09-25 13:12:14 +00001360 codeEqualityTerm(pParse, pTerm, brk, pLevel);
danielk19774adee202004-05-08 08:23:19 +00001361 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
danielk19774adee202004-05-08 08:23:19 +00001362 sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001363 VdbeComment((v, "pk"));
drh6b563442001-11-07 16:48:26 +00001364 pLevel->op = OP_Noop;
drhfe05af82005-07-21 03:14:59 +00001365 }else if( pLevel->flags & WHERE_ROWID_RANGE ){
drh51147ba2005-07-23 22:59:55 +00001366 /* Case 2: We have an inequality comparison against the ROWID field.
drh8aff1012001-12-22 14:49:24 +00001367 */
1368 int testOp = OP_Noop;
1369 int start;
drhfe05af82005-07-21 03:14:59 +00001370 WhereTerm *pStart, *pEnd;
drh8aff1012001-12-22 14:49:24 +00001371
drh9012bcb2004-12-19 00:11:35 +00001372 assert( omitTable==0 );
drhfe05af82005-07-21 03:14:59 +00001373 if( pLevel->flags & WHERE_BTM_LIMIT ){
1374 pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
1375 assert( pStart!=0 );
1376 }else{
1377 pStart = 0;
drhb6c29892004-11-22 19:12:19 +00001378 }
drhfe05af82005-07-21 03:14:59 +00001379 if( pLevel->flags & WHERE_TOP_LIMIT ){
1380 pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
1381 assert( pEnd!=0 );
1382 }else{
1383 pEnd = 0;
1384 }
drhfe05af82005-07-21 03:14:59 +00001385 if( bRev ){
1386 pTerm = pStart;
1387 pStart = pEnd;
1388 pEnd = pTerm;
1389 }
1390 if( pStart ){
drh94a11212004-09-25 13:12:14 +00001391 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001392 pX = pStart->pExpr;
drh94a11212004-09-25 13:12:14 +00001393 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001394 assert( pStart->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001395 sqlite3ExprCode(pParse, pX->pRight);
danielk1977d0a69322005-02-02 01:10:44 +00001396 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
drhb6c29892004-11-22 19:12:19 +00001397 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001398 VdbeComment((v, "pk"));
drhfe05af82005-07-21 03:14:59 +00001399 disableTerm(pLevel, pStart);
drh8aff1012001-12-22 14:49:24 +00001400 }else{
drhb6c29892004-11-22 19:12:19 +00001401 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
drh8aff1012001-12-22 14:49:24 +00001402 }
drhfe05af82005-07-21 03:14:59 +00001403 if( pEnd ){
drh94a11212004-09-25 13:12:14 +00001404 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001405 pX = pEnd->pExpr;
drh94a11212004-09-25 13:12:14 +00001406 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001407 assert( pEnd->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001408 sqlite3ExprCode(pParse, pX->pRight);
drh8aff1012001-12-22 14:49:24 +00001409 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001410 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drh94a11212004-09-25 13:12:14 +00001411 if( pX->op==TK_LT || pX->op==TK_GT ){
drhb6c29892004-11-22 19:12:19 +00001412 testOp = bRev ? OP_Le : OP_Ge;
drh8aff1012001-12-22 14:49:24 +00001413 }else{
drhb6c29892004-11-22 19:12:19 +00001414 testOp = bRev ? OP_Lt : OP_Gt;
drh8aff1012001-12-22 14:49:24 +00001415 }
drhfe05af82005-07-21 03:14:59 +00001416 disableTerm(pLevel, pEnd);
drh8aff1012001-12-22 14:49:24 +00001417 }
danielk19774adee202004-05-08 08:23:19 +00001418 start = sqlite3VdbeCurrentAddr(v);
drhb6c29892004-11-22 19:12:19 +00001419 pLevel->op = bRev ? OP_Prev : OP_Next;
drh6a3ea0e2003-05-02 14:32:12 +00001420 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001421 pLevel->p2 = start;
1422 if( testOp!=OP_Noop ){
drhf0863fe2005-06-12 21:35:51 +00001423 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001424 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drhf0863fe2005-06-12 21:35:51 +00001425 sqlite3VdbeAddOp(v, testOp, 'n', brk);
drh8aff1012001-12-22 14:49:24 +00001426 }
drhfe05af82005-07-21 03:14:59 +00001427 }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
drh51147ba2005-07-23 22:59:55 +00001428 /* Case 3: The WHERE clause term that refers to the right-most
drhc27a1ce2002-06-14 20:58:45 +00001429 ** column of the index is an inequality. For example, if
1430 ** the index is on (x,y,z) and the WHERE clause is of the
1431 ** form "x=5 AND y<10" then this case is used. Only the
1432 ** right-most column can be an inequality - the rest must
drh51147ba2005-07-23 22:59:55 +00001433 ** use the "==" and "IN" operators.
drhe3184742002-06-19 14:27:05 +00001434 **
1435 ** This case is also used when there are no WHERE clause
1436 ** constraints but an index is selected anyway, in order
1437 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +00001438 */
drh487ab3c2001-11-08 00:45:21 +00001439 int start;
drh51147ba2005-07-23 22:59:55 +00001440 int nEq = pLevel->nEq;
danielk1977f7df9cc2004-06-16 12:02:47 +00001441 int leFlag=0, geFlag=0;
drh487ab3c2001-11-08 00:45:21 +00001442 int testOp;
drhfe05af82005-07-21 03:14:59 +00001443 int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
1444 int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
drh487ab3c2001-11-08 00:45:21 +00001445
drh51147ba2005-07-23 22:59:55 +00001446 /* Generate code to evaluate all constraint terms using == or IN
1447 ** and level the values of those terms on the stack.
drh487ab3c2001-11-08 00:45:21 +00001448 */
drh51147ba2005-07-23 22:59:55 +00001449 codeAllEqualityTerms(pParse, pLevel, &wc, notReady, brk);
drh487ab3c2001-11-08 00:45:21 +00001450
drhc27a1ce2002-06-14 20:58:45 +00001451 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +00001452 ** used twice: once to make the termination key and once to make the
1453 ** start key.
1454 */
drh51147ba2005-07-23 22:59:55 +00001455 for(j=0; j<nEq; j++){
1456 sqlite3VdbeAddOp(v, OP_Dup, nEq-1, 0);
drh487ab3c2001-11-08 00:45:21 +00001457 }
1458
1459 /* Generate the termination key. This is the key value that
1460 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +00001461 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +00001462 **
1463 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1464 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +00001465 */
drhfe05af82005-07-21 03:14:59 +00001466 if( topLimit ){
drhe8b97272005-07-19 22:22:12 +00001467 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001468 int k = pIdx->aiColumn[j];
1469 pTerm = findTerm(&wc, iCur, k, notReady, WO_LT|WO_LE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001470 assert( pTerm!=0 );
1471 pX = pTerm->pExpr;
1472 assert( (pTerm->flags & TERM_CODED)==0 );
1473 sqlite3ExprCode(pParse, pX->pRight);
1474 leFlag = pX->op==TK_LE;
1475 disableTerm(pLevel, pTerm);
drh487ab3c2001-11-08 00:45:21 +00001476 testOp = OP_IdxGE;
1477 }else{
drh51147ba2005-07-23 22:59:55 +00001478 testOp = nEq>0 ? OP_IdxGE : OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001479 leFlag = 1;
1480 }
1481 if( testOp!=OP_Noop ){
drh51147ba2005-07-23 22:59:55 +00001482 int nCol = nEq + topLimit;
drh487ab3c2001-11-08 00:45:21 +00001483 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001484 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001485 if( bRev ){
drh7cf6e4d2004-05-19 14:56:55 +00001486 int op = leFlag ? OP_MoveLe : OP_MoveLt;
drh9012bcb2004-12-19 00:11:35 +00001487 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001488 }else{
danielk19774adee202004-05-08 08:23:19 +00001489 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001490 }
drhfe05af82005-07-21 03:14:59 +00001491 }else if( bRev ){
drh9012bcb2004-12-19 00:11:35 +00001492 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001493 }
1494
1495 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001496 ** bound on the search. There is no start key if there are no
1497 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001498 ** that case, generate a "Rewind" instruction in place of the
1499 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001500 **
1501 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1502 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001503 */
drhfe05af82005-07-21 03:14:59 +00001504 if( btmLimit ){
drhe8b97272005-07-19 22:22:12 +00001505 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001506 int k = pIdx->aiColumn[j];
1507 pTerm = findTerm(&wc, iCur, k, notReady, WO_GT|WO_GE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001508 assert( pTerm!=0 );
1509 pX = pTerm->pExpr;
1510 assert( (pTerm->flags & TERM_CODED)==0 );
1511 sqlite3ExprCode(pParse, pX->pRight);
1512 geFlag = pX->op==TK_GE;
1513 disableTerm(pLevel, pTerm);
drh7900ead2001-11-12 13:51:43 +00001514 }else{
1515 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001516 }
drh51147ba2005-07-23 22:59:55 +00001517 if( nEq>0 || btmLimit ){
1518 int nCol = nEq + btmLimit;
drh94a11212004-09-25 13:12:14 +00001519 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001520 if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001521 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001522 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001523 testOp = OP_IdxLT;
1524 }else{
drh7cf6e4d2004-05-19 14:56:55 +00001525 int op = geFlag ? OP_MoveGe : OP_MoveGt;
drh9012bcb2004-12-19 00:11:35 +00001526 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001527 }
drhfe05af82005-07-21 03:14:59 +00001528 }else if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001529 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001530 }else{
drh9012bcb2004-12-19 00:11:35 +00001531 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001532 }
1533
1534 /* Generate the the top of the loop. If there is a termination
1535 ** key we have to test for that key and abort at the top of the
1536 ** loop.
1537 */
danielk19774adee202004-05-08 08:23:19 +00001538 start = sqlite3VdbeCurrentAddr(v);
drh487ab3c2001-11-08 00:45:21 +00001539 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001540 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001541 sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
drhfe05af82005-07-21 03:14:59 +00001542 if( (leFlag && !bRev) || (!geFlag && bRev) ){
danielk19773d1bfea2004-05-14 11:00:53 +00001543 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
1544 }
drh487ab3c2001-11-08 00:45:21 +00001545 }
drh9012bcb2004-12-19 00:11:35 +00001546 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
drh51147ba2005-07-23 22:59:55 +00001547 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEq + topLimit, cont);
drhe6f85e72004-12-25 01:03:13 +00001548 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001549 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001550 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh487ab3c2001-11-08 00:45:21 +00001551 }
1552
1553 /* Record the instruction used to terminate the loop.
1554 */
drhfe05af82005-07-21 03:14:59 +00001555 pLevel->op = bRev ? OP_Prev : OP_Next;
drh9012bcb2004-12-19 00:11:35 +00001556 pLevel->p1 = iIdxCur;
drh487ab3c2001-11-08 00:45:21 +00001557 pLevel->p2 = start;
drh51147ba2005-07-23 22:59:55 +00001558 }else if( pLevel->flags & WHERE_COLUMN_EQ ){
1559 /* Case 4: There is an index and all terms of the WHERE clause that
1560 ** refer to the index using the "==" or "IN" operators.
1561 */
1562 int start;
1563 int nEq = pLevel->nEq;
1564
1565 /* Generate code to evaluate all constraint terms using == or IN
1566 ** and level the values of those terms on the stack.
1567 */
1568 codeAllEqualityTerms(pParse, pLevel, &wc, notReady, brk);
1569
1570 /* Generate a single key that will be used to both start and terminate
1571 ** the search
1572 */
1573 buildIndexProbe(v, nEq, brk, pIdx);
1574 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
1575
1576 /* Generate code (1) to move to the first matching element of the table.
1577 ** Then generate code (2) that jumps to "brk" after the cursor is past
1578 ** the last matching element of the table. The code (1) is executed
1579 ** once to initialize the search, the code (2) is executed before each
1580 ** iteration of the scan to see if the scan has finished. */
1581 if( bRev ){
1582 /* Scan in reverse order */
1583 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
1584 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1585 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
1586 pLevel->op = OP_Prev;
1587 }else{
1588 /* Scan in the forward order */
1589 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
1590 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1591 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
1592 pLevel->op = OP_Next;
1593 }
1594 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
1595 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEq, cont);
1596 if( !omitTable ){
1597 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
1598 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
1599 }
1600 pLevel->p1 = iIdxCur;
1601 pLevel->p2 = start;
drhfe05af82005-07-21 03:14:59 +00001602 }else{
1603 /* Case 5: There is no usable index. We must do a complete
1604 ** scan of the entire table.
1605 */
drhfe05af82005-07-21 03:14:59 +00001606 int opRewind;
1607
1608 assert( omitTable==0 );
drh29dda4a2005-07-21 18:23:20 +00001609 if( bRev ){
drhfe05af82005-07-21 03:14:59 +00001610 opRewind = OP_Last;
1611 pLevel->op = OP_Prev;
1612 }else{
1613 opRewind = OP_Rewind;
1614 pLevel->op = OP_Next;
1615 }
drhfe05af82005-07-21 03:14:59 +00001616 pLevel->p1 = iCur;
drh29dda4a2005-07-21 18:23:20 +00001617 pLevel->p2 = 1 + sqlite3VdbeAddOp(v, opRewind, iCur, brk);
drh75897232000-05-29 14:26:00 +00001618 }
drhfe05af82005-07-21 03:14:59 +00001619 notReady &= ~getMask(&maskSet, iCur);
drh75897232000-05-29 14:26:00 +00001620
1621 /* Insert code to test every subexpression that can be completely
1622 ** computed using the current set of tables.
1623 */
drh0fcef5e2005-07-19 17:38:22 +00001624 for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
1625 Expr *pE;
1626 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001627 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001628 pE = pTerm->pExpr;
1629 assert( pE!=0 );
drh392e5972005-07-08 14:14:22 +00001630 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
drh1f162302002-10-27 19:35:33 +00001631 continue;
1632 }
drh392e5972005-07-08 14:14:22 +00001633 sqlite3ExprIfFalse(pParse, pE, cont, 1);
drh0fcef5e2005-07-19 17:38:22 +00001634 pTerm->flags |= TERM_CODED;
drh75897232000-05-29 14:26:00 +00001635 }
drhad2d8302002-05-24 20:31:36 +00001636
1637 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1638 ** at least one row of the right table has matched the left table.
1639 */
1640 if( pLevel->iLeftJoin ){
danielk19774adee202004-05-08 08:23:19 +00001641 pLevel->top = sqlite3VdbeCurrentAddr(v);
1642 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1643 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001644 VdbeComment((v, "# record LEFT JOIN hit"));
drh0aa74ed2005-07-16 13:33:20 +00001645 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
drh0fcef5e2005-07-19 17:38:22 +00001646 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001647 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001648 assert( pTerm->pExpr );
1649 sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
1650 pTerm->flags |= TERM_CODED;
drh1cc093c2002-06-24 22:01:57 +00001651 }
drhad2d8302002-05-24 20:31:36 +00001652 }
drh75897232000-05-29 14:26:00 +00001653 }
drh7ec764a2005-07-21 03:48:20 +00001654
1655#ifdef SQLITE_TEST /* For testing and debugging use only */
1656 /* Record in the query plan information about the current table
1657 ** and the index used to access it (if any). If the table itself
1658 ** is not used, its name is just '{}'. If no index is used
1659 ** the index is listed as "{}". If the primary key is used the
1660 ** index name is '*'.
1661 */
1662 for(i=0; i<pTabList->nSrc; i++){
1663 char *z;
1664 int n;
drh7ec764a2005-07-21 03:48:20 +00001665 pLevel = &pWInfo->a[i];
drh29dda4a2005-07-21 18:23:20 +00001666 pTabItem = &pTabList->a[pLevel->iFrom];
drh7ec764a2005-07-21 03:48:20 +00001667 z = pTabItem->zAlias;
1668 if( z==0 ) z = pTabItem->pTab->zName;
1669 n = strlen(z);
1670 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
1671 if( pLevel->flags & WHERE_IDX_ONLY ){
1672 strcpy(&sqlite3_query_plan[nQPlan], "{}");
1673 nQPlan += 2;
1674 }else{
1675 strcpy(&sqlite3_query_plan[nQPlan], z);
1676 nQPlan += n;
1677 }
1678 sqlite3_query_plan[nQPlan++] = ' ';
1679 }
1680 if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
1681 strcpy(&sqlite3_query_plan[nQPlan], "* ");
1682 nQPlan += 2;
1683 }else if( pLevel->pIdx==0 ){
1684 strcpy(&sqlite3_query_plan[nQPlan], "{} ");
1685 nQPlan += 3;
1686 }else{
1687 n = strlen(pLevel->pIdx->zName);
1688 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
1689 strcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName);
1690 nQPlan += n;
1691 sqlite3_query_plan[nQPlan++] = ' ';
1692 }
1693 }
1694 }
1695 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
1696 sqlite3_query_plan[--nQPlan] = 0;
1697 }
1698 sqlite3_query_plan[nQPlan] = 0;
1699 nQPlan = 0;
1700#endif /* SQLITE_TEST // Testing and debugging use only */
1701
drh29dda4a2005-07-21 18:23:20 +00001702 /* Record the continuation address in the WhereInfo structure. Then
1703 ** clean up and return.
1704 */
drh75897232000-05-29 14:26:00 +00001705 pWInfo->iContinue = cont;
drh0aa74ed2005-07-16 13:33:20 +00001706 whereClauseClear(&wc);
drh75897232000-05-29 14:26:00 +00001707 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00001708
1709 /* Jump here if malloc fails */
1710whereBeginNoMem:
1711 whereClauseClear(&wc);
1712 sqliteFree(pWInfo);
1713 return 0;
drh75897232000-05-29 14:26:00 +00001714}
1715
1716/*
drhc27a1ce2002-06-14 20:58:45 +00001717** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00001718** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001719*/
danielk19774adee202004-05-08 08:23:19 +00001720void sqlite3WhereEnd(WhereInfo *pWInfo){
drh75897232000-05-29 14:26:00 +00001721 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001722 int i;
drh6b563442001-11-07 16:48:26 +00001723 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001724 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001725
drh9012bcb2004-12-19 00:11:35 +00001726 /* Generate loop termination code.
1727 */
drhad3cab52002-05-24 02:04:32 +00001728 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001729 pLevel = &pWInfo->a[i];
danielk19774adee202004-05-08 08:23:19 +00001730 sqlite3VdbeResolveLabel(v, pLevel->cont);
drh6b563442001-11-07 16:48:26 +00001731 if( pLevel->op!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001732 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001733 }
danielk19774adee202004-05-08 08:23:19 +00001734 sqlite3VdbeResolveLabel(v, pLevel->brk);
drhe23399f2005-07-22 00:31:39 +00001735 if( pLevel->nIn ){
1736 int *a;
1737 int j;
1738 for(j=pLevel->nIn, a=&pLevel->aInLoop[j*3-3]; j>0; j--, a-=3){
1739 sqlite3VdbeAddOp(v, a[0], a[1], a[2]);
1740 }
1741 sqliteFree(pLevel->aInLoop);
drhd99f7062002-06-08 23:25:08 +00001742 }
drhad2d8302002-05-24 20:31:36 +00001743 if( pLevel->iLeftJoin ){
1744 int addr;
danielk19774adee202004-05-08 08:23:19 +00001745 addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh9012bcb2004-12-19 00:11:35 +00001746 sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
danielk19774adee202004-05-08 08:23:19 +00001747 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
drh9012bcb2004-12-19 00:11:35 +00001748 if( pLevel->iIdxCur>=0 ){
1749 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
drh7f09b3e2002-08-13 13:15:49 +00001750 }
danielk19774adee202004-05-08 08:23:19 +00001751 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
drhad2d8302002-05-24 20:31:36 +00001752 }
drh19a775c2000-06-05 18:54:46 +00001753 }
drh9012bcb2004-12-19 00:11:35 +00001754
1755 /* The "break" point is here, just past the end of the outer loop.
1756 ** Set it.
1757 */
danielk19774adee202004-05-08 08:23:19 +00001758 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00001759
drh29dda4a2005-07-21 18:23:20 +00001760 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00001761 */
drh29dda4a2005-07-21 18:23:20 +00001762 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1763 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001764 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00001765 assert( pTab!=0 );
1766 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001767 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001768 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
1769 }
drh6b563442001-11-07 16:48:26 +00001770 if( pLevel->pIdx!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001771 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
1772 }
1773
drhacf3b982005-01-03 01:27:18 +00001774 /* Make cursor substitutions for cases where we want to use
drh9012bcb2004-12-19 00:11:35 +00001775 ** just the index and never reference the table.
1776 **
1777 ** Calls to the code generator in between sqlite3WhereBegin and
1778 ** sqlite3WhereEnd will have created code that references the table
1779 ** directly. This loop scans all that code looking for opcodes
1780 ** that reference the table and converts them into opcodes that
1781 ** reference the index.
1782 */
drhfe05af82005-07-21 03:14:59 +00001783 if( pLevel->flags & WHERE_IDX_ONLY ){
drh9012bcb2004-12-19 00:11:35 +00001784 int i, j, last;
1785 VdbeOp *pOp;
1786 Index *pIdx = pLevel->pIdx;
1787
1788 assert( pIdx!=0 );
1789 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1790 last = sqlite3VdbeCurrentAddr(v);
1791 for(i=pWInfo->iTop; i<last; i++, pOp++){
1792 if( pOp->p1!=pLevel->iTabCur ) continue;
1793 if( pOp->opcode==OP_Column ){
1794 pOp->p1 = pLevel->iIdxCur;
1795 for(j=0; j<pIdx->nColumn; j++){
1796 if( pOp->p2==pIdx->aiColumn[j] ){
1797 pOp->p2 = j;
1798 break;
1799 }
1800 }
drhf0863fe2005-06-12 21:35:51 +00001801 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00001802 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00001803 pOp->opcode = OP_IdxRowid;
danielk19776c18b6e2005-01-30 09:17:58 +00001804 }else if( pOp->opcode==OP_NullRow ){
1805 pOp->opcode = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001806 }
1807 }
drh6b563442001-11-07 16:48:26 +00001808 }
drh19a775c2000-06-05 18:54:46 +00001809 }
drh9012bcb2004-12-19 00:11:35 +00001810
1811 /* Final cleanup
1812 */
drh75897232000-05-29 14:26:00 +00001813 sqliteFree(pWInfo);
1814 return;
1815}