blob: 1054bf55baf700451eef2e2a75b0098058d648db [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**
drhfe2093d2005-01-20 22:48:47 +000019** $Id: where.c,v 1.131 2005/01/20 22:48:48 drh Exp $
drh75897232000-05-29 14:26:00 +000020*/
21#include "sqliteInt.h"
22
23/*
24** The query generator uses an array of instances of this structure to
25** help it analyze the subexpressions of the WHERE clause. Each WHERE
26** clause subexpression is separated from the others by an AND operator.
drh51669862004-12-18 18:40:26 +000027**
28** The idxLeft and idxRight fields are the VDBE cursor numbers for the
29** table that contains the column that appears on the left-hand and
30** right-hand side of ExprInfo.p. If either side of ExprInfo.p is
31** something other than a simple column reference, then idxLeft or
32** idxRight are -1.
33**
34** It is the VDBE cursor number is the value stored in Expr.iTable
35** when Expr.op==TK_COLUMN and the value stored in SrcList.a[].iCursor.
36**
37** prereqLeft, prereqRight, and prereqAll record sets of cursor numbers,
38** but they do so indirectly. A single ExprMaskSet structure translates
39** cursor number into bits and the translated bit is stored in the prereq
40** fields. The translation is used in order to maximize the number of
41** bits that will fit in a Bitmask. The VDBE cursor numbers might be
42** spread out over the non-negative integers. For example, the cursor
43** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The ExprMaskSet
44** translates these sparse cursor numbers into consecutive integers
45** beginning with 0 in order to make the best possible use of the available
46** bits in the Bitmask. So, in the example above, the cursor numbers
47** would be mapped into integers 0 through 7.
48**
49** prereqLeft tells us every VDBE cursor that is referenced on the
50** left-hand side of ExprInfo.p. prereqRight does the same for the
51** right-hand side of the expression. The following identity always
52** holds:
53**
54** prereqAll = prereqLeft | prereqRight
55**
56** The ExprInfo.indexable field is true if the ExprInfo.p expression
57** is of a form that might control an index. Indexable expressions
58** look like this:
59**
60** <column> <op> <expr>
61**
62** Where <column> is a simple column name and <op> is on of the operators
63** that allowedOp() recognizes.
drh75897232000-05-29 14:26:00 +000064*/
65typedef struct ExprInfo ExprInfo;
66struct ExprInfo {
67 Expr *p; /* Pointer to the subexpression */
drhe3184742002-06-19 14:27:05 +000068 u8 indexable; /* True if this subexprssion is usable by an index */
69 short int idxLeft; /* p->pLeft is a column in this table number. -1 if
drh967e8b72000-06-21 13:59:10 +000070 ** p->pLeft is not the column of any table */
drhe3184742002-06-19 14:27:05 +000071 short int idxRight; /* p->pRight is a column in this table number. -1 if
drh967e8b72000-06-21 13:59:10 +000072 ** p->pRight is not the column of any table */
drh51669862004-12-18 18:40:26 +000073 Bitmask prereqLeft; /* Bitmask of tables referenced by p->pLeft */
74 Bitmask prereqRight; /* Bitmask of tables referenced by p->pRight */
75 Bitmask prereqAll; /* Bitmask of tables referenced by p */
drh75897232000-05-29 14:26:00 +000076};
77
78/*
drh6a3ea0e2003-05-02 14:32:12 +000079** An instance of the following structure keeps track of a mapping
drh51669862004-12-18 18:40:26 +000080** between VDBE cursor numbers and bits of the bitmasks in ExprInfo.
81**
82** The VDBE cursor numbers are small integers contained in
83** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
84** clause, the cursor numbers might not begin with 0 and they might
85** contain gaps in the numbering sequence. But we want to make maximum
86** use of the bits in our bitmasks. This structure provides a mapping
87** from the sparse cursor numbers into consecutive integers beginning
88** with 0.
89**
90** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
91** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
92**
93** For example, if the WHERE clause expression used these VDBE
94** cursors: 4, 5, 8, 29, 57, 73. Then the ExprMaskSet structure
95** would map those cursor numbers into bits 0 through 5.
96**
97** Note that the mapping is not necessarily ordered. In the example
98** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
99** 57->5, 73->4. Or one of 719 other combinations might be used. It
100** does not really matter. What is important is that sparse cursor
101** numbers all get mapped into bit numbers that begin with 0 and contain
102** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000103*/
104typedef struct ExprMaskSet ExprMaskSet;
105struct ExprMaskSet {
drh1398ad32005-01-19 23:24:50 +0000106 int n; /* Number of assigned cursor values */
107 int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000108};
109
110/*
drh75897232000-05-29 14:26:00 +0000111** Determine the number of elements in an array.
112*/
113#define ARRAYSIZE(X) (sizeof(X)/sizeof(X[0]))
114
115/*
drh51669862004-12-18 18:40:26 +0000116** This routine identifies subexpressions in the WHERE clause where
117** each subexpression is separate by the AND operator. aSlot is
118** filled with pointers to the subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000119**
drh51669862004-12-18 18:40:26 +0000120** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
121** \________/ \_______________/ \________________/
122** slot[0] slot[1] slot[2]
123**
124** The original WHERE clause in pExpr is unaltered. All this routine
125** does is make aSlot[] entries point to substructure within pExpr.
126**
127** aSlot[] is an array of subexpressions structures. There are nSlot
128** spaces left in this array. This routine finds as many AND-separated
129** subexpressions as it can and puts pointers to those subexpressions
130** into aSlot[] entries. The return value is the number of slots filled.
drh75897232000-05-29 14:26:00 +0000131*/
132static int exprSplit(int nSlot, ExprInfo *aSlot, Expr *pExpr){
133 int cnt = 0;
134 if( pExpr==0 || nSlot<1 ) return 0;
135 if( nSlot==1 || pExpr->op!=TK_AND ){
136 aSlot[0].p = pExpr;
137 return 1;
138 }
139 if( pExpr->pLeft->op!=TK_AND ){
140 aSlot[0].p = pExpr->pLeft;
141 cnt = 1 + exprSplit(nSlot-1, &aSlot[1], pExpr->pRight);
142 }else{
drhdcd997e2003-01-31 17:21:49 +0000143 cnt = exprSplit(nSlot, aSlot, pExpr->pLeft);
144 cnt += exprSplit(nSlot-cnt, &aSlot[cnt], pExpr->pRight);
drh75897232000-05-29 14:26:00 +0000145 }
146 return cnt;
147}
148
149/*
drh6a3ea0e2003-05-02 14:32:12 +0000150** Initialize an expression mask set
151*/
152#define initMaskSet(P) memset(P, 0, sizeof(*P))
153
154/*
drh1398ad32005-01-19 23:24:50 +0000155** Return the bitmask for the given cursor number. Return 0 if
156** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000157*/
drh51669862004-12-18 18:40:26 +0000158static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000159 int i;
160 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000161 if( pMaskSet->ix[i]==iCursor ){
162 return ((Bitmask)1)<<i;
163 }
drh6a3ea0e2003-05-02 14:32:12 +0000164 }
drh6a3ea0e2003-05-02 14:32:12 +0000165 return 0;
166}
167
168/*
drh1398ad32005-01-19 23:24:50 +0000169** Create a new mask for cursor iCursor.
170*/
171static void createMask(ExprMaskSet *pMaskSet, int iCursor){
172 if( pMaskSet->n<ARRAYSIZE(pMaskSet->ix) ){
173 pMaskSet->ix[pMaskSet->n++] = iCursor;
174 }
175}
176
177/*
drh6a3ea0e2003-05-02 14:32:12 +0000178** Destroy an expression mask set
179*/
180#define freeMaskSet(P) /* NO-OP */
181
182/*
drh75897232000-05-29 14:26:00 +0000183** This routine walks (recursively) an expression tree and generates
184** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000185** tree.
drh75897232000-05-29 14:26:00 +0000186**
187** In order for this routine to work, the calling function must have
drh626a8792005-01-17 22:08:19 +0000188** previously invoked sqlite3ExprResolveNames() on the expression. See
drh75897232000-05-29 14:26:00 +0000189** the header comment on that routine for additional information.
drh626a8792005-01-17 22:08:19 +0000190** The sqlite3ExprResolveNames() routines looks for column names and
drh6a3ea0e2003-05-02 14:32:12 +0000191** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
192** the VDBE cursor number of the table.
drh75897232000-05-29 14:26:00 +0000193*/
drh51669862004-12-18 18:40:26 +0000194static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
195 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000196 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000197 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000198 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000199 return mask;
drh75897232000-05-29 14:26:00 +0000200 }
201 if( p->pRight ){
drh6a3ea0e2003-05-02 14:32:12 +0000202 mask = exprTableUsage(pMaskSet, p->pRight);
drh75897232000-05-29 14:26:00 +0000203 }
204 if( p->pLeft ){
drh6a3ea0e2003-05-02 14:32:12 +0000205 mask |= exprTableUsage(pMaskSet, p->pLeft);
drh75897232000-05-29 14:26:00 +0000206 }
drhdd579122002-04-02 01:58:57 +0000207 if( p->pList ){
208 int i;
209 for(i=0; i<p->pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +0000210 mask |= exprTableUsage(pMaskSet, p->pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000211 }
212 }
drh75897232000-05-29 14:26:00 +0000213 return mask;
214}
215
216/*
drh487ab3c2001-11-08 00:45:21 +0000217** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000218** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000219** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000220*/
221static int allowedOp(int op){
drh9a432672004-10-04 13:38:09 +0000222 assert( TK_GT==TK_LE-1 && TK_LE==TK_LT-1 && TK_LT==TK_GE-1 && TK_EQ==TK_GT-1);
223 return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
drh487ab3c2001-11-08 00:45:21 +0000224}
225
226/*
drh51669862004-12-18 18:40:26 +0000227** Swap two objects of type T.
drh193bd772004-07-20 18:23:14 +0000228*/
229#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
230
231/*
232** Return the index in the SrcList that uses cursor iCur. If iCur is
233** used by the first entry in SrcList return 0. If iCur is used by
234** the second entry return 1. And so forth.
235**
236** SrcList is the set of tables in the FROM clause in the order that
237** they will be processed. The value returned here gives us an index
238** of which tables will be processed first.
239*/
240static int tableOrder(SrcList *pList, int iCur){
241 int i;
drh51669862004-12-18 18:40:26 +0000242 struct SrcList_item *pItem;
243 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
244 if( pItem->iCursor==iCur ) return i;
drh193bd772004-07-20 18:23:14 +0000245 }
246 return -1;
247}
248
249/*
drh75897232000-05-29 14:26:00 +0000250** The input to this routine is an ExprInfo structure with only the
251** "p" field filled in. The job of this routine is to analyze the
252** subexpression and populate all the other fields of the ExprInfo
253** structure.
254*/
drh193bd772004-07-20 18:23:14 +0000255static void exprAnalyze(SrcList *pSrc, ExprMaskSet *pMaskSet, ExprInfo *pInfo){
drh75897232000-05-29 14:26:00 +0000256 Expr *pExpr = pInfo->p;
drh6a3ea0e2003-05-02 14:32:12 +0000257 pInfo->prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
258 pInfo->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
259 pInfo->prereqAll = exprTableUsage(pMaskSet, pExpr);
drh75897232000-05-29 14:26:00 +0000260 pInfo->indexable = 0;
261 pInfo->idxLeft = -1;
262 pInfo->idxRight = -1;
drh487ab3c2001-11-08 00:45:21 +0000263 if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
drhd99f7062002-06-08 23:25:08 +0000264 if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
drh6a3ea0e2003-05-02 14:32:12 +0000265 pInfo->idxRight = pExpr->pRight->iTable;
drh75897232000-05-29 14:26:00 +0000266 pInfo->indexable = 1;
267 }
drh967e8b72000-06-21 13:59:10 +0000268 if( pExpr->pLeft->op==TK_COLUMN ){
drh6a3ea0e2003-05-02 14:32:12 +0000269 pInfo->idxLeft = pExpr->pLeft->iTable;
drh75897232000-05-29 14:26:00 +0000270 pInfo->indexable = 1;
271 }
272 }
drh193bd772004-07-20 18:23:14 +0000273 if( pInfo->indexable ){
274 assert( pInfo->idxLeft!=pInfo->idxRight );
275
276 /* We want the expression to be of the form "X = expr", not "expr = X".
277 ** So flip it over if necessary. If the expression is "X = Y", then
278 ** we want Y to come from an earlier table than X.
279 **
280 ** The collating sequence rule is to always choose the left expression.
281 ** So if we do a flip, we also have to move the collating sequence.
282 */
283 if( tableOrder(pSrc,pInfo->idxLeft)<tableOrder(pSrc,pInfo->idxRight) ){
284 assert( pExpr->op!=TK_IN );
285 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
286 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
drh9a432672004-10-04 13:38:09 +0000287 if( pExpr->op>=TK_GT ){
288 assert( TK_LT==TK_GT+2 );
289 assert( TK_GE==TK_LE+2 );
290 assert( TK_GT>TK_EQ );
291 assert( TK_GT<TK_LE );
292 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
293 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000294 }
295 SWAP(unsigned, pInfo->prereqLeft, pInfo->prereqRight);
296 SWAP(short int, pInfo->idxLeft, pInfo->idxRight);
297 }
298 }
299
drh75897232000-05-29 14:26:00 +0000300}
301
302/*
drh51669862004-12-18 18:40:26 +0000303** This routine decides if pIdx can be used to satisfy the ORDER BY
304** clause. If it can, it returns 1. If pIdx cannot satisfy the
305** ORDER BY clause, this routine returns 0.
306**
307** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
308** left-most table in the FROM clause of that same SELECT statement and
309** the table has a cursor number of "base". pIdx is an index on pTab.
310**
311** nEqCol is the number of columns of pIdx that are used as equality
312** constraints. Any of these columns may be missing from the ORDER BY
313** clause and the match can still be a success.
314**
315** If the index is UNIQUE, then the ORDER BY clause is allowed to have
316** additional terms past the end of the index and the match will still
317** be a success.
318**
319** All terms of the ORDER BY that match against the index must be either
320** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
321** index do not need to satisfy this constraint.) The *pbRev value is
322** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
323** the ORDER BY clause is all ASC.
324*/
325static int isSortingIndex(
326 Parse *pParse, /* Parsing context */
327 Index *pIdx, /* The index we are testing */
328 Table *pTab, /* The table to be sorted */
329 int base, /* Cursor number for pTab */
330 ExprList *pOrderBy, /* The ORDER BY clause */
331 int nEqCol, /* Number of index columns with == constraints */
332 int *pbRev /* Set to 1 if ORDER BY is DESC */
333){
334 int i, j; /* Loop counters */
335 int sortOrder; /* Which direction we are sorting */
336 int nTerm; /* Number of ORDER BY terms */
337 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
338 sqlite3 *db = pParse->db;
339
340 assert( pOrderBy!=0 );
341 nTerm = pOrderBy->nExpr;
342 assert( nTerm>0 );
343
344 /* Match terms of the ORDER BY clause against columns of
345 ** the index.
346 */
347 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
348 Expr *pExpr; /* The expression of the ORDER BY pTerm */
349 CollSeq *pColl; /* The collating sequence of pExpr */
350
351 pExpr = pTerm->pExpr;
352 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
353 /* Can not use an index sort on anything that is not a column in the
354 ** left-most table of the FROM clause */
355 return 0;
356 }
357 pColl = sqlite3ExprCollSeq(pParse, pExpr);
358 if( !pColl ) pColl = db->pDfltColl;
drh9012bcb2004-12-19 00:11:35 +0000359 if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
360 /* Term j of the ORDER BY clause does not match column i of the index */
361 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +0000362 /* If an index column that is constrained by == fails to match an
363 ** ORDER BY term, that is OK. Just ignore that column of the index
364 */
365 continue;
366 }else{
367 /* If an index column fails to match and is not constrained by ==
368 ** then the index cannot satisfy the ORDER BY constraint.
369 */
370 return 0;
371 }
372 }
373 if( i>nEqCol ){
374 if( pTerm->sortOrder!=sortOrder ){
375 /* Indices can only be used if all ORDER BY terms past the
376 ** equality constraints are all either DESC or ASC. */
377 return 0;
378 }
379 }else{
380 sortOrder = pTerm->sortOrder;
381 }
382 j++;
383 pTerm++;
384 }
385
386 /* The index can be used for sorting if all terms of the ORDER BY clause
387 ** or covered or if we ran out of index columns and the it is a UNIQUE
388 ** index.
389 */
390 if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
391 *pbRev = sortOrder==SQLITE_SO_DESC;
392 return 1;
393 }
394 return 0;
395}
396
397/*
drhb6c29892004-11-22 19:12:19 +0000398** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
399** by sorting in order of ROWID. Return true if so and set *pbRev to be
400** true for reverse ROWID and false for forward ROWID order.
401*/
402static int sortableByRowid(
403 int base, /* Cursor number for table to be sorted */
404 ExprList *pOrderBy, /* The ORDER BY clause */
405 int *pbRev /* Set to 1 if ORDER BY is DESC */
406){
407 Expr *p;
408
409 assert( pOrderBy!=0 );
410 assert( pOrderBy->nExpr>0 );
411 p = pOrderBy->a[0].pExpr;
412 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
413 *pbRev = pOrderBy->a[0].sortOrder;
414 return 1;
415 }
416 return 0;
417}
418
419
420/*
drh2ffb1182004-07-19 19:14:01 +0000421** Disable a term in the WHERE clause. Except, do not disable the term
422** if it controls a LEFT OUTER JOIN and it did not originate in the ON
423** or USING clause of that join.
424**
425** Consider the term t2.z='ok' in the following queries:
426**
427** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
428** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
429** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
430**
drh23bf66d2004-12-14 03:34:34 +0000431** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +0000432** in the ON clause. The term is disabled in (3) because it is not part
433** of a LEFT OUTER JOIN. In (1), the term is not disabled.
434**
435** Disabling a term causes that term to not be tested in the inner loop
436** of the join. Disabling is an optimization. We would get the correct
437** results if nothing were ever disabled, but joins might run a little
438** slower. The trick is to disable as much as we can without disabling
439** too much. If we disabled in (1), we'd get the wrong answer.
440** See ticket #813.
441*/
442static void disableTerm(WhereLevel *pLevel, Expr **ppExpr){
443 Expr *pExpr = *ppExpr;
444 if( pLevel->iLeftJoin==0 || ExprHasProperty(pExpr, EP_FromJoin) ){
445 *ppExpr = 0;
446 }
447}
448
449/*
drh94a11212004-09-25 13:12:14 +0000450** Generate code that builds a probe for an index. Details:
451**
452** * Check the top nColumn entries on the stack. If any
453** of those entries are NULL, jump immediately to brk,
454** which is the loop exit, since no index entry will match
455** if any part of the key is NULL.
456**
457** * Construct a probe entry from the top nColumn entries in
458** the stack with affinities appropriate for index pIdx.
459*/
460static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
461 sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
462 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
463 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
464 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
465 sqlite3IndexAffinityStr(v, pIdx);
466}
467
468/*
469** Generate code for an equality term of the WHERE clause. An equality
470** term can be either X=expr or X IN (...). pTerm is the X.
471*/
472static void codeEqualityTerm(
473 Parse *pParse, /* The parsing context */
474 ExprInfo *pTerm, /* The term of the WHERE clause to be coded */
475 int brk, /* Jump here to abandon the loop */
476 WhereLevel *pLevel /* When level of the FROM clause we are working on */
477){
478 Expr *pX = pTerm->p;
479 if( pX->op!=TK_IN ){
480 assert( pX->op==TK_EQ );
481 sqlite3ExprCode(pParse, pX->pRight);
482 }else{
483 int iTab = pX->iTable;
484 Vdbe *v = pParse->pVdbe;
485 sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
486 sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
drh9012bcb2004-12-19 00:11:35 +0000487 pLevel->inP2 = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
drh94a11212004-09-25 13:12:14 +0000488 pLevel->inOp = OP_Next;
489 pLevel->inP1 = iTab;
490 }
491 disableTerm(pLevel, &pTerm->p);
492}
493
drh51669862004-12-18 18:40:26 +0000494/*
495** The number of bits in a Bitmask
496*/
497#define BMS (sizeof(Bitmask)*8-1)
498
drh94a11212004-09-25 13:12:14 +0000499
500/*
drhe3184742002-06-19 14:27:05 +0000501** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +0000502** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +0000503** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +0000504** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +0000505** in order to complete the WHERE clause processing.
506**
507** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +0000508**
509** The basic idea is to do a nested loop, one loop for each table in
510** the FROM clause of a select. (INSERT and UPDATE statements are the
511** same as a SELECT with only a single table in the FROM clause.) For
512** example, if the SQL is this:
513**
514** SELECT * FROM t1, t2, t3 WHERE ...;
515**
516** Then the code generated is conceptually like the following:
517**
518** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000519** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +0000520** foreach row3 in t3 do /
521** ...
522** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000523** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +0000524** end /
525**
526** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +0000527** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
528** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +0000529** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +0000530**
drhe6f85e72004-12-25 01:03:13 +0000531** The code that sqlite3WhereBegin() generates leaves the cursors named
532** in pTabList pointing at their appropriate entries. The [...] code
drh7465a802005-01-03 01:28:51 +0000533** can use OP_Column and OP_Recno opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +0000534** data from the various tables of the loop.
535**
drhc27a1ce2002-06-14 20:58:45 +0000536** If the WHERE clause is empty, the foreach loops must each scan their
537** entire tables. Thus a three-way join is an O(N^3) operation. But if
538** the tables have indices and there are terms in the WHERE clause that
539** refer to those indices, a complete table scan can be avoided and the
540** code will run much faster. Most of the work of this routine is checking
541** to see if there are indices that can be used to speed up the loop.
542**
543** Terms of the WHERE clause are also used to limit which rows actually
544** make it to the "..." in the middle of the loop. After each "foreach",
545** terms of the WHERE clause that use only terms in that loop and outer
546** loops are evaluated and if false a jump is made around all subsequent
547** inner loops (or around the "..." if the test occurs within the inner-
548** most loop)
549**
550** OUTER JOINS
551**
552** An outer join of tables t1 and t2 is conceptally coded as follows:
553**
554** foreach row1 in t1 do
555** flag = 0
556** foreach row2 in t2 do
557** start:
558** ...
559** flag = 1
560** end
drhe3184742002-06-19 14:27:05 +0000561** if flag==0 then
562** move the row2 cursor to a null row
563** goto start
564** fi
drhc27a1ce2002-06-14 20:58:45 +0000565** end
566**
drhe3184742002-06-19 14:27:05 +0000567** ORDER BY CLAUSE PROCESSING
568**
569** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
570** if there is one. If there is no ORDER BY clause or if this routine
571** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
572**
573** If an index can be used so that the natural output order of the table
574** scan is correct for the ORDER BY clause, then that index is used and
575** *ppOrderBy is set to NULL. This is an optimization that prevents an
576** unnecessary sort of the result set if an index appropriate for the
577** ORDER BY clause already exists.
578**
579** If the where clause loops cannot be arranged to provide the correct
580** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +0000581*/
danielk19774adee202004-05-08 08:23:19 +0000582WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +0000583 Parse *pParse, /* The parser context */
584 SrcList *pTabList, /* A list of all tables to be scanned */
585 Expr *pWhere, /* The WHERE clause */
drhe4e72072004-11-23 01:47:30 +0000586 ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
587 Fetch *pFetch /* Initial location of cursors. NULL otherwise */
drh75897232000-05-29 14:26:00 +0000588){
589 int i; /* Loop counter */
590 WhereInfo *pWInfo; /* Will become the return value of this function */
591 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhd4f5ee22003-07-16 00:54:31 +0000592 int brk, cont = 0; /* Addresses used during code generation */
drh75897232000-05-29 14:26:00 +0000593 int nExpr; /* Number of subexpressions in the WHERE clause */
drh51669862004-12-18 18:40:26 +0000594 Bitmask loopMask; /* One bit set for each outer loop */
drh193bd772004-07-20 18:23:14 +0000595 ExprInfo *pTerm; /* A single term in the WHERE clause; ptr to aExpr[] */
drh6a3ea0e2003-05-02 14:32:12 +0000596 ExprMaskSet maskSet; /* The expression mask set */
drh51669862004-12-18 18:40:26 +0000597 int iDirectEq[BMS]; /* Term of the form ROWID==X for the N-th table */
598 int iDirectLt[BMS]; /* Term of the form ROWID<X or ROWID<=X */
599 int iDirectGt[BMS]; /* Term of the form ROWID>X or ROWID>=X */
drh193bd772004-07-20 18:23:14 +0000600 ExprInfo aExpr[101]; /* The WHERE clause is divided into these terms */
drh9012bcb2004-12-19 00:11:35 +0000601 struct SrcList_item *pTabItem; /* A single entry from pTabList */
602 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh75897232000-05-29 14:26:00 +0000603
drh1398ad32005-01-19 23:24:50 +0000604 /* The number of terms in the FROM clause is limited by the number of
605 ** bits in a Bitmask
606 */
607 if( pTabList->nSrc>sizeof(Bitmask)*8 ){
608 sqlite3ErrorMsg(pParse, "at most %d tables in a join",
609 sizeof(Bitmask)*8);
610 return 0;
611 }
612
drh83dcb1a2002-06-28 01:02:38 +0000613 /* Split the WHERE clause into separate subexpressions where each
614 ** subexpression is separated by an AND operator. If the aExpr[]
615 ** array fills up, the last entry might point to an expression which
616 ** contains additional unfactored AND operators.
617 */
drh6a3ea0e2003-05-02 14:32:12 +0000618 initMaskSet(&maskSet);
drh83dcb1a2002-06-28 01:02:38 +0000619 memset(aExpr, 0, sizeof(aExpr));
620 nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
621 if( nExpr==ARRAYSIZE(aExpr) ){
danielk19774adee202004-05-08 08:23:19 +0000622 sqlite3ErrorMsg(pParse, "WHERE clause too complex - no more "
drhf7a9e1a2004-02-22 18:40:56 +0000623 "than %d terms allowed", (int)ARRAYSIZE(aExpr)-1);
drh83dcb1a2002-06-28 01:02:38 +0000624 return 0;
625 }
drh1398ad32005-01-19 23:24:50 +0000626
drh75897232000-05-29 14:26:00 +0000627 /* Allocate and initialize the WhereInfo structure that will become the
628 ** return value.
629 */
drhad3cab52002-05-24 02:04:32 +0000630 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
danielk1977132872b2004-05-10 10:37:18 +0000631 if( sqlite3_malloc_failed ){
drh193bd772004-07-20 18:23:14 +0000632 /* sqliteFree(pWInfo); // Leak memory when malloc fails */
drh75897232000-05-29 14:26:00 +0000633 return 0;
634 }
635 pWInfo->pParse = pParse;
636 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +0000637 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh08192d52002-04-30 19:20:28 +0000638
639 /* Special case: a WHERE clause that is constant. Evaluate the
640 ** expression and either jump over all of the code or fall thru.
641 */
danielk19774adee202004-05-08 08:23:19 +0000642 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
643 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +0000644 pWhere = 0;
drh08192d52002-04-30 19:20:28 +0000645 }
drh75897232000-05-29 14:26:00 +0000646
drh75897232000-05-29 14:26:00 +0000647 /* Analyze all of the subexpressions.
648 */
drh1398ad32005-01-19 23:24:50 +0000649 for(i=0; i<pTabList->nSrc; i++){
650 createMask(&maskSet, pTabList->a[i].iCursor);
651 }
drh193bd772004-07-20 18:23:14 +0000652 for(pTerm=aExpr, i=0; i<nExpr; i++, pTerm++){
drh193bd772004-07-20 18:23:14 +0000653 exprAnalyze(pTabList, &maskSet, pTerm);
drh75897232000-05-29 14:26:00 +0000654 }
655
drh75897232000-05-29 14:26:00 +0000656 /* Figure out what index to use (if any) for each nested loop.
drh6b563442001-11-07 16:48:26 +0000657 ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
drhad3cab52002-05-24 02:04:32 +0000658 ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
drh8aff1012001-12-22 14:49:24 +0000659 ** loop.
660 **
661 ** If terms exist that use the ROWID of any table, then set the
662 ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
663 ** to the index of the term containing the ROWID. We always prefer
664 ** to use a ROWID which can directly access a table rather than an
drh0a36c572002-02-18 22:49:59 +0000665 ** index which requires reading an index first to get the rowid then
666 ** doing a second read of the actual database table.
drh75897232000-05-29 14:26:00 +0000667 **
668 ** Actually, if there are more than 32 tables in the join, only the
drh0a36c572002-02-18 22:49:59 +0000669 ** first 32 tables are candidates for indices. This is (again) due
670 ** to the limit of 32 bits in an integer bitmask.
drh75897232000-05-29 14:26:00 +0000671 */
672 loopMask = 0;
drh9012bcb2004-12-19 00:11:35 +0000673 pTabItem = pTabList->a;
674 pLevel = pWInfo->a;
675 for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++,pTabItem++,pLevel++){
drhc4a3c772001-04-04 11:48:57 +0000676 int j;
drh9012bcb2004-12-19 00:11:35 +0000677 int iCur = pTabItem->iCursor; /* The cursor for this table */
drh51669862004-12-18 18:40:26 +0000678 Bitmask mask = getMask(&maskSet, iCur); /* Cursor mask for this table */
drh9012bcb2004-12-19 00:11:35 +0000679 Table *pTab = pTabItem->pTab;
drh75897232000-05-29 14:26:00 +0000680 Index *pIdx;
681 Index *pBestIdx = 0;
drh487ab3c2001-11-08 00:45:21 +0000682 int bestScore = 0;
drh51669862004-12-18 18:40:26 +0000683 int bestRev = 0;
drh75897232000-05-29 14:26:00 +0000684
drhc4a3c772001-04-04 11:48:57 +0000685 /* Check to see if there is an expression that uses only the
drh8aff1012001-12-22 14:49:24 +0000686 ** ROWID field of this table. For terms of the form ROWID==expr
687 ** set iDirectEq[i] to the index of the term. For terms of the
688 ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
689 ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
drh174b6192002-12-03 02:22:52 +0000690 **
691 ** (Added:) Treat ROWID IN expr like ROWID=expr.
drhc4a3c772001-04-04 11:48:57 +0000692 */
drh9012bcb2004-12-19 00:11:35 +0000693 pLevel->iIdxCur = -1;
drh8aff1012001-12-22 14:49:24 +0000694 iDirectEq[i] = -1;
695 iDirectLt[i] = -1;
696 iDirectGt[i] = -1;
drh193bd772004-07-20 18:23:14 +0000697 for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
698 Expr *pX = pTerm->p;
699 if( pTerm->idxLeft==iCur && pX->pLeft->iColumn<0
700 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight ){
701 switch( pX->op ){
drhd99f7062002-06-08 23:25:08 +0000702 case TK_IN:
drh8aff1012001-12-22 14:49:24 +0000703 case TK_EQ: iDirectEq[i] = j; break;
704 case TK_LE:
705 case TK_LT: iDirectLt[i] = j; break;
706 case TK_GE:
707 case TK_GT: iDirectGt[i] = j; break;
708 }
drhc4a3c772001-04-04 11:48:57 +0000709 }
drhc4a3c772001-04-04 11:48:57 +0000710 }
drhb6c29892004-11-22 19:12:19 +0000711
712 /* If we found a term that tests ROWID with == or IN, that term
713 ** will be used to locate the rows in the database table. There
714 ** is not need to continue into the code below that looks for
715 ** an index. We will always use the ROWID over an index.
716 */
drh8aff1012001-12-22 14:49:24 +0000717 if( iDirectEq[i]>=0 ){
drh6a3ea0e2003-05-02 14:32:12 +0000718 loopMask |= mask;
drh94a11212004-09-25 13:12:14 +0000719 pLevel->pIdx = 0;
drhc4a3c772001-04-04 11:48:57 +0000720 continue;
721 }
722
drh75897232000-05-29 14:26:00 +0000723 /* Do a search for usable indices. Leave pBestIdx pointing to
drh487ab3c2001-11-08 00:45:21 +0000724 ** the "best" index. pBestIdx is left set to NULL if no indices
725 ** are usable.
drh75897232000-05-29 14:26:00 +0000726 **
drhacf3b982005-01-03 01:27:18 +0000727 ** The best index is the one with the highest score. The score
728 ** for the index is determined as follows. For each of the
drh487ab3c2001-11-08 00:45:21 +0000729 ** left-most terms that is fixed by an equality operator, add
drh51669862004-12-18 18:40:26 +0000730 ** 32 to the score. The right-most term of the index may be
731 ** constrained by an inequality. Add 4 if for an "x<..." constraint
732 ** and add 8 for an "x>..." constraint. If both constraints
733 ** are present, add 12.
734 **
735 ** If the left-most term of the index uses an IN operator
736 ** (ex: "x IN (...)") then add 16 to the score.
737 **
738 ** If an index can be used for sorting, add 2 to the score.
739 ** If an index contains all the terms of a table that are ever
740 ** used by any expression in the SQL statement, then add 1 to
741 ** the score.
drh487ab3c2001-11-08 00:45:21 +0000742 **
743 ** This scoring system is designed so that the score can later be
drh51669862004-12-18 18:40:26 +0000744 ** used to determine how the index is used. If the score&0x1c is 0
745 ** then all constraints are equalities. If score&0x4 is not 0 then
drh487ab3c2001-11-08 00:45:21 +0000746 ** there is an inequality used as a termination key. (ex: "x<...")
drh51669862004-12-18 18:40:26 +0000747 ** If score&0x8 is not 0 then there is an inequality used as the
748 ** start key. (ex: "x>..."). A score or 0x10 is the special case
drhc045ec52002-12-04 20:01:06 +0000749 ** of an IN operator constraint. (ex: "x IN ...").
drhd99f7062002-06-08 23:25:08 +0000750 **
drhc27a1ce2002-06-14 20:58:45 +0000751 ** The IN operator (as in "<expr> IN (...)") is treated the same as
752 ** an equality comparison except that it can only be used on the
753 ** left-most column of an index and other terms of the WHERE clause
754 ** cannot be used in conjunction with the IN operator to help satisfy
755 ** other columns of the index.
drh75897232000-05-29 14:26:00 +0000756 */
757 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh51669862004-12-18 18:40:26 +0000758 Bitmask eqMask = 0; /* Index columns covered by an x=... term */
759 Bitmask ltMask = 0; /* Index columns covered by an x<... term */
760 Bitmask gtMask = 0; /* Index columns covered by an x>... term */
761 Bitmask inMask = 0; /* Index columns covered by an x IN .. term */
762 Bitmask m;
763 int nEq, score, bRev = 0;
drh75897232000-05-29 14:26:00 +0000764
drh51669862004-12-18 18:40:26 +0000765 if( pIdx->nColumn>sizeof(eqMask)*8 ){
766 continue; /* Ignore indices with too many columns to analyze */
767 }
drh193bd772004-07-20 18:23:14 +0000768 for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
drh193bd772004-07-20 18:23:14 +0000769 Expr *pX = pTerm->p;
drh94a11212004-09-25 13:12:14 +0000770 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
drh193bd772004-07-20 18:23:14 +0000771 if( !pColl && pX->pRight ){
772 pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
danielk19770202b292004-06-09 09:55:16 +0000773 }
774 if( !pColl ){
775 pColl = pParse->db->pDfltColl;
776 }
drh193bd772004-07-20 18:23:14 +0000777 if( pTerm->idxLeft==iCur
778 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight ){
779 int iColumn = pX->pLeft->iColumn;
drh75897232000-05-29 14:26:00 +0000780 int k;
danielk1977e014a832004-05-17 10:48:57 +0000781 char idxaff = pIdx->pTable->aCol[iColumn].affinity;
drh967e8b72000-06-21 13:59:10 +0000782 for(k=0; k<pIdx->nColumn; k++){
danielk19770202b292004-06-09 09:55:16 +0000783 /* If the collating sequences or affinities don't match,
784 ** ignore this index. */
785 if( pColl!=pIdx->keyInfo.aColl[k] ) continue;
drh193bd772004-07-20 18:23:14 +0000786 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
danielk19770202b292004-06-09 09:55:16 +0000787 if( pIdx->aiColumn[k]==iColumn ){
drh193bd772004-07-20 18:23:14 +0000788 switch( pX->op ){
drh48185c12002-06-09 01:55:20 +0000789 case TK_IN: {
790 if( k==0 ) inMask |= 1;
791 break;
792 }
drh487ab3c2001-11-08 00:45:21 +0000793 case TK_EQ: {
drh51669862004-12-18 18:40:26 +0000794 eqMask |= ((Bitmask)1)<<k;
drh487ab3c2001-11-08 00:45:21 +0000795 break;
796 }
797 case TK_LE:
798 case TK_LT: {
drh51669862004-12-18 18:40:26 +0000799 ltMask |= ((Bitmask)1)<<k;
drh487ab3c2001-11-08 00:45:21 +0000800 break;
801 }
802 case TK_GE:
803 case TK_GT: {
drh51669862004-12-18 18:40:26 +0000804 gtMask |= ((Bitmask)1)<<k;
drh487ab3c2001-11-08 00:45:21 +0000805 break;
806 }
807 default: {
808 /* CANT_HAPPEN */
809 assert( 0 );
810 break;
811 }
812 }
drh75897232000-05-29 14:26:00 +0000813 break;
814 }
815 }
816 }
drh75897232000-05-29 14:26:00 +0000817 }
drhc045ec52002-12-04 20:01:06 +0000818
819 /* The following loop ends with nEq set to the number of columns
820 ** on the left of the index with == constraints.
821 */
drh487ab3c2001-11-08 00:45:21 +0000822 for(nEq=0; nEq<pIdx->nColumn; nEq++){
drh51669862004-12-18 18:40:26 +0000823 m = (((Bitmask)1)<<(nEq+1))-1;
drh487ab3c2001-11-08 00:45:21 +0000824 if( (m & eqMask)!=m ) break;
825 }
drh51669862004-12-18 18:40:26 +0000826
827 /* Begin assemblying the score
828 */
829 score = nEq*32; /* Base score is 32 times number of == constraints */
830 m = ((Bitmask)1)<<nEq;
831 if( m & ltMask ) score+=4; /* Increase score for a < constraint */
832 if( m & gtMask ) score+=8; /* Increase score for a > constraint */
833 if( score==0 && inMask ) score = 16; /* Default score for IN constraint */
834
835 /* Give bonus points if this index can be used for sorting
836 */
drh9012bcb2004-12-19 00:11:35 +0000837 if( i==0 && score!=16 && ppOrderBy && *ppOrderBy ){
drh51669862004-12-18 18:40:26 +0000838 int base = pTabList->a[0].iCursor;
839 if( isSortingIndex(pParse, pIdx, pTab, base, *ppOrderBy, nEq, &bRev) ){
840 score += 2;
841 }
842 }
843
drh9012bcb2004-12-19 00:11:35 +0000844 /* Check to see if we can get away with using just the index without
845 ** ever reading the table. If that is the case, then add one bonus
846 ** point to the score.
847 */
848 if( score && pTabItem->colUsed < (((Bitmask)1)<<(BMS-1)) ){
849 for(m=0, j=0; j<pIdx->nColumn; j++){
850 int x = pIdx->aiColumn[j];
851 if( x<BMS-1 ){
852 m |= ((Bitmask)1)<<x;
853 }
854 }
855 if( (pTabItem->colUsed & m)==pTabItem->colUsed ){
856 score++;
857 }
858 }
859
drh51669862004-12-18 18:40:26 +0000860 /* If the score for this index is the best we have seen so far, then
861 ** save it
862 */
drh487ab3c2001-11-08 00:45:21 +0000863 if( score>bestScore ){
864 pBestIdx = pIdx;
865 bestScore = score;
drh51669862004-12-18 18:40:26 +0000866 bestRev = bRev;
drh75897232000-05-29 14:26:00 +0000867 }
868 }
drh94a11212004-09-25 13:12:14 +0000869 pLevel->pIdx = pBestIdx;
870 pLevel->score = bestScore;
drh51669862004-12-18 18:40:26 +0000871 pLevel->bRev = bestRev;
drh6a3ea0e2003-05-02 14:32:12 +0000872 loopMask |= mask;
drh6b563442001-11-07 16:48:26 +0000873 if( pBestIdx ){
drh9012bcb2004-12-19 00:11:35 +0000874 pLevel->iIdxCur = pParse->nTab++;
drh6b563442001-11-07 16:48:26 +0000875 }
drh75897232000-05-29 14:26:00 +0000876 }
877
drhe3184742002-06-19 14:27:05 +0000878 /* Check to see if the ORDER BY clause is or can be satisfied by the
879 ** use of an index on the first table.
880 */
881 if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
drh9012bcb2004-12-19 00:11:35 +0000882 Index *pIdx; /* Index derived from the WHERE clause */
883 Table *pTab; /* Left-most table in the FROM clause */
884 int bRev = 0; /* True to reverse the output order */
885 int iCur; /* Btree-cursor that will be used by pTab */
886 WhereLevel *pLevel0 = &pWInfo->a[0];
drhe3184742002-06-19 14:27:05 +0000887
drh9012bcb2004-12-19 00:11:35 +0000888 pTab = pTabList->a[0].pTab;
889 pIdx = pLevel0->pIdx;
890 iCur = pTabList->a[0].iCursor;
891 if( pIdx==0 && sortableByRowid(iCur, *ppOrderBy, &bRev) ){
892 /* The ORDER BY clause specifies ROWID order, which is what we
893 ** were going to be doing anyway...
894 */
895 *ppOrderBy = 0;
896 pLevel0->bRev = bRev;
897 }else if( pLevel0->score==16 ){
898 /* If there is already an IN index on the left-most table,
899 ** it will not give the correct sort order.
900 ** So, pretend that no suitable index is found.
901 */
902 }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
903 /* If the left-most column is accessed using its ROWID, then do
904 ** not try to sort by index. But do delete the ORDER BY clause
905 ** if it is redundant.
906 */
907 }else if( (pLevel0->score&2)!=0 ){
908 /* The index that was selected for searching will cause rows to
909 ** appear in sorted order.
910 */
911 *ppOrderBy = 0;
drh75897232000-05-29 14:26:00 +0000912 }
913 }
914
drh9012bcb2004-12-19 00:11:35 +0000915 /* Open all tables in the pTabList and any indices selected for
916 ** searching those tables.
917 */
918 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
919 pLevel = pWInfo->a;
920 for(i=0, pTabItem=pTabList->a; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
921 Table *pTab;
922 Index *pIx;
923 int iIdxCur = pLevel->iIdxCur;
924
925 pTab = pTabItem->pTab;
926 if( pTab->isTransient || pTab->pSelect ) continue;
927 if( (pLevel->score & 1)==0 ){
928 sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
929 }
930 pLevel->iTabCur = pTabItem->iCursor;
931 if( (pIx = pLevel->pIdx)!=0 ){
932 sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
933 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
934 (char*)&pIx->keyInfo, P3_KEYINFO);
935 }
936 if( (pLevel->score & 1)!=0 ){
937 sqlite3VdbeAddOp(v, OP_KeyAsData, iIdxCur, 1);
938 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
939 }
940 sqlite3CodeVerifySchema(pParse, pTab->iDb);
941 }
942 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
943
drh75897232000-05-29 14:26:00 +0000944 /* Generate the code to do the search
945 */
drh75897232000-05-29 14:26:00 +0000946 loopMask = 0;
drh9012bcb2004-12-19 00:11:35 +0000947 pLevel = pWInfo->a;
948 pTabItem = pTabList->a;
949 for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
drh75897232000-05-29 14:26:00 +0000950 int j, k;
drh9012bcb2004-12-19 00:11:35 +0000951 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
952 Index *pIdx; /* The index we will be using */
953 int iIdxCur; /* The VDBE cursor for the index */
954 int omitTable; /* True if we use the index only */
955
956 pIdx = pLevel->pIdx;
957 iIdxCur = pLevel->iIdxCur;
958 pLevel->inOp = OP_Noop;
959
960 /* Check to see if it is appropriate to omit the use of the table
961 ** here and use its index instead.
962 */
963 omitTable = (pLevel->score&1)!=0;
drh75897232000-05-29 14:26:00 +0000964
drhad2d8302002-05-24 20:31:36 +0000965 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +0000966 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +0000967 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +0000968 */
969 if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
970 if( !pParse->nMem ) pParse->nMem++;
971 pLevel->iLeftJoin = pParse->nMem++;
danielk19770f69c1e2004-05-29 11:24:50 +0000972 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000973 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +0000974 VdbeComment((v, "# init LEFT JOIN no-match flag"));
drhad2d8302002-05-24 20:31:36 +0000975 }
976
drh94a11212004-09-25 13:12:14 +0000977 if( i<ARRAYSIZE(iDirectEq) && (k = iDirectEq[i])>=0 ){
drh8aff1012001-12-22 14:49:24 +0000978 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +0000979 ** equality comparison against the ROWID field. Or
980 ** we reference multiple rows using a "rowid IN (...)"
981 ** construct.
drhc4a3c772001-04-04 11:48:57 +0000982 */
drh8aff1012001-12-22 14:49:24 +0000983 assert( k<nExpr );
drh193bd772004-07-20 18:23:14 +0000984 pTerm = &aExpr[k];
985 assert( pTerm->p!=0 );
drh193bd772004-07-20 18:23:14 +0000986 assert( pTerm->idxLeft==iCur );
drh9012bcb2004-12-19 00:11:35 +0000987 assert( omitTable==0 );
drh94a11212004-09-25 13:12:14 +0000988 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
989 codeEqualityTerm(pParse, pTerm, brk, pLevel);
danielk19774adee202004-05-08 08:23:19 +0000990 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
991 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
danielk19774adee202004-05-08 08:23:19 +0000992 sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +0000993 VdbeComment((v, "pk"));
drh6b563442001-11-07 16:48:26 +0000994 pLevel->op = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +0000995 }else if( pIdx!=0 && pLevel->score>3 && (pLevel->score&0x0c)==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000996 /* Case 2: There is an index and all terms of the WHERE clause that
drhb6c29892004-11-22 19:12:19 +0000997 ** refer to the index using the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +0000998 */
drh6b563442001-11-07 16:48:26 +0000999 int start;
drh51669862004-12-18 18:40:26 +00001000 int nColumn = (pLevel->score+16)/32;
danielk19774adee202004-05-08 08:23:19 +00001001 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
drh772ae622004-05-19 13:13:08 +00001002
1003 /* For each column of the index, find the term of the WHERE clause that
1004 ** constraints that column. If the WHERE clause term is X=expr, then
1005 ** evaluation expr and leave the result on the stack */
drh487ab3c2001-11-08 00:45:21 +00001006 for(j=0; j<nColumn; j++){
drh193bd772004-07-20 18:23:14 +00001007 for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
1008 Expr *pX = pTerm->p;
drhd99f7062002-06-08 23:25:08 +00001009 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001010 if( pTerm->idxLeft==iCur
1011 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drhd99f7062002-06-08 23:25:08 +00001012 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drhac931eb2005-01-11 18:13:56 +00001013 && (pX->op==TK_EQ || pX->op==TK_IN)
drh75897232000-05-29 14:26:00 +00001014 ){
danielk1977e014a832004-05-17 10:48:57 +00001015 char idxaff = pIdx->pTable->aCol[pX->pLeft->iColumn].affinity;
drh94a11212004-09-25 13:12:14 +00001016 if( sqlite3IndexAffinityOk(pX, idxaff) ){
1017 codeEqualityTerm(pParse, pTerm, brk, pLevel);
1018 break;
drhd99f7062002-06-08 23:25:08 +00001019 }
drh75897232000-05-29 14:26:00 +00001020 }
drh75897232000-05-29 14:26:00 +00001021 }
1022 }
drh6b563442001-11-07 16:48:26 +00001023 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001024 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drh94a11212004-09-25 13:12:14 +00001025 buildIndexProbe(v, nColumn, brk, pIdx);
danielk19773d1bfea2004-05-14 11:00:53 +00001026 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
drh772ae622004-05-19 13:13:08 +00001027
drh772ae622004-05-19 13:13:08 +00001028 /* Generate code (1) to move to the first matching element of the table.
1029 ** Then generate code (2) that jumps to "brk" after the cursor is past
1030 ** the last matching element of the table. The code (1) is executed
1031 ** once to initialize the search, the code (2) is executed before each
1032 ** iteration of the scan to see if the scan has finished. */
drhc045ec52002-12-04 20:01:06 +00001033 if( pLevel->bRev ){
1034 /* Scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001035 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001036 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001037 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001038 pLevel->op = OP_Prev;
1039 }else{
1040 /* Scan in the forward order */
drh9012bcb2004-12-19 00:11:35 +00001041 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001042 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001043 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
drhc045ec52002-12-04 20:01:06 +00001044 pLevel->op = OP_Next;
1045 }
drh9012bcb2004-12-19 00:11:35 +00001046 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001047 sqlite3VdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
drhe6f85e72004-12-25 01:03:13 +00001048 if( !omitTable ){
drh9012bcb2004-12-19 00:11:35 +00001049 sqlite3VdbeAddOp(v, OP_IdxRecno, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001050 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh75897232000-05-29 14:26:00 +00001051 }
drh9012bcb2004-12-19 00:11:35 +00001052 pLevel->p1 = iIdxCur;
drh6b563442001-11-07 16:48:26 +00001053 pLevel->p2 = start;
drh8aff1012001-12-22 14:49:24 +00001054 }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
1055 /* Case 3: We have an inequality comparison against the ROWID field.
1056 */
1057 int testOp = OP_Noop;
1058 int start;
drhb6c29892004-11-22 19:12:19 +00001059 int bRev = pLevel->bRev;
drh8aff1012001-12-22 14:49:24 +00001060
drh9012bcb2004-12-19 00:11:35 +00001061 assert( omitTable==0 );
danielk19774adee202004-05-08 08:23:19 +00001062 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1063 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drhb6c29892004-11-22 19:12:19 +00001064 if( bRev ){
1065 int t = iDirectGt[i];
1066 iDirectGt[i] = iDirectLt[i];
1067 iDirectLt[i] = t;
1068 }
drh8aff1012001-12-22 14:49:24 +00001069 if( iDirectGt[i]>=0 ){
drh94a11212004-09-25 13:12:14 +00001070 Expr *pX;
drh8aff1012001-12-22 14:49:24 +00001071 k = iDirectGt[i];
1072 assert( k<nExpr );
drh193bd772004-07-20 18:23:14 +00001073 pTerm = &aExpr[k];
drh94a11212004-09-25 13:12:14 +00001074 pX = pTerm->p;
1075 assert( pX!=0 );
drh193bd772004-07-20 18:23:14 +00001076 assert( pTerm->idxLeft==iCur );
drh94a11212004-09-25 13:12:14 +00001077 sqlite3ExprCode(pParse, pX->pRight);
1078 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LT || pX->op==TK_GT, brk);
drhb6c29892004-11-22 19:12:19 +00001079 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001080 VdbeComment((v, "pk"));
drh193bd772004-07-20 18:23:14 +00001081 disableTerm(pLevel, &pTerm->p);
drh8aff1012001-12-22 14:49:24 +00001082 }else{
drhb6c29892004-11-22 19:12:19 +00001083 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
drh8aff1012001-12-22 14:49:24 +00001084 }
1085 if( iDirectLt[i]>=0 ){
drh94a11212004-09-25 13:12:14 +00001086 Expr *pX;
drh8aff1012001-12-22 14:49:24 +00001087 k = iDirectLt[i];
1088 assert( k<nExpr );
drh193bd772004-07-20 18:23:14 +00001089 pTerm = &aExpr[k];
drh94a11212004-09-25 13:12:14 +00001090 pX = pTerm->p;
1091 assert( pX!=0 );
drh193bd772004-07-20 18:23:14 +00001092 assert( pTerm->idxLeft==iCur );
drh94a11212004-09-25 13:12:14 +00001093 sqlite3ExprCode(pParse, pX->pRight);
drh8aff1012001-12-22 14:49:24 +00001094 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001095 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drh94a11212004-09-25 13:12:14 +00001096 if( pX->op==TK_LT || pX->op==TK_GT ){
drhb6c29892004-11-22 19:12:19 +00001097 testOp = bRev ? OP_Le : OP_Ge;
drh8aff1012001-12-22 14:49:24 +00001098 }else{
drhb6c29892004-11-22 19:12:19 +00001099 testOp = bRev ? OP_Lt : OP_Gt;
drh8aff1012001-12-22 14:49:24 +00001100 }
drh193bd772004-07-20 18:23:14 +00001101 disableTerm(pLevel, &pTerm->p);
drh8aff1012001-12-22 14:49:24 +00001102 }
danielk19774adee202004-05-08 08:23:19 +00001103 start = sqlite3VdbeCurrentAddr(v);
drhb6c29892004-11-22 19:12:19 +00001104 pLevel->op = bRev ? OP_Prev : OP_Next;
drh6a3ea0e2003-05-02 14:32:12 +00001105 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001106 pLevel->p2 = start;
1107 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001108 sqlite3VdbeAddOp(v, OP_Recno, iCur, 0);
1109 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1110 sqlite3VdbeAddOp(v, testOp, 0, brk);
drh8aff1012001-12-22 14:49:24 +00001111 }
drh8aff1012001-12-22 14:49:24 +00001112 }else if( pIdx==0 ){
drhc27a1ce2002-06-14 20:58:45 +00001113 /* Case 4: There is no usable index. We must do a complete
drh8aff1012001-12-22 14:49:24 +00001114 ** scan of the entire database table.
1115 */
1116 int start;
drhb6c29892004-11-22 19:12:19 +00001117 int opRewind;
drh8aff1012001-12-22 14:49:24 +00001118
drh9012bcb2004-12-19 00:11:35 +00001119 assert( omitTable==0 );
danielk19774adee202004-05-08 08:23:19 +00001120 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1121 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drhb6c29892004-11-22 19:12:19 +00001122 if( pLevel->bRev ){
1123 opRewind = OP_Last;
1124 pLevel->op = OP_Prev;
1125 }else{
1126 opRewind = OP_Rewind;
1127 pLevel->op = OP_Next;
1128 }
1129 sqlite3VdbeAddOp(v, opRewind, iCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001130 start = sqlite3VdbeCurrentAddr(v);
drh6a3ea0e2003-05-02 14:32:12 +00001131 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001132 pLevel->p2 = start;
drh487ab3c2001-11-08 00:45:21 +00001133 }else{
drhc27a1ce2002-06-14 20:58:45 +00001134 /* Case 5: The WHERE clause term that refers to the right-most
1135 ** column of the index is an inequality. For example, if
1136 ** the index is on (x,y,z) and the WHERE clause is of the
1137 ** form "x=5 AND y<10" then this case is used. Only the
1138 ** right-most column can be an inequality - the rest must
1139 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +00001140 **
1141 ** This case is also used when there are no WHERE clause
1142 ** constraints but an index is selected anyway, in order
1143 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +00001144 */
1145 int score = pLevel->score;
drh51669862004-12-18 18:40:26 +00001146 int nEqColumn = score/32;
drh487ab3c2001-11-08 00:45:21 +00001147 int start;
danielk1977f7df9cc2004-06-16 12:02:47 +00001148 int leFlag=0, geFlag=0;
drh487ab3c2001-11-08 00:45:21 +00001149 int testOp;
1150
1151 /* Evaluate the equality constraints
1152 */
1153 for(j=0; j<nEqColumn; j++){
drh94a11212004-09-25 13:12:14 +00001154 int iIdxCol = pIdx->aiColumn[j];
drh193bd772004-07-20 18:23:14 +00001155 for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
drh94a11212004-09-25 13:12:14 +00001156 Expr *pX = pTerm->p;
1157 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001158 if( pTerm->idxLeft==iCur
drh94a11212004-09-25 13:12:14 +00001159 && pX->op==TK_EQ
drh193bd772004-07-20 18:23:14 +00001160 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drh94a11212004-09-25 13:12:14 +00001161 && pX->pLeft->iColumn==iIdxCol
drh487ab3c2001-11-08 00:45:21 +00001162 ){
drh94a11212004-09-25 13:12:14 +00001163 sqlite3ExprCode(pParse, pX->pRight);
drh193bd772004-07-20 18:23:14 +00001164 disableTerm(pLevel, &pTerm->p);
drh487ab3c2001-11-08 00:45:21 +00001165 break;
1166 }
1167 }
1168 }
1169
drhc27a1ce2002-06-14 20:58:45 +00001170 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +00001171 ** used twice: once to make the termination key and once to make the
1172 ** start key.
1173 */
1174 for(j=0; j<nEqColumn; j++){
danielk19774adee202004-05-08 08:23:19 +00001175 sqlite3VdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
drh487ab3c2001-11-08 00:45:21 +00001176 }
1177
drhc045ec52002-12-04 20:01:06 +00001178 /* Labels for the beginning and end of the loop
1179 */
danielk19774adee202004-05-08 08:23:19 +00001180 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1181 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
drhc045ec52002-12-04 20:01:06 +00001182
drh487ab3c2001-11-08 00:45:21 +00001183 /* Generate the termination key. This is the key value that
1184 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +00001185 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +00001186 **
1187 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1188 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +00001189 */
drh51669862004-12-18 18:40:26 +00001190 if( (score & 4)!=0 ){
drh193bd772004-07-20 18:23:14 +00001191 for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
drh94a11212004-09-25 13:12:14 +00001192 Expr *pX = pTerm->p;
1193 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001194 if( pTerm->idxLeft==iCur
drh94a11212004-09-25 13:12:14 +00001195 && (pX->op==TK_LT || pX->op==TK_LE)
drh193bd772004-07-20 18:23:14 +00001196 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drh94a11212004-09-25 13:12:14 +00001197 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh487ab3c2001-11-08 00:45:21 +00001198 ){
drh94a11212004-09-25 13:12:14 +00001199 sqlite3ExprCode(pParse, pX->pRight);
1200 leFlag = pX->op==TK_LE;
drh193bd772004-07-20 18:23:14 +00001201 disableTerm(pLevel, &pTerm->p);
drh487ab3c2001-11-08 00:45:21 +00001202 break;
1203 }
1204 }
1205 testOp = OP_IdxGE;
1206 }else{
1207 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
1208 leFlag = 1;
1209 }
1210 if( testOp!=OP_Noop ){
drh51669862004-12-18 18:40:26 +00001211 int nCol = nEqColumn + ((score & 4)!=0);
drh487ab3c2001-11-08 00:45:21 +00001212 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001213 buildIndexProbe(v, nCol, brk, pIdx);
drhc045ec52002-12-04 20:01:06 +00001214 if( pLevel->bRev ){
drh7cf6e4d2004-05-19 14:56:55 +00001215 int op = leFlag ? OP_MoveLe : OP_MoveLt;
drh9012bcb2004-12-19 00:11:35 +00001216 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001217 }else{
danielk19774adee202004-05-08 08:23:19 +00001218 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001219 }
1220 }else if( pLevel->bRev ){
drh9012bcb2004-12-19 00:11:35 +00001221 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001222 }
1223
1224 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001225 ** bound on the search. There is no start key if there are no
1226 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001227 ** that case, generate a "Rewind" instruction in place of the
1228 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001229 **
1230 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1231 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001232 */
drh51669862004-12-18 18:40:26 +00001233 if( (score & 8)!=0 ){
drh193bd772004-07-20 18:23:14 +00001234 for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
drh94a11212004-09-25 13:12:14 +00001235 Expr *pX = pTerm->p;
1236 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001237 if( pTerm->idxLeft==iCur
drh94a11212004-09-25 13:12:14 +00001238 && (pX->op==TK_GT || pX->op==TK_GE)
drh193bd772004-07-20 18:23:14 +00001239 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drh94a11212004-09-25 13:12:14 +00001240 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh487ab3c2001-11-08 00:45:21 +00001241 ){
drh94a11212004-09-25 13:12:14 +00001242 sqlite3ExprCode(pParse, pX->pRight);
1243 geFlag = pX->op==TK_GE;
drh193bd772004-07-20 18:23:14 +00001244 disableTerm(pLevel, &pTerm->p);
drh487ab3c2001-11-08 00:45:21 +00001245 break;
1246 }
1247 }
drh7900ead2001-11-12 13:51:43 +00001248 }else{
1249 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001250 }
drh51669862004-12-18 18:40:26 +00001251 if( nEqColumn>0 || (score&8)!=0 ){
1252 int nCol = nEqColumn + ((score&8)!=0);
drh94a11212004-09-25 13:12:14 +00001253 buildIndexProbe(v, nCol, brk, pIdx);
drhc045ec52002-12-04 20:01:06 +00001254 if( pLevel->bRev ){
1255 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001256 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001257 testOp = OP_IdxLT;
1258 }else{
drh7cf6e4d2004-05-19 14:56:55 +00001259 int op = geFlag ? OP_MoveGe : OP_MoveGt;
drh9012bcb2004-12-19 00:11:35 +00001260 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001261 }
1262 }else if( pLevel->bRev ){
1263 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001264 }else{
drh9012bcb2004-12-19 00:11:35 +00001265 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001266 }
1267
1268 /* Generate the the top of the loop. If there is a termination
1269 ** key we have to test for that key and abort at the top of the
1270 ** loop.
1271 */
danielk19774adee202004-05-08 08:23:19 +00001272 start = sqlite3VdbeCurrentAddr(v);
drh487ab3c2001-11-08 00:45:21 +00001273 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001274 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001275 sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
danielk19773d1bfea2004-05-14 11:00:53 +00001276 if( (leFlag && !pLevel->bRev) || (!geFlag && pLevel->bRev) ){
1277 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
1278 }
drh487ab3c2001-11-08 00:45:21 +00001279 }
drh9012bcb2004-12-19 00:11:35 +00001280 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
drh51669862004-12-18 18:40:26 +00001281 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEqColumn + ((score&4)!=0), cont);
drhe6f85e72004-12-25 01:03:13 +00001282 if( !omitTable ){
drh9012bcb2004-12-19 00:11:35 +00001283 sqlite3VdbeAddOp(v, OP_IdxRecno, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001284 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh487ab3c2001-11-08 00:45:21 +00001285 }
1286
1287 /* Record the instruction used to terminate the loop.
1288 */
drhc045ec52002-12-04 20:01:06 +00001289 pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
drh9012bcb2004-12-19 00:11:35 +00001290 pLevel->p1 = iIdxCur;
drh487ab3c2001-11-08 00:45:21 +00001291 pLevel->p2 = start;
drh75897232000-05-29 14:26:00 +00001292 }
drh6a3ea0e2003-05-02 14:32:12 +00001293 loopMask |= getMask(&maskSet, iCur);
drh75897232000-05-29 14:26:00 +00001294
1295 /* Insert code to test every subexpression that can be completely
1296 ** computed using the current set of tables.
1297 */
drh193bd772004-07-20 18:23:14 +00001298 for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
1299 if( pTerm->p==0 ) continue;
1300 if( (pTerm->prereqAll & loopMask)!=pTerm->prereqAll ) continue;
1301 if( pLevel->iLeftJoin && !ExprHasProperty(pTerm->p,EP_FromJoin) ){
drh1f162302002-10-27 19:35:33 +00001302 continue;
1303 }
drh193bd772004-07-20 18:23:14 +00001304 sqlite3ExprIfFalse(pParse, pTerm->p, cont, 1);
1305 pTerm->p = 0;
drh75897232000-05-29 14:26:00 +00001306 }
1307 brk = cont;
drhad2d8302002-05-24 20:31:36 +00001308
1309 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1310 ** at least one row of the right table has matched the left table.
1311 */
1312 if( pLevel->iLeftJoin ){
danielk19774adee202004-05-08 08:23:19 +00001313 pLevel->top = sqlite3VdbeCurrentAddr(v);
1314 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1315 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001316 VdbeComment((v, "# record LEFT JOIN hit"));
drh193bd772004-07-20 18:23:14 +00001317 for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
1318 if( pTerm->p==0 ) continue;
1319 if( (pTerm->prereqAll & loopMask)!=pTerm->prereqAll ) continue;
drh193bd772004-07-20 18:23:14 +00001320 sqlite3ExprIfFalse(pParse, pTerm->p, cont, 1);
1321 pTerm->p = 0;
drh1cc093c2002-06-24 22:01:57 +00001322 }
drhad2d8302002-05-24 20:31:36 +00001323 }
drh75897232000-05-29 14:26:00 +00001324 }
1325 pWInfo->iContinue = cont;
drh6a3ea0e2003-05-02 14:32:12 +00001326 freeMaskSet(&maskSet);
drh75897232000-05-29 14:26:00 +00001327 return pWInfo;
1328}
1329
1330/*
drhc27a1ce2002-06-14 20:58:45 +00001331** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00001332** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001333*/
danielk19774adee202004-05-08 08:23:19 +00001334void sqlite3WhereEnd(WhereInfo *pWInfo){
drh75897232000-05-29 14:26:00 +00001335 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001336 int i;
drh6b563442001-11-07 16:48:26 +00001337 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001338 SrcList *pTabList = pWInfo->pTabList;
drh9012bcb2004-12-19 00:11:35 +00001339 struct SrcList_item *pTabItem;
drh19a775c2000-06-05 18:54:46 +00001340
drh9012bcb2004-12-19 00:11:35 +00001341 /* Generate loop termination code.
1342 */
drhad3cab52002-05-24 02:04:32 +00001343 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001344 pLevel = &pWInfo->a[i];
danielk19774adee202004-05-08 08:23:19 +00001345 sqlite3VdbeResolveLabel(v, pLevel->cont);
drh6b563442001-11-07 16:48:26 +00001346 if( pLevel->op!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001347 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001348 }
danielk19774adee202004-05-08 08:23:19 +00001349 sqlite3VdbeResolveLabel(v, pLevel->brk);
drhd99f7062002-06-08 23:25:08 +00001350 if( pLevel->inOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001351 sqlite3VdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
drhd99f7062002-06-08 23:25:08 +00001352 }
drhad2d8302002-05-24 20:31:36 +00001353 if( pLevel->iLeftJoin ){
1354 int addr;
danielk19774adee202004-05-08 08:23:19 +00001355 addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh9012bcb2004-12-19 00:11:35 +00001356 sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
danielk19774adee202004-05-08 08:23:19 +00001357 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
drh9012bcb2004-12-19 00:11:35 +00001358 if( pLevel->iIdxCur>=0 ){
1359 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
drh7f09b3e2002-08-13 13:15:49 +00001360 }
danielk19774adee202004-05-08 08:23:19 +00001361 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
drhad2d8302002-05-24 20:31:36 +00001362 }
drh19a775c2000-06-05 18:54:46 +00001363 }
drh9012bcb2004-12-19 00:11:35 +00001364
1365 /* The "break" point is here, just past the end of the outer loop.
1366 ** Set it.
1367 */
danielk19774adee202004-05-08 08:23:19 +00001368 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00001369
drhacf3b982005-01-03 01:27:18 +00001370 /* Close all of the cursors that were opend by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00001371 */
1372 pLevel = pWInfo->a;
1373 pTabItem = pTabList->a;
1374 for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
1375 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00001376 assert( pTab!=0 );
1377 if( pTab->isTransient || pTab->pSelect ) continue;
drh9012bcb2004-12-19 00:11:35 +00001378 if( (pLevel->score & 1)==0 ){
1379 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
1380 }
drh6b563442001-11-07 16:48:26 +00001381 if( pLevel->pIdx!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001382 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
1383 }
1384
drhacf3b982005-01-03 01:27:18 +00001385 /* Make cursor substitutions for cases where we want to use
drh9012bcb2004-12-19 00:11:35 +00001386 ** just the index and never reference the table.
1387 **
1388 ** Calls to the code generator in between sqlite3WhereBegin and
1389 ** sqlite3WhereEnd will have created code that references the table
1390 ** directly. This loop scans all that code looking for opcodes
1391 ** that reference the table and converts them into opcodes that
1392 ** reference the index.
1393 */
1394 if( pLevel->score & 1 ){
1395 int i, j, last;
1396 VdbeOp *pOp;
1397 Index *pIdx = pLevel->pIdx;
1398
1399 assert( pIdx!=0 );
1400 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1401 last = sqlite3VdbeCurrentAddr(v);
1402 for(i=pWInfo->iTop; i<last; i++, pOp++){
1403 if( pOp->p1!=pLevel->iTabCur ) continue;
1404 if( pOp->opcode==OP_Column ){
1405 pOp->p1 = pLevel->iIdxCur;
1406 for(j=0; j<pIdx->nColumn; j++){
1407 if( pOp->p2==pIdx->aiColumn[j] ){
1408 pOp->p2 = j;
1409 break;
1410 }
1411 }
1412 }else if( pOp->opcode==OP_Recno ){
1413 pOp->p1 = pLevel->iIdxCur;
1414 pOp->opcode = OP_IdxRecno;
1415 }
1416 }
drh6b563442001-11-07 16:48:26 +00001417 }
drh19a775c2000-06-05 18:54:46 +00001418 }
drh9012bcb2004-12-19 00:11:35 +00001419
1420 /* Final cleanup
1421 */
drh75897232000-05-29 14:26:00 +00001422 sqliteFree(pWInfo);
1423 return;
1424}