blob: 88f96f4235cb3560bd79c450ec52e26db1740612 [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**
drha6110402005-07-28 20:51:19 +000019** $Id: where.c,v 1.155 2005/07/28 20:51:19 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
drha6110402005-07-28 20:51:19 +0000152#define WO_EQ 2
drh51147ba2005-07-23 22:59:55 +0000153#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
154#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
155#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
156#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
157
158/*
159** Value for flags returned by bestIndex()
160*/
161#define WHERE_ROWID_EQ 0x0001 /* rowid=EXPR or rowid IN (...) */
162#define WHERE_ROWID_RANGE 0x0002 /* rowid<EXPR and/or rowid>EXPR */
163#define WHERE_COLUMN_EQ 0x0010 /* x=EXPR or x IN (...) */
164#define WHERE_COLUMN_RANGE 0x0020 /* x<EXPR and/or x>EXPR */
165#define WHERE_COLUMN_IN 0x0040 /* x IN (...) */
166#define WHERE_TOP_LIMIT 0x0100 /* x<EXPR or x<=EXPR constraint */
167#define WHERE_BTM_LIMIT 0x0200 /* x>EXPR or x>=EXPR constraint */
168#define WHERE_IDX_ONLY 0x0800 /* Use index only - omit table */
169#define WHERE_ORDERBY 0x1000 /* Output will appear in correct order */
170#define WHERE_REVERSE 0x2000 /* Scan in reverse order */
171
172/*
drh0aa74ed2005-07-16 13:33:20 +0000173** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000174*/
drhfe05af82005-07-21 03:14:59 +0000175static void whereClauseInit(WhereClause *pWC, Parse *pParse){
176 pWC->pParse = pParse;
drh0aa74ed2005-07-16 13:33:20 +0000177 pWC->nTerm = 0;
178 pWC->nSlot = ARRAYSIZE(pWC->aStatic);
179 pWC->a = pWC->aStatic;
180}
181
182/*
183** Deallocate a WhereClause structure. The WhereClause structure
184** itself is not freed. This routine is the inverse of whereClauseInit().
185*/
186static void whereClauseClear(WhereClause *pWC){
187 int i;
188 WhereTerm *a;
189 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
190 if( a->flags & TERM_DYNAMIC ){
drh0fcef5e2005-07-19 17:38:22 +0000191 sqlite3ExprDelete(a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000192 }
193 }
194 if( pWC->a!=pWC->aStatic ){
195 sqliteFree(pWC->a);
196 }
197}
198
199/*
200** Add a new entries to the WhereClause structure. Increase the allocated
201** space as necessary.
202*/
drh0fcef5e2005-07-19 17:38:22 +0000203static WhereTerm *whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
drh0aa74ed2005-07-16 13:33:20 +0000204 WhereTerm *pTerm;
205 if( pWC->nTerm>=pWC->nSlot ){
206 WhereTerm *pOld = pWC->a;
207 pWC->a = sqliteMalloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
drh0fcef5e2005-07-19 17:38:22 +0000208 if( pWC->a==0 ) return 0;
drh0aa74ed2005-07-16 13:33:20 +0000209 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
210 if( pOld!=pWC->aStatic ){
211 sqliteFree(pOld);
212 }
213 pWC->nSlot *= 2;
214 }
drh0fcef5e2005-07-19 17:38:22 +0000215 pTerm = &pWC->a[pWC->nTerm];
216 pTerm->idx = pWC->nTerm;
217 pWC->nTerm++;
218 pTerm->pExpr = p;
drh0aa74ed2005-07-16 13:33:20 +0000219 pTerm->flags = flags;
drh0fcef5e2005-07-19 17:38:22 +0000220 pTerm->pWC = pWC;
221 pTerm->iPartner = -1;
222 return pTerm;
drh0aa74ed2005-07-16 13:33:20 +0000223}
drh75897232000-05-29 14:26:00 +0000224
225/*
drh51669862004-12-18 18:40:26 +0000226** This routine identifies subexpressions in the WHERE clause where
227** each subexpression is separate by the AND operator. aSlot is
228** filled with pointers to the subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000229**
drh51669862004-12-18 18:40:26 +0000230** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
231** \________/ \_______________/ \________________/
232** slot[0] slot[1] slot[2]
233**
234** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000235** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000236**
drh51147ba2005-07-23 22:59:55 +0000237** In the previous sentence and in the diagram, "slot[]" refers to
238** the WhereClause.a[] array. This array grows as needed to contain
239** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000240*/
drh0aa74ed2005-07-16 13:33:20 +0000241static void whereSplit(WhereClause *pWC, Expr *pExpr){
242 if( pExpr==0 ) return;
243 if( pExpr->op!=TK_AND ){
244 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000245 }else{
drh0aa74ed2005-07-16 13:33:20 +0000246 whereSplit(pWC, pExpr->pLeft);
247 whereSplit(pWC, pExpr->pRight);
drh75897232000-05-29 14:26:00 +0000248 }
drh75897232000-05-29 14:26:00 +0000249}
250
251/*
drh6a3ea0e2003-05-02 14:32:12 +0000252** Initialize an expression mask set
253*/
254#define initMaskSet(P) memset(P, 0, sizeof(*P))
255
256/*
drh1398ad32005-01-19 23:24:50 +0000257** Return the bitmask for the given cursor number. Return 0 if
258** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000259*/
drh51669862004-12-18 18:40:26 +0000260static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000261 int i;
262 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000263 if( pMaskSet->ix[i]==iCursor ){
264 return ((Bitmask)1)<<i;
265 }
drh6a3ea0e2003-05-02 14:32:12 +0000266 }
drh6a3ea0e2003-05-02 14:32:12 +0000267 return 0;
268}
269
270/*
drh1398ad32005-01-19 23:24:50 +0000271** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000272**
273** There is one cursor per table in the FROM clause. The number of
274** tables in the FROM clause is limited by a test early in the
275** sqlite3WhereBegin() routien. So we know that the pMaskSet->ix[]
276** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000277*/
278static void createMask(ExprMaskSet *pMaskSet, int iCursor){
drh0fcef5e2005-07-19 17:38:22 +0000279 assert( pMaskSet->n < ARRAYSIZE(pMaskSet->ix) );
280 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000281}
282
283/*
drh75897232000-05-29 14:26:00 +0000284** This routine walks (recursively) an expression tree and generates
285** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000286** tree.
drh75897232000-05-29 14:26:00 +0000287**
288** In order for this routine to work, the calling function must have
drh626a8792005-01-17 22:08:19 +0000289** previously invoked sqlite3ExprResolveNames() on the expression. See
drh75897232000-05-29 14:26:00 +0000290** the header comment on that routine for additional information.
drh626a8792005-01-17 22:08:19 +0000291** The sqlite3ExprResolveNames() routines looks for column names and
drh6a3ea0e2003-05-02 14:32:12 +0000292** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
drh51147ba2005-07-23 22:59:55 +0000293** the VDBE cursor number of the table. This routine just has to
294** translate the cursor numbers into bitmask values and OR all
295** the bitmasks together.
drh75897232000-05-29 14:26:00 +0000296*/
danielk1977b3bce662005-01-29 08:32:43 +0000297static Bitmask exprListTableUsage(ExprMaskSet *, ExprList *);
drh51669862004-12-18 18:40:26 +0000298static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
299 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000300 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000301 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000302 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000303 return mask;
drh75897232000-05-29 14:26:00 +0000304 }
danielk1977b3bce662005-01-29 08:32:43 +0000305 mask = exprTableUsage(pMaskSet, p->pRight);
306 mask |= exprTableUsage(pMaskSet, p->pLeft);
307 mask |= exprListTableUsage(pMaskSet, p->pList);
308 if( p->pSelect ){
309 Select *pS = p->pSelect;
310 mask |= exprListTableUsage(pMaskSet, pS->pEList);
311 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
312 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
313 mask |= exprTableUsage(pMaskSet, pS->pWhere);
314 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drh75897232000-05-29 14:26:00 +0000315 }
danielk1977b3bce662005-01-29 08:32:43 +0000316 return mask;
317}
318static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
319 int i;
320 Bitmask mask = 0;
321 if( pList ){
322 for(i=0; i<pList->nExpr; i++){
323 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000324 }
325 }
drh75897232000-05-29 14:26:00 +0000326 return mask;
327}
328
329/*
drh487ab3c2001-11-08 00:45:21 +0000330** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000331** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000332** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000333*/
334static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000335 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
336 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
337 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
338 assert( TK_GE==TK_EQ+4 );
drh9a432672004-10-04 13:38:09 +0000339 return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
drh487ab3c2001-11-08 00:45:21 +0000340}
341
342/*
drh51669862004-12-18 18:40:26 +0000343** Swap two objects of type T.
drh193bd772004-07-20 18:23:14 +0000344*/
345#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
346
347/*
drh0fcef5e2005-07-19 17:38:22 +0000348** Commute a comparision operator. Expressions of the form "X op Y"
349** are converted into "Y op X".
drh193bd772004-07-20 18:23:14 +0000350*/
drh0fcef5e2005-07-19 17:38:22 +0000351static void exprCommute(Expr *pExpr){
drhfe05af82005-07-21 03:14:59 +0000352 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drh0fcef5e2005-07-19 17:38:22 +0000353 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
354 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
355 if( pExpr->op>=TK_GT ){
356 assert( TK_LT==TK_GT+2 );
357 assert( TK_GE==TK_LE+2 );
358 assert( TK_GT>TK_EQ );
359 assert( TK_GT<TK_LE );
360 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
361 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000362 }
drh193bd772004-07-20 18:23:14 +0000363}
364
365/*
drhfe05af82005-07-21 03:14:59 +0000366** Translate from TK_xx operator to WO_xx bitmask.
367*/
368static int operatorMask(int op){
drh51147ba2005-07-23 22:59:55 +0000369 int c;
drhfe05af82005-07-21 03:14:59 +0000370 assert( allowedOp(op) );
371 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000372 c = WO_IN;
drhfe05af82005-07-21 03:14:59 +0000373 }else{
drh51147ba2005-07-23 22:59:55 +0000374 c = WO_EQ<<(op-TK_EQ);
drhfe05af82005-07-21 03:14:59 +0000375 }
drh51147ba2005-07-23 22:59:55 +0000376 assert( op!=TK_IN || c==WO_IN );
377 assert( op!=TK_EQ || c==WO_EQ );
378 assert( op!=TK_LT || c==WO_LT );
379 assert( op!=TK_LE || c==WO_LE );
380 assert( op!=TK_GT || c==WO_GT );
381 assert( op!=TK_GE || c==WO_GE );
382 return c;
drhfe05af82005-07-21 03:14:59 +0000383}
384
385/*
386** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
387** where X is a reference to the iColumn of table iCur and <op> is one of
388** the WO_xx operator codes specified by the op parameter.
389** Return a pointer to the term. Return 0 if not found.
390*/
391static WhereTerm *findTerm(
392 WhereClause *pWC, /* The WHERE clause to be searched */
393 int iCur, /* Cursor number of LHS */
394 int iColumn, /* Column number of LHS */
395 Bitmask notReady, /* RHS must not overlap with this mask */
drh51147ba2005-07-23 22:59:55 +0000396 u16 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000397 Index *pIdx /* Must be compatible with this index, if not NULL */
398){
399 WhereTerm *pTerm;
400 int k;
401 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
402 if( pTerm->leftCursor==iCur
403 && (pTerm->prereqRight & notReady)==0
404 && pTerm->leftColumn==iColumn
405 && (pTerm->operator & op)!=0
406 ){
407 if( iCur>=0 && pIdx ){
408 Expr *pX = pTerm->pExpr;
409 CollSeq *pColl;
410 char idxaff;
411 int k;
412 Parse *pParse = pWC->pParse;
413
414 idxaff = pIdx->pTable->aCol[iColumn].affinity;
415 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
416 pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
417 if( !pColl ){
418 if( pX->pRight ){
419 pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
420 }
421 if( !pColl ){
422 pColl = pParse->db->pDfltColl;
423 }
424 }
425 for(k=0; k<pIdx->nColumn && pIdx->aiColumn[k]!=iColumn; k++){}
426 assert( k<pIdx->nColumn );
427 if( pColl!=pIdx->keyInfo.aColl[k] ) continue;
428 }
429 return pTerm;
430 }
431 }
432 return 0;
433}
434
435/*
drh0aa74ed2005-07-16 13:33:20 +0000436** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +0000437** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +0000438** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +0000439** structure.
drh51147ba2005-07-23 22:59:55 +0000440**
441** If the expression is of the form "<expr> <op> X" it gets commuted
442** to the standard form of "X <op> <expr>". If the expression is of
443** the form "X <op> Y" where both X and Y are columns, then the original
444** expression is unchanged and a new virtual expression of the form
445** "Y <op> X" is added to the WHERE clause.
drh75897232000-05-29 14:26:00 +0000446*/
drh0fcef5e2005-07-19 17:38:22 +0000447static void exprAnalyze(
448 SrcList *pSrc, /* the FROM clause */
449 ExprMaskSet *pMaskSet, /* table masks */
450 WhereTerm *pTerm /* the WHERE clause term to be analyzed */
451){
452 Expr *pExpr = pTerm->pExpr;
453 Bitmask prereqLeft;
454 Bitmask prereqAll;
455 int idxRight;
456
457 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
458 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
459 pTerm->prereqAll = prereqAll = exprTableUsage(pMaskSet, pExpr);
460 pTerm->leftCursor = -1;
461 pTerm->iPartner = -1;
drhfe05af82005-07-21 03:14:59 +0000462 pTerm->operator = 0;
drh0fcef5e2005-07-19 17:38:22 +0000463 idxRight = -1;
464 if( allowedOp(pExpr->op) && (pTerm->prereqRight & prereqLeft)==0 ){
465 Expr *pLeft = pExpr->pLeft;
466 Expr *pRight = pExpr->pRight;
467 if( pLeft->op==TK_COLUMN ){
468 pTerm->leftCursor = pLeft->iTable;
469 pTerm->leftColumn = pLeft->iColumn;
drhfe05af82005-07-21 03:14:59 +0000470 pTerm->operator = operatorMask(pExpr->op);
drh75897232000-05-29 14:26:00 +0000471 }
drh0fcef5e2005-07-19 17:38:22 +0000472 if( pRight && pRight->op==TK_COLUMN ){
473 WhereTerm *pNew;
474 Expr *pDup;
475 if( pTerm->leftCursor>=0 ){
476 pDup = sqlite3ExprDup(pExpr);
477 pNew = whereClauseInsert(pTerm->pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
478 if( pNew==0 ) return;
479 pNew->iPartner = pTerm->idx;
480 }else{
481 pDup = pExpr;
482 pNew = pTerm;
483 }
484 exprCommute(pDup);
485 pLeft = pDup->pLeft;
486 pNew->leftCursor = pLeft->iTable;
487 pNew->leftColumn = pLeft->iColumn;
488 pNew->prereqRight = prereqLeft;
489 pNew->prereqAll = prereqAll;
drhfe05af82005-07-21 03:14:59 +0000490 pNew->operator = operatorMask(pDup->op);
drh75897232000-05-29 14:26:00 +0000491 }
492 }
493}
494
drh0fcef5e2005-07-19 17:38:22 +0000495
drh75897232000-05-29 14:26:00 +0000496/*
drh51669862004-12-18 18:40:26 +0000497** This routine decides if pIdx can be used to satisfy the ORDER BY
498** clause. If it can, it returns 1. If pIdx cannot satisfy the
499** ORDER BY clause, this routine returns 0.
500**
501** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
502** left-most table in the FROM clause of that same SELECT statement and
503** the table has a cursor number of "base". pIdx is an index on pTab.
504**
505** nEqCol is the number of columns of pIdx that are used as equality
506** constraints. Any of these columns may be missing from the ORDER BY
507** clause and the match can still be a success.
508**
509** If the index is UNIQUE, then the ORDER BY clause is allowed to have
510** additional terms past the end of the index and the match will still
511** be a success.
512**
513** All terms of the ORDER BY that match against the index must be either
514** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
515** index do not need to satisfy this constraint.) The *pbRev value is
516** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
517** the ORDER BY clause is all ASC.
518*/
519static int isSortingIndex(
520 Parse *pParse, /* Parsing context */
521 Index *pIdx, /* The index we are testing */
522 Table *pTab, /* The table to be sorted */
523 int base, /* Cursor number for pTab */
524 ExprList *pOrderBy, /* The ORDER BY clause */
525 int nEqCol, /* Number of index columns with == constraints */
526 int *pbRev /* Set to 1 if ORDER BY is DESC */
527){
528 int i, j; /* Loop counters */
529 int sortOrder; /* Which direction we are sorting */
530 int nTerm; /* Number of ORDER BY terms */
531 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
532 sqlite3 *db = pParse->db;
533
534 assert( pOrderBy!=0 );
535 nTerm = pOrderBy->nExpr;
536 assert( nTerm>0 );
537
drh28c4cf42005-07-27 20:41:43 +0000538 /* A UNIQUE index that is fully specified is always a sorting
539 ** index.
540 */
541 if( pIdx->onError!=OE_None && nEqCol==pIdx->nColumn ){
542 *pbRev = 0;
543 return 1;
544 }
545
drh51669862004-12-18 18:40:26 +0000546 /* Match terms of the ORDER BY clause against columns of
547 ** the index.
548 */
549 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
550 Expr *pExpr; /* The expression of the ORDER BY pTerm */
551 CollSeq *pColl; /* The collating sequence of pExpr */
552
553 pExpr = pTerm->pExpr;
554 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
555 /* Can not use an index sort on anything that is not a column in the
556 ** left-most table of the FROM clause */
557 return 0;
558 }
559 pColl = sqlite3ExprCollSeq(pParse, pExpr);
560 if( !pColl ) pColl = db->pDfltColl;
drh9012bcb2004-12-19 00:11:35 +0000561 if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
562 /* Term j of the ORDER BY clause does not match column i of the index */
563 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +0000564 /* If an index column that is constrained by == fails to match an
565 ** ORDER BY term, that is OK. Just ignore that column of the index
566 */
567 continue;
568 }else{
569 /* If an index column fails to match and is not constrained by ==
570 ** then the index cannot satisfy the ORDER BY constraint.
571 */
572 return 0;
573 }
574 }
575 if( i>nEqCol ){
576 if( pTerm->sortOrder!=sortOrder ){
577 /* Indices can only be used if all ORDER BY terms past the
578 ** equality constraints are all either DESC or ASC. */
579 return 0;
580 }
581 }else{
582 sortOrder = pTerm->sortOrder;
583 }
584 j++;
585 pTerm++;
586 }
587
588 /* The index can be used for sorting if all terms of the ORDER BY clause
589 ** or covered or if we ran out of index columns and the it is a UNIQUE
590 ** index.
591 */
592 if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
593 *pbRev = sortOrder==SQLITE_SO_DESC;
594 return 1;
595 }
596 return 0;
597}
598
599/*
drhb6c29892004-11-22 19:12:19 +0000600** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
601** by sorting in order of ROWID. Return true if so and set *pbRev to be
602** true for reverse ROWID and false for forward ROWID order.
603*/
604static int sortableByRowid(
605 int base, /* Cursor number for table to be sorted */
606 ExprList *pOrderBy, /* The ORDER BY clause */
607 int *pbRev /* Set to 1 if ORDER BY is DESC */
608){
609 Expr *p;
610
611 assert( pOrderBy!=0 );
612 assert( pOrderBy->nExpr>0 );
613 p = pOrderBy->a[0].pExpr;
614 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
615 *pbRev = pOrderBy->a[0].sortOrder;
616 return 1;
617 }
618 return 0;
619}
620
drhfe05af82005-07-21 03:14:59 +0000621/*
drh28c4cf42005-07-27 20:41:43 +0000622** Prepare a crude estimate of the logorithm of the input value.
623** The results need not be exact. This is only used for estimating
624** the total cost of performing operatings with O(logN) or O(NlogN)
625** complexity. Because N is just a guess, it is no great tragedy if
626** logN is a little off.
627**
628** We can assume N>=1.0;
629*/
630static double estLog(double N){
631 double logN = 1.0;
632 double x = 10.0;
633 while( N>x ){
634 logN = logN+1.0;
635 x *= 10;
636 }
637 return logN;
638}
639
640/*
drh51147ba2005-07-23 22:59:55 +0000641** Find the best index for accessing a particular table. Return a pointer
642** to the index, flags that describe how the index should be used, the
drha6110402005-07-28 20:51:19 +0000643** number of equality constraints, and the "cost" for this index.
drh51147ba2005-07-23 22:59:55 +0000644**
645** The lowest cost index wins. The cost is an estimate of the amount of
646** CPU and disk I/O need to process the request using the selected index.
647** Factors that influence cost include:
648**
649** * The estimated number of rows that will be retrieved. (The
650** fewer the better.)
651**
652** * Whether or not sorting must occur.
653**
654** * Whether or not there must be separate lookups in the
655** index and in the main table.
656**
drhfe05af82005-07-21 03:14:59 +0000657*/
658static double bestIndex(
659 Parse *pParse, /* The parsing context */
660 WhereClause *pWC, /* The WHERE clause */
661 struct SrcList_item *pSrc, /* The FROM clause term to search */
662 Bitmask notReady, /* Mask of cursors that are not available */
663 ExprList *pOrderBy, /* The order by clause */
664 Index **ppIndex, /* Make *ppIndex point to the best index */
drh51147ba2005-07-23 22:59:55 +0000665 int *pFlags, /* Put flags describing this choice in *pFlags */
666 int *pnEq /* Put the number of == or IN constraints here */
drhfe05af82005-07-21 03:14:59 +0000667){
668 WhereTerm *pTerm;
drh51147ba2005-07-23 22:59:55 +0000669 Index *bestIdx = 0; /* Index that gives the lowest cost */
670 double lowestCost = 1.0e99; /* The cost of using bestIdx */
671 int bestFlags = 0; /* Flags associated with bestIdx */
672 int bestNEq = 0; /* Best value for nEq */
673 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
674 Index *pProbe; /* An index we are evaluating */
675 int rev; /* True to scan in reverse order */
676 int flags; /* Flags associated with pProbe */
677 int nEq; /* Number of == or IN constraints */
678 double cost; /* Cost of using pProbe */
drhfe05af82005-07-21 03:14:59 +0000679
drh51147ba2005-07-23 22:59:55 +0000680 TRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
681
682 /* Check for a rowid=EXPR or rowid IN (...) constraints
drhfe05af82005-07-21 03:14:59 +0000683 */
684 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
685 if( pTerm ){
drha6110402005-07-28 20:51:19 +0000686 Expr *pExpr;
drhfe05af82005-07-21 03:14:59 +0000687 *ppIndex = 0;
drh51147ba2005-07-23 22:59:55 +0000688 bestFlags = WHERE_ROWID_EQ;
drhfe05af82005-07-21 03:14:59 +0000689 if( pTerm->operator & WO_EQ ){
drh28c4cf42005-07-27 20:41:43 +0000690 /* Rowid== is always the best pick. Look no further. Because only
691 ** a single row is generated, output is always in sorted order */
drhfe05af82005-07-21 03:14:59 +0000692 *pFlags = WHERE_ROWID_EQ;
drh51147ba2005-07-23 22:59:55 +0000693 *pnEq = 1;
drhfe05af82005-07-21 03:14:59 +0000694 if( pOrderBy ) *pFlags |= WHERE_ORDERBY;
drh51147ba2005-07-23 22:59:55 +0000695 TRACE(("... best is rowid\n"));
696 return 0.0;
drha6110402005-07-28 20:51:19 +0000697 }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
drh28c4cf42005-07-27 20:41:43 +0000698 /* Rowid IN (LIST): cost is NlogN where N is the number of list
699 ** elements. */
drha6110402005-07-28 20:51:19 +0000700 lowestCost = pExpr->pList->nExpr;
drh28c4cf42005-07-27 20:41:43 +0000701 lowestCost *= estLog(lowestCost);
drhfe05af82005-07-21 03:14:59 +0000702 }else{
drh28c4cf42005-07-27 20:41:43 +0000703 /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
704 ** in the result of the inner select. We have no way to estimate
705 ** that value so make a wild guess. */
706 lowestCost = 200.0;
drhfe05af82005-07-21 03:14:59 +0000707 }
drh3adc9ce2005-07-28 16:51:51 +0000708 TRACE(("... rowid IN cost: %.9g\n", lowestCost));
drhfe05af82005-07-21 03:14:59 +0000709 }
710
drh28c4cf42005-07-27 20:41:43 +0000711 /* Estimate the cost of a table scan. If we do not know how many
712 ** entries are in the table, use 1 million as a guess.
drhfe05af82005-07-21 03:14:59 +0000713 */
drh51147ba2005-07-23 22:59:55 +0000714 pProbe = pSrc->pTab->pIndex;
drh28c4cf42005-07-27 20:41:43 +0000715 cost = pProbe ? pProbe->aiRowEst[0] : 1000000.0;
drh3adc9ce2005-07-28 16:51:51 +0000716 TRACE(("... table scan base cost: %.9g\n", cost));
drh28c4cf42005-07-27 20:41:43 +0000717 flags = WHERE_ROWID_RANGE;
718
719 /* Check for constraints on a range of rowids in a table scan.
720 */
drhfe05af82005-07-21 03:14:59 +0000721 pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
722 if( pTerm ){
drh51147ba2005-07-23 22:59:55 +0000723 if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
724 flags |= WHERE_TOP_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000725 cost *= 0.333; /* Guess that rowid<EXPR eliminates two-thirds or rows */
drhfe05af82005-07-21 03:14:59 +0000726 }
drh51147ba2005-07-23 22:59:55 +0000727 if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
728 flags |= WHERE_BTM_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000729 cost *= 0.333; /* Guess that rowid>EXPR eliminates two-thirds of rows */
drhfe05af82005-07-21 03:14:59 +0000730 }
drh3adc9ce2005-07-28 16:51:51 +0000731 TRACE(("... rowid range reduces cost to %.9g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000732 }else{
733 flags = 0;
734 }
drh28c4cf42005-07-27 20:41:43 +0000735
736 /* If the table scan does not satisfy the ORDER BY clause, increase
737 ** the cost by NlogN to cover the expense of sorting. */
738 if( pOrderBy ){
739 if( sortableByRowid(iCur, pOrderBy, &rev) ){
740 flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
741 if( rev ){
742 flags |= WHERE_REVERSE;
743 }
744 }else{
745 cost += cost*estLog(cost);
drh3adc9ce2005-07-28 16:51:51 +0000746 TRACE(("... sorting increases cost to %.9g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000747 }
drh51147ba2005-07-23 22:59:55 +0000748 }
749 if( cost<lowestCost ){
750 lowestCost = cost;
drhfe05af82005-07-21 03:14:59 +0000751 bestFlags = flags;
752 }
753
754 /* Look at each index.
755 */
drh51147ba2005-07-23 22:59:55 +0000756 for(; pProbe; pProbe=pProbe->pNext){
757 int i; /* Loop counter */
drh28c4cf42005-07-27 20:41:43 +0000758 double inMultiplier = 1.0;
drh51147ba2005-07-23 22:59:55 +0000759
760 TRACE(("... index %s:\n", pProbe->zName));
drhfe05af82005-07-21 03:14:59 +0000761
762 /* Count the number of columns in the index that are satisfied
763 ** by x=EXPR constraints or x IN (...) constraints.
764 */
drh51147ba2005-07-23 22:59:55 +0000765 flags = 0;
drhfe05af82005-07-21 03:14:59 +0000766 for(i=0; i<pProbe->nColumn; i++){
767 int j = pProbe->aiColumn[i];
768 pTerm = findTerm(pWC, iCur, j, notReady, WO_EQ|WO_IN, pProbe);
769 if( pTerm==0 ) break;
drh51147ba2005-07-23 22:59:55 +0000770 flags |= WHERE_COLUMN_EQ;
771 if( pTerm->operator & WO_IN ){
drha6110402005-07-28 20:51:19 +0000772 Expr *pExpr = pTerm->pExpr;
drh51147ba2005-07-23 22:59:55 +0000773 flags |= WHERE_COLUMN_IN;
drha6110402005-07-28 20:51:19 +0000774 if( pExpr->pSelect!=0 ){
drh51147ba2005-07-23 22:59:55 +0000775 inMultiplier *= 100.0;
drha6110402005-07-28 20:51:19 +0000776 }else if( pExpr->pList!=0 ){
777 inMultiplier *= pExpr->pList->nExpr + 1.0;
drhfe05af82005-07-21 03:14:59 +0000778 }
779 }
780 }
drh28c4cf42005-07-27 20:41:43 +0000781 cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
drh51147ba2005-07-23 22:59:55 +0000782 nEq = i;
drh3adc9ce2005-07-28 16:51:51 +0000783 TRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n", nEq, inMultiplier, cost));
drhfe05af82005-07-21 03:14:59 +0000784
drh51147ba2005-07-23 22:59:55 +0000785 /* Look for range constraints
drhfe05af82005-07-21 03:14:59 +0000786 */
drh51147ba2005-07-23 22:59:55 +0000787 if( nEq<pProbe->nColumn ){
788 int j = pProbe->aiColumn[nEq];
789 pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
790 if( pTerm ){
drha6110402005-07-28 20:51:19 +0000791 flags |= WHERE_COLUMN_RANGE;
drh51147ba2005-07-23 22:59:55 +0000792 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
793 flags |= WHERE_TOP_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000794 cost *= 0.333;
drh51147ba2005-07-23 22:59:55 +0000795 }
796 if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
797 flags |= WHERE_BTM_LIMIT;
drh28c4cf42005-07-27 20:41:43 +0000798 cost *= 0.333;
drh51147ba2005-07-23 22:59:55 +0000799 }
drh3adc9ce2005-07-28 16:51:51 +0000800 TRACE(("...... range reduces cost to %.9g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000801 }
802 }
803
drh28c4cf42005-07-27 20:41:43 +0000804 /* Add the additional cost of sorting if that is a factor.
drh51147ba2005-07-23 22:59:55 +0000805 */
drh28c4cf42005-07-27 20:41:43 +0000806 if( pOrderBy ){
807 if( (flags & WHERE_COLUMN_IN)==0 &&
drhfe05af82005-07-21 03:14:59 +0000808 isSortingIndex(pParse, pProbe, pSrc->pTab, iCur, pOrderBy, nEq, &rev) ){
drh28c4cf42005-07-27 20:41:43 +0000809 if( flags==0 ){
810 flags = WHERE_COLUMN_RANGE;
811 }
812 flags |= WHERE_ORDERBY;
813 if( rev ){
814 flags |= WHERE_REVERSE;
815 }
816 }else{
817 cost += cost*estLog(cost);
drh3adc9ce2005-07-28 16:51:51 +0000818 TRACE(("...... orderby increases cost to %.9g\n", cost));
drh51147ba2005-07-23 22:59:55 +0000819 }
drhfe05af82005-07-21 03:14:59 +0000820 }
821
822 /* Check to see if we can get away with using just the index without
drh51147ba2005-07-23 22:59:55 +0000823 ** ever reading the table. If that is the case, then halve the
824 ** cost of this index.
drhfe05af82005-07-21 03:14:59 +0000825 */
drh51147ba2005-07-23 22:59:55 +0000826 if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
drhfe05af82005-07-21 03:14:59 +0000827 Bitmask m = pSrc->colUsed;
828 int j;
829 for(j=0; j<pProbe->nColumn; j++){
830 int x = pProbe->aiColumn[j];
831 if( x<BMS-1 ){
832 m &= ~(((Bitmask)1)<<x);
833 }
834 }
835 if( m==0 ){
836 flags |= WHERE_IDX_ONLY;
drh51147ba2005-07-23 22:59:55 +0000837 cost *= 0.5;
drh3adc9ce2005-07-28 16:51:51 +0000838 TRACE(("...... idx-only reduces cost to %.9g\n", cost));
drhfe05af82005-07-21 03:14:59 +0000839 }
840 }
841
drh51147ba2005-07-23 22:59:55 +0000842 /* If this index has achieved the lowest cost so far, then use it.
drhfe05af82005-07-21 03:14:59 +0000843 */
drh51147ba2005-07-23 22:59:55 +0000844 if( cost < lowestCost ){
drhfe05af82005-07-21 03:14:59 +0000845 bestIdx = pProbe;
drh51147ba2005-07-23 22:59:55 +0000846 lowestCost = cost;
drha6110402005-07-28 20:51:19 +0000847 assert( flags!=0 );
drhfe05af82005-07-21 03:14:59 +0000848 bestFlags = flags;
drh51147ba2005-07-23 22:59:55 +0000849 bestNEq = nEq;
drhfe05af82005-07-21 03:14:59 +0000850 }
851 }
852
drhfe05af82005-07-21 03:14:59 +0000853 /* Report the best result
854 */
855 *ppIndex = bestIdx;
drh3adc9ce2005-07-28 16:51:51 +0000856 TRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
drh51147ba2005-07-23 22:59:55 +0000857 bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
drhfe05af82005-07-21 03:14:59 +0000858 *pFlags = bestFlags;
drh51147ba2005-07-23 22:59:55 +0000859 *pnEq = bestNEq;
860 return lowestCost;
drhfe05af82005-07-21 03:14:59 +0000861}
862
drhb6c29892004-11-22 19:12:19 +0000863
864/*
drh2ffb1182004-07-19 19:14:01 +0000865** Disable a term in the WHERE clause. Except, do not disable the term
866** if it controls a LEFT OUTER JOIN and it did not originate in the ON
867** or USING clause of that join.
868**
869** Consider the term t2.z='ok' in the following queries:
870**
871** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
872** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
873** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
874**
drh23bf66d2004-12-14 03:34:34 +0000875** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +0000876** in the ON clause. The term is disabled in (3) because it is not part
877** of a LEFT OUTER JOIN. In (1), the term is not disabled.
878**
879** Disabling a term causes that term to not be tested in the inner loop
880** of the join. Disabling is an optimization. We would get the correct
881** results if nothing were ever disabled, but joins might run a little
882** slower. The trick is to disable as much as we can without disabling
883** too much. If we disabled in (1), we'd get the wrong answer.
884** See ticket #813.
885*/
drh0fcef5e2005-07-19 17:38:22 +0000886static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
887 if( pTerm
888 && (pTerm->flags & TERM_CODED)==0
889 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
890 ){
891 pTerm->flags |= TERM_CODED;
892 if( pTerm->iPartner>=0 ){
893 disableTerm(pLevel, &pTerm->pWC->a[pTerm->iPartner]);
894 }
drh2ffb1182004-07-19 19:14:01 +0000895 }
896}
897
898/*
drh94a11212004-09-25 13:12:14 +0000899** Generate code that builds a probe for an index. Details:
900**
901** * Check the top nColumn entries on the stack. If any
902** of those entries are NULL, jump immediately to brk,
903** which is the loop exit, since no index entry will match
904** if any part of the key is NULL.
905**
906** * Construct a probe entry from the top nColumn entries in
907** the stack with affinities appropriate for index pIdx.
908*/
909static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
910 sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
911 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
912 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
913 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
914 sqlite3IndexAffinityStr(v, pIdx);
915}
916
drhe8b97272005-07-19 22:22:12 +0000917
918/*
drh51147ba2005-07-23 22:59:55 +0000919** Generate code for a single equality term of the WHERE clause. An equality
920** term can be either X=expr or X IN (...). pTerm is the term to be
921** coded.
922**
923** The current value for the constraint is left on the top of the stack.
924**
925** For a constraint of the form X=expr, the expression is evaluated and its
926** result is left on the stack. For constraints of the form X IN (...)
927** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +0000928*/
929static void codeEqualityTerm(
930 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +0000931 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh94a11212004-09-25 13:12:14 +0000932 int brk, /* Jump here to abandon the loop */
933 WhereLevel *pLevel /* When level of the FROM clause we are working on */
934){
drh0fcef5e2005-07-19 17:38:22 +0000935 Expr *pX = pTerm->pExpr;
drh94a11212004-09-25 13:12:14 +0000936 if( pX->op!=TK_IN ){
937 assert( pX->op==TK_EQ );
938 sqlite3ExprCode(pParse, pX->pRight);
danielk1977b3bce662005-01-29 08:32:43 +0000939#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +0000940 }else{
danielk1977b3bce662005-01-29 08:32:43 +0000941 int iTab;
drhe23399f2005-07-22 00:31:39 +0000942 int *aIn;
drh94a11212004-09-25 13:12:14 +0000943 Vdbe *v = pParse->pVdbe;
danielk1977b3bce662005-01-29 08:32:43 +0000944
945 sqlite3CodeSubselect(pParse, pX);
946 iTab = pX->iTable;
drh94a11212004-09-25 13:12:14 +0000947 sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
danielk1977b3bce662005-01-29 08:32:43 +0000948 VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
drhe23399f2005-07-22 00:31:39 +0000949 pLevel->nIn++;
950 pLevel->aInLoop = aIn = sqliteRealloc(pLevel->aInLoop,
951 sizeof(pLevel->aInLoop[0])*3*pLevel->nIn);
952 if( aIn ){
953 aIn += pLevel->nIn*3 - 3;
954 aIn[0] = OP_Next;
955 aIn[1] = iTab;
956 aIn[2] = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
drha6110402005-07-28 20:51:19 +0000957 }else{
958 pLevel->nIn = 0;
drhe23399f2005-07-22 00:31:39 +0000959 }
danielk1977b3bce662005-01-29 08:32:43 +0000960#endif
drh94a11212004-09-25 13:12:14 +0000961 }
drh0fcef5e2005-07-19 17:38:22 +0000962 disableTerm(pLevel, pTerm);
drh94a11212004-09-25 13:12:14 +0000963}
964
drh51147ba2005-07-23 22:59:55 +0000965/*
966** Generate code that will evaluate all == and IN constraints for an
967** index. The values for all constraints are left on the stack.
968**
969** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
970** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
971** The index has as many as three equality constraints, but in this
972** example, the third "c" value is an inequality. So only two
973** constraints are coded. This routine will generate code to evaluate
974** a==5 and b IN (1,2,3). The current values for a and b will be left
975** on the stack - a is the deepest and b the shallowest.
976**
977** In the example above nEq==2. But this subroutine works for any value
978** of nEq including 0. If nEq==0, this routine is nearly a no-op.
979** The only thing it does is allocate the pLevel->iMem memory cell.
980**
981** This routine always allocates at least one memory cell and puts
982** the address of that memory cell in pLevel->iMem. The code that
983** calls this routine will use pLevel->iMem to store the termination
984** key value of the loop. If one or more IN operators appear, then
985** this routine allocates an additional nEq memory cells for internal
986** use.
987*/
988static void codeAllEqualityTerms(
989 Parse *pParse, /* Parsing context */
990 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
991 WhereClause *pWC, /* The WHERE clause */
992 Bitmask notReady, /* Which parts of FROM have not yet been coded */
993 int brk /* Jump here to end the loop */
994){
995 int nEq = pLevel->nEq; /* The number of == or IN constraints to code */
996 int termsInMem = 0; /* If true, store value in mem[] cells */
997 Vdbe *v = pParse->pVdbe; /* The virtual machine under construction */
998 Index *pIdx = pLevel->pIdx; /* The index being used for this loop */
999 int iCur = pLevel->iTabCur; /* The cursor of the table */
1000 WhereTerm *pTerm; /* A single constraint term */
1001 int j; /* Loop counter */
1002
1003 /* Figure out how many memory cells we will need then allocate them.
1004 ** We always need at least one used to store the loop terminator
1005 ** value. If there are IN operators we'll need one for each == or
1006 ** IN constraint.
1007 */
1008 pLevel->iMem = pParse->nMem++;
1009 if( pLevel->flags & WHERE_COLUMN_IN ){
1010 pParse->nMem += pLevel->nEq;
1011 termsInMem = 1;
1012 }
1013
1014 /* Evaluate the equality constraints
1015 */
1016 for(j=0; 1; j++){
1017 int k = pIdx->aiColumn[j];
1018 pTerm = findTerm(pWC, iCur, k, notReady, WO_EQ|WO_IN, pIdx);
1019 if( pTerm==0 ) break;
1020 assert( (pTerm->flags & TERM_CODED)==0 );
1021 codeEqualityTerm(pParse, pTerm, brk, pLevel);
1022 if( termsInMem ){
1023 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1);
1024 }
1025 }
1026 assert( j==nEq );
1027
1028 /* Make sure all the constraint values are on the top of the stack
1029 */
1030 if( termsInMem ){
1031 for(j=0; j<nEq; j++){
1032 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem+j+1, 0);
1033 }
1034 }
1035}
1036
drh84bfda42005-07-15 13:05:21 +00001037#ifdef SQLITE_TEST
1038/*
1039** The following variable holds a text description of query plan generated
1040** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
1041** overwrites the previous. This information is used for testing and
1042** analysis only.
1043*/
1044char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
1045static int nQPlan = 0; /* Next free slow in _query_plan[] */
1046
1047#endif /* SQLITE_TEST */
1048
1049
drh94a11212004-09-25 13:12:14 +00001050
1051/*
drhe3184742002-06-19 14:27:05 +00001052** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00001053** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00001054** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00001055** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00001056** in order to complete the WHERE clause processing.
1057**
1058** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00001059**
1060** The basic idea is to do a nested loop, one loop for each table in
1061** the FROM clause of a select. (INSERT and UPDATE statements are the
1062** same as a SELECT with only a single table in the FROM clause.) For
1063** example, if the SQL is this:
1064**
1065** SELECT * FROM t1, t2, t3 WHERE ...;
1066**
1067** Then the code generated is conceptually like the following:
1068**
1069** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00001070** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00001071** foreach row3 in t3 do /
1072** ...
1073** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00001074** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00001075** end /
1076**
drh29dda4a2005-07-21 18:23:20 +00001077** Note that the loops might not be nested in the order in which they
1078** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00001079** use of indices. Note also that when the IN operator appears in
1080** the WHERE clause, it might result in additional nested loops for
1081** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00001082**
drhc27a1ce2002-06-14 20:58:45 +00001083** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00001084** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
1085** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00001086** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00001087**
drhe6f85e72004-12-25 01:03:13 +00001088** The code that sqlite3WhereBegin() generates leaves the cursors named
1089** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00001090** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00001091** data from the various tables of the loop.
1092**
drhc27a1ce2002-06-14 20:58:45 +00001093** If the WHERE clause is empty, the foreach loops must each scan their
1094** entire tables. Thus a three-way join is an O(N^3) operation. But if
1095** the tables have indices and there are terms in the WHERE clause that
1096** refer to those indices, a complete table scan can be avoided and the
1097** code will run much faster. Most of the work of this routine is checking
1098** to see if there are indices that can be used to speed up the loop.
1099**
1100** Terms of the WHERE clause are also used to limit which rows actually
1101** make it to the "..." in the middle of the loop. After each "foreach",
1102** terms of the WHERE clause that use only terms in that loop and outer
1103** loops are evaluated and if false a jump is made around all subsequent
1104** inner loops (or around the "..." if the test occurs within the inner-
1105** most loop)
1106**
1107** OUTER JOINS
1108**
1109** An outer join of tables t1 and t2 is conceptally coded as follows:
1110**
1111** foreach row1 in t1 do
1112** flag = 0
1113** foreach row2 in t2 do
1114** start:
1115** ...
1116** flag = 1
1117** end
drhe3184742002-06-19 14:27:05 +00001118** if flag==0 then
1119** move the row2 cursor to a null row
1120** goto start
1121** fi
drhc27a1ce2002-06-14 20:58:45 +00001122** end
1123**
drhe3184742002-06-19 14:27:05 +00001124** ORDER BY CLAUSE PROCESSING
1125**
1126** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
1127** if there is one. If there is no ORDER BY clause or if this routine
1128** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
1129**
1130** If an index can be used so that the natural output order of the table
1131** scan is correct for the ORDER BY clause, then that index is used and
1132** *ppOrderBy is set to NULL. This is an optimization that prevents an
1133** unnecessary sort of the result set if an index appropriate for the
1134** ORDER BY clause already exists.
1135**
1136** If the where clause loops cannot be arranged to provide the correct
1137** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +00001138*/
danielk19774adee202004-05-08 08:23:19 +00001139WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00001140 Parse *pParse, /* The parser context */
1141 SrcList *pTabList, /* A list of all tables to be scanned */
1142 Expr *pWhere, /* The WHERE clause */
drhf8db1bc2005-04-22 02:38:37 +00001143 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +00001144){
1145 int i; /* Loop counter */
1146 WhereInfo *pWInfo; /* Will become the return value of this function */
1147 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhd4f5ee22003-07-16 00:54:31 +00001148 int brk, cont = 0; /* Addresses used during code generation */
drhfe05af82005-07-21 03:14:59 +00001149 Bitmask notReady; /* Cursors that are not yet positioned */
drh0aa74ed2005-07-16 13:33:20 +00001150 WhereTerm *pTerm; /* A single term in the WHERE clause */
1151 ExprMaskSet maskSet; /* The expression mask set */
drh0aa74ed2005-07-16 13:33:20 +00001152 WhereClause wc; /* The WHERE clause is divided into these terms */
drh9012bcb2004-12-19 00:11:35 +00001153 struct SrcList_item *pTabItem; /* A single entry from pTabList */
1154 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh29dda4a2005-07-21 18:23:20 +00001155 int iFrom; /* First unused FROM clause element */
drh75897232000-05-29 14:26:00 +00001156
drh29dda4a2005-07-21 18:23:20 +00001157 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00001158 ** bits in a Bitmask
1159 */
drh29dda4a2005-07-21 18:23:20 +00001160 if( pTabList->nSrc>BMS ){
1161 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00001162 return 0;
1163 }
1164
drh83dcb1a2002-06-28 01:02:38 +00001165 /* Split the WHERE clause into separate subexpressions where each
drh29dda4a2005-07-21 18:23:20 +00001166 ** subexpression is separated by an AND operator.
drh83dcb1a2002-06-28 01:02:38 +00001167 */
drh6a3ea0e2003-05-02 14:32:12 +00001168 initMaskSet(&maskSet);
drhfe05af82005-07-21 03:14:59 +00001169 whereClauseInit(&wc, pParse);
drh0aa74ed2005-07-16 13:33:20 +00001170 whereSplit(&wc, pWhere);
drh1398ad32005-01-19 23:24:50 +00001171
drh75897232000-05-29 14:26:00 +00001172 /* Allocate and initialize the WhereInfo structure that will become the
1173 ** return value.
1174 */
drhad3cab52002-05-24 02:04:32 +00001175 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
danielk1977132872b2004-05-10 10:37:18 +00001176 if( sqlite3_malloc_failed ){
drhe23399f2005-07-22 00:31:39 +00001177 goto whereBeginNoMem;
drh75897232000-05-29 14:26:00 +00001178 }
1179 pWInfo->pParse = pParse;
1180 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +00001181 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh08192d52002-04-30 19:20:28 +00001182
1183 /* Special case: a WHERE clause that is constant. Evaluate the
1184 ** expression and either jump over all of the code or fall thru.
1185 */
danielk19774adee202004-05-08 08:23:19 +00001186 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
1187 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +00001188 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00001189 }
drh75897232000-05-29 14:26:00 +00001190
drh29dda4a2005-07-21 18:23:20 +00001191 /* Analyze all of the subexpressions. Note that exprAnalyze() might
1192 ** add new virtual terms onto the end of the WHERE clause. We do not
1193 ** want to analyze these virtual terms, so start analyzing at the end
1194 ** and work forward so that they added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00001195 */
drh1398ad32005-01-19 23:24:50 +00001196 for(i=0; i<pTabList->nSrc; i++){
1197 createMask(&maskSet, pTabList->a[i].iCursor);
1198 }
drh0fcef5e2005-07-19 17:38:22 +00001199 for(i=wc.nTerm-1; i>=0; i--){
1200 exprAnalyze(pTabList, &maskSet, &wc.a[i]);
drh75897232000-05-29 14:26:00 +00001201 }
1202
drh29dda4a2005-07-21 18:23:20 +00001203 /* Chose the best index to use for each table in the FROM clause.
1204 **
drh51147ba2005-07-23 22:59:55 +00001205 ** This loop fills in the following fields:
1206 **
1207 ** pWInfo->a[].pIdx The index to use for this level of the loop.
1208 ** pWInfo->a[].flags WHERE_xxx flags associated with pIdx
1209 ** pWInfo->a[].nEq The number of == and IN constraints
1210 ** pWInfo->a[].iFrom When term of the FROM clause is being coded
1211 ** pWInfo->a[].iTabCur The VDBE cursor for the database table
1212 ** pWInfo->a[].iIdxCur The VDBE cursor for the index
1213 **
1214 ** This loop also figures out the nesting order of tables in the FROM
1215 ** clause.
drh75897232000-05-29 14:26:00 +00001216 */
drhfe05af82005-07-21 03:14:59 +00001217 notReady = ~(Bitmask)0;
drh9012bcb2004-12-19 00:11:35 +00001218 pTabItem = pTabList->a;
1219 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001220 for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1221 Index *pIdx; /* Index for FROM table at pTabItem */
1222 int flags; /* Flags asssociated with pIdx */
drh51147ba2005-07-23 22:59:55 +00001223 int nEq; /* Number of == or IN constraints */
1224 double cost; /* The cost for pIdx */
drh29dda4a2005-07-21 18:23:20 +00001225 int j; /* For looping over FROM tables */
1226 Index *pBest = 0; /* The best index seen so far */
1227 int bestFlags = 0; /* Flags associated with pBest */
drh51147ba2005-07-23 22:59:55 +00001228 int bestNEq = 0; /* nEq associated with pBest */
1229 double lowestCost = 1.0e99; /* Cost of the pBest */
drh29dda4a2005-07-21 18:23:20 +00001230 int bestJ; /* The value of j */
1231 Bitmask m; /* Bitmask value for j or bestJ */
1232
1233 for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
1234 m = getMask(&maskSet, pTabItem->iCursor);
1235 if( (m & notReady)==0 ){
1236 if( j==iFrom ) iFrom++;
1237 continue;
1238 }
drh51147ba2005-07-23 22:59:55 +00001239 cost = bestIndex(pParse, &wc, pTabItem, notReady,
1240 (j==0 && ppOrderBy) ? *ppOrderBy : 0,
1241 &pIdx, &flags, &nEq);
1242 if( cost<lowestCost ){
1243 lowestCost = cost;
drh29dda4a2005-07-21 18:23:20 +00001244 pBest = pIdx;
1245 bestFlags = flags;
drh51147ba2005-07-23 22:59:55 +00001246 bestNEq = nEq;
drh29dda4a2005-07-21 18:23:20 +00001247 bestJ = j;
1248 }
1249 if( (pTabItem->jointype & JT_LEFT)!=0
1250 || (j>0 && (pTabItem[-1].jointype & JT_LEFT)!=0)
1251 ){
1252 break;
1253 }
1254 }
1255 if( bestFlags & WHERE_ORDERBY ){
drhfe05af82005-07-21 03:14:59 +00001256 *ppOrderBy = 0;
drhc4a3c772001-04-04 11:48:57 +00001257 }
drh29dda4a2005-07-21 18:23:20 +00001258 pLevel->flags = bestFlags;
drhfe05af82005-07-21 03:14:59 +00001259 pLevel->pIdx = pBest;
drh51147ba2005-07-23 22:59:55 +00001260 pLevel->nEq = bestNEq;
drhe23399f2005-07-22 00:31:39 +00001261 pLevel->aInLoop = 0;
1262 pLevel->nIn = 0;
drhfe05af82005-07-21 03:14:59 +00001263 if( pBest ){
drh9012bcb2004-12-19 00:11:35 +00001264 pLevel->iIdxCur = pParse->nTab++;
drhfe05af82005-07-21 03:14:59 +00001265 }else{
1266 pLevel->iIdxCur = -1;
drh6b563442001-11-07 16:48:26 +00001267 }
drh29dda4a2005-07-21 18:23:20 +00001268 notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
1269 pLevel->iFrom = bestJ;
drh75897232000-05-29 14:26:00 +00001270 }
1271
drh9012bcb2004-12-19 00:11:35 +00001272 /* Open all tables in the pTabList and any indices selected for
1273 ** searching those tables.
1274 */
1275 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
1276 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001277 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drh9012bcb2004-12-19 00:11:35 +00001278 Table *pTab;
1279 Index *pIx;
1280 int iIdxCur = pLevel->iIdxCur;
1281
drh29dda4a2005-07-21 18:23:20 +00001282 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001283 pTab = pTabItem->pTab;
1284 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001285 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001286 sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
1287 }
1288 pLevel->iTabCur = pTabItem->iCursor;
1289 if( (pIx = pLevel->pIdx)!=0 ){
1290 sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
drh29dda4a2005-07-21 18:23:20 +00001291 VdbeComment((v, "# %s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00001292 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
1293 (char*)&pIx->keyInfo, P3_KEYINFO);
1294 }
drhfe05af82005-07-21 03:14:59 +00001295 if( (pLevel->flags & WHERE_IDX_ONLY)!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001296 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
1297 }
1298 sqlite3CodeVerifySchema(pParse, pTab->iDb);
1299 }
1300 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
1301
drh29dda4a2005-07-21 18:23:20 +00001302 /* Generate the code to do the search. Each iteration of the for
1303 ** loop below generates code for a single nested loop of the VM
1304 ** program.
drh75897232000-05-29 14:26:00 +00001305 */
drhfe05af82005-07-21 03:14:59 +00001306 notReady = ~(Bitmask)0;
drh29dda4a2005-07-21 18:23:20 +00001307 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drhfe05af82005-07-21 03:14:59 +00001308 int j;
drh9012bcb2004-12-19 00:11:35 +00001309 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
1310 Index *pIdx; /* The index we will be using */
1311 int iIdxCur; /* The VDBE cursor for the index */
1312 int omitTable; /* True if we use the index only */
drh29dda4a2005-07-21 18:23:20 +00001313 int bRev; /* True if we need to scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001314
drh29dda4a2005-07-21 18:23:20 +00001315 pTabItem = &pTabList->a[pLevel->iFrom];
1316 iCur = pTabItem->iCursor;
drh9012bcb2004-12-19 00:11:35 +00001317 pIdx = pLevel->pIdx;
1318 iIdxCur = pLevel->iIdxCur;
drh29dda4a2005-07-21 18:23:20 +00001319 bRev = (pLevel->flags & WHERE_REVERSE)!=0;
drhfe05af82005-07-21 03:14:59 +00001320 omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
drh75897232000-05-29 14:26:00 +00001321
drh29dda4a2005-07-21 18:23:20 +00001322 /* Create labels for the "break" and "continue" instructions
1323 ** for the current loop. Jump to brk to break out of a loop.
1324 ** Jump to cont to go immediately to the next iteration of the
1325 ** loop.
1326 */
1327 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1328 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1329
drhad2d8302002-05-24 20:31:36 +00001330 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +00001331 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +00001332 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +00001333 */
drh29dda4a2005-07-21 18:23:20 +00001334 if( pLevel->iFrom>0 && (pTabItem[-1].jointype & JT_LEFT)!=0 ){
drhad2d8302002-05-24 20:31:36 +00001335 if( !pParse->nMem ) pParse->nMem++;
1336 pLevel->iLeftJoin = pParse->nMem++;
drhf0863fe2005-06-12 21:35:51 +00001337 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001338 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001339 VdbeComment((v, "# init LEFT JOIN no-match flag"));
drhad2d8302002-05-24 20:31:36 +00001340 }
1341
drhfe05af82005-07-21 03:14:59 +00001342 if( pLevel->flags & WHERE_ROWID_EQ ){
drh8aff1012001-12-22 14:49:24 +00001343 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +00001344 ** equality comparison against the ROWID field. Or
1345 ** we reference multiple rows using a "rowid IN (...)"
1346 ** construct.
drhc4a3c772001-04-04 11:48:57 +00001347 */
drhfe05af82005-07-21 03:14:59 +00001348 pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1349 assert( pTerm!=0 );
drh0fcef5e2005-07-19 17:38:22 +00001350 assert( pTerm->pExpr!=0 );
1351 assert( pTerm->leftCursor==iCur );
drh9012bcb2004-12-19 00:11:35 +00001352 assert( omitTable==0 );
drh94a11212004-09-25 13:12:14 +00001353 codeEqualityTerm(pParse, pTerm, brk, pLevel);
danielk19774adee202004-05-08 08:23:19 +00001354 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
danielk19774adee202004-05-08 08:23:19 +00001355 sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001356 VdbeComment((v, "pk"));
drh6b563442001-11-07 16:48:26 +00001357 pLevel->op = OP_Noop;
drhfe05af82005-07-21 03:14:59 +00001358 }else if( pLevel->flags & WHERE_ROWID_RANGE ){
drh51147ba2005-07-23 22:59:55 +00001359 /* Case 2: We have an inequality comparison against the ROWID field.
drh8aff1012001-12-22 14:49:24 +00001360 */
1361 int testOp = OP_Noop;
1362 int start;
drhfe05af82005-07-21 03:14:59 +00001363 WhereTerm *pStart, *pEnd;
drh8aff1012001-12-22 14:49:24 +00001364
drh9012bcb2004-12-19 00:11:35 +00001365 assert( omitTable==0 );
drha6110402005-07-28 20:51:19 +00001366 pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
1367 pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
drhfe05af82005-07-21 03:14:59 +00001368 if( bRev ){
1369 pTerm = pStart;
1370 pStart = pEnd;
1371 pEnd = pTerm;
1372 }
1373 if( pStart ){
drh94a11212004-09-25 13:12:14 +00001374 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001375 pX = pStart->pExpr;
drh94a11212004-09-25 13:12:14 +00001376 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001377 assert( pStart->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001378 sqlite3ExprCode(pParse, pX->pRight);
danielk1977d0a69322005-02-02 01:10:44 +00001379 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
drhb6c29892004-11-22 19:12:19 +00001380 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001381 VdbeComment((v, "pk"));
drhfe05af82005-07-21 03:14:59 +00001382 disableTerm(pLevel, pStart);
drh8aff1012001-12-22 14:49:24 +00001383 }else{
drhb6c29892004-11-22 19:12:19 +00001384 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
drh8aff1012001-12-22 14:49:24 +00001385 }
drhfe05af82005-07-21 03:14:59 +00001386 if( pEnd ){
drh94a11212004-09-25 13:12:14 +00001387 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001388 pX = pEnd->pExpr;
drh94a11212004-09-25 13:12:14 +00001389 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001390 assert( pEnd->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001391 sqlite3ExprCode(pParse, pX->pRight);
drh8aff1012001-12-22 14:49:24 +00001392 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001393 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drh94a11212004-09-25 13:12:14 +00001394 if( pX->op==TK_LT || pX->op==TK_GT ){
drhb6c29892004-11-22 19:12:19 +00001395 testOp = bRev ? OP_Le : OP_Ge;
drh8aff1012001-12-22 14:49:24 +00001396 }else{
drhb6c29892004-11-22 19:12:19 +00001397 testOp = bRev ? OP_Lt : OP_Gt;
drh8aff1012001-12-22 14:49:24 +00001398 }
drhfe05af82005-07-21 03:14:59 +00001399 disableTerm(pLevel, pEnd);
drh8aff1012001-12-22 14:49:24 +00001400 }
danielk19774adee202004-05-08 08:23:19 +00001401 start = sqlite3VdbeCurrentAddr(v);
drhb6c29892004-11-22 19:12:19 +00001402 pLevel->op = bRev ? OP_Prev : OP_Next;
drh6a3ea0e2003-05-02 14:32:12 +00001403 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001404 pLevel->p2 = start;
1405 if( testOp!=OP_Noop ){
drhf0863fe2005-06-12 21:35:51 +00001406 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001407 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drhf0863fe2005-06-12 21:35:51 +00001408 sqlite3VdbeAddOp(v, testOp, 'n', brk);
drh8aff1012001-12-22 14:49:24 +00001409 }
drhfe05af82005-07-21 03:14:59 +00001410 }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
drh51147ba2005-07-23 22:59:55 +00001411 /* Case 3: The WHERE clause term that refers to the right-most
drhc27a1ce2002-06-14 20:58:45 +00001412 ** column of the index is an inequality. For example, if
1413 ** the index is on (x,y,z) and the WHERE clause is of the
1414 ** form "x=5 AND y<10" then this case is used. Only the
1415 ** right-most column can be an inequality - the rest must
drh51147ba2005-07-23 22:59:55 +00001416 ** use the "==" and "IN" operators.
drhe3184742002-06-19 14:27:05 +00001417 **
1418 ** This case is also used when there are no WHERE clause
1419 ** constraints but an index is selected anyway, in order
1420 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +00001421 */
drh487ab3c2001-11-08 00:45:21 +00001422 int start;
drh51147ba2005-07-23 22:59:55 +00001423 int nEq = pLevel->nEq;
danielk1977f7df9cc2004-06-16 12:02:47 +00001424 int leFlag=0, geFlag=0;
drh487ab3c2001-11-08 00:45:21 +00001425 int testOp;
drhfe05af82005-07-21 03:14:59 +00001426 int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
1427 int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
drh487ab3c2001-11-08 00:45:21 +00001428
drh51147ba2005-07-23 22:59:55 +00001429 /* Generate code to evaluate all constraint terms using == or IN
1430 ** and level the values of those terms on the stack.
drh487ab3c2001-11-08 00:45:21 +00001431 */
drh51147ba2005-07-23 22:59:55 +00001432 codeAllEqualityTerms(pParse, pLevel, &wc, notReady, brk);
drh487ab3c2001-11-08 00:45:21 +00001433
drhc27a1ce2002-06-14 20:58:45 +00001434 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +00001435 ** used twice: once to make the termination key and once to make the
1436 ** start key.
1437 */
drh51147ba2005-07-23 22:59:55 +00001438 for(j=0; j<nEq; j++){
1439 sqlite3VdbeAddOp(v, OP_Dup, nEq-1, 0);
drh487ab3c2001-11-08 00:45:21 +00001440 }
1441
1442 /* Generate the termination key. This is the key value that
1443 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +00001444 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +00001445 **
1446 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1447 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +00001448 */
drhfe05af82005-07-21 03:14:59 +00001449 if( topLimit ){
drhe8b97272005-07-19 22:22:12 +00001450 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001451 int k = pIdx->aiColumn[j];
1452 pTerm = findTerm(&wc, iCur, k, notReady, WO_LT|WO_LE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001453 assert( pTerm!=0 );
1454 pX = pTerm->pExpr;
1455 assert( (pTerm->flags & TERM_CODED)==0 );
1456 sqlite3ExprCode(pParse, pX->pRight);
1457 leFlag = pX->op==TK_LE;
1458 disableTerm(pLevel, pTerm);
drh487ab3c2001-11-08 00:45:21 +00001459 testOp = OP_IdxGE;
1460 }else{
drh51147ba2005-07-23 22:59:55 +00001461 testOp = nEq>0 ? OP_IdxGE : OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001462 leFlag = 1;
1463 }
1464 if( testOp!=OP_Noop ){
drh51147ba2005-07-23 22:59:55 +00001465 int nCol = nEq + topLimit;
drh487ab3c2001-11-08 00:45:21 +00001466 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001467 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001468 if( bRev ){
drh7cf6e4d2004-05-19 14:56:55 +00001469 int op = leFlag ? OP_MoveLe : OP_MoveLt;
drh9012bcb2004-12-19 00:11:35 +00001470 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001471 }else{
danielk19774adee202004-05-08 08:23:19 +00001472 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001473 }
drhfe05af82005-07-21 03:14:59 +00001474 }else if( bRev ){
drh9012bcb2004-12-19 00:11:35 +00001475 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001476 }
1477
1478 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001479 ** bound on the search. There is no start key if there are no
1480 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001481 ** that case, generate a "Rewind" instruction in place of the
1482 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001483 **
1484 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1485 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001486 */
drhfe05af82005-07-21 03:14:59 +00001487 if( btmLimit ){
drhe8b97272005-07-19 22:22:12 +00001488 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001489 int k = pIdx->aiColumn[j];
1490 pTerm = findTerm(&wc, iCur, k, notReady, WO_GT|WO_GE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001491 assert( pTerm!=0 );
1492 pX = pTerm->pExpr;
1493 assert( (pTerm->flags & TERM_CODED)==0 );
1494 sqlite3ExprCode(pParse, pX->pRight);
1495 geFlag = pX->op==TK_GE;
1496 disableTerm(pLevel, pTerm);
drh7900ead2001-11-12 13:51:43 +00001497 }else{
1498 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001499 }
drh51147ba2005-07-23 22:59:55 +00001500 if( nEq>0 || btmLimit ){
1501 int nCol = nEq + btmLimit;
drh94a11212004-09-25 13:12:14 +00001502 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001503 if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001504 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001505 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001506 testOp = OP_IdxLT;
1507 }else{
drh7cf6e4d2004-05-19 14:56:55 +00001508 int op = geFlag ? OP_MoveGe : OP_MoveGt;
drh9012bcb2004-12-19 00:11:35 +00001509 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001510 }
drhfe05af82005-07-21 03:14:59 +00001511 }else if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001512 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001513 }else{
drh9012bcb2004-12-19 00:11:35 +00001514 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001515 }
1516
1517 /* Generate the the top of the loop. If there is a termination
1518 ** key we have to test for that key and abort at the top of the
1519 ** loop.
1520 */
danielk19774adee202004-05-08 08:23:19 +00001521 start = sqlite3VdbeCurrentAddr(v);
drh487ab3c2001-11-08 00:45:21 +00001522 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001523 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001524 sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
drhfe05af82005-07-21 03:14:59 +00001525 if( (leFlag && !bRev) || (!geFlag && bRev) ){
danielk19773d1bfea2004-05-14 11:00:53 +00001526 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
1527 }
drh487ab3c2001-11-08 00:45:21 +00001528 }
drh9012bcb2004-12-19 00:11:35 +00001529 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
drh51147ba2005-07-23 22:59:55 +00001530 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEq + topLimit, cont);
drhe6f85e72004-12-25 01:03:13 +00001531 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001532 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001533 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh487ab3c2001-11-08 00:45:21 +00001534 }
1535
1536 /* Record the instruction used to terminate the loop.
1537 */
drhfe05af82005-07-21 03:14:59 +00001538 pLevel->op = bRev ? OP_Prev : OP_Next;
drh9012bcb2004-12-19 00:11:35 +00001539 pLevel->p1 = iIdxCur;
drh487ab3c2001-11-08 00:45:21 +00001540 pLevel->p2 = start;
drh51147ba2005-07-23 22:59:55 +00001541 }else if( pLevel->flags & WHERE_COLUMN_EQ ){
1542 /* Case 4: There is an index and all terms of the WHERE clause that
1543 ** refer to the index using the "==" or "IN" operators.
1544 */
1545 int start;
1546 int nEq = pLevel->nEq;
1547
1548 /* Generate code to evaluate all constraint terms using == or IN
1549 ** and level the values of those terms on the stack.
1550 */
1551 codeAllEqualityTerms(pParse, pLevel, &wc, notReady, brk);
1552
1553 /* Generate a single key that will be used to both start and terminate
1554 ** the search
1555 */
1556 buildIndexProbe(v, nEq, brk, pIdx);
1557 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
1558
1559 /* Generate code (1) to move to the first matching element of the table.
1560 ** Then generate code (2) that jumps to "brk" after the cursor is past
1561 ** the last matching element of the table. The code (1) is executed
1562 ** once to initialize the search, the code (2) is executed before each
1563 ** iteration of the scan to see if the scan has finished. */
1564 if( bRev ){
1565 /* Scan in reverse order */
1566 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
1567 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1568 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
1569 pLevel->op = OP_Prev;
1570 }else{
1571 /* Scan in the forward order */
1572 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
1573 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1574 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
1575 pLevel->op = OP_Next;
1576 }
1577 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
1578 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEq, cont);
1579 if( !omitTable ){
1580 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
1581 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
1582 }
1583 pLevel->p1 = iIdxCur;
1584 pLevel->p2 = start;
drhfe05af82005-07-21 03:14:59 +00001585 }else{
1586 /* Case 5: There is no usable index. We must do a complete
1587 ** scan of the entire table.
1588 */
drhfe05af82005-07-21 03:14:59 +00001589 assert( omitTable==0 );
drha6110402005-07-28 20:51:19 +00001590 assert( bRev==0 );
1591 pLevel->op = OP_Next;
drhfe05af82005-07-21 03:14:59 +00001592 pLevel->p1 = iCur;
drha6110402005-07-28 20:51:19 +00001593 pLevel->p2 = 1 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, brk);
drh75897232000-05-29 14:26:00 +00001594 }
drhfe05af82005-07-21 03:14:59 +00001595 notReady &= ~getMask(&maskSet, iCur);
drh75897232000-05-29 14:26:00 +00001596
1597 /* Insert code to test every subexpression that can be completely
1598 ** computed using the current set of tables.
1599 */
drh0fcef5e2005-07-19 17:38:22 +00001600 for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
1601 Expr *pE;
1602 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001603 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001604 pE = pTerm->pExpr;
1605 assert( pE!=0 );
drh392e5972005-07-08 14:14:22 +00001606 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
drh1f162302002-10-27 19:35:33 +00001607 continue;
1608 }
drh392e5972005-07-08 14:14:22 +00001609 sqlite3ExprIfFalse(pParse, pE, cont, 1);
drh0fcef5e2005-07-19 17:38:22 +00001610 pTerm->flags |= TERM_CODED;
drh75897232000-05-29 14:26:00 +00001611 }
drhad2d8302002-05-24 20:31:36 +00001612
1613 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1614 ** at least one row of the right table has matched the left table.
1615 */
1616 if( pLevel->iLeftJoin ){
danielk19774adee202004-05-08 08:23:19 +00001617 pLevel->top = sqlite3VdbeCurrentAddr(v);
1618 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1619 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001620 VdbeComment((v, "# record LEFT JOIN hit"));
drh0aa74ed2005-07-16 13:33:20 +00001621 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
drh0fcef5e2005-07-19 17:38:22 +00001622 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001623 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001624 assert( pTerm->pExpr );
1625 sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
1626 pTerm->flags |= TERM_CODED;
drh1cc093c2002-06-24 22:01:57 +00001627 }
drhad2d8302002-05-24 20:31:36 +00001628 }
drh75897232000-05-29 14:26:00 +00001629 }
drh7ec764a2005-07-21 03:48:20 +00001630
1631#ifdef SQLITE_TEST /* For testing and debugging use only */
1632 /* Record in the query plan information about the current table
1633 ** and the index used to access it (if any). If the table itself
1634 ** is not used, its name is just '{}'. If no index is used
1635 ** the index is listed as "{}". If the primary key is used the
1636 ** index name is '*'.
1637 */
1638 for(i=0; i<pTabList->nSrc; i++){
1639 char *z;
1640 int n;
drh7ec764a2005-07-21 03:48:20 +00001641 pLevel = &pWInfo->a[i];
drh29dda4a2005-07-21 18:23:20 +00001642 pTabItem = &pTabList->a[pLevel->iFrom];
drh7ec764a2005-07-21 03:48:20 +00001643 z = pTabItem->zAlias;
1644 if( z==0 ) z = pTabItem->pTab->zName;
1645 n = strlen(z);
1646 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
1647 if( pLevel->flags & WHERE_IDX_ONLY ){
1648 strcpy(&sqlite3_query_plan[nQPlan], "{}");
1649 nQPlan += 2;
1650 }else{
1651 strcpy(&sqlite3_query_plan[nQPlan], z);
1652 nQPlan += n;
1653 }
1654 sqlite3_query_plan[nQPlan++] = ' ';
1655 }
1656 if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
1657 strcpy(&sqlite3_query_plan[nQPlan], "* ");
1658 nQPlan += 2;
1659 }else if( pLevel->pIdx==0 ){
1660 strcpy(&sqlite3_query_plan[nQPlan], "{} ");
1661 nQPlan += 3;
1662 }else{
1663 n = strlen(pLevel->pIdx->zName);
1664 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
1665 strcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName);
1666 nQPlan += n;
1667 sqlite3_query_plan[nQPlan++] = ' ';
1668 }
1669 }
1670 }
1671 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
1672 sqlite3_query_plan[--nQPlan] = 0;
1673 }
1674 sqlite3_query_plan[nQPlan] = 0;
1675 nQPlan = 0;
1676#endif /* SQLITE_TEST // Testing and debugging use only */
1677
drh29dda4a2005-07-21 18:23:20 +00001678 /* Record the continuation address in the WhereInfo structure. Then
1679 ** clean up and return.
1680 */
drh75897232000-05-29 14:26:00 +00001681 pWInfo->iContinue = cont;
drh0aa74ed2005-07-16 13:33:20 +00001682 whereClauseClear(&wc);
drh75897232000-05-29 14:26:00 +00001683 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00001684
1685 /* Jump here if malloc fails */
1686whereBeginNoMem:
1687 whereClauseClear(&wc);
1688 sqliteFree(pWInfo);
1689 return 0;
drh75897232000-05-29 14:26:00 +00001690}
1691
1692/*
drhc27a1ce2002-06-14 20:58:45 +00001693** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00001694** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001695*/
danielk19774adee202004-05-08 08:23:19 +00001696void sqlite3WhereEnd(WhereInfo *pWInfo){
drh75897232000-05-29 14:26:00 +00001697 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001698 int i;
drh6b563442001-11-07 16:48:26 +00001699 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001700 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001701
drh9012bcb2004-12-19 00:11:35 +00001702 /* Generate loop termination code.
1703 */
drhad3cab52002-05-24 02:04:32 +00001704 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001705 pLevel = &pWInfo->a[i];
danielk19774adee202004-05-08 08:23:19 +00001706 sqlite3VdbeResolveLabel(v, pLevel->cont);
drh6b563442001-11-07 16:48:26 +00001707 if( pLevel->op!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001708 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001709 }
danielk19774adee202004-05-08 08:23:19 +00001710 sqlite3VdbeResolveLabel(v, pLevel->brk);
drhe23399f2005-07-22 00:31:39 +00001711 if( pLevel->nIn ){
1712 int *a;
1713 int j;
1714 for(j=pLevel->nIn, a=&pLevel->aInLoop[j*3-3]; j>0; j--, a-=3){
1715 sqlite3VdbeAddOp(v, a[0], a[1], a[2]);
1716 }
1717 sqliteFree(pLevel->aInLoop);
drhd99f7062002-06-08 23:25:08 +00001718 }
drhad2d8302002-05-24 20:31:36 +00001719 if( pLevel->iLeftJoin ){
1720 int addr;
danielk19774adee202004-05-08 08:23:19 +00001721 addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh9012bcb2004-12-19 00:11:35 +00001722 sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
danielk19774adee202004-05-08 08:23:19 +00001723 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
drh9012bcb2004-12-19 00:11:35 +00001724 if( pLevel->iIdxCur>=0 ){
1725 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
drh7f09b3e2002-08-13 13:15:49 +00001726 }
danielk19774adee202004-05-08 08:23:19 +00001727 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
drhad2d8302002-05-24 20:31:36 +00001728 }
drh19a775c2000-06-05 18:54:46 +00001729 }
drh9012bcb2004-12-19 00:11:35 +00001730
1731 /* The "break" point is here, just past the end of the outer loop.
1732 ** Set it.
1733 */
danielk19774adee202004-05-08 08:23:19 +00001734 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00001735
drh29dda4a2005-07-21 18:23:20 +00001736 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00001737 */
drh29dda4a2005-07-21 18:23:20 +00001738 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1739 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001740 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00001741 assert( pTab!=0 );
1742 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001743 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001744 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
1745 }
drh6b563442001-11-07 16:48:26 +00001746 if( pLevel->pIdx!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001747 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
1748 }
1749
drhacf3b982005-01-03 01:27:18 +00001750 /* Make cursor substitutions for cases where we want to use
drh9012bcb2004-12-19 00:11:35 +00001751 ** just the index and never reference the table.
1752 **
1753 ** Calls to the code generator in between sqlite3WhereBegin and
1754 ** sqlite3WhereEnd will have created code that references the table
1755 ** directly. This loop scans all that code looking for opcodes
1756 ** that reference the table and converts them into opcodes that
1757 ** reference the index.
1758 */
drhfe05af82005-07-21 03:14:59 +00001759 if( pLevel->flags & WHERE_IDX_ONLY ){
drh9012bcb2004-12-19 00:11:35 +00001760 int i, j, last;
1761 VdbeOp *pOp;
1762 Index *pIdx = pLevel->pIdx;
1763
1764 assert( pIdx!=0 );
1765 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1766 last = sqlite3VdbeCurrentAddr(v);
1767 for(i=pWInfo->iTop; i<last; i++, pOp++){
1768 if( pOp->p1!=pLevel->iTabCur ) continue;
1769 if( pOp->opcode==OP_Column ){
1770 pOp->p1 = pLevel->iIdxCur;
1771 for(j=0; j<pIdx->nColumn; j++){
1772 if( pOp->p2==pIdx->aiColumn[j] ){
1773 pOp->p2 = j;
1774 break;
1775 }
1776 }
drhf0863fe2005-06-12 21:35:51 +00001777 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00001778 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00001779 pOp->opcode = OP_IdxRowid;
danielk19776c18b6e2005-01-30 09:17:58 +00001780 }else if( pOp->opcode==OP_NullRow ){
1781 pOp->opcode = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001782 }
1783 }
drh6b563442001-11-07 16:48:26 +00001784 }
drh19a775c2000-06-05 18:54:46 +00001785 }
drh9012bcb2004-12-19 00:11:35 +00001786
1787 /* Final cleanup
1788 */
drh75897232000-05-29 14:26:00 +00001789 sqliteFree(pWInfo);
1790 return;
1791}