blob: b30a70ae9a3292ac48c52bf625af0cf445caee4c [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**
drh0aa74ed2005-07-16 13:33:20 +000019** $Id: where.c,v 1.145 2005/07/16 13:33:21 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*/
26#define BMS (sizeof(Bitmask)*8-1)
27
28/*
29** Determine the number of elements in an array.
30*/
31#define ARRAYSIZE(X) (sizeof(X)/sizeof(X[0]))
32
33
34/*
drh75897232000-05-29 14:26:00 +000035** The query generator uses an array of instances of this structure to
36** help it analyze the subexpressions of the WHERE clause. Each WHERE
37** clause subexpression is separated from the others by an AND operator.
drh51669862004-12-18 18:40:26 +000038**
39** The idxLeft and idxRight fields are the VDBE cursor numbers for the
40** table that contains the column that appears on the left-hand and
drh0aa74ed2005-07-16 13:33:20 +000041** right-hand side of WhereTerm.p. If either side of WhereTerm.p is
drh51669862004-12-18 18:40:26 +000042** something other than a simple column reference, then idxLeft or
43** idxRight are -1.
44**
45** It is the VDBE cursor number is the value stored in Expr.iTable
46** when Expr.op==TK_COLUMN and the value stored in SrcList.a[].iCursor.
47**
48** prereqLeft, prereqRight, and prereqAll record sets of cursor numbers,
49** but they do so indirectly. A single ExprMaskSet structure translates
50** cursor number into bits and the translated bit is stored in the prereq
51** fields. The translation is used in order to maximize the number of
52** bits that will fit in a Bitmask. The VDBE cursor numbers might be
53** spread out over the non-negative integers. For example, the cursor
54** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The ExprMaskSet
55** translates these sparse cursor numbers into consecutive integers
56** beginning with 0 in order to make the best possible use of the available
57** bits in the Bitmask. So, in the example above, the cursor numbers
58** would be mapped into integers 0 through 7.
59**
60** prereqLeft tells us every VDBE cursor that is referenced on the
drh0aa74ed2005-07-16 13:33:20 +000061** left-hand side of WhereTerm.p. prereqRight does the same for the
drh51669862004-12-18 18:40:26 +000062** right-hand side of the expression. The following identity always
63** holds:
64**
65** prereqAll = prereqLeft | prereqRight
66**
drh0aa74ed2005-07-16 13:33:20 +000067** The WhereTerm.indexable field is true if the WhereTerm.p expression
drh51669862004-12-18 18:40:26 +000068** is of a form that might control an index. Indexable expressions
69** look like this:
70**
71** <column> <op> <expr>
72**
73** Where <column> is a simple column name and <op> is on of the operators
74** that allowedOp() recognizes.
drh75897232000-05-29 14:26:00 +000075*/
drh0aa74ed2005-07-16 13:33:20 +000076typedef struct WhereTerm WhereTerm;
77struct WhereTerm {
drh75897232000-05-29 14:26:00 +000078 Expr *p; /* Pointer to the subexpression */
drh0aa74ed2005-07-16 13:33:20 +000079 u16 flags; /* Bit flags. See below */
drhe3184742002-06-19 14:27:05 +000080 u8 indexable; /* True if this subexprssion is usable by an index */
81 short int idxLeft; /* p->pLeft is a column in this table number. -1 if
drh0aa74ed2005-07-16 13:33:20 +000082 ** p->pLeft is not a column of any table */
drhe3184742002-06-19 14:27:05 +000083 short int idxRight; /* p->pRight is a column in this table number. -1 if
drh0aa74ed2005-07-16 13:33:20 +000084 ** p->pRight is not a column of any table */
drh51669862004-12-18 18:40:26 +000085 Bitmask prereqLeft; /* Bitmask of tables referenced by p->pLeft */
86 Bitmask prereqRight; /* Bitmask of tables referenced by p->pRight */
87 Bitmask prereqAll; /* Bitmask of tables referenced by p */
drh75897232000-05-29 14:26:00 +000088};
89
90/*
drh0aa74ed2005-07-16 13:33:20 +000091** Allowed values of WhereTerm.flags
92*/
93#define TERM_DYNAMIC 0x0001 /* Need to call sqlite3ExprDelete(p) */
94#define TERM_VIRTUAL 0x0002 /* Added by the optimizer. Do not code */
95
96/*
97** An instance of the following structure holds all information about a
98** WHERE clause. Mostly this is a container for one or more WhereTerms.
99*/
100typedef struct WhereClause WhereClause;
101struct WhereClause {
102 int nTerm; /* Number of terms */
103 int nSlot; /* Number of entries in a[] */
104 WhereTerm *a; /* Pointer to an array of terms */
105 WhereTerm aStatic[10]; /* Initial static space for the terms */
106};
107
108/*
drh6a3ea0e2003-05-02 14:32:12 +0000109** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000110** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000111**
112** The VDBE cursor numbers are small integers contained in
113** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
114** clause, the cursor numbers might not begin with 0 and they might
115** contain gaps in the numbering sequence. But we want to make maximum
116** use of the bits in our bitmasks. This structure provides a mapping
117** from the sparse cursor numbers into consecutive integers beginning
118** with 0.
119**
120** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
121** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
122**
123** For example, if the WHERE clause expression used these VDBE
124** cursors: 4, 5, 8, 29, 57, 73. Then the ExprMaskSet structure
125** would map those cursor numbers into bits 0 through 5.
126**
127** Note that the mapping is not necessarily ordered. In the example
128** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
129** 57->5, 73->4. Or one of 719 other combinations might be used. It
130** does not really matter. What is important is that sparse cursor
131** numbers all get mapped into bit numbers that begin with 0 and contain
132** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000133*/
134typedef struct ExprMaskSet ExprMaskSet;
135struct ExprMaskSet {
drh1398ad32005-01-19 23:24:50 +0000136 int n; /* Number of assigned cursor values */
137 int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000138};
139
drh0aa74ed2005-07-16 13:33:20 +0000140
drh6a3ea0e2003-05-02 14:32:12 +0000141/*
drh0aa74ed2005-07-16 13:33:20 +0000142** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000143*/
drh0aa74ed2005-07-16 13:33:20 +0000144static void whereClauseInit(WhereClause *pWC){
145 pWC->nTerm = 0;
146 pWC->nSlot = ARRAYSIZE(pWC->aStatic);
147 pWC->a = pWC->aStatic;
148}
149
150/*
151** Deallocate a WhereClause structure. The WhereClause structure
152** itself is not freed. This routine is the inverse of whereClauseInit().
153*/
154static void whereClauseClear(WhereClause *pWC){
155 int i;
156 WhereTerm *a;
157 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
158 if( a->flags & TERM_DYNAMIC ){
159 sqlite3ExprDelete(a->p);
160 }
161 }
162 if( pWC->a!=pWC->aStatic ){
163 sqliteFree(pWC->a);
164 }
165}
166
167/*
168** Add a new entries to the WhereClause structure. Increase the allocated
169** space as necessary.
170*/
171static void whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
172 WhereTerm *pTerm;
173 if( pWC->nTerm>=pWC->nSlot ){
174 WhereTerm *pOld = pWC->a;
175 pWC->a = sqliteMalloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
176 if( pWC->a==0 ) return;
177 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
178 if( pOld!=pWC->aStatic ){
179 sqliteFree(pOld);
180 }
181 pWC->nSlot *= 2;
182 }
183 pTerm = &pWC->a[pWC->nTerm++];
184 pTerm->p = p;
185 pTerm->flags = flags;
186}
drh75897232000-05-29 14:26:00 +0000187
188/*
drh51669862004-12-18 18:40:26 +0000189** This routine identifies subexpressions in the WHERE clause where
190** each subexpression is separate by the AND operator. aSlot is
191** filled with pointers to the subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000192**
drh51669862004-12-18 18:40:26 +0000193** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
194** \________/ \_______________/ \________________/
195** slot[0] slot[1] slot[2]
196**
197** The original WHERE clause in pExpr is unaltered. All this routine
198** does is make aSlot[] entries point to substructure within pExpr.
199**
200** aSlot[] is an array of subexpressions structures. There are nSlot
201** spaces left in this array. This routine finds as many AND-separated
202** subexpressions as it can and puts pointers to those subexpressions
203** into aSlot[] entries. The return value is the number of slots filled.
drh75897232000-05-29 14:26:00 +0000204*/
drh0aa74ed2005-07-16 13:33:20 +0000205static void whereSplit(WhereClause *pWC, Expr *pExpr){
206 if( pExpr==0 ) return;
207 if( pExpr->op!=TK_AND ){
208 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000209 }else{
drh0aa74ed2005-07-16 13:33:20 +0000210 whereSplit(pWC, pExpr->pLeft);
211 whereSplit(pWC, pExpr->pRight);
drh75897232000-05-29 14:26:00 +0000212 }
drh75897232000-05-29 14:26:00 +0000213}
214
215/*
drh6a3ea0e2003-05-02 14:32:12 +0000216** Initialize an expression mask set
217*/
218#define initMaskSet(P) memset(P, 0, sizeof(*P))
219
220/*
drh1398ad32005-01-19 23:24:50 +0000221** Return the bitmask for the given cursor number. Return 0 if
222** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000223*/
drh51669862004-12-18 18:40:26 +0000224static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000225 int i;
226 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000227 if( pMaskSet->ix[i]==iCursor ){
228 return ((Bitmask)1)<<i;
229 }
drh6a3ea0e2003-05-02 14:32:12 +0000230 }
drh6a3ea0e2003-05-02 14:32:12 +0000231 return 0;
232}
233
234/*
drh1398ad32005-01-19 23:24:50 +0000235** Create a new mask for cursor iCursor.
236*/
237static void createMask(ExprMaskSet *pMaskSet, int iCursor){
238 if( pMaskSet->n<ARRAYSIZE(pMaskSet->ix) ){
239 pMaskSet->ix[pMaskSet->n++] = iCursor;
240 }
241}
242
243/*
drh6a3ea0e2003-05-02 14:32:12 +0000244** Destroy an expression mask set
245*/
246#define freeMaskSet(P) /* NO-OP */
247
248/*
drh75897232000-05-29 14:26:00 +0000249** This routine walks (recursively) an expression tree and generates
250** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000251** tree.
drh75897232000-05-29 14:26:00 +0000252**
253** In order for this routine to work, the calling function must have
drh626a8792005-01-17 22:08:19 +0000254** previously invoked sqlite3ExprResolveNames() on the expression. See
drh75897232000-05-29 14:26:00 +0000255** the header comment on that routine for additional information.
drh626a8792005-01-17 22:08:19 +0000256** The sqlite3ExprResolveNames() routines looks for column names and
drh6a3ea0e2003-05-02 14:32:12 +0000257** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
258** the VDBE cursor number of the table.
drh75897232000-05-29 14:26:00 +0000259*/
danielk1977b3bce662005-01-29 08:32:43 +0000260static Bitmask exprListTableUsage(ExprMaskSet *, ExprList *);
drh51669862004-12-18 18:40:26 +0000261static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
262 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000263 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000264 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000265 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000266 return mask;
drh75897232000-05-29 14:26:00 +0000267 }
danielk1977b3bce662005-01-29 08:32:43 +0000268 mask = exprTableUsage(pMaskSet, p->pRight);
269 mask |= exprTableUsage(pMaskSet, p->pLeft);
270 mask |= exprListTableUsage(pMaskSet, p->pList);
271 if( p->pSelect ){
272 Select *pS = p->pSelect;
273 mask |= exprListTableUsage(pMaskSet, pS->pEList);
274 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
275 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
276 mask |= exprTableUsage(pMaskSet, pS->pWhere);
277 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drh75897232000-05-29 14:26:00 +0000278 }
danielk1977b3bce662005-01-29 08:32:43 +0000279 return mask;
280}
281static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
282 int i;
283 Bitmask mask = 0;
284 if( pList ){
285 for(i=0; i<pList->nExpr; i++){
286 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000287 }
288 }
drh75897232000-05-29 14:26:00 +0000289 return mask;
290}
291
292/*
drh487ab3c2001-11-08 00:45:21 +0000293** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000294** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000295** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000296*/
297static int allowedOp(int op){
drh9a432672004-10-04 13:38:09 +0000298 assert( TK_GT==TK_LE-1 && TK_LE==TK_LT-1 && TK_LT==TK_GE-1 && TK_EQ==TK_GT-1);
299 return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
drh487ab3c2001-11-08 00:45:21 +0000300}
301
302/*
drh51669862004-12-18 18:40:26 +0000303** Swap two objects of type T.
drh193bd772004-07-20 18:23:14 +0000304*/
305#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
306
307/*
308** Return the index in the SrcList that uses cursor iCur. If iCur is
309** used by the first entry in SrcList return 0. If iCur is used by
310** the second entry return 1. And so forth.
311**
312** SrcList is the set of tables in the FROM clause in the order that
313** they will be processed. The value returned here gives us an index
314** of which tables will be processed first.
315*/
316static int tableOrder(SrcList *pList, int iCur){
317 int i;
drh51669862004-12-18 18:40:26 +0000318 struct SrcList_item *pItem;
319 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
320 if( pItem->iCursor==iCur ) return i;
drh193bd772004-07-20 18:23:14 +0000321 }
322 return -1;
323}
324
325/*
drh0aa74ed2005-07-16 13:33:20 +0000326** The input to this routine is an WhereTerm structure with only the
drh75897232000-05-29 14:26:00 +0000327** "p" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +0000328** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +0000329** structure.
330*/
drh0aa74ed2005-07-16 13:33:20 +0000331static void exprAnalyze(SrcList *pSrc, ExprMaskSet *pMaskSet, WhereTerm *pInfo){
drh75897232000-05-29 14:26:00 +0000332 Expr *pExpr = pInfo->p;
drh6a3ea0e2003-05-02 14:32:12 +0000333 pInfo->prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
334 pInfo->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
335 pInfo->prereqAll = exprTableUsage(pMaskSet, pExpr);
drh75897232000-05-29 14:26:00 +0000336 pInfo->indexable = 0;
337 pInfo->idxLeft = -1;
338 pInfo->idxRight = -1;
drh487ab3c2001-11-08 00:45:21 +0000339 if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
drhd99f7062002-06-08 23:25:08 +0000340 if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
drh6a3ea0e2003-05-02 14:32:12 +0000341 pInfo->idxRight = pExpr->pRight->iTable;
drh75897232000-05-29 14:26:00 +0000342 pInfo->indexable = 1;
343 }
drh967e8b72000-06-21 13:59:10 +0000344 if( pExpr->pLeft->op==TK_COLUMN ){
drh6a3ea0e2003-05-02 14:32:12 +0000345 pInfo->idxLeft = pExpr->pLeft->iTable;
drh75897232000-05-29 14:26:00 +0000346 pInfo->indexable = 1;
347 }
348 }
drh193bd772004-07-20 18:23:14 +0000349 if( pInfo->indexable ){
350 assert( pInfo->idxLeft!=pInfo->idxRight );
351
352 /* We want the expression to be of the form "X = expr", not "expr = X".
353 ** So flip it over if necessary. If the expression is "X = Y", then
354 ** we want Y to come from an earlier table than X.
355 **
356 ** The collating sequence rule is to always choose the left expression.
357 ** So if we do a flip, we also have to move the collating sequence.
358 */
359 if( tableOrder(pSrc,pInfo->idxLeft)<tableOrder(pSrc,pInfo->idxRight) ){
360 assert( pExpr->op!=TK_IN );
361 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
362 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
drh9a432672004-10-04 13:38:09 +0000363 if( pExpr->op>=TK_GT ){
364 assert( TK_LT==TK_GT+2 );
365 assert( TK_GE==TK_LE+2 );
366 assert( TK_GT>TK_EQ );
367 assert( TK_GT<TK_LE );
368 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
369 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000370 }
371 SWAP(unsigned, pInfo->prereqLeft, pInfo->prereqRight);
372 SWAP(short int, pInfo->idxLeft, pInfo->idxRight);
373 }
374 }
375
drh75897232000-05-29 14:26:00 +0000376}
377
378/*
drh51669862004-12-18 18:40:26 +0000379** This routine decides if pIdx can be used to satisfy the ORDER BY
380** clause. If it can, it returns 1. If pIdx cannot satisfy the
381** ORDER BY clause, this routine returns 0.
382**
383** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
384** left-most table in the FROM clause of that same SELECT statement and
385** the table has a cursor number of "base". pIdx is an index on pTab.
386**
387** nEqCol is the number of columns of pIdx that are used as equality
388** constraints. Any of these columns may be missing from the ORDER BY
389** clause and the match can still be a success.
390**
391** If the index is UNIQUE, then the ORDER BY clause is allowed to have
392** additional terms past the end of the index and the match will still
393** be a success.
394**
395** All terms of the ORDER BY that match against the index must be either
396** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
397** index do not need to satisfy this constraint.) The *pbRev value is
398** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
399** the ORDER BY clause is all ASC.
400*/
401static int isSortingIndex(
402 Parse *pParse, /* Parsing context */
403 Index *pIdx, /* The index we are testing */
404 Table *pTab, /* The table to be sorted */
405 int base, /* Cursor number for pTab */
406 ExprList *pOrderBy, /* The ORDER BY clause */
407 int nEqCol, /* Number of index columns with == constraints */
408 int *pbRev /* Set to 1 if ORDER BY is DESC */
409){
410 int i, j; /* Loop counters */
411 int sortOrder; /* Which direction we are sorting */
412 int nTerm; /* Number of ORDER BY terms */
413 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
414 sqlite3 *db = pParse->db;
415
416 assert( pOrderBy!=0 );
417 nTerm = pOrderBy->nExpr;
418 assert( nTerm>0 );
419
420 /* Match terms of the ORDER BY clause against columns of
421 ** the index.
422 */
423 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
424 Expr *pExpr; /* The expression of the ORDER BY pTerm */
425 CollSeq *pColl; /* The collating sequence of pExpr */
426
427 pExpr = pTerm->pExpr;
428 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
429 /* Can not use an index sort on anything that is not a column in the
430 ** left-most table of the FROM clause */
431 return 0;
432 }
433 pColl = sqlite3ExprCollSeq(pParse, pExpr);
434 if( !pColl ) pColl = db->pDfltColl;
drh9012bcb2004-12-19 00:11:35 +0000435 if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
436 /* Term j of the ORDER BY clause does not match column i of the index */
437 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +0000438 /* If an index column that is constrained by == fails to match an
439 ** ORDER BY term, that is OK. Just ignore that column of the index
440 */
441 continue;
442 }else{
443 /* If an index column fails to match and is not constrained by ==
444 ** then the index cannot satisfy the ORDER BY constraint.
445 */
446 return 0;
447 }
448 }
449 if( i>nEqCol ){
450 if( pTerm->sortOrder!=sortOrder ){
451 /* Indices can only be used if all ORDER BY terms past the
452 ** equality constraints are all either DESC or ASC. */
453 return 0;
454 }
455 }else{
456 sortOrder = pTerm->sortOrder;
457 }
458 j++;
459 pTerm++;
460 }
461
462 /* The index can be used for sorting if all terms of the ORDER BY clause
463 ** or covered or if we ran out of index columns and the it is a UNIQUE
464 ** index.
465 */
466 if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
467 *pbRev = sortOrder==SQLITE_SO_DESC;
468 return 1;
469 }
470 return 0;
471}
472
473/*
drhb6c29892004-11-22 19:12:19 +0000474** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
475** by sorting in order of ROWID. Return true if so and set *pbRev to be
476** true for reverse ROWID and false for forward ROWID order.
477*/
478static int sortableByRowid(
479 int base, /* Cursor number for table to be sorted */
480 ExprList *pOrderBy, /* The ORDER BY clause */
481 int *pbRev /* Set to 1 if ORDER BY is DESC */
482){
483 Expr *p;
484
485 assert( pOrderBy!=0 );
486 assert( pOrderBy->nExpr>0 );
487 p = pOrderBy->a[0].pExpr;
488 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
489 *pbRev = pOrderBy->a[0].sortOrder;
490 return 1;
491 }
492 return 0;
493}
494
495
496/*
drh2ffb1182004-07-19 19:14:01 +0000497** Disable a term in the WHERE clause. Except, do not disable the term
498** if it controls a LEFT OUTER JOIN and it did not originate in the ON
499** or USING clause of that join.
500**
501** Consider the term t2.z='ok' in the following queries:
502**
503** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
504** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
505** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
506**
drh23bf66d2004-12-14 03:34:34 +0000507** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +0000508** in the ON clause. The term is disabled in (3) because it is not part
509** of a LEFT OUTER JOIN. In (1), the term is not disabled.
510**
511** Disabling a term causes that term to not be tested in the inner loop
512** of the join. Disabling is an optimization. We would get the correct
513** results if nothing were ever disabled, but joins might run a little
514** slower. The trick is to disable as much as we can without disabling
515** too much. If we disabled in (1), we'd get the wrong answer.
516** See ticket #813.
517*/
518static void disableTerm(WhereLevel *pLevel, Expr **ppExpr){
519 Expr *pExpr = *ppExpr;
520 if( pLevel->iLeftJoin==0 || ExprHasProperty(pExpr, EP_FromJoin) ){
521 *ppExpr = 0;
522 }
523}
524
525/*
drh94a11212004-09-25 13:12:14 +0000526** Generate code that builds a probe for an index. Details:
527**
528** * Check the top nColumn entries on the stack. If any
529** of those entries are NULL, jump immediately to brk,
530** which is the loop exit, since no index entry will match
531** if any part of the key is NULL.
532**
533** * Construct a probe entry from the top nColumn entries in
534** the stack with affinities appropriate for index pIdx.
535*/
536static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
537 sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
538 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
539 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
540 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
541 sqlite3IndexAffinityStr(v, pIdx);
542}
543
544/*
545** Generate code for an equality term of the WHERE clause. An equality
546** term can be either X=expr or X IN (...). pTerm is the X.
547*/
548static void codeEqualityTerm(
549 Parse *pParse, /* The parsing context */
drh0aa74ed2005-07-16 13:33:20 +0000550 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh94a11212004-09-25 13:12:14 +0000551 int brk, /* Jump here to abandon the loop */
552 WhereLevel *pLevel /* When level of the FROM clause we are working on */
553){
554 Expr *pX = pTerm->p;
555 if( pX->op!=TK_IN ){
556 assert( pX->op==TK_EQ );
557 sqlite3ExprCode(pParse, pX->pRight);
danielk1977b3bce662005-01-29 08:32:43 +0000558#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +0000559 }else{
danielk1977b3bce662005-01-29 08:32:43 +0000560 int iTab;
drh94a11212004-09-25 13:12:14 +0000561 Vdbe *v = pParse->pVdbe;
danielk1977b3bce662005-01-29 08:32:43 +0000562
563 sqlite3CodeSubselect(pParse, pX);
564 iTab = pX->iTable;
drh94a11212004-09-25 13:12:14 +0000565 sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
danielk1977b3bce662005-01-29 08:32:43 +0000566 VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
drh9012bcb2004-12-19 00:11:35 +0000567 pLevel->inP2 = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
drh94a11212004-09-25 13:12:14 +0000568 pLevel->inOp = OP_Next;
569 pLevel->inP1 = iTab;
danielk1977b3bce662005-01-29 08:32:43 +0000570#endif
drh94a11212004-09-25 13:12:14 +0000571 }
572 disableTerm(pLevel, &pTerm->p);
573}
574
drh84bfda42005-07-15 13:05:21 +0000575#ifdef SQLITE_TEST
576/*
577** The following variable holds a text description of query plan generated
578** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
579** overwrites the previous. This information is used for testing and
580** analysis only.
581*/
582char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
583static int nQPlan = 0; /* Next free slow in _query_plan[] */
584
585#endif /* SQLITE_TEST */
586
587
drh94a11212004-09-25 13:12:14 +0000588
589/*
drhe3184742002-06-19 14:27:05 +0000590** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +0000591** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +0000592** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +0000593** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +0000594** in order to complete the WHERE clause processing.
595**
596** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +0000597**
598** The basic idea is to do a nested loop, one loop for each table in
599** the FROM clause of a select. (INSERT and UPDATE statements are the
600** same as a SELECT with only a single table in the FROM clause.) For
601** example, if the SQL is this:
602**
603** SELECT * FROM t1, t2, t3 WHERE ...;
604**
605** Then the code generated is conceptually like the following:
606**
607** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000608** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +0000609** foreach row3 in t3 do /
610** ...
611** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000612** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +0000613** end /
614**
615** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +0000616** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
617** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +0000618** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +0000619**
drhe6f85e72004-12-25 01:03:13 +0000620** The code that sqlite3WhereBegin() generates leaves the cursors named
621** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +0000622** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +0000623** data from the various tables of the loop.
624**
drhc27a1ce2002-06-14 20:58:45 +0000625** If the WHERE clause is empty, the foreach loops must each scan their
626** entire tables. Thus a three-way join is an O(N^3) operation. But if
627** the tables have indices and there are terms in the WHERE clause that
628** refer to those indices, a complete table scan can be avoided and the
629** code will run much faster. Most of the work of this routine is checking
630** to see if there are indices that can be used to speed up the loop.
631**
632** Terms of the WHERE clause are also used to limit which rows actually
633** make it to the "..." in the middle of the loop. After each "foreach",
634** terms of the WHERE clause that use only terms in that loop and outer
635** loops are evaluated and if false a jump is made around all subsequent
636** inner loops (or around the "..." if the test occurs within the inner-
637** most loop)
638**
639** OUTER JOINS
640**
641** An outer join of tables t1 and t2 is conceptally coded as follows:
642**
643** foreach row1 in t1 do
644** flag = 0
645** foreach row2 in t2 do
646** start:
647** ...
648** flag = 1
649** end
drhe3184742002-06-19 14:27:05 +0000650** if flag==0 then
651** move the row2 cursor to a null row
652** goto start
653** fi
drhc27a1ce2002-06-14 20:58:45 +0000654** end
655**
drhe3184742002-06-19 14:27:05 +0000656** ORDER BY CLAUSE PROCESSING
657**
658** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
659** if there is one. If there is no ORDER BY clause or if this routine
660** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
661**
662** If an index can be used so that the natural output order of the table
663** scan is correct for the ORDER BY clause, then that index is used and
664** *ppOrderBy is set to NULL. This is an optimization that prevents an
665** unnecessary sort of the result set if an index appropriate for the
666** ORDER BY clause already exists.
667**
668** If the where clause loops cannot be arranged to provide the correct
669** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +0000670*/
danielk19774adee202004-05-08 08:23:19 +0000671WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +0000672 Parse *pParse, /* The parser context */
673 SrcList *pTabList, /* A list of all tables to be scanned */
674 Expr *pWhere, /* The WHERE clause */
drhf8db1bc2005-04-22 02:38:37 +0000675 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +0000676){
677 int i; /* Loop counter */
678 WhereInfo *pWInfo; /* Will become the return value of this function */
679 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhd4f5ee22003-07-16 00:54:31 +0000680 int brk, cont = 0; /* Addresses used during code generation */
drh0aa74ed2005-07-16 13:33:20 +0000681 Bitmask loopMask; /* One bit set for each outer loop */
682 WhereTerm *pTerm; /* A single term in the WHERE clause */
683 ExprMaskSet maskSet; /* The expression mask set */
684 int iDirectEq[BMS]; /* Term of the form ROWID==X for the N-th table */
685 int iDirectLt[BMS]; /* Term of the form ROWID<X or ROWID<=X */
686 int iDirectGt[BMS]; /* Term of the form ROWID>X or ROWID>=X */
687 WhereClause wc; /* The WHERE clause is divided into these terms */
drh9012bcb2004-12-19 00:11:35 +0000688 struct SrcList_item *pTabItem; /* A single entry from pTabList */
689 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh75897232000-05-29 14:26:00 +0000690
drh1398ad32005-01-19 23:24:50 +0000691 /* The number of terms in the FROM clause is limited by the number of
692 ** bits in a Bitmask
693 */
694 if( pTabList->nSrc>sizeof(Bitmask)*8 ){
695 sqlite3ErrorMsg(pParse, "at most %d tables in a join",
696 sizeof(Bitmask)*8);
697 return 0;
698 }
699
drh83dcb1a2002-06-28 01:02:38 +0000700 /* Split the WHERE clause into separate subexpressions where each
drh0aa74ed2005-07-16 13:33:20 +0000701 ** subexpression is separated by an AND operator. If the wc.a[]
drh83dcb1a2002-06-28 01:02:38 +0000702 ** array fills up, the last entry might point to an expression which
703 ** contains additional unfactored AND operators.
704 */
drh6a3ea0e2003-05-02 14:32:12 +0000705 initMaskSet(&maskSet);
drh0aa74ed2005-07-16 13:33:20 +0000706 whereClauseInit(&wc);
707 whereSplit(&wc, pWhere);
drh1398ad32005-01-19 23:24:50 +0000708
drh75897232000-05-29 14:26:00 +0000709 /* Allocate and initialize the WhereInfo structure that will become the
710 ** return value.
711 */
drhad3cab52002-05-24 02:04:32 +0000712 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
danielk1977132872b2004-05-10 10:37:18 +0000713 if( sqlite3_malloc_failed ){
danielk1977d5d56522005-03-16 12:15:20 +0000714 sqliteFree(pWInfo); /* Avoid leaking memory when malloc fails */
drh0aa74ed2005-07-16 13:33:20 +0000715 whereClauseClear(&wc);
drh75897232000-05-29 14:26:00 +0000716 return 0;
717 }
718 pWInfo->pParse = pParse;
719 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +0000720 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh08192d52002-04-30 19:20:28 +0000721
722 /* Special case: a WHERE clause that is constant. Evaluate the
723 ** expression and either jump over all of the code or fall thru.
724 */
danielk19774adee202004-05-08 08:23:19 +0000725 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
726 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +0000727 pWhere = 0;
drh08192d52002-04-30 19:20:28 +0000728 }
drh75897232000-05-29 14:26:00 +0000729
drh75897232000-05-29 14:26:00 +0000730 /* Analyze all of the subexpressions.
731 */
drh1398ad32005-01-19 23:24:50 +0000732 for(i=0; i<pTabList->nSrc; i++){
733 createMask(&maskSet, pTabList->a[i].iCursor);
734 }
drh0aa74ed2005-07-16 13:33:20 +0000735 for(pTerm=wc.a, i=0; i<wc.nTerm; i++, pTerm++){
drh193bd772004-07-20 18:23:14 +0000736 exprAnalyze(pTabList, &maskSet, pTerm);
drh75897232000-05-29 14:26:00 +0000737 }
738
drh75897232000-05-29 14:26:00 +0000739 /* Figure out what index to use (if any) for each nested loop.
drh6b563442001-11-07 16:48:26 +0000740 ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
drhad3cab52002-05-24 02:04:32 +0000741 ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
drh8aff1012001-12-22 14:49:24 +0000742 ** loop.
743 **
744 ** If terms exist that use the ROWID of any table, then set the
745 ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
746 ** to the index of the term containing the ROWID. We always prefer
747 ** to use a ROWID which can directly access a table rather than an
drh0a36c572002-02-18 22:49:59 +0000748 ** index which requires reading an index first to get the rowid then
749 ** doing a second read of the actual database table.
drh75897232000-05-29 14:26:00 +0000750 **
751 ** Actually, if there are more than 32 tables in the join, only the
drh0a36c572002-02-18 22:49:59 +0000752 ** first 32 tables are candidates for indices. This is (again) due
753 ** to the limit of 32 bits in an integer bitmask.
drh75897232000-05-29 14:26:00 +0000754 */
755 loopMask = 0;
drh9012bcb2004-12-19 00:11:35 +0000756 pTabItem = pTabList->a;
757 pLevel = pWInfo->a;
758 for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++,pTabItem++,pLevel++){
drhc4a3c772001-04-04 11:48:57 +0000759 int j;
drh9012bcb2004-12-19 00:11:35 +0000760 int iCur = pTabItem->iCursor; /* The cursor for this table */
drh51669862004-12-18 18:40:26 +0000761 Bitmask mask = getMask(&maskSet, iCur); /* Cursor mask for this table */
drh9012bcb2004-12-19 00:11:35 +0000762 Table *pTab = pTabItem->pTab;
drh75897232000-05-29 14:26:00 +0000763 Index *pIdx;
764 Index *pBestIdx = 0;
drh487ab3c2001-11-08 00:45:21 +0000765 int bestScore = 0;
drh51669862004-12-18 18:40:26 +0000766 int bestRev = 0;
drh75897232000-05-29 14:26:00 +0000767
drhc4a3c772001-04-04 11:48:57 +0000768 /* Check to see if there is an expression that uses only the
drh8aff1012001-12-22 14:49:24 +0000769 ** ROWID field of this table. For terms of the form ROWID==expr
770 ** set iDirectEq[i] to the index of the term. For terms of the
771 ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
772 ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
drh174b6192002-12-03 02:22:52 +0000773 **
774 ** (Added:) Treat ROWID IN expr like ROWID=expr.
drhc4a3c772001-04-04 11:48:57 +0000775 */
drh9012bcb2004-12-19 00:11:35 +0000776 pLevel->iIdxCur = -1;
drh8aff1012001-12-22 14:49:24 +0000777 iDirectEq[i] = -1;
778 iDirectLt[i] = -1;
779 iDirectGt[i] = -1;
drh0aa74ed2005-07-16 13:33:20 +0000780 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
drh193bd772004-07-20 18:23:14 +0000781 Expr *pX = pTerm->p;
782 if( pTerm->idxLeft==iCur && pX->pLeft->iColumn<0
783 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight ){
784 switch( pX->op ){
drhd99f7062002-06-08 23:25:08 +0000785 case TK_IN:
drh8aff1012001-12-22 14:49:24 +0000786 case TK_EQ: iDirectEq[i] = j; break;
787 case TK_LE:
788 case TK_LT: iDirectLt[i] = j; break;
789 case TK_GE:
790 case TK_GT: iDirectGt[i] = j; break;
791 }
drhc4a3c772001-04-04 11:48:57 +0000792 }
drhc4a3c772001-04-04 11:48:57 +0000793 }
drhb6c29892004-11-22 19:12:19 +0000794
795 /* If we found a term that tests ROWID with == or IN, that term
796 ** will be used to locate the rows in the database table. There
drh7bac7002005-07-01 11:38:44 +0000797 ** is no need to continue into the code below that looks for
drhb6c29892004-11-22 19:12:19 +0000798 ** an index. We will always use the ROWID over an index.
799 */
drh8aff1012001-12-22 14:49:24 +0000800 if( iDirectEq[i]>=0 ){
drh6a3ea0e2003-05-02 14:32:12 +0000801 loopMask |= mask;
drh94a11212004-09-25 13:12:14 +0000802 pLevel->pIdx = 0;
drhc4a3c772001-04-04 11:48:57 +0000803 continue;
804 }
805
drh75897232000-05-29 14:26:00 +0000806 /* Do a search for usable indices. Leave pBestIdx pointing to
drh487ab3c2001-11-08 00:45:21 +0000807 ** the "best" index. pBestIdx is left set to NULL if no indices
808 ** are usable.
drh75897232000-05-29 14:26:00 +0000809 **
drhacf3b982005-01-03 01:27:18 +0000810 ** The best index is the one with the highest score. The score
811 ** for the index is determined as follows. For each of the
drh487ab3c2001-11-08 00:45:21 +0000812 ** left-most terms that is fixed by an equality operator, add
drh51669862004-12-18 18:40:26 +0000813 ** 32 to the score. The right-most term of the index may be
814 ** constrained by an inequality. Add 4 if for an "x<..." constraint
815 ** and add 8 for an "x>..." constraint. If both constraints
816 ** are present, add 12.
817 **
818 ** If the left-most term of the index uses an IN operator
819 ** (ex: "x IN (...)") then add 16 to the score.
820 **
821 ** If an index can be used for sorting, add 2 to the score.
822 ** If an index contains all the terms of a table that are ever
823 ** used by any expression in the SQL statement, then add 1 to
824 ** the score.
drh487ab3c2001-11-08 00:45:21 +0000825 **
826 ** This scoring system is designed so that the score can later be
drh51669862004-12-18 18:40:26 +0000827 ** used to determine how the index is used. If the score&0x1c is 0
828 ** then all constraints are equalities. If score&0x4 is not 0 then
drh487ab3c2001-11-08 00:45:21 +0000829 ** there is an inequality used as a termination key. (ex: "x<...")
drh51669862004-12-18 18:40:26 +0000830 ** If score&0x8 is not 0 then there is an inequality used as the
831 ** start key. (ex: "x>..."). A score or 0x10 is the special case
drhc045ec52002-12-04 20:01:06 +0000832 ** of an IN operator constraint. (ex: "x IN ...").
drhd99f7062002-06-08 23:25:08 +0000833 **
drhc27a1ce2002-06-14 20:58:45 +0000834 ** The IN operator (as in "<expr> IN (...)") is treated the same as
835 ** an equality comparison except that it can only be used on the
836 ** left-most column of an index and other terms of the WHERE clause
837 ** cannot be used in conjunction with the IN operator to help satisfy
838 ** other columns of the index.
drh75897232000-05-29 14:26:00 +0000839 */
840 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh51669862004-12-18 18:40:26 +0000841 Bitmask eqMask = 0; /* Index columns covered by an x=... term */
842 Bitmask ltMask = 0; /* Index columns covered by an x<... term */
843 Bitmask gtMask = 0; /* Index columns covered by an x>... term */
844 Bitmask inMask = 0; /* Index columns covered by an x IN .. term */
845 Bitmask m;
846 int nEq, score, bRev = 0;
drh75897232000-05-29 14:26:00 +0000847
drh51669862004-12-18 18:40:26 +0000848 if( pIdx->nColumn>sizeof(eqMask)*8 ){
849 continue; /* Ignore indices with too many columns to analyze */
850 }
drh0aa74ed2005-07-16 13:33:20 +0000851 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
drh193bd772004-07-20 18:23:14 +0000852 Expr *pX = pTerm->p;
drh94a11212004-09-25 13:12:14 +0000853 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
drh193bd772004-07-20 18:23:14 +0000854 if( !pColl && pX->pRight ){
855 pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
danielk19770202b292004-06-09 09:55:16 +0000856 }
857 if( !pColl ){
858 pColl = pParse->db->pDfltColl;
859 }
drh193bd772004-07-20 18:23:14 +0000860 if( pTerm->idxLeft==iCur
861 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight ){
862 int iColumn = pX->pLeft->iColumn;
drh75897232000-05-29 14:26:00 +0000863 int k;
drhdd9f8b42005-05-19 01:26:14 +0000864 char idxaff = iColumn>=0 ? pIdx->pTable->aCol[iColumn].affinity : 0;
drh967e8b72000-06-21 13:59:10 +0000865 for(k=0; k<pIdx->nColumn; k++){
danielk19770202b292004-06-09 09:55:16 +0000866 /* If the collating sequences or affinities don't match,
867 ** ignore this index. */
868 if( pColl!=pIdx->keyInfo.aColl[k] ) continue;
drh193bd772004-07-20 18:23:14 +0000869 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
danielk19770202b292004-06-09 09:55:16 +0000870 if( pIdx->aiColumn[k]==iColumn ){
drh193bd772004-07-20 18:23:14 +0000871 switch( pX->op ){
drh48185c12002-06-09 01:55:20 +0000872 case TK_IN: {
873 if( k==0 ) inMask |= 1;
874 break;
875 }
drh487ab3c2001-11-08 00:45:21 +0000876 case TK_EQ: {
drh51669862004-12-18 18:40:26 +0000877 eqMask |= ((Bitmask)1)<<k;
drh487ab3c2001-11-08 00:45:21 +0000878 break;
879 }
880 case TK_LE:
881 case TK_LT: {
drh51669862004-12-18 18:40:26 +0000882 ltMask |= ((Bitmask)1)<<k;
drh487ab3c2001-11-08 00:45:21 +0000883 break;
884 }
885 case TK_GE:
886 case TK_GT: {
drh51669862004-12-18 18:40:26 +0000887 gtMask |= ((Bitmask)1)<<k;
drh487ab3c2001-11-08 00:45:21 +0000888 break;
889 }
890 default: {
891 /* CANT_HAPPEN */
892 assert( 0 );
893 break;
894 }
895 }
drh75897232000-05-29 14:26:00 +0000896 break;
897 }
898 }
899 }
drh75897232000-05-29 14:26:00 +0000900 }
drhc045ec52002-12-04 20:01:06 +0000901
902 /* The following loop ends with nEq set to the number of columns
903 ** on the left of the index with == constraints.
904 */
drh487ab3c2001-11-08 00:45:21 +0000905 for(nEq=0; nEq<pIdx->nColumn; nEq++){
drh51669862004-12-18 18:40:26 +0000906 m = (((Bitmask)1)<<(nEq+1))-1;
drh487ab3c2001-11-08 00:45:21 +0000907 if( (m & eqMask)!=m ) break;
908 }
drh51669862004-12-18 18:40:26 +0000909
drh7bac7002005-07-01 11:38:44 +0000910 /* Begin assembling the score
drh51669862004-12-18 18:40:26 +0000911 */
912 score = nEq*32; /* Base score is 32 times number of == constraints */
913 m = ((Bitmask)1)<<nEq;
914 if( m & ltMask ) score+=4; /* Increase score for a < constraint */
915 if( m & gtMask ) score+=8; /* Increase score for a > constraint */
916 if( score==0 && inMask ) score = 16; /* Default score for IN constraint */
917
918 /* Give bonus points if this index can be used for sorting
919 */
drh9012bcb2004-12-19 00:11:35 +0000920 if( i==0 && score!=16 && ppOrderBy && *ppOrderBy ){
drh51669862004-12-18 18:40:26 +0000921 int base = pTabList->a[0].iCursor;
922 if( isSortingIndex(pParse, pIdx, pTab, base, *ppOrderBy, nEq, &bRev) ){
923 score += 2;
924 }
925 }
926
drh9012bcb2004-12-19 00:11:35 +0000927 /* Check to see if we can get away with using just the index without
928 ** ever reading the table. If that is the case, then add one bonus
929 ** point to the score.
930 */
931 if( score && pTabItem->colUsed < (((Bitmask)1)<<(BMS-1)) ){
932 for(m=0, j=0; j<pIdx->nColumn; j++){
933 int x = pIdx->aiColumn[j];
934 if( x<BMS-1 ){
935 m |= ((Bitmask)1)<<x;
936 }
937 }
938 if( (pTabItem->colUsed & m)==pTabItem->colUsed ){
939 score++;
940 }
941 }
942
drh51669862004-12-18 18:40:26 +0000943 /* If the score for this index is the best we have seen so far, then
944 ** save it
945 */
drh487ab3c2001-11-08 00:45:21 +0000946 if( score>bestScore ){
947 pBestIdx = pIdx;
948 bestScore = score;
drh51669862004-12-18 18:40:26 +0000949 bestRev = bRev;
drh75897232000-05-29 14:26:00 +0000950 }
951 }
drh94a11212004-09-25 13:12:14 +0000952 pLevel->pIdx = pBestIdx;
953 pLevel->score = bestScore;
drh51669862004-12-18 18:40:26 +0000954 pLevel->bRev = bestRev;
drh6a3ea0e2003-05-02 14:32:12 +0000955 loopMask |= mask;
drh6b563442001-11-07 16:48:26 +0000956 if( pBestIdx ){
drh9012bcb2004-12-19 00:11:35 +0000957 pLevel->iIdxCur = pParse->nTab++;
drh6b563442001-11-07 16:48:26 +0000958 }
drh75897232000-05-29 14:26:00 +0000959 }
960
drhe3184742002-06-19 14:27:05 +0000961 /* Check to see if the ORDER BY clause is or can be satisfied by the
962 ** use of an index on the first table.
963 */
964 if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
drh9012bcb2004-12-19 00:11:35 +0000965 Index *pIdx; /* Index derived from the WHERE clause */
966 Table *pTab; /* Left-most table in the FROM clause */
967 int bRev = 0; /* True to reverse the output order */
968 int iCur; /* Btree-cursor that will be used by pTab */
969 WhereLevel *pLevel0 = &pWInfo->a[0];
drhe3184742002-06-19 14:27:05 +0000970
drh9012bcb2004-12-19 00:11:35 +0000971 pTab = pTabList->a[0].pTab;
972 pIdx = pLevel0->pIdx;
973 iCur = pTabList->a[0].iCursor;
974 if( pIdx==0 && sortableByRowid(iCur, *ppOrderBy, &bRev) ){
975 /* The ORDER BY clause specifies ROWID order, which is what we
976 ** were going to be doing anyway...
977 */
978 *ppOrderBy = 0;
979 pLevel0->bRev = bRev;
980 }else if( pLevel0->score==16 ){
981 /* If there is already an IN index on the left-most table,
982 ** it will not give the correct sort order.
983 ** So, pretend that no suitable index is found.
984 */
985 }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
986 /* If the left-most column is accessed using its ROWID, then do
987 ** not try to sort by index. But do delete the ORDER BY clause
988 ** if it is redundant.
989 */
990 }else if( (pLevel0->score&2)!=0 ){
991 /* The index that was selected for searching will cause rows to
992 ** appear in sorted order.
993 */
994 *ppOrderBy = 0;
drh75897232000-05-29 14:26:00 +0000995 }
996 }
997
drh9012bcb2004-12-19 00:11:35 +0000998 /* Open all tables in the pTabList and any indices selected for
999 ** searching those tables.
1000 */
1001 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
1002 pLevel = pWInfo->a;
1003 for(i=0, pTabItem=pTabList->a; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
1004 Table *pTab;
1005 Index *pIx;
1006 int iIdxCur = pLevel->iIdxCur;
1007
1008 pTab = pTabItem->pTab;
1009 if( pTab->isTransient || pTab->pSelect ) continue;
1010 if( (pLevel->score & 1)==0 ){
1011 sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
1012 }
1013 pLevel->iTabCur = pTabItem->iCursor;
1014 if( (pIx = pLevel->pIdx)!=0 ){
1015 sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
1016 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
1017 (char*)&pIx->keyInfo, P3_KEYINFO);
1018 }
1019 if( (pLevel->score & 1)!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001020 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
1021 }
1022 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh84bfda42005-07-15 13:05:21 +00001023
1024#ifdef SQLITE_TEST
1025 /* Record in the query plan information about the current table
1026 ** and the index used to access it (if any). If the table itself
drh9042f392005-07-15 23:24:23 +00001027 ** is not used, its name is just '{}'. If no index is used
drh84bfda42005-07-15 13:05:21 +00001028 ** the index is listed as "{}"
1029 */
1030 {
drh9042f392005-07-15 23:24:23 +00001031 char *z = pTabItem->zAlias;
1032 int n;
1033 if( z==0 ) z = pTab->zName;
1034 n = strlen(z);
drh84bfda42005-07-15 13:05:21 +00001035 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
drh9042f392005-07-15 23:24:23 +00001036 if( (pLevel->score & 1)!=0 ){
1037 strcpy(&sqlite3_query_plan[nQPlan], "{}");
1038 nQPlan += 2;
1039 }else{
1040 strcpy(&sqlite3_query_plan[nQPlan], z);
1041 nQPlan += n;
drh84bfda42005-07-15 13:05:21 +00001042 }
1043 sqlite3_query_plan[nQPlan++] = ' ';
1044 }
1045 if( pIx==0 ){
1046 strcpy(&sqlite3_query_plan[nQPlan], " {}");
1047 nQPlan += 3;
1048 }else{
1049 n = strlen(pIx->zName);
1050 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
1051 strcpy(&sqlite3_query_plan[nQPlan], pIx->zName);
1052 nQPlan += n;
1053 sqlite3_query_plan[nQPlan++] = ' ';
1054 }
1055 }
1056 }
1057#endif
drh9012bcb2004-12-19 00:11:35 +00001058 }
1059 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
1060
drh84bfda42005-07-15 13:05:21 +00001061#ifdef SQLITE_TEST
1062 /* Terminate the query plan description
1063 */
1064 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
1065 sqlite3_query_plan[--nQPlan] = 0;
1066 }
1067 sqlite3_query_plan[nQPlan] = 0;
1068 nQPlan = 0;
1069#endif
1070
drh75897232000-05-29 14:26:00 +00001071 /* Generate the code to do the search
1072 */
drh75897232000-05-29 14:26:00 +00001073 loopMask = 0;
drh9012bcb2004-12-19 00:11:35 +00001074 pLevel = pWInfo->a;
1075 pTabItem = pTabList->a;
1076 for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
drh75897232000-05-29 14:26:00 +00001077 int j, k;
drh9012bcb2004-12-19 00:11:35 +00001078 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
1079 Index *pIdx; /* The index we will be using */
1080 int iIdxCur; /* The VDBE cursor for the index */
1081 int omitTable; /* True if we use the index only */
1082
1083 pIdx = pLevel->pIdx;
1084 iIdxCur = pLevel->iIdxCur;
1085 pLevel->inOp = OP_Noop;
1086
1087 /* Check to see if it is appropriate to omit the use of the table
1088 ** here and use its index instead.
1089 */
1090 omitTable = (pLevel->score&1)!=0;
drh75897232000-05-29 14:26:00 +00001091
drhad2d8302002-05-24 20:31:36 +00001092 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +00001093 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +00001094 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +00001095 */
1096 if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
1097 if( !pParse->nMem ) pParse->nMem++;
1098 pLevel->iLeftJoin = pParse->nMem++;
drhf0863fe2005-06-12 21:35:51 +00001099 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001100 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001101 VdbeComment((v, "# init LEFT JOIN no-match flag"));
drhad2d8302002-05-24 20:31:36 +00001102 }
1103
drh94a11212004-09-25 13:12:14 +00001104 if( i<ARRAYSIZE(iDirectEq) && (k = iDirectEq[i])>=0 ){
drh8aff1012001-12-22 14:49:24 +00001105 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +00001106 ** equality comparison against the ROWID field. Or
1107 ** we reference multiple rows using a "rowid IN (...)"
1108 ** construct.
drhc4a3c772001-04-04 11:48:57 +00001109 */
drh0aa74ed2005-07-16 13:33:20 +00001110 assert( k<wc.nTerm );
1111 pTerm = &wc.a[k];
drh193bd772004-07-20 18:23:14 +00001112 assert( pTerm->p!=0 );
drh193bd772004-07-20 18:23:14 +00001113 assert( pTerm->idxLeft==iCur );
drh9012bcb2004-12-19 00:11:35 +00001114 assert( omitTable==0 );
drh94a11212004-09-25 13:12:14 +00001115 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1116 codeEqualityTerm(pParse, pTerm, brk, pLevel);
danielk19774adee202004-05-08 08:23:19 +00001117 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1118 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
danielk19774adee202004-05-08 08:23:19 +00001119 sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001120 VdbeComment((v, "pk"));
drh6b563442001-11-07 16:48:26 +00001121 pLevel->op = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001122 }else if( pIdx!=0 && pLevel->score>3 && (pLevel->score&0x0c)==0 ){
drhc27a1ce2002-06-14 20:58:45 +00001123 /* Case 2: There is an index and all terms of the WHERE clause that
drhb6c29892004-11-22 19:12:19 +00001124 ** refer to the index using the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +00001125 */
drh6b563442001-11-07 16:48:26 +00001126 int start;
drh51669862004-12-18 18:40:26 +00001127 int nColumn = (pLevel->score+16)/32;
danielk19774adee202004-05-08 08:23:19 +00001128 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
drh772ae622004-05-19 13:13:08 +00001129
1130 /* For each column of the index, find the term of the WHERE clause that
1131 ** constraints that column. If the WHERE clause term is X=expr, then
drh0aa74ed2005-07-16 13:33:20 +00001132 ** generate code to evaluate expr and leave the result on the stack */
drh487ab3c2001-11-08 00:45:21 +00001133 for(j=0; j<nColumn; j++){
drh0aa74ed2005-07-16 13:33:20 +00001134 for(pTerm=wc.a, k=0; k<wc.nTerm; k++, pTerm++){
drh193bd772004-07-20 18:23:14 +00001135 Expr *pX = pTerm->p;
drhd99f7062002-06-08 23:25:08 +00001136 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001137 if( pTerm->idxLeft==iCur
1138 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drhd99f7062002-06-08 23:25:08 +00001139 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drhac931eb2005-01-11 18:13:56 +00001140 && (pX->op==TK_EQ || pX->op==TK_IN)
drh75897232000-05-29 14:26:00 +00001141 ){
danielk1977e014a832004-05-17 10:48:57 +00001142 char idxaff = pIdx->pTable->aCol[pX->pLeft->iColumn].affinity;
drh94a11212004-09-25 13:12:14 +00001143 if( sqlite3IndexAffinityOk(pX, idxaff) ){
1144 codeEqualityTerm(pParse, pTerm, brk, pLevel);
1145 break;
drhd99f7062002-06-08 23:25:08 +00001146 }
drh75897232000-05-29 14:26:00 +00001147 }
drh75897232000-05-29 14:26:00 +00001148 }
1149 }
drh6b563442001-11-07 16:48:26 +00001150 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001151 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drh94a11212004-09-25 13:12:14 +00001152 buildIndexProbe(v, nColumn, brk, pIdx);
danielk19773d1bfea2004-05-14 11:00:53 +00001153 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
drh772ae622004-05-19 13:13:08 +00001154
drh772ae622004-05-19 13:13:08 +00001155 /* Generate code (1) to move to the first matching element of the table.
1156 ** Then generate code (2) that jumps to "brk" after the cursor is past
1157 ** the last matching element of the table. The code (1) is executed
1158 ** once to initialize the search, the code (2) is executed before each
1159 ** iteration of the scan to see if the scan has finished. */
drhc045ec52002-12-04 20:01:06 +00001160 if( pLevel->bRev ){
1161 /* Scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001162 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001163 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001164 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001165 pLevel->op = OP_Prev;
1166 }else{
1167 /* Scan in the forward order */
drh9012bcb2004-12-19 00:11:35 +00001168 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001169 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001170 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
drhc045ec52002-12-04 20:01:06 +00001171 pLevel->op = OP_Next;
1172 }
drh9012bcb2004-12-19 00:11:35 +00001173 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001174 sqlite3VdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
drhe6f85e72004-12-25 01:03:13 +00001175 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001176 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001177 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh75897232000-05-29 14:26:00 +00001178 }
drh9012bcb2004-12-19 00:11:35 +00001179 pLevel->p1 = iIdxCur;
drh6b563442001-11-07 16:48:26 +00001180 pLevel->p2 = start;
drh8aff1012001-12-22 14:49:24 +00001181 }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
1182 /* Case 3: We have an inequality comparison against the ROWID field.
1183 */
1184 int testOp = OP_Noop;
1185 int start;
drhb6c29892004-11-22 19:12:19 +00001186 int bRev = pLevel->bRev;
drh8aff1012001-12-22 14:49:24 +00001187
drh9012bcb2004-12-19 00:11:35 +00001188 assert( omitTable==0 );
danielk19774adee202004-05-08 08:23:19 +00001189 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1190 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drhb6c29892004-11-22 19:12:19 +00001191 if( bRev ){
1192 int t = iDirectGt[i];
1193 iDirectGt[i] = iDirectLt[i];
1194 iDirectLt[i] = t;
1195 }
drh8aff1012001-12-22 14:49:24 +00001196 if( iDirectGt[i]>=0 ){
drh94a11212004-09-25 13:12:14 +00001197 Expr *pX;
drh8aff1012001-12-22 14:49:24 +00001198 k = iDirectGt[i];
drh0aa74ed2005-07-16 13:33:20 +00001199 assert( k<wc.nTerm );
1200 pTerm = &wc.a[k];
drh94a11212004-09-25 13:12:14 +00001201 pX = pTerm->p;
1202 assert( pX!=0 );
drh193bd772004-07-20 18:23:14 +00001203 assert( pTerm->idxLeft==iCur );
drh94a11212004-09-25 13:12:14 +00001204 sqlite3ExprCode(pParse, pX->pRight);
danielk1977d0a69322005-02-02 01:10:44 +00001205 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
drhb6c29892004-11-22 19:12:19 +00001206 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001207 VdbeComment((v, "pk"));
drh193bd772004-07-20 18:23:14 +00001208 disableTerm(pLevel, &pTerm->p);
drh8aff1012001-12-22 14:49:24 +00001209 }else{
drhb6c29892004-11-22 19:12:19 +00001210 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
drh8aff1012001-12-22 14:49:24 +00001211 }
1212 if( iDirectLt[i]>=0 ){
drh94a11212004-09-25 13:12:14 +00001213 Expr *pX;
drh8aff1012001-12-22 14:49:24 +00001214 k = iDirectLt[i];
drh0aa74ed2005-07-16 13:33:20 +00001215 assert( k<wc.nTerm );
1216 pTerm = &wc.a[k];
drh94a11212004-09-25 13:12:14 +00001217 pX = pTerm->p;
1218 assert( pX!=0 );
drh193bd772004-07-20 18:23:14 +00001219 assert( pTerm->idxLeft==iCur );
drh94a11212004-09-25 13:12:14 +00001220 sqlite3ExprCode(pParse, pX->pRight);
drh8aff1012001-12-22 14:49:24 +00001221 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001222 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drh94a11212004-09-25 13:12:14 +00001223 if( pX->op==TK_LT || pX->op==TK_GT ){
drhb6c29892004-11-22 19:12:19 +00001224 testOp = bRev ? OP_Le : OP_Ge;
drh8aff1012001-12-22 14:49:24 +00001225 }else{
drhb6c29892004-11-22 19:12:19 +00001226 testOp = bRev ? OP_Lt : OP_Gt;
drh8aff1012001-12-22 14:49:24 +00001227 }
drh193bd772004-07-20 18:23:14 +00001228 disableTerm(pLevel, &pTerm->p);
drh8aff1012001-12-22 14:49:24 +00001229 }
danielk19774adee202004-05-08 08:23:19 +00001230 start = sqlite3VdbeCurrentAddr(v);
drhb6c29892004-11-22 19:12:19 +00001231 pLevel->op = bRev ? OP_Prev : OP_Next;
drh6a3ea0e2003-05-02 14:32:12 +00001232 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001233 pLevel->p2 = start;
1234 if( testOp!=OP_Noop ){
drhf0863fe2005-06-12 21:35:51 +00001235 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001236 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drhf0863fe2005-06-12 21:35:51 +00001237 sqlite3VdbeAddOp(v, testOp, 'n', brk);
drh8aff1012001-12-22 14:49:24 +00001238 }
drh8aff1012001-12-22 14:49:24 +00001239 }else if( pIdx==0 ){
drhc27a1ce2002-06-14 20:58:45 +00001240 /* Case 4: There is no usable index. We must do a complete
drh8aff1012001-12-22 14:49:24 +00001241 ** scan of the entire database table.
1242 */
1243 int start;
drhb6c29892004-11-22 19:12:19 +00001244 int opRewind;
drh8aff1012001-12-22 14:49:24 +00001245
drh9012bcb2004-12-19 00:11:35 +00001246 assert( omitTable==0 );
danielk19774adee202004-05-08 08:23:19 +00001247 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1248 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drhb6c29892004-11-22 19:12:19 +00001249 if( pLevel->bRev ){
1250 opRewind = OP_Last;
1251 pLevel->op = OP_Prev;
1252 }else{
1253 opRewind = OP_Rewind;
1254 pLevel->op = OP_Next;
1255 }
1256 sqlite3VdbeAddOp(v, opRewind, iCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001257 start = sqlite3VdbeCurrentAddr(v);
drh6a3ea0e2003-05-02 14:32:12 +00001258 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001259 pLevel->p2 = start;
drh487ab3c2001-11-08 00:45:21 +00001260 }else{
drhc27a1ce2002-06-14 20:58:45 +00001261 /* Case 5: The WHERE clause term that refers to the right-most
1262 ** column of the index is an inequality. For example, if
1263 ** the index is on (x,y,z) and the WHERE clause is of the
1264 ** form "x=5 AND y<10" then this case is used. Only the
1265 ** right-most column can be an inequality - the rest must
1266 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +00001267 **
1268 ** This case is also used when there are no WHERE clause
1269 ** constraints but an index is selected anyway, in order
1270 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +00001271 */
1272 int score = pLevel->score;
drh51669862004-12-18 18:40:26 +00001273 int nEqColumn = score/32;
drh487ab3c2001-11-08 00:45:21 +00001274 int start;
danielk1977f7df9cc2004-06-16 12:02:47 +00001275 int leFlag=0, geFlag=0;
drh487ab3c2001-11-08 00:45:21 +00001276 int testOp;
1277
1278 /* Evaluate the equality constraints
1279 */
1280 for(j=0; j<nEqColumn; j++){
drh94a11212004-09-25 13:12:14 +00001281 int iIdxCol = pIdx->aiColumn[j];
drh0aa74ed2005-07-16 13:33:20 +00001282 for(pTerm=wc.a, k=0; k<wc.nTerm; k++, pTerm++){
drh94a11212004-09-25 13:12:14 +00001283 Expr *pX = pTerm->p;
1284 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001285 if( pTerm->idxLeft==iCur
drh94a11212004-09-25 13:12:14 +00001286 && pX->op==TK_EQ
drh193bd772004-07-20 18:23:14 +00001287 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drh94a11212004-09-25 13:12:14 +00001288 && pX->pLeft->iColumn==iIdxCol
drh487ab3c2001-11-08 00:45:21 +00001289 ){
drh94a11212004-09-25 13:12:14 +00001290 sqlite3ExprCode(pParse, pX->pRight);
drh193bd772004-07-20 18:23:14 +00001291 disableTerm(pLevel, &pTerm->p);
drh487ab3c2001-11-08 00:45:21 +00001292 break;
1293 }
1294 }
1295 }
1296
drhc27a1ce2002-06-14 20:58:45 +00001297 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +00001298 ** used twice: once to make the termination key and once to make the
1299 ** start key.
1300 */
1301 for(j=0; j<nEqColumn; j++){
danielk19774adee202004-05-08 08:23:19 +00001302 sqlite3VdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
drh487ab3c2001-11-08 00:45:21 +00001303 }
1304
drhc045ec52002-12-04 20:01:06 +00001305 /* Labels for the beginning and end of the loop
1306 */
danielk19774adee202004-05-08 08:23:19 +00001307 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1308 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
drhc045ec52002-12-04 20:01:06 +00001309
drh487ab3c2001-11-08 00:45:21 +00001310 /* Generate the termination key. This is the key value that
1311 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +00001312 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +00001313 **
1314 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1315 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +00001316 */
drh51669862004-12-18 18:40:26 +00001317 if( (score & 4)!=0 ){
drh0aa74ed2005-07-16 13:33:20 +00001318 for(pTerm=wc.a, k=0; k<wc.nTerm; k++, pTerm++){
drh94a11212004-09-25 13:12:14 +00001319 Expr *pX = pTerm->p;
1320 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001321 if( pTerm->idxLeft==iCur
drh94a11212004-09-25 13:12:14 +00001322 && (pX->op==TK_LT || pX->op==TK_LE)
drh193bd772004-07-20 18:23:14 +00001323 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drh94a11212004-09-25 13:12:14 +00001324 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh487ab3c2001-11-08 00:45:21 +00001325 ){
drh94a11212004-09-25 13:12:14 +00001326 sqlite3ExprCode(pParse, pX->pRight);
1327 leFlag = pX->op==TK_LE;
drh193bd772004-07-20 18:23:14 +00001328 disableTerm(pLevel, &pTerm->p);
drh487ab3c2001-11-08 00:45:21 +00001329 break;
1330 }
1331 }
1332 testOp = OP_IdxGE;
1333 }else{
1334 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
1335 leFlag = 1;
1336 }
1337 if( testOp!=OP_Noop ){
drh51669862004-12-18 18:40:26 +00001338 int nCol = nEqColumn + ((score & 4)!=0);
drh487ab3c2001-11-08 00:45:21 +00001339 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001340 buildIndexProbe(v, nCol, brk, pIdx);
drhc045ec52002-12-04 20:01:06 +00001341 if( pLevel->bRev ){
drh7cf6e4d2004-05-19 14:56:55 +00001342 int op = leFlag ? OP_MoveLe : OP_MoveLt;
drh9012bcb2004-12-19 00:11:35 +00001343 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001344 }else{
danielk19774adee202004-05-08 08:23:19 +00001345 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001346 }
1347 }else if( pLevel->bRev ){
drh9012bcb2004-12-19 00:11:35 +00001348 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001349 }
1350
1351 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001352 ** bound on the search. There is no start key if there are no
1353 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001354 ** that case, generate a "Rewind" instruction in place of the
1355 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001356 **
1357 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1358 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001359 */
drh51669862004-12-18 18:40:26 +00001360 if( (score & 8)!=0 ){
drh0aa74ed2005-07-16 13:33:20 +00001361 for(pTerm=wc.a, k=0; k<wc.nTerm; k++, pTerm++){
drh94a11212004-09-25 13:12:14 +00001362 Expr *pX = pTerm->p;
1363 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001364 if( pTerm->idxLeft==iCur
drh94a11212004-09-25 13:12:14 +00001365 && (pX->op==TK_GT || pX->op==TK_GE)
drh193bd772004-07-20 18:23:14 +00001366 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drh94a11212004-09-25 13:12:14 +00001367 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh487ab3c2001-11-08 00:45:21 +00001368 ){
drh94a11212004-09-25 13:12:14 +00001369 sqlite3ExprCode(pParse, pX->pRight);
1370 geFlag = pX->op==TK_GE;
drh193bd772004-07-20 18:23:14 +00001371 disableTerm(pLevel, &pTerm->p);
drh487ab3c2001-11-08 00:45:21 +00001372 break;
1373 }
1374 }
drh7900ead2001-11-12 13:51:43 +00001375 }else{
1376 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001377 }
drh51669862004-12-18 18:40:26 +00001378 if( nEqColumn>0 || (score&8)!=0 ){
1379 int nCol = nEqColumn + ((score&8)!=0);
drh94a11212004-09-25 13:12:14 +00001380 buildIndexProbe(v, nCol, brk, pIdx);
drhc045ec52002-12-04 20:01:06 +00001381 if( pLevel->bRev ){
1382 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001383 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001384 testOp = OP_IdxLT;
1385 }else{
drh7cf6e4d2004-05-19 14:56:55 +00001386 int op = geFlag ? OP_MoveGe : OP_MoveGt;
drh9012bcb2004-12-19 00:11:35 +00001387 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001388 }
1389 }else if( pLevel->bRev ){
1390 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001391 }else{
drh9012bcb2004-12-19 00:11:35 +00001392 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001393 }
1394
1395 /* Generate the the top of the loop. If there is a termination
1396 ** key we have to test for that key and abort at the top of the
1397 ** loop.
1398 */
danielk19774adee202004-05-08 08:23:19 +00001399 start = sqlite3VdbeCurrentAddr(v);
drh487ab3c2001-11-08 00:45:21 +00001400 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001401 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001402 sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
danielk19773d1bfea2004-05-14 11:00:53 +00001403 if( (leFlag && !pLevel->bRev) || (!geFlag && pLevel->bRev) ){
1404 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
1405 }
drh487ab3c2001-11-08 00:45:21 +00001406 }
drh9012bcb2004-12-19 00:11:35 +00001407 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
drh51669862004-12-18 18:40:26 +00001408 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEqColumn + ((score&4)!=0), cont);
drhe6f85e72004-12-25 01:03:13 +00001409 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001410 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001411 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh487ab3c2001-11-08 00:45:21 +00001412 }
1413
1414 /* Record the instruction used to terminate the loop.
1415 */
drhc045ec52002-12-04 20:01:06 +00001416 pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
drh9012bcb2004-12-19 00:11:35 +00001417 pLevel->p1 = iIdxCur;
drh487ab3c2001-11-08 00:45:21 +00001418 pLevel->p2 = start;
drh75897232000-05-29 14:26:00 +00001419 }
drh6a3ea0e2003-05-02 14:32:12 +00001420 loopMask |= getMask(&maskSet, iCur);
drh75897232000-05-29 14:26:00 +00001421
1422 /* Insert code to test every subexpression that can be completely
1423 ** computed using the current set of tables.
1424 */
drh0aa74ed2005-07-16 13:33:20 +00001425 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
drh392e5972005-07-08 14:14:22 +00001426 Expr *pE = pTerm->p;
1427 if( pE==0 || ExprHasProperty(pE, EP_OptOnly) ) continue;
drh193bd772004-07-20 18:23:14 +00001428 if( (pTerm->prereqAll & loopMask)!=pTerm->prereqAll ) continue;
drh392e5972005-07-08 14:14:22 +00001429 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
drh1f162302002-10-27 19:35:33 +00001430 continue;
1431 }
drh392e5972005-07-08 14:14:22 +00001432 sqlite3ExprIfFalse(pParse, pE, cont, 1);
drh193bd772004-07-20 18:23:14 +00001433 pTerm->p = 0;
drh75897232000-05-29 14:26:00 +00001434 }
1435 brk = cont;
drhad2d8302002-05-24 20:31:36 +00001436
1437 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1438 ** at least one row of the right table has matched the left table.
1439 */
1440 if( pLevel->iLeftJoin ){
danielk19774adee202004-05-08 08:23:19 +00001441 pLevel->top = sqlite3VdbeCurrentAddr(v);
1442 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1443 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001444 VdbeComment((v, "# record LEFT JOIN hit"));
drh0aa74ed2005-07-16 13:33:20 +00001445 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
drh392e5972005-07-08 14:14:22 +00001446 Expr *pE = pTerm->p;
1447 if( pE==0 || ExprHasProperty(pE, EP_OptOnly) ) continue;
drh193bd772004-07-20 18:23:14 +00001448 if( (pTerm->prereqAll & loopMask)!=pTerm->prereqAll ) continue;
drh392e5972005-07-08 14:14:22 +00001449 sqlite3ExprIfFalse(pParse, pE, cont, 1);
drh193bd772004-07-20 18:23:14 +00001450 pTerm->p = 0;
drh1cc093c2002-06-24 22:01:57 +00001451 }
drhad2d8302002-05-24 20:31:36 +00001452 }
drh75897232000-05-29 14:26:00 +00001453 }
1454 pWInfo->iContinue = cont;
drh6a3ea0e2003-05-02 14:32:12 +00001455 freeMaskSet(&maskSet);
drh0aa74ed2005-07-16 13:33:20 +00001456 whereClauseClear(&wc);
drh75897232000-05-29 14:26:00 +00001457 return pWInfo;
1458}
1459
1460/*
drhc27a1ce2002-06-14 20:58:45 +00001461** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00001462** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001463*/
danielk19774adee202004-05-08 08:23:19 +00001464void sqlite3WhereEnd(WhereInfo *pWInfo){
drh75897232000-05-29 14:26:00 +00001465 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001466 int i;
drh6b563442001-11-07 16:48:26 +00001467 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001468 SrcList *pTabList = pWInfo->pTabList;
drh9012bcb2004-12-19 00:11:35 +00001469 struct SrcList_item *pTabItem;
drh19a775c2000-06-05 18:54:46 +00001470
drh9012bcb2004-12-19 00:11:35 +00001471 /* Generate loop termination code.
1472 */
drhad3cab52002-05-24 02:04:32 +00001473 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001474 pLevel = &pWInfo->a[i];
danielk19774adee202004-05-08 08:23:19 +00001475 sqlite3VdbeResolveLabel(v, pLevel->cont);
drh6b563442001-11-07 16:48:26 +00001476 if( pLevel->op!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001477 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001478 }
danielk19774adee202004-05-08 08:23:19 +00001479 sqlite3VdbeResolveLabel(v, pLevel->brk);
drhd99f7062002-06-08 23:25:08 +00001480 if( pLevel->inOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001481 sqlite3VdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
drhd99f7062002-06-08 23:25:08 +00001482 }
drhad2d8302002-05-24 20:31:36 +00001483 if( pLevel->iLeftJoin ){
1484 int addr;
danielk19774adee202004-05-08 08:23:19 +00001485 addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh9012bcb2004-12-19 00:11:35 +00001486 sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
danielk19774adee202004-05-08 08:23:19 +00001487 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
drh9012bcb2004-12-19 00:11:35 +00001488 if( pLevel->iIdxCur>=0 ){
1489 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
drh7f09b3e2002-08-13 13:15:49 +00001490 }
danielk19774adee202004-05-08 08:23:19 +00001491 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
drhad2d8302002-05-24 20:31:36 +00001492 }
drh19a775c2000-06-05 18:54:46 +00001493 }
drh9012bcb2004-12-19 00:11:35 +00001494
1495 /* The "break" point is here, just past the end of the outer loop.
1496 ** Set it.
1497 */
danielk19774adee202004-05-08 08:23:19 +00001498 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00001499
drhacf3b982005-01-03 01:27:18 +00001500 /* Close all of the cursors that were opend by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00001501 */
1502 pLevel = pWInfo->a;
1503 pTabItem = pTabList->a;
1504 for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
1505 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00001506 assert( pTab!=0 );
1507 if( pTab->isTransient || pTab->pSelect ) continue;
drh9012bcb2004-12-19 00:11:35 +00001508 if( (pLevel->score & 1)==0 ){
1509 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
1510 }
drh6b563442001-11-07 16:48:26 +00001511 if( pLevel->pIdx!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001512 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
1513 }
1514
drhacf3b982005-01-03 01:27:18 +00001515 /* Make cursor substitutions for cases where we want to use
drh9012bcb2004-12-19 00:11:35 +00001516 ** just the index and never reference the table.
1517 **
1518 ** Calls to the code generator in between sqlite3WhereBegin and
1519 ** sqlite3WhereEnd will have created code that references the table
1520 ** directly. This loop scans all that code looking for opcodes
1521 ** that reference the table and converts them into opcodes that
1522 ** reference the index.
1523 */
1524 if( pLevel->score & 1 ){
1525 int i, j, last;
1526 VdbeOp *pOp;
1527 Index *pIdx = pLevel->pIdx;
1528
1529 assert( pIdx!=0 );
1530 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1531 last = sqlite3VdbeCurrentAddr(v);
1532 for(i=pWInfo->iTop; i<last; i++, pOp++){
1533 if( pOp->p1!=pLevel->iTabCur ) continue;
1534 if( pOp->opcode==OP_Column ){
1535 pOp->p1 = pLevel->iIdxCur;
1536 for(j=0; j<pIdx->nColumn; j++){
1537 if( pOp->p2==pIdx->aiColumn[j] ){
1538 pOp->p2 = j;
1539 break;
1540 }
1541 }
drhf0863fe2005-06-12 21:35:51 +00001542 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00001543 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00001544 pOp->opcode = OP_IdxRowid;
danielk19776c18b6e2005-01-30 09:17:58 +00001545 }else if( pOp->opcode==OP_NullRow ){
1546 pOp->opcode = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001547 }
1548 }
drh6b563442001-11-07 16:48:26 +00001549 }
drh19a775c2000-06-05 18:54:46 +00001550 }
drh9012bcb2004-12-19 00:11:35 +00001551
1552 /* Final cleanup
1553 */
drh75897232000-05-29 14:26:00 +00001554 sqliteFree(pWInfo);
1555 return;
1556}