blob: 2dbcf2ea51576fe80d54c47534d4ff8d2d043b26 [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**
drh51147ba2005-07-23 22:59:55 +000019** $Id: where.c,v 1.152 2005/07/23 22:59:56 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
547 /* Match terms of the ORDER BY clause against columns of
548 ** the index.
549 */
550 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
551 Expr *pExpr; /* The expression of the ORDER BY pTerm */
552 CollSeq *pColl; /* The collating sequence of pExpr */
553
554 pExpr = pTerm->pExpr;
555 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
556 /* Can not use an index sort on anything that is not a column in the
557 ** left-most table of the FROM clause */
558 return 0;
559 }
560 pColl = sqlite3ExprCollSeq(pParse, pExpr);
561 if( !pColl ) pColl = db->pDfltColl;
drh9012bcb2004-12-19 00:11:35 +0000562 if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
563 /* Term j of the ORDER BY clause does not match column i of the index */
564 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +0000565 /* If an index column that is constrained by == fails to match an
566 ** ORDER BY term, that is OK. Just ignore that column of the index
567 */
568 continue;
569 }else{
570 /* If an index column fails to match and is not constrained by ==
571 ** then the index cannot satisfy the ORDER BY constraint.
572 */
573 return 0;
574 }
575 }
576 if( i>nEqCol ){
577 if( pTerm->sortOrder!=sortOrder ){
578 /* Indices can only be used if all ORDER BY terms past the
579 ** equality constraints are all either DESC or ASC. */
580 return 0;
581 }
582 }else{
583 sortOrder = pTerm->sortOrder;
584 }
585 j++;
586 pTerm++;
587 }
588
589 /* The index can be used for sorting if all terms of the ORDER BY clause
590 ** or covered or if we ran out of index columns and the it is a UNIQUE
591 ** index.
592 */
593 if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
594 *pbRev = sortOrder==SQLITE_SO_DESC;
595 return 1;
596 }
597 return 0;
598}
599
600/*
drhb6c29892004-11-22 19:12:19 +0000601** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
602** by sorting in order of ROWID. Return true if so and set *pbRev to be
603** true for reverse ROWID and false for forward ROWID order.
604*/
605static int sortableByRowid(
606 int base, /* Cursor number for table to be sorted */
607 ExprList *pOrderBy, /* The ORDER BY clause */
608 int *pbRev /* Set to 1 if ORDER BY is DESC */
609){
610 Expr *p;
611
612 assert( pOrderBy!=0 );
613 assert( pOrderBy->nExpr>0 );
614 p = pOrderBy->a[0].pExpr;
615 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
616 *pbRev = pOrderBy->a[0].sortOrder;
617 return 1;
618 }
619 return 0;
620}
621
drhfe05af82005-07-21 03:14:59 +0000622/*
drh51147ba2005-07-23 22:59:55 +0000623** Find the best index for accessing a particular table. Return a pointer
624** to the index, flags that describe how the index should be used, the
625** number of equality constraints and the "cost" for this index.
626**
627** The lowest cost index wins. The cost is an estimate of the amount of
628** CPU and disk I/O need to process the request using the selected index.
629** Factors that influence cost include:
630**
631** * The estimated number of rows that will be retrieved. (The
632** fewer the better.)
633**
634** * Whether or not sorting must occur.
635**
636** * Whether or not there must be separate lookups in the
637** index and in the main table.
638**
drhfe05af82005-07-21 03:14:59 +0000639*/
640static double bestIndex(
641 Parse *pParse, /* The parsing context */
642 WhereClause *pWC, /* The WHERE clause */
643 struct SrcList_item *pSrc, /* The FROM clause term to search */
644 Bitmask notReady, /* Mask of cursors that are not available */
645 ExprList *pOrderBy, /* The order by clause */
646 Index **ppIndex, /* Make *ppIndex point to the best index */
drh51147ba2005-07-23 22:59:55 +0000647 int *pFlags, /* Put flags describing this choice in *pFlags */
648 int *pnEq /* Put the number of == or IN constraints here */
drhfe05af82005-07-21 03:14:59 +0000649){
650 WhereTerm *pTerm;
drh51147ba2005-07-23 22:59:55 +0000651 Index *bestIdx = 0; /* Index that gives the lowest cost */
652 double lowestCost = 1.0e99; /* The cost of using bestIdx */
653 int bestFlags = 0; /* Flags associated with bestIdx */
654 int bestNEq = 0; /* Best value for nEq */
655 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
656 Index *pProbe; /* An index we are evaluating */
657 int rev; /* True to scan in reverse order */
658 int flags; /* Flags associated with pProbe */
659 int nEq; /* Number of == or IN constraints */
660 double cost; /* Cost of using pProbe */
drhfe05af82005-07-21 03:14:59 +0000661
drh51147ba2005-07-23 22:59:55 +0000662 TRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
663
664 /* Check for a rowid=EXPR or rowid IN (...) constraints
drhfe05af82005-07-21 03:14:59 +0000665 */
666 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
667 if( pTerm ){
668 *ppIndex = 0;
drh51147ba2005-07-23 22:59:55 +0000669 bestFlags = WHERE_ROWID_EQ;
drhfe05af82005-07-21 03:14:59 +0000670 if( pTerm->operator & WO_EQ ){
671 *pFlags = WHERE_ROWID_EQ;
drh51147ba2005-07-23 22:59:55 +0000672 *pnEq = 1;
drhfe05af82005-07-21 03:14:59 +0000673 if( pOrderBy ) *pFlags |= WHERE_ORDERBY;
drh51147ba2005-07-23 22:59:55 +0000674 TRACE(("... best is rowid\n"));
675 return 0.0;
676 }else if( pTerm->operator & WO_LIST ){
677 lowestCost = pTerm->pExpr->pList->nExpr;
drhfe05af82005-07-21 03:14:59 +0000678 }else{
drh51147ba2005-07-23 22:59:55 +0000679 lowestCost = 100.0;
drhfe05af82005-07-21 03:14:59 +0000680 }
drh51147ba2005-07-23 22:59:55 +0000681 TRACE(("... rowid IN cost: %g\n", lowestCost));
drhfe05af82005-07-21 03:14:59 +0000682 }
683
drh51147ba2005-07-23 22:59:55 +0000684 /* Check for constraints on a range of rowids or a full table scan.
drhfe05af82005-07-21 03:14:59 +0000685 */
drh51147ba2005-07-23 22:59:55 +0000686 pProbe = pSrc->pTab->pIndex;
687 cost = pProbe ? pProbe->aiRowEst[0] : 100000.0;
688 TRACE(("... base cost: %g\n", cost));
drhfe05af82005-07-21 03:14:59 +0000689 pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
690 if( pTerm ){
drh51147ba2005-07-23 22:59:55 +0000691 flags = WHERE_ROWID_RANGE;
692 if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
693 flags |= WHERE_TOP_LIMIT;
694 cost *= 0.25; /* Guess that rowid<EXPR eliminates 75% of the search */
drhfe05af82005-07-21 03:14:59 +0000695 }
drh51147ba2005-07-23 22:59:55 +0000696 if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
697 flags |= WHERE_BTM_LIMIT;
698 cost *= 0.25; /* Guess that rowid>EXPR eliminates 75% of the search */
drhfe05af82005-07-21 03:14:59 +0000699 }
drh51147ba2005-07-23 22:59:55 +0000700 TRACE(("... rowid range cost: %g\n", cost));
701 }else{
702 flags = 0;
703 }
704 if( pOrderBy && sortableByRowid(iCur, pOrderBy, &rev) ){
705 flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
706 cost *= 0.5;
707 if( rev ){
708 flags |= WHERE_REVERSE;
709 }
710 TRACE(("... order by reduces cost to %g\n", cost));
711 }
712 if( cost<lowestCost ){
713 lowestCost = cost;
drhfe05af82005-07-21 03:14:59 +0000714 bestFlags = flags;
715 }
716
717 /* Look at each index.
718 */
drh51147ba2005-07-23 22:59:55 +0000719 for(; pProbe; pProbe=pProbe->pNext){
720 int i; /* Loop counter */
721 double inMultiplier = 2.0; /* Includes built-in index lookup penalty */
722
723 TRACE(("... index %s:\n", pProbe->zName));
drhfe05af82005-07-21 03:14:59 +0000724
725 /* Count the number of columns in the index that are satisfied
726 ** by x=EXPR constraints or x IN (...) constraints.
727 */
drh51147ba2005-07-23 22:59:55 +0000728 flags = 0;
drhfe05af82005-07-21 03:14:59 +0000729 for(i=0; i<pProbe->nColumn; i++){
730 int j = pProbe->aiColumn[i];
731 pTerm = findTerm(pWC, iCur, j, notReady, WO_EQ|WO_IN, pProbe);
732 if( pTerm==0 ) break;
drh51147ba2005-07-23 22:59:55 +0000733 flags |= WHERE_COLUMN_EQ;
734 if( pTerm->operator & WO_IN ){
735 flags |= WHERE_COLUMN_IN;
736 if( pTerm->operator & WO_SELECT ){
737 inMultiplier *= 100.0;
738 }else if( pTerm->operator & WO_LIST ){
739 inMultiplier *= pTerm->pExpr->pList->nExpr + 1.0;
drhfe05af82005-07-21 03:14:59 +0000740 }
741 }
742 }
drh51147ba2005-07-23 22:59:55 +0000743 cost = pProbe->aiRowEst[i] * inMultiplier;
744 nEq = i;
745 TRACE(("...... nEq=%d inMult=%g cost=%g\n", nEq, inMultiplier, cost));
drhfe05af82005-07-21 03:14:59 +0000746
drh51147ba2005-07-23 22:59:55 +0000747 /* Look for range constraints
drhfe05af82005-07-21 03:14:59 +0000748 */
drh51147ba2005-07-23 22:59:55 +0000749 if( nEq<pProbe->nColumn ){
750 int j = pProbe->aiColumn[nEq];
751 pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
752 if( pTerm ){
753 flags = WHERE_COLUMN_RANGE;
754 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
755 flags |= WHERE_TOP_LIMIT;
756 cost *= 0.5;
757 }
758 if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
759 flags |= WHERE_BTM_LIMIT;
760 cost *= 0.5;
761 }
762 TRACE(("...... range reduces cost to %g\n", cost));
763 }
764 }
765
766 /* Reduce the cost substantially if this index can be used to satisfy
767 ** the ORDER BY clause
768 */
769 if( pOrderBy && (flags & WHERE_COLUMN_IN)==0 &&
drhfe05af82005-07-21 03:14:59 +0000770 isSortingIndex(pParse, pProbe, pSrc->pTab, iCur, pOrderBy, nEq, &rev) ){
drh51147ba2005-07-23 22:59:55 +0000771 if( flags==0 ){
772 flags = WHERE_COLUMN_RANGE;
773 }
drhfe05af82005-07-21 03:14:59 +0000774 flags |= WHERE_ORDERBY;
drh51147ba2005-07-23 22:59:55 +0000775 cost *= 0.5;
776 if( rev ){
777 flags |= WHERE_REVERSE;
778 }
779 TRACE(("...... orderby reduces cost to %g\n", cost));
drhfe05af82005-07-21 03:14:59 +0000780 }
781
782 /* Check to see if we can get away with using just the index without
drh51147ba2005-07-23 22:59:55 +0000783 ** ever reading the table. If that is the case, then halve the
784 ** cost of this index.
drhfe05af82005-07-21 03:14:59 +0000785 */
drh51147ba2005-07-23 22:59:55 +0000786 if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
drhfe05af82005-07-21 03:14:59 +0000787 Bitmask m = pSrc->colUsed;
788 int j;
789 for(j=0; j<pProbe->nColumn; j++){
790 int x = pProbe->aiColumn[j];
791 if( x<BMS-1 ){
792 m &= ~(((Bitmask)1)<<x);
793 }
794 }
795 if( m==0 ){
796 flags |= WHERE_IDX_ONLY;
drh51147ba2005-07-23 22:59:55 +0000797 cost *= 0.5;
798 TRACE(("...... idx-only reduces cost to %g\n", cost));
drhfe05af82005-07-21 03:14:59 +0000799 }
800 }
801
drh51147ba2005-07-23 22:59:55 +0000802 /* If this index has achieved the lowest cost so far, then use it.
drhfe05af82005-07-21 03:14:59 +0000803 */
drh51147ba2005-07-23 22:59:55 +0000804 if( cost < lowestCost ){
drhfe05af82005-07-21 03:14:59 +0000805 bestIdx = pProbe;
drh51147ba2005-07-23 22:59:55 +0000806 lowestCost = cost;
807 if( flags==0 ){
808 flags = WHERE_COLUMN_RANGE;
809 }
drhfe05af82005-07-21 03:14:59 +0000810 bestFlags = flags;
drh51147ba2005-07-23 22:59:55 +0000811 bestNEq = nEq;
drhfe05af82005-07-21 03:14:59 +0000812 }
813 }
814
drhfe05af82005-07-21 03:14:59 +0000815 /* Report the best result
816 */
817 *ppIndex = bestIdx;
drh51147ba2005-07-23 22:59:55 +0000818 TRACE(("best index is %s, cost=%g, flags=%x, nEq=%d\n",
819 bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
drhfe05af82005-07-21 03:14:59 +0000820 *pFlags = bestFlags;
drh51147ba2005-07-23 22:59:55 +0000821 *pnEq = bestNEq;
822 return lowestCost;
drhfe05af82005-07-21 03:14:59 +0000823}
824
drhb6c29892004-11-22 19:12:19 +0000825
826/*
drh2ffb1182004-07-19 19:14:01 +0000827** Disable a term in the WHERE clause. Except, do not disable the term
828** if it controls a LEFT OUTER JOIN and it did not originate in the ON
829** or USING clause of that join.
830**
831** Consider the term t2.z='ok' in the following queries:
832**
833** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
834** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
835** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
836**
drh23bf66d2004-12-14 03:34:34 +0000837** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +0000838** in the ON clause. The term is disabled in (3) because it is not part
839** of a LEFT OUTER JOIN. In (1), the term is not disabled.
840**
841** Disabling a term causes that term to not be tested in the inner loop
842** of the join. Disabling is an optimization. We would get the correct
843** results if nothing were ever disabled, but joins might run a little
844** slower. The trick is to disable as much as we can without disabling
845** too much. If we disabled in (1), we'd get the wrong answer.
846** See ticket #813.
847*/
drh0fcef5e2005-07-19 17:38:22 +0000848static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
849 if( pTerm
850 && (pTerm->flags & TERM_CODED)==0
851 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
852 ){
853 pTerm->flags |= TERM_CODED;
854 if( pTerm->iPartner>=0 ){
855 disableTerm(pLevel, &pTerm->pWC->a[pTerm->iPartner]);
856 }
drh2ffb1182004-07-19 19:14:01 +0000857 }
858}
859
860/*
drh94a11212004-09-25 13:12:14 +0000861** Generate code that builds a probe for an index. Details:
862**
863** * Check the top nColumn entries on the stack. If any
864** of those entries are NULL, jump immediately to brk,
865** which is the loop exit, since no index entry will match
866** if any part of the key is NULL.
867**
868** * Construct a probe entry from the top nColumn entries in
869** the stack with affinities appropriate for index pIdx.
870*/
871static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
872 sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
873 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
874 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
875 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
876 sqlite3IndexAffinityStr(v, pIdx);
877}
878
drhe8b97272005-07-19 22:22:12 +0000879
880/*
drh51147ba2005-07-23 22:59:55 +0000881** Generate code for a single equality term of the WHERE clause. An equality
882** term can be either X=expr or X IN (...). pTerm is the term to be
883** coded.
884**
885** The current value for the constraint is left on the top of the stack.
886**
887** For a constraint of the form X=expr, the expression is evaluated and its
888** result is left on the stack. For constraints of the form X IN (...)
889** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +0000890*/
891static void codeEqualityTerm(
892 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +0000893 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh94a11212004-09-25 13:12:14 +0000894 int brk, /* Jump here to abandon the loop */
895 WhereLevel *pLevel /* When level of the FROM clause we are working on */
896){
drh0fcef5e2005-07-19 17:38:22 +0000897 Expr *pX = pTerm->pExpr;
drh94a11212004-09-25 13:12:14 +0000898 if( pX->op!=TK_IN ){
899 assert( pX->op==TK_EQ );
900 sqlite3ExprCode(pParse, pX->pRight);
danielk1977b3bce662005-01-29 08:32:43 +0000901#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +0000902 }else{
danielk1977b3bce662005-01-29 08:32:43 +0000903 int iTab;
drhe23399f2005-07-22 00:31:39 +0000904 int *aIn;
drh94a11212004-09-25 13:12:14 +0000905 Vdbe *v = pParse->pVdbe;
danielk1977b3bce662005-01-29 08:32:43 +0000906
907 sqlite3CodeSubselect(pParse, pX);
908 iTab = pX->iTable;
drh94a11212004-09-25 13:12:14 +0000909 sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
danielk1977b3bce662005-01-29 08:32:43 +0000910 VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
drhe23399f2005-07-22 00:31:39 +0000911 pLevel->nIn++;
912 pLevel->aInLoop = aIn = sqliteRealloc(pLevel->aInLoop,
913 sizeof(pLevel->aInLoop[0])*3*pLevel->nIn);
914 if( aIn ){
915 aIn += pLevel->nIn*3 - 3;
916 aIn[0] = OP_Next;
917 aIn[1] = iTab;
918 aIn[2] = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
919 }
danielk1977b3bce662005-01-29 08:32:43 +0000920#endif
drh94a11212004-09-25 13:12:14 +0000921 }
drh0fcef5e2005-07-19 17:38:22 +0000922 disableTerm(pLevel, pTerm);
drh94a11212004-09-25 13:12:14 +0000923}
924
drh51147ba2005-07-23 22:59:55 +0000925/*
926** Generate code that will evaluate all == and IN constraints for an
927** index. The values for all constraints are left on the stack.
928**
929** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
930** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
931** The index has as many as three equality constraints, but in this
932** example, the third "c" value is an inequality. So only two
933** constraints are coded. This routine will generate code to evaluate
934** a==5 and b IN (1,2,3). The current values for a and b will be left
935** on the stack - a is the deepest and b the shallowest.
936**
937** In the example above nEq==2. But this subroutine works for any value
938** of nEq including 0. If nEq==0, this routine is nearly a no-op.
939** The only thing it does is allocate the pLevel->iMem memory cell.
940**
941** This routine always allocates at least one memory cell and puts
942** the address of that memory cell in pLevel->iMem. The code that
943** calls this routine will use pLevel->iMem to store the termination
944** key value of the loop. If one or more IN operators appear, then
945** this routine allocates an additional nEq memory cells for internal
946** use.
947*/
948static void codeAllEqualityTerms(
949 Parse *pParse, /* Parsing context */
950 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
951 WhereClause *pWC, /* The WHERE clause */
952 Bitmask notReady, /* Which parts of FROM have not yet been coded */
953 int brk /* Jump here to end the loop */
954){
955 int nEq = pLevel->nEq; /* The number of == or IN constraints to code */
956 int termsInMem = 0; /* If true, store value in mem[] cells */
957 Vdbe *v = pParse->pVdbe; /* The virtual machine under construction */
958 Index *pIdx = pLevel->pIdx; /* The index being used for this loop */
959 int iCur = pLevel->iTabCur; /* The cursor of the table */
960 WhereTerm *pTerm; /* A single constraint term */
961 int j; /* Loop counter */
962
963 /* Figure out how many memory cells we will need then allocate them.
964 ** We always need at least one used to store the loop terminator
965 ** value. If there are IN operators we'll need one for each == or
966 ** IN constraint.
967 */
968 pLevel->iMem = pParse->nMem++;
969 if( pLevel->flags & WHERE_COLUMN_IN ){
970 pParse->nMem += pLevel->nEq;
971 termsInMem = 1;
972 }
973
974 /* Evaluate the equality constraints
975 */
976 for(j=0; 1; j++){
977 int k = pIdx->aiColumn[j];
978 pTerm = findTerm(pWC, iCur, k, notReady, WO_EQ|WO_IN, pIdx);
979 if( pTerm==0 ) break;
980 assert( (pTerm->flags & TERM_CODED)==0 );
981 codeEqualityTerm(pParse, pTerm, brk, pLevel);
982 if( termsInMem ){
983 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1);
984 }
985 }
986 assert( j==nEq );
987
988 /* Make sure all the constraint values are on the top of the stack
989 */
990 if( termsInMem ){
991 for(j=0; j<nEq; j++){
992 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem+j+1, 0);
993 }
994 }
995}
996
drh84bfda42005-07-15 13:05:21 +0000997#ifdef SQLITE_TEST
998/*
999** The following variable holds a text description of query plan generated
1000** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
1001** overwrites the previous. This information is used for testing and
1002** analysis only.
1003*/
1004char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
1005static int nQPlan = 0; /* Next free slow in _query_plan[] */
1006
1007#endif /* SQLITE_TEST */
1008
1009
drh94a11212004-09-25 13:12:14 +00001010
1011/*
drhe3184742002-06-19 14:27:05 +00001012** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00001013** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00001014** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00001015** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00001016** in order to complete the WHERE clause processing.
1017**
1018** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00001019**
1020** The basic idea is to do a nested loop, one loop for each table in
1021** the FROM clause of a select. (INSERT and UPDATE statements are the
1022** same as a SELECT with only a single table in the FROM clause.) For
1023** example, if the SQL is this:
1024**
1025** SELECT * FROM t1, t2, t3 WHERE ...;
1026**
1027** Then the code generated is conceptually like the following:
1028**
1029** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00001030** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00001031** foreach row3 in t3 do /
1032** ...
1033** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00001034** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00001035** end /
1036**
drh29dda4a2005-07-21 18:23:20 +00001037** Note that the loops might not be nested in the order in which they
1038** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00001039** use of indices. Note also that when the IN operator appears in
1040** the WHERE clause, it might result in additional nested loops for
1041** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00001042**
drhc27a1ce2002-06-14 20:58:45 +00001043** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00001044** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
1045** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00001046** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00001047**
drhe6f85e72004-12-25 01:03:13 +00001048** The code that sqlite3WhereBegin() generates leaves the cursors named
1049** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00001050** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00001051** data from the various tables of the loop.
1052**
drhc27a1ce2002-06-14 20:58:45 +00001053** If the WHERE clause is empty, the foreach loops must each scan their
1054** entire tables. Thus a three-way join is an O(N^3) operation. But if
1055** the tables have indices and there are terms in the WHERE clause that
1056** refer to those indices, a complete table scan can be avoided and the
1057** code will run much faster. Most of the work of this routine is checking
1058** to see if there are indices that can be used to speed up the loop.
1059**
1060** Terms of the WHERE clause are also used to limit which rows actually
1061** make it to the "..." in the middle of the loop. After each "foreach",
1062** terms of the WHERE clause that use only terms in that loop and outer
1063** loops are evaluated and if false a jump is made around all subsequent
1064** inner loops (or around the "..." if the test occurs within the inner-
1065** most loop)
1066**
1067** OUTER JOINS
1068**
1069** An outer join of tables t1 and t2 is conceptally coded as follows:
1070**
1071** foreach row1 in t1 do
1072** flag = 0
1073** foreach row2 in t2 do
1074** start:
1075** ...
1076** flag = 1
1077** end
drhe3184742002-06-19 14:27:05 +00001078** if flag==0 then
1079** move the row2 cursor to a null row
1080** goto start
1081** fi
drhc27a1ce2002-06-14 20:58:45 +00001082** end
1083**
drhe3184742002-06-19 14:27:05 +00001084** ORDER BY CLAUSE PROCESSING
1085**
1086** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
1087** if there is one. If there is no ORDER BY clause or if this routine
1088** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
1089**
1090** If an index can be used so that the natural output order of the table
1091** scan is correct for the ORDER BY clause, then that index is used and
1092** *ppOrderBy is set to NULL. This is an optimization that prevents an
1093** unnecessary sort of the result set if an index appropriate for the
1094** ORDER BY clause already exists.
1095**
1096** If the where clause loops cannot be arranged to provide the correct
1097** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +00001098*/
danielk19774adee202004-05-08 08:23:19 +00001099WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00001100 Parse *pParse, /* The parser context */
1101 SrcList *pTabList, /* A list of all tables to be scanned */
1102 Expr *pWhere, /* The WHERE clause */
drhf8db1bc2005-04-22 02:38:37 +00001103 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +00001104){
1105 int i; /* Loop counter */
1106 WhereInfo *pWInfo; /* Will become the return value of this function */
1107 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhd4f5ee22003-07-16 00:54:31 +00001108 int brk, cont = 0; /* Addresses used during code generation */
drhfe05af82005-07-21 03:14:59 +00001109 Bitmask notReady; /* Cursors that are not yet positioned */
drh0aa74ed2005-07-16 13:33:20 +00001110 WhereTerm *pTerm; /* A single term in the WHERE clause */
1111 ExprMaskSet maskSet; /* The expression mask set */
drh0aa74ed2005-07-16 13:33:20 +00001112 WhereClause wc; /* The WHERE clause is divided into these terms */
drh9012bcb2004-12-19 00:11:35 +00001113 struct SrcList_item *pTabItem; /* A single entry from pTabList */
1114 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh29dda4a2005-07-21 18:23:20 +00001115 int iFrom; /* First unused FROM clause element */
drh75897232000-05-29 14:26:00 +00001116
drh29dda4a2005-07-21 18:23:20 +00001117 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00001118 ** bits in a Bitmask
1119 */
drh29dda4a2005-07-21 18:23:20 +00001120 if( pTabList->nSrc>BMS ){
1121 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00001122 return 0;
1123 }
1124
drh83dcb1a2002-06-28 01:02:38 +00001125 /* Split the WHERE clause into separate subexpressions where each
drh29dda4a2005-07-21 18:23:20 +00001126 ** subexpression is separated by an AND operator.
drh83dcb1a2002-06-28 01:02:38 +00001127 */
drh6a3ea0e2003-05-02 14:32:12 +00001128 initMaskSet(&maskSet);
drhfe05af82005-07-21 03:14:59 +00001129 whereClauseInit(&wc, pParse);
drh0aa74ed2005-07-16 13:33:20 +00001130 whereSplit(&wc, pWhere);
drh1398ad32005-01-19 23:24:50 +00001131
drh75897232000-05-29 14:26:00 +00001132 /* Allocate and initialize the WhereInfo structure that will become the
1133 ** return value.
1134 */
drhad3cab52002-05-24 02:04:32 +00001135 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
danielk1977132872b2004-05-10 10:37:18 +00001136 if( sqlite3_malloc_failed ){
drhe23399f2005-07-22 00:31:39 +00001137 goto whereBeginNoMem;
drh75897232000-05-29 14:26:00 +00001138 }
1139 pWInfo->pParse = pParse;
1140 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +00001141 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh08192d52002-04-30 19:20:28 +00001142
1143 /* Special case: a WHERE clause that is constant. Evaluate the
1144 ** expression and either jump over all of the code or fall thru.
1145 */
danielk19774adee202004-05-08 08:23:19 +00001146 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
1147 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +00001148 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00001149 }
drh75897232000-05-29 14:26:00 +00001150
drh29dda4a2005-07-21 18:23:20 +00001151 /* Analyze all of the subexpressions. Note that exprAnalyze() might
1152 ** add new virtual terms onto the end of the WHERE clause. We do not
1153 ** want to analyze these virtual terms, so start analyzing at the end
1154 ** and work forward so that they added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00001155 */
drh1398ad32005-01-19 23:24:50 +00001156 for(i=0; i<pTabList->nSrc; i++){
1157 createMask(&maskSet, pTabList->a[i].iCursor);
1158 }
drh0fcef5e2005-07-19 17:38:22 +00001159 for(i=wc.nTerm-1; i>=0; i--){
1160 exprAnalyze(pTabList, &maskSet, &wc.a[i]);
drh75897232000-05-29 14:26:00 +00001161 }
1162
drh29dda4a2005-07-21 18:23:20 +00001163 /* Chose the best index to use for each table in the FROM clause.
1164 **
drh51147ba2005-07-23 22:59:55 +00001165 ** This loop fills in the following fields:
1166 **
1167 ** pWInfo->a[].pIdx The index to use for this level of the loop.
1168 ** pWInfo->a[].flags WHERE_xxx flags associated with pIdx
1169 ** pWInfo->a[].nEq The number of == and IN constraints
1170 ** pWInfo->a[].iFrom When term of the FROM clause is being coded
1171 ** pWInfo->a[].iTabCur The VDBE cursor for the database table
1172 ** pWInfo->a[].iIdxCur The VDBE cursor for the index
1173 **
1174 ** This loop also figures out the nesting order of tables in the FROM
1175 ** clause.
drh75897232000-05-29 14:26:00 +00001176 */
drhfe05af82005-07-21 03:14:59 +00001177 notReady = ~(Bitmask)0;
drh9012bcb2004-12-19 00:11:35 +00001178 pTabItem = pTabList->a;
1179 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001180 for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1181 Index *pIdx; /* Index for FROM table at pTabItem */
1182 int flags; /* Flags asssociated with pIdx */
drh51147ba2005-07-23 22:59:55 +00001183 int nEq; /* Number of == or IN constraints */
1184 double cost; /* The cost for pIdx */
drh29dda4a2005-07-21 18:23:20 +00001185 int j; /* For looping over FROM tables */
1186 Index *pBest = 0; /* The best index seen so far */
1187 int bestFlags = 0; /* Flags associated with pBest */
drh51147ba2005-07-23 22:59:55 +00001188 int bestNEq = 0; /* nEq associated with pBest */
1189 double lowestCost = 1.0e99; /* Cost of the pBest */
drh29dda4a2005-07-21 18:23:20 +00001190 int bestJ; /* The value of j */
1191 Bitmask m; /* Bitmask value for j or bestJ */
1192
1193 for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
1194 m = getMask(&maskSet, pTabItem->iCursor);
1195 if( (m & notReady)==0 ){
1196 if( j==iFrom ) iFrom++;
1197 continue;
1198 }
drh51147ba2005-07-23 22:59:55 +00001199 cost = bestIndex(pParse, &wc, pTabItem, notReady,
1200 (j==0 && ppOrderBy) ? *ppOrderBy : 0,
1201 &pIdx, &flags, &nEq);
1202 if( cost<lowestCost ){
1203 lowestCost = cost;
drh29dda4a2005-07-21 18:23:20 +00001204 pBest = pIdx;
1205 bestFlags = flags;
drh51147ba2005-07-23 22:59:55 +00001206 bestNEq = nEq;
drh29dda4a2005-07-21 18:23:20 +00001207 bestJ = j;
1208 }
1209 if( (pTabItem->jointype & JT_LEFT)!=0
1210 || (j>0 && (pTabItem[-1].jointype & JT_LEFT)!=0)
1211 ){
1212 break;
1213 }
1214 }
1215 if( bestFlags & WHERE_ORDERBY ){
drhfe05af82005-07-21 03:14:59 +00001216 *ppOrderBy = 0;
drhc4a3c772001-04-04 11:48:57 +00001217 }
drh29dda4a2005-07-21 18:23:20 +00001218 pLevel->flags = bestFlags;
drhfe05af82005-07-21 03:14:59 +00001219 pLevel->pIdx = pBest;
drh51147ba2005-07-23 22:59:55 +00001220 pLevel->nEq = bestNEq;
drhe23399f2005-07-22 00:31:39 +00001221 pLevel->aInLoop = 0;
1222 pLevel->nIn = 0;
drhfe05af82005-07-21 03:14:59 +00001223 if( pBest ){
drh9012bcb2004-12-19 00:11:35 +00001224 pLevel->iIdxCur = pParse->nTab++;
drhfe05af82005-07-21 03:14:59 +00001225 }else{
1226 pLevel->iIdxCur = -1;
drh6b563442001-11-07 16:48:26 +00001227 }
drh29dda4a2005-07-21 18:23:20 +00001228 notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
1229 pLevel->iFrom = bestJ;
drh75897232000-05-29 14:26:00 +00001230 }
1231
drh9012bcb2004-12-19 00:11:35 +00001232 /* Open all tables in the pTabList and any indices selected for
1233 ** searching those tables.
1234 */
1235 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
1236 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001237 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drh9012bcb2004-12-19 00:11:35 +00001238 Table *pTab;
1239 Index *pIx;
1240 int iIdxCur = pLevel->iIdxCur;
1241
drh29dda4a2005-07-21 18:23:20 +00001242 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001243 pTab = pTabItem->pTab;
1244 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001245 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001246 sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
1247 }
1248 pLevel->iTabCur = pTabItem->iCursor;
1249 if( (pIx = pLevel->pIdx)!=0 ){
1250 sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
drh29dda4a2005-07-21 18:23:20 +00001251 VdbeComment((v, "# %s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00001252 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
1253 (char*)&pIx->keyInfo, P3_KEYINFO);
1254 }
drhfe05af82005-07-21 03:14:59 +00001255 if( (pLevel->flags & WHERE_IDX_ONLY)!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001256 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
1257 }
1258 sqlite3CodeVerifySchema(pParse, pTab->iDb);
1259 }
1260 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
1261
drh29dda4a2005-07-21 18:23:20 +00001262 /* Generate the code to do the search. Each iteration of the for
1263 ** loop below generates code for a single nested loop of the VM
1264 ** program.
drh75897232000-05-29 14:26:00 +00001265 */
drhfe05af82005-07-21 03:14:59 +00001266 notReady = ~(Bitmask)0;
drh29dda4a2005-07-21 18:23:20 +00001267 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drhfe05af82005-07-21 03:14:59 +00001268 int j;
drh9012bcb2004-12-19 00:11:35 +00001269 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
1270 Index *pIdx; /* The index we will be using */
1271 int iIdxCur; /* The VDBE cursor for the index */
1272 int omitTable; /* True if we use the index only */
drh29dda4a2005-07-21 18:23:20 +00001273 int bRev; /* True if we need to scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001274
drh29dda4a2005-07-21 18:23:20 +00001275 pTabItem = &pTabList->a[pLevel->iFrom];
1276 iCur = pTabItem->iCursor;
drh9012bcb2004-12-19 00:11:35 +00001277 pIdx = pLevel->pIdx;
1278 iIdxCur = pLevel->iIdxCur;
drh29dda4a2005-07-21 18:23:20 +00001279 bRev = (pLevel->flags & WHERE_REVERSE)!=0;
drhfe05af82005-07-21 03:14:59 +00001280 omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
drh75897232000-05-29 14:26:00 +00001281
drh29dda4a2005-07-21 18:23:20 +00001282 /* Create labels for the "break" and "continue" instructions
1283 ** for the current loop. Jump to brk to break out of a loop.
1284 ** Jump to cont to go immediately to the next iteration of the
1285 ** loop.
1286 */
1287 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1288 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1289
drhad2d8302002-05-24 20:31:36 +00001290 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +00001291 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +00001292 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +00001293 */
drh29dda4a2005-07-21 18:23:20 +00001294 if( pLevel->iFrom>0 && (pTabItem[-1].jointype & JT_LEFT)!=0 ){
drhad2d8302002-05-24 20:31:36 +00001295 if( !pParse->nMem ) pParse->nMem++;
1296 pLevel->iLeftJoin = pParse->nMem++;
drhf0863fe2005-06-12 21:35:51 +00001297 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001298 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001299 VdbeComment((v, "# init LEFT JOIN no-match flag"));
drhad2d8302002-05-24 20:31:36 +00001300 }
1301
drhfe05af82005-07-21 03:14:59 +00001302 if( pLevel->flags & WHERE_ROWID_EQ ){
drh8aff1012001-12-22 14:49:24 +00001303 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +00001304 ** equality comparison against the ROWID field. Or
1305 ** we reference multiple rows using a "rowid IN (...)"
1306 ** construct.
drhc4a3c772001-04-04 11:48:57 +00001307 */
drhfe05af82005-07-21 03:14:59 +00001308 pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1309 assert( pTerm!=0 );
drh0fcef5e2005-07-19 17:38:22 +00001310 assert( pTerm->pExpr!=0 );
1311 assert( pTerm->leftCursor==iCur );
drh9012bcb2004-12-19 00:11:35 +00001312 assert( omitTable==0 );
drh94a11212004-09-25 13:12:14 +00001313 codeEqualityTerm(pParse, pTerm, brk, pLevel);
danielk19774adee202004-05-08 08:23:19 +00001314 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
danielk19774adee202004-05-08 08:23:19 +00001315 sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001316 VdbeComment((v, "pk"));
drh6b563442001-11-07 16:48:26 +00001317 pLevel->op = OP_Noop;
drhfe05af82005-07-21 03:14:59 +00001318 }else if( pLevel->flags & WHERE_ROWID_RANGE ){
drh51147ba2005-07-23 22:59:55 +00001319 /* Case 2: We have an inequality comparison against the ROWID field.
drh8aff1012001-12-22 14:49:24 +00001320 */
1321 int testOp = OP_Noop;
1322 int start;
drhfe05af82005-07-21 03:14:59 +00001323 WhereTerm *pStart, *pEnd;
drh8aff1012001-12-22 14:49:24 +00001324
drh9012bcb2004-12-19 00:11:35 +00001325 assert( omitTable==0 );
drhfe05af82005-07-21 03:14:59 +00001326 if( pLevel->flags & WHERE_BTM_LIMIT ){
1327 pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
1328 assert( pStart!=0 );
1329 }else{
1330 pStart = 0;
drhb6c29892004-11-22 19:12:19 +00001331 }
drhfe05af82005-07-21 03:14:59 +00001332 if( pLevel->flags & WHERE_TOP_LIMIT ){
1333 pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
1334 assert( pEnd!=0 );
1335 }else{
1336 pEnd = 0;
1337 }
drhfe05af82005-07-21 03:14:59 +00001338 if( bRev ){
1339 pTerm = pStart;
1340 pStart = pEnd;
1341 pEnd = pTerm;
1342 }
1343 if( pStart ){
drh94a11212004-09-25 13:12:14 +00001344 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001345 pX = pStart->pExpr;
drh94a11212004-09-25 13:12:14 +00001346 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001347 assert( pStart->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001348 sqlite3ExprCode(pParse, pX->pRight);
danielk1977d0a69322005-02-02 01:10:44 +00001349 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
drhb6c29892004-11-22 19:12:19 +00001350 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001351 VdbeComment((v, "pk"));
drhfe05af82005-07-21 03:14:59 +00001352 disableTerm(pLevel, pStart);
drh8aff1012001-12-22 14:49:24 +00001353 }else{
drhb6c29892004-11-22 19:12:19 +00001354 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
drh8aff1012001-12-22 14:49:24 +00001355 }
drhfe05af82005-07-21 03:14:59 +00001356 if( pEnd ){
drh94a11212004-09-25 13:12:14 +00001357 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001358 pX = pEnd->pExpr;
drh94a11212004-09-25 13:12:14 +00001359 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001360 assert( pEnd->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001361 sqlite3ExprCode(pParse, pX->pRight);
drh8aff1012001-12-22 14:49:24 +00001362 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001363 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drh94a11212004-09-25 13:12:14 +00001364 if( pX->op==TK_LT || pX->op==TK_GT ){
drhb6c29892004-11-22 19:12:19 +00001365 testOp = bRev ? OP_Le : OP_Ge;
drh8aff1012001-12-22 14:49:24 +00001366 }else{
drhb6c29892004-11-22 19:12:19 +00001367 testOp = bRev ? OP_Lt : OP_Gt;
drh8aff1012001-12-22 14:49:24 +00001368 }
drhfe05af82005-07-21 03:14:59 +00001369 disableTerm(pLevel, pEnd);
drh8aff1012001-12-22 14:49:24 +00001370 }
danielk19774adee202004-05-08 08:23:19 +00001371 start = sqlite3VdbeCurrentAddr(v);
drhb6c29892004-11-22 19:12:19 +00001372 pLevel->op = bRev ? OP_Prev : OP_Next;
drh6a3ea0e2003-05-02 14:32:12 +00001373 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001374 pLevel->p2 = start;
1375 if( testOp!=OP_Noop ){
drhf0863fe2005-06-12 21:35:51 +00001376 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001377 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drhf0863fe2005-06-12 21:35:51 +00001378 sqlite3VdbeAddOp(v, testOp, 'n', brk);
drh8aff1012001-12-22 14:49:24 +00001379 }
drhfe05af82005-07-21 03:14:59 +00001380 }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
drh51147ba2005-07-23 22:59:55 +00001381 /* Case 3: The WHERE clause term that refers to the right-most
drhc27a1ce2002-06-14 20:58:45 +00001382 ** column of the index is an inequality. For example, if
1383 ** the index is on (x,y,z) and the WHERE clause is of the
1384 ** form "x=5 AND y<10" then this case is used. Only the
1385 ** right-most column can be an inequality - the rest must
drh51147ba2005-07-23 22:59:55 +00001386 ** use the "==" and "IN" operators.
drhe3184742002-06-19 14:27:05 +00001387 **
1388 ** This case is also used when there are no WHERE clause
1389 ** constraints but an index is selected anyway, in order
1390 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +00001391 */
drh487ab3c2001-11-08 00:45:21 +00001392 int start;
drh51147ba2005-07-23 22:59:55 +00001393 int nEq = pLevel->nEq;
danielk1977f7df9cc2004-06-16 12:02:47 +00001394 int leFlag=0, geFlag=0;
drh487ab3c2001-11-08 00:45:21 +00001395 int testOp;
drhfe05af82005-07-21 03:14:59 +00001396 int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
1397 int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
drh487ab3c2001-11-08 00:45:21 +00001398
drh51147ba2005-07-23 22:59:55 +00001399 /* Generate code to evaluate all constraint terms using == or IN
1400 ** and level the values of those terms on the stack.
drh487ab3c2001-11-08 00:45:21 +00001401 */
drh51147ba2005-07-23 22:59:55 +00001402 codeAllEqualityTerms(pParse, pLevel, &wc, notReady, brk);
drh487ab3c2001-11-08 00:45:21 +00001403
drhc27a1ce2002-06-14 20:58:45 +00001404 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +00001405 ** used twice: once to make the termination key and once to make the
1406 ** start key.
1407 */
drh51147ba2005-07-23 22:59:55 +00001408 for(j=0; j<nEq; j++){
1409 sqlite3VdbeAddOp(v, OP_Dup, nEq-1, 0);
drh487ab3c2001-11-08 00:45:21 +00001410 }
1411
1412 /* Generate the termination key. This is the key value that
1413 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +00001414 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +00001415 **
1416 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1417 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +00001418 */
drhfe05af82005-07-21 03:14:59 +00001419 if( topLimit ){
drhe8b97272005-07-19 22:22:12 +00001420 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001421 int k = pIdx->aiColumn[j];
1422 pTerm = findTerm(&wc, iCur, k, notReady, WO_LT|WO_LE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001423 assert( pTerm!=0 );
1424 pX = pTerm->pExpr;
1425 assert( (pTerm->flags & TERM_CODED)==0 );
1426 sqlite3ExprCode(pParse, pX->pRight);
1427 leFlag = pX->op==TK_LE;
1428 disableTerm(pLevel, pTerm);
drh487ab3c2001-11-08 00:45:21 +00001429 testOp = OP_IdxGE;
1430 }else{
drh51147ba2005-07-23 22:59:55 +00001431 testOp = nEq>0 ? OP_IdxGE : OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001432 leFlag = 1;
1433 }
1434 if( testOp!=OP_Noop ){
drh51147ba2005-07-23 22:59:55 +00001435 int nCol = nEq + topLimit;
drh487ab3c2001-11-08 00:45:21 +00001436 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001437 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001438 if( bRev ){
drh7cf6e4d2004-05-19 14:56:55 +00001439 int op = leFlag ? OP_MoveLe : OP_MoveLt;
drh9012bcb2004-12-19 00:11:35 +00001440 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001441 }else{
danielk19774adee202004-05-08 08:23:19 +00001442 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001443 }
drhfe05af82005-07-21 03:14:59 +00001444 }else if( bRev ){
drh9012bcb2004-12-19 00:11:35 +00001445 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001446 }
1447
1448 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001449 ** bound on the search. There is no start key if there are no
1450 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001451 ** that case, generate a "Rewind" instruction in place of the
1452 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001453 **
1454 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1455 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001456 */
drhfe05af82005-07-21 03:14:59 +00001457 if( btmLimit ){
drhe8b97272005-07-19 22:22:12 +00001458 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001459 int k = pIdx->aiColumn[j];
1460 pTerm = findTerm(&wc, iCur, k, notReady, WO_GT|WO_GE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001461 assert( pTerm!=0 );
1462 pX = pTerm->pExpr;
1463 assert( (pTerm->flags & TERM_CODED)==0 );
1464 sqlite3ExprCode(pParse, pX->pRight);
1465 geFlag = pX->op==TK_GE;
1466 disableTerm(pLevel, pTerm);
drh7900ead2001-11-12 13:51:43 +00001467 }else{
1468 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001469 }
drh51147ba2005-07-23 22:59:55 +00001470 if( nEq>0 || btmLimit ){
1471 int nCol = nEq + btmLimit;
drh94a11212004-09-25 13:12:14 +00001472 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001473 if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001474 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001475 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001476 testOp = OP_IdxLT;
1477 }else{
drh7cf6e4d2004-05-19 14:56:55 +00001478 int op = geFlag ? OP_MoveGe : OP_MoveGt;
drh9012bcb2004-12-19 00:11:35 +00001479 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001480 }
drhfe05af82005-07-21 03:14:59 +00001481 }else if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001482 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001483 }else{
drh9012bcb2004-12-19 00:11:35 +00001484 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001485 }
1486
1487 /* Generate the the top of the loop. If there is a termination
1488 ** key we have to test for that key and abort at the top of the
1489 ** loop.
1490 */
danielk19774adee202004-05-08 08:23:19 +00001491 start = sqlite3VdbeCurrentAddr(v);
drh487ab3c2001-11-08 00:45:21 +00001492 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001493 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001494 sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
drhfe05af82005-07-21 03:14:59 +00001495 if( (leFlag && !bRev) || (!geFlag && bRev) ){
danielk19773d1bfea2004-05-14 11:00:53 +00001496 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
1497 }
drh487ab3c2001-11-08 00:45:21 +00001498 }
drh9012bcb2004-12-19 00:11:35 +00001499 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
drh51147ba2005-07-23 22:59:55 +00001500 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEq + topLimit, cont);
drhe6f85e72004-12-25 01:03:13 +00001501 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001502 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001503 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh487ab3c2001-11-08 00:45:21 +00001504 }
1505
1506 /* Record the instruction used to terminate the loop.
1507 */
drhfe05af82005-07-21 03:14:59 +00001508 pLevel->op = bRev ? OP_Prev : OP_Next;
drh9012bcb2004-12-19 00:11:35 +00001509 pLevel->p1 = iIdxCur;
drh487ab3c2001-11-08 00:45:21 +00001510 pLevel->p2 = start;
drh51147ba2005-07-23 22:59:55 +00001511 }else if( pLevel->flags & WHERE_COLUMN_EQ ){
1512 /* Case 4: There is an index and all terms of the WHERE clause that
1513 ** refer to the index using the "==" or "IN" operators.
1514 */
1515 int start;
1516 int nEq = pLevel->nEq;
1517
1518 /* Generate code to evaluate all constraint terms using == or IN
1519 ** and level the values of those terms on the stack.
1520 */
1521 codeAllEqualityTerms(pParse, pLevel, &wc, notReady, brk);
1522
1523 /* Generate a single key that will be used to both start and terminate
1524 ** the search
1525 */
1526 buildIndexProbe(v, nEq, brk, pIdx);
1527 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
1528
1529 /* Generate code (1) to move to the first matching element of the table.
1530 ** Then generate code (2) that jumps to "brk" after the cursor is past
1531 ** the last matching element of the table. The code (1) is executed
1532 ** once to initialize the search, the code (2) is executed before each
1533 ** iteration of the scan to see if the scan has finished. */
1534 if( bRev ){
1535 /* Scan in reverse order */
1536 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
1537 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1538 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
1539 pLevel->op = OP_Prev;
1540 }else{
1541 /* Scan in the forward order */
1542 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
1543 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1544 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
1545 pLevel->op = OP_Next;
1546 }
1547 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
1548 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEq, cont);
1549 if( !omitTable ){
1550 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
1551 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
1552 }
1553 pLevel->p1 = iIdxCur;
1554 pLevel->p2 = start;
drhfe05af82005-07-21 03:14:59 +00001555 }else{
1556 /* Case 5: There is no usable index. We must do a complete
1557 ** scan of the entire table.
1558 */
drhfe05af82005-07-21 03:14:59 +00001559 int opRewind;
1560
1561 assert( omitTable==0 );
drh29dda4a2005-07-21 18:23:20 +00001562 if( bRev ){
drhfe05af82005-07-21 03:14:59 +00001563 opRewind = OP_Last;
1564 pLevel->op = OP_Prev;
1565 }else{
1566 opRewind = OP_Rewind;
1567 pLevel->op = OP_Next;
1568 }
drhfe05af82005-07-21 03:14:59 +00001569 pLevel->p1 = iCur;
drh29dda4a2005-07-21 18:23:20 +00001570 pLevel->p2 = 1 + sqlite3VdbeAddOp(v, opRewind, iCur, brk);
drh75897232000-05-29 14:26:00 +00001571 }
drhfe05af82005-07-21 03:14:59 +00001572 notReady &= ~getMask(&maskSet, iCur);
drh75897232000-05-29 14:26:00 +00001573
1574 /* Insert code to test every subexpression that can be completely
1575 ** computed using the current set of tables.
1576 */
drh0fcef5e2005-07-19 17:38:22 +00001577 for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
1578 Expr *pE;
1579 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001580 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001581 pE = pTerm->pExpr;
1582 assert( pE!=0 );
drh392e5972005-07-08 14:14:22 +00001583 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
drh1f162302002-10-27 19:35:33 +00001584 continue;
1585 }
drh392e5972005-07-08 14:14:22 +00001586 sqlite3ExprIfFalse(pParse, pE, cont, 1);
drh0fcef5e2005-07-19 17:38:22 +00001587 pTerm->flags |= TERM_CODED;
drh75897232000-05-29 14:26:00 +00001588 }
drhad2d8302002-05-24 20:31:36 +00001589
1590 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1591 ** at least one row of the right table has matched the left table.
1592 */
1593 if( pLevel->iLeftJoin ){
danielk19774adee202004-05-08 08:23:19 +00001594 pLevel->top = sqlite3VdbeCurrentAddr(v);
1595 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1596 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001597 VdbeComment((v, "# record LEFT JOIN hit"));
drh0aa74ed2005-07-16 13:33:20 +00001598 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
drh0fcef5e2005-07-19 17:38:22 +00001599 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001600 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001601 assert( pTerm->pExpr );
1602 sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
1603 pTerm->flags |= TERM_CODED;
drh1cc093c2002-06-24 22:01:57 +00001604 }
drhad2d8302002-05-24 20:31:36 +00001605 }
drh75897232000-05-29 14:26:00 +00001606 }
drh7ec764a2005-07-21 03:48:20 +00001607
1608#ifdef SQLITE_TEST /* For testing and debugging use only */
1609 /* Record in the query plan information about the current table
1610 ** and the index used to access it (if any). If the table itself
1611 ** is not used, its name is just '{}'. If no index is used
1612 ** the index is listed as "{}". If the primary key is used the
1613 ** index name is '*'.
1614 */
1615 for(i=0; i<pTabList->nSrc; i++){
1616 char *z;
1617 int n;
drh7ec764a2005-07-21 03:48:20 +00001618 pLevel = &pWInfo->a[i];
drh29dda4a2005-07-21 18:23:20 +00001619 pTabItem = &pTabList->a[pLevel->iFrom];
drh7ec764a2005-07-21 03:48:20 +00001620 z = pTabItem->zAlias;
1621 if( z==0 ) z = pTabItem->pTab->zName;
1622 n = strlen(z);
1623 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
1624 if( pLevel->flags & WHERE_IDX_ONLY ){
1625 strcpy(&sqlite3_query_plan[nQPlan], "{}");
1626 nQPlan += 2;
1627 }else{
1628 strcpy(&sqlite3_query_plan[nQPlan], z);
1629 nQPlan += n;
1630 }
1631 sqlite3_query_plan[nQPlan++] = ' ';
1632 }
1633 if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
1634 strcpy(&sqlite3_query_plan[nQPlan], "* ");
1635 nQPlan += 2;
1636 }else if( pLevel->pIdx==0 ){
1637 strcpy(&sqlite3_query_plan[nQPlan], "{} ");
1638 nQPlan += 3;
1639 }else{
1640 n = strlen(pLevel->pIdx->zName);
1641 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
1642 strcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName);
1643 nQPlan += n;
1644 sqlite3_query_plan[nQPlan++] = ' ';
1645 }
1646 }
1647 }
1648 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
1649 sqlite3_query_plan[--nQPlan] = 0;
1650 }
1651 sqlite3_query_plan[nQPlan] = 0;
1652 nQPlan = 0;
1653#endif /* SQLITE_TEST // Testing and debugging use only */
1654
drh29dda4a2005-07-21 18:23:20 +00001655 /* Record the continuation address in the WhereInfo structure. Then
1656 ** clean up and return.
1657 */
drh75897232000-05-29 14:26:00 +00001658 pWInfo->iContinue = cont;
drh0aa74ed2005-07-16 13:33:20 +00001659 whereClauseClear(&wc);
drh75897232000-05-29 14:26:00 +00001660 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00001661
1662 /* Jump here if malloc fails */
1663whereBeginNoMem:
1664 whereClauseClear(&wc);
1665 sqliteFree(pWInfo);
1666 return 0;
drh75897232000-05-29 14:26:00 +00001667}
1668
1669/*
drhc27a1ce2002-06-14 20:58:45 +00001670** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00001671** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001672*/
danielk19774adee202004-05-08 08:23:19 +00001673void sqlite3WhereEnd(WhereInfo *pWInfo){
drh75897232000-05-29 14:26:00 +00001674 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001675 int i;
drh6b563442001-11-07 16:48:26 +00001676 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001677 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001678
drh9012bcb2004-12-19 00:11:35 +00001679 /* Generate loop termination code.
1680 */
drhad3cab52002-05-24 02:04:32 +00001681 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001682 pLevel = &pWInfo->a[i];
danielk19774adee202004-05-08 08:23:19 +00001683 sqlite3VdbeResolveLabel(v, pLevel->cont);
drh6b563442001-11-07 16:48:26 +00001684 if( pLevel->op!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001685 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001686 }
danielk19774adee202004-05-08 08:23:19 +00001687 sqlite3VdbeResolveLabel(v, pLevel->brk);
drhe23399f2005-07-22 00:31:39 +00001688 if( pLevel->nIn ){
1689 int *a;
1690 int j;
1691 for(j=pLevel->nIn, a=&pLevel->aInLoop[j*3-3]; j>0; j--, a-=3){
1692 sqlite3VdbeAddOp(v, a[0], a[1], a[2]);
1693 }
1694 sqliteFree(pLevel->aInLoop);
drhd99f7062002-06-08 23:25:08 +00001695 }
drhad2d8302002-05-24 20:31:36 +00001696 if( pLevel->iLeftJoin ){
1697 int addr;
danielk19774adee202004-05-08 08:23:19 +00001698 addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh9012bcb2004-12-19 00:11:35 +00001699 sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
danielk19774adee202004-05-08 08:23:19 +00001700 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
drh9012bcb2004-12-19 00:11:35 +00001701 if( pLevel->iIdxCur>=0 ){
1702 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
drh7f09b3e2002-08-13 13:15:49 +00001703 }
danielk19774adee202004-05-08 08:23:19 +00001704 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
drhad2d8302002-05-24 20:31:36 +00001705 }
drh19a775c2000-06-05 18:54:46 +00001706 }
drh9012bcb2004-12-19 00:11:35 +00001707
1708 /* The "break" point is here, just past the end of the outer loop.
1709 ** Set it.
1710 */
danielk19774adee202004-05-08 08:23:19 +00001711 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00001712
drh29dda4a2005-07-21 18:23:20 +00001713 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00001714 */
drh29dda4a2005-07-21 18:23:20 +00001715 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1716 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001717 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00001718 assert( pTab!=0 );
1719 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001720 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001721 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
1722 }
drh6b563442001-11-07 16:48:26 +00001723 if( pLevel->pIdx!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001724 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
1725 }
1726
drhacf3b982005-01-03 01:27:18 +00001727 /* Make cursor substitutions for cases where we want to use
drh9012bcb2004-12-19 00:11:35 +00001728 ** just the index and never reference the table.
1729 **
1730 ** Calls to the code generator in between sqlite3WhereBegin and
1731 ** sqlite3WhereEnd will have created code that references the table
1732 ** directly. This loop scans all that code looking for opcodes
1733 ** that reference the table and converts them into opcodes that
1734 ** reference the index.
1735 */
drhfe05af82005-07-21 03:14:59 +00001736 if( pLevel->flags & WHERE_IDX_ONLY ){
drh9012bcb2004-12-19 00:11:35 +00001737 int i, j, last;
1738 VdbeOp *pOp;
1739 Index *pIdx = pLevel->pIdx;
1740
1741 assert( pIdx!=0 );
1742 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1743 last = sqlite3VdbeCurrentAddr(v);
1744 for(i=pWInfo->iTop; i<last; i++, pOp++){
1745 if( pOp->p1!=pLevel->iTabCur ) continue;
1746 if( pOp->opcode==OP_Column ){
1747 pOp->p1 = pLevel->iIdxCur;
1748 for(j=0; j<pIdx->nColumn; j++){
1749 if( pOp->p2==pIdx->aiColumn[j] ){
1750 pOp->p2 = j;
1751 break;
1752 }
1753 }
drhf0863fe2005-06-12 21:35:51 +00001754 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00001755 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00001756 pOp->opcode = OP_IdxRowid;
danielk19776c18b6e2005-01-30 09:17:58 +00001757 }else if( pOp->opcode==OP_NullRow ){
1758 pOp->opcode = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001759 }
1760 }
drh6b563442001-11-07 16:48:26 +00001761 }
drh19a775c2000-06-05 18:54:46 +00001762 }
drh9012bcb2004-12-19 00:11:35 +00001763
1764 /* Final cleanup
1765 */
drh75897232000-05-29 14:26:00 +00001766 sqliteFree(pWInfo);
1767 return;
1768}