blob: e1998624fa04ec1062fdb6e73dae690afa551799 [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**
drh9012bcb2004-12-19 00:11:35 +000019** $Id: where.c,v 1.123 2004/12/19 00:11:35 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 {
drh51669862004-12-18 18:40:26 +0000106 int n; /* Number of assigned cursor values */
107 int ix[sizeof(Bitmask)*8-1]; /* 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/*
drh51669862004-12-18 18:40:26 +0000155** Return the bitmask for the given cursor number. Assign a new bitmask
drh6a3ea0e2003-05-02 14:32:12 +0000156** if this is the first time the cursor has been seen.
157*/
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 }
165 if( i==pMaskSet->n && i<ARRAYSIZE(pMaskSet->ix) ){
166 pMaskSet->n++;
167 pMaskSet->ix[i] = iCursor;
drh51669862004-12-18 18:40:26 +0000168 return ((Bitmask)1)<<i;
drh6a3ea0e2003-05-02 14:32:12 +0000169 }
170 return 0;
171}
172
173/*
174** Destroy an expression mask set
175*/
176#define freeMaskSet(P) /* NO-OP */
177
178/*
drh75897232000-05-29 14:26:00 +0000179** This routine walks (recursively) an expression tree and generates
180** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000181** tree.
drh75897232000-05-29 14:26:00 +0000182**
183** In order for this routine to work, the calling function must have
danielk19774adee202004-05-08 08:23:19 +0000184** previously invoked sqlite3ExprResolveIds() on the expression. See
drh75897232000-05-29 14:26:00 +0000185** the header comment on that routine for additional information.
danielk19774adee202004-05-08 08:23:19 +0000186** The sqlite3ExprResolveIds() routines looks for column names and
drh6a3ea0e2003-05-02 14:32:12 +0000187** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
188** the VDBE cursor number of the table.
drh75897232000-05-29 14:26:00 +0000189*/
drh51669862004-12-18 18:40:26 +0000190static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
191 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000192 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000193 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000194 mask = getMask(pMaskSet, p->iTable);
195 if( mask==0 ) mask = -1;
196 return mask;
drh75897232000-05-29 14:26:00 +0000197 }
198 if( p->pRight ){
drh6a3ea0e2003-05-02 14:32:12 +0000199 mask = exprTableUsage(pMaskSet, p->pRight);
drh75897232000-05-29 14:26:00 +0000200 }
201 if( p->pLeft ){
drh6a3ea0e2003-05-02 14:32:12 +0000202 mask |= exprTableUsage(pMaskSet, p->pLeft);
drh75897232000-05-29 14:26:00 +0000203 }
drhdd579122002-04-02 01:58:57 +0000204 if( p->pList ){
205 int i;
206 for(i=0; i<p->pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +0000207 mask |= exprTableUsage(pMaskSet, p->pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000208 }
209 }
drh75897232000-05-29 14:26:00 +0000210 return mask;
211}
212
213/*
drh487ab3c2001-11-08 00:45:21 +0000214** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000215** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000216** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000217*/
218static int allowedOp(int op){
drh9a432672004-10-04 13:38:09 +0000219 assert( TK_GT==TK_LE-1 && TK_LE==TK_LT-1 && TK_LT==TK_GE-1 && TK_EQ==TK_GT-1);
220 return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
drh487ab3c2001-11-08 00:45:21 +0000221}
222
223/*
drh51669862004-12-18 18:40:26 +0000224** Swap two objects of type T.
drh193bd772004-07-20 18:23:14 +0000225*/
226#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
227
228/*
229** Return the index in the SrcList that uses cursor iCur. If iCur is
230** used by the first entry in SrcList return 0. If iCur is used by
231** the second entry return 1. And so forth.
232**
233** SrcList is the set of tables in the FROM clause in the order that
234** they will be processed. The value returned here gives us an index
235** of which tables will be processed first.
236*/
237static int tableOrder(SrcList *pList, int iCur){
238 int i;
drh51669862004-12-18 18:40:26 +0000239 struct SrcList_item *pItem;
240 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
241 if( pItem->iCursor==iCur ) return i;
drh193bd772004-07-20 18:23:14 +0000242 }
243 return -1;
244}
245
246/*
drh75897232000-05-29 14:26:00 +0000247** The input to this routine is an ExprInfo structure with only the
248** "p" field filled in. The job of this routine is to analyze the
249** subexpression and populate all the other fields of the ExprInfo
250** structure.
251*/
drh193bd772004-07-20 18:23:14 +0000252static void exprAnalyze(SrcList *pSrc, ExprMaskSet *pMaskSet, ExprInfo *pInfo){
drh75897232000-05-29 14:26:00 +0000253 Expr *pExpr = pInfo->p;
drh6a3ea0e2003-05-02 14:32:12 +0000254 pInfo->prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
255 pInfo->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
256 pInfo->prereqAll = exprTableUsage(pMaskSet, pExpr);
drh75897232000-05-29 14:26:00 +0000257 pInfo->indexable = 0;
258 pInfo->idxLeft = -1;
259 pInfo->idxRight = -1;
drh487ab3c2001-11-08 00:45:21 +0000260 if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
drhd99f7062002-06-08 23:25:08 +0000261 if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
drh6a3ea0e2003-05-02 14:32:12 +0000262 pInfo->idxRight = pExpr->pRight->iTable;
drh75897232000-05-29 14:26:00 +0000263 pInfo->indexable = 1;
264 }
drh967e8b72000-06-21 13:59:10 +0000265 if( pExpr->pLeft->op==TK_COLUMN ){
drh6a3ea0e2003-05-02 14:32:12 +0000266 pInfo->idxLeft = pExpr->pLeft->iTable;
drh75897232000-05-29 14:26:00 +0000267 pInfo->indexable = 1;
268 }
269 }
drh193bd772004-07-20 18:23:14 +0000270 if( pInfo->indexable ){
271 assert( pInfo->idxLeft!=pInfo->idxRight );
272
273 /* We want the expression to be of the form "X = expr", not "expr = X".
274 ** So flip it over if necessary. If the expression is "X = Y", then
275 ** we want Y to come from an earlier table than X.
276 **
277 ** The collating sequence rule is to always choose the left expression.
278 ** So if we do a flip, we also have to move the collating sequence.
279 */
280 if( tableOrder(pSrc,pInfo->idxLeft)<tableOrder(pSrc,pInfo->idxRight) ){
281 assert( pExpr->op!=TK_IN );
282 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
283 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
drh9a432672004-10-04 13:38:09 +0000284 if( pExpr->op>=TK_GT ){
285 assert( TK_LT==TK_GT+2 );
286 assert( TK_GE==TK_LE+2 );
287 assert( TK_GT>TK_EQ );
288 assert( TK_GT<TK_LE );
289 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
290 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000291 }
292 SWAP(unsigned, pInfo->prereqLeft, pInfo->prereqRight);
293 SWAP(short int, pInfo->idxLeft, pInfo->idxRight);
294 }
295 }
296
drh75897232000-05-29 14:26:00 +0000297}
298
299/*
drh51669862004-12-18 18:40:26 +0000300** This routine decides if pIdx can be used to satisfy the ORDER BY
301** clause. If it can, it returns 1. If pIdx cannot satisfy the
302** ORDER BY clause, this routine returns 0.
303**
304** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
305** left-most table in the FROM clause of that same SELECT statement and
306** the table has a cursor number of "base". pIdx is an index on pTab.
307**
308** nEqCol is the number of columns of pIdx that are used as equality
309** constraints. Any of these columns may be missing from the ORDER BY
310** clause and the match can still be a success.
311**
312** If the index is UNIQUE, then the ORDER BY clause is allowed to have
313** additional terms past the end of the index and the match will still
314** be a success.
315**
316** All terms of the ORDER BY that match against the index must be either
317** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
318** index do not need to satisfy this constraint.) The *pbRev value is
319** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
320** the ORDER BY clause is all ASC.
321*/
322static int isSortingIndex(
323 Parse *pParse, /* Parsing context */
324 Index *pIdx, /* The index we are testing */
325 Table *pTab, /* The table to be sorted */
326 int base, /* Cursor number for pTab */
327 ExprList *pOrderBy, /* The ORDER BY clause */
328 int nEqCol, /* Number of index columns with == constraints */
329 int *pbRev /* Set to 1 if ORDER BY is DESC */
330){
331 int i, j; /* Loop counters */
332 int sortOrder; /* Which direction we are sorting */
333 int nTerm; /* Number of ORDER BY terms */
334 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
335 sqlite3 *db = pParse->db;
336
337 assert( pOrderBy!=0 );
338 nTerm = pOrderBy->nExpr;
339 assert( nTerm>0 );
340
341 /* Match terms of the ORDER BY clause against columns of
342 ** the index.
343 */
344 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
345 Expr *pExpr; /* The expression of the ORDER BY pTerm */
346 CollSeq *pColl; /* The collating sequence of pExpr */
347
348 pExpr = pTerm->pExpr;
349 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
350 /* Can not use an index sort on anything that is not a column in the
351 ** left-most table of the FROM clause */
352 return 0;
353 }
354 pColl = sqlite3ExprCollSeq(pParse, pExpr);
355 if( !pColl ) pColl = db->pDfltColl;
drh9012bcb2004-12-19 00:11:35 +0000356 if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
357 /* Term j of the ORDER BY clause does not match column i of the index */
358 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +0000359 /* If an index column that is constrained by == fails to match an
360 ** ORDER BY term, that is OK. Just ignore that column of the index
361 */
362 continue;
363 }else{
364 /* If an index column fails to match and is not constrained by ==
365 ** then the index cannot satisfy the ORDER BY constraint.
366 */
367 return 0;
368 }
369 }
370 if( i>nEqCol ){
371 if( pTerm->sortOrder!=sortOrder ){
372 /* Indices can only be used if all ORDER BY terms past the
373 ** equality constraints are all either DESC or ASC. */
374 return 0;
375 }
376 }else{
377 sortOrder = pTerm->sortOrder;
378 }
379 j++;
380 pTerm++;
381 }
382
383 /* The index can be used for sorting if all terms of the ORDER BY clause
384 ** or covered or if we ran out of index columns and the it is a UNIQUE
385 ** index.
386 */
387 if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
388 *pbRev = sortOrder==SQLITE_SO_DESC;
389 return 1;
390 }
391 return 0;
392}
393
394/*
drhb6c29892004-11-22 19:12:19 +0000395** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
396** by sorting in order of ROWID. Return true if so and set *pbRev to be
397** true for reverse ROWID and false for forward ROWID order.
398*/
399static int sortableByRowid(
400 int base, /* Cursor number for table to be sorted */
401 ExprList *pOrderBy, /* The ORDER BY clause */
402 int *pbRev /* Set to 1 if ORDER BY is DESC */
403){
404 Expr *p;
405
406 assert( pOrderBy!=0 );
407 assert( pOrderBy->nExpr>0 );
408 p = pOrderBy->a[0].pExpr;
409 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
410 *pbRev = pOrderBy->a[0].sortOrder;
411 return 1;
412 }
413 return 0;
414}
415
416
417/*
drh2ffb1182004-07-19 19:14:01 +0000418** Disable a term in the WHERE clause. Except, do not disable the term
419** if it controls a LEFT OUTER JOIN and it did not originate in the ON
420** or USING clause of that join.
421**
422** Consider the term t2.z='ok' in the following queries:
423**
424** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
425** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
426** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
427**
drh23bf66d2004-12-14 03:34:34 +0000428** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +0000429** in the ON clause. The term is disabled in (3) because it is not part
430** of a LEFT OUTER JOIN. In (1), the term is not disabled.
431**
432** Disabling a term causes that term to not be tested in the inner loop
433** of the join. Disabling is an optimization. We would get the correct
434** results if nothing were ever disabled, but joins might run a little
435** slower. The trick is to disable as much as we can without disabling
436** too much. If we disabled in (1), we'd get the wrong answer.
437** See ticket #813.
438*/
439static void disableTerm(WhereLevel *pLevel, Expr **ppExpr){
440 Expr *pExpr = *ppExpr;
441 if( pLevel->iLeftJoin==0 || ExprHasProperty(pExpr, EP_FromJoin) ){
442 *ppExpr = 0;
443 }
444}
445
446/*
drh94a11212004-09-25 13:12:14 +0000447** Generate code that builds a probe for an index. Details:
448**
449** * Check the top nColumn entries on the stack. If any
450** of those entries are NULL, jump immediately to brk,
451** which is the loop exit, since no index entry will match
452** if any part of the key is NULL.
453**
454** * Construct a probe entry from the top nColumn entries in
455** the stack with affinities appropriate for index pIdx.
456*/
457static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
458 sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
459 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
460 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
461 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
462 sqlite3IndexAffinityStr(v, pIdx);
463}
464
465/*
466** Generate code for an equality term of the WHERE clause. An equality
467** term can be either X=expr or X IN (...). pTerm is the X.
468*/
469static void codeEqualityTerm(
470 Parse *pParse, /* The parsing context */
471 ExprInfo *pTerm, /* The term of the WHERE clause to be coded */
472 int brk, /* Jump here to abandon the loop */
473 WhereLevel *pLevel /* When level of the FROM clause we are working on */
474){
475 Expr *pX = pTerm->p;
476 if( pX->op!=TK_IN ){
477 assert( pX->op==TK_EQ );
478 sqlite3ExprCode(pParse, pX->pRight);
479 }else{
480 int iTab = pX->iTable;
481 Vdbe *v = pParse->pVdbe;
482 sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
483 sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
drh9012bcb2004-12-19 00:11:35 +0000484 pLevel->inP2 = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
drh94a11212004-09-25 13:12:14 +0000485 pLevel->inOp = OP_Next;
486 pLevel->inP1 = iTab;
487 }
488 disableTerm(pLevel, &pTerm->p);
489}
490
drh51669862004-12-18 18:40:26 +0000491/*
492** The number of bits in a Bitmask
493*/
494#define BMS (sizeof(Bitmask)*8-1)
495
drh94a11212004-09-25 13:12:14 +0000496
497/*
drhe3184742002-06-19 14:27:05 +0000498** Generate the beginning of the loop used for WHERE clause processing.
drh75897232000-05-29 14:26:00 +0000499** The return value is a pointer to an (opaque) structure that contains
500** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +0000501** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +0000502** in order to complete the WHERE clause processing.
503**
504** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +0000505**
506** The basic idea is to do a nested loop, one loop for each table in
507** the FROM clause of a select. (INSERT and UPDATE statements are the
508** same as a SELECT with only a single table in the FROM clause.) For
509** example, if the SQL is this:
510**
511** SELECT * FROM t1, t2, t3 WHERE ...;
512**
513** Then the code generated is conceptually like the following:
514**
515** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000516** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +0000517** foreach row3 in t3 do /
518** ...
519** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000520** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +0000521** end /
522**
523** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +0000524** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
525** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +0000526** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +0000527**
528** If the WHERE clause is empty, the foreach loops must each scan their
529** entire tables. Thus a three-way join is an O(N^3) operation. But if
530** the tables have indices and there are terms in the WHERE clause that
531** refer to those indices, a complete table scan can be avoided and the
532** code will run much faster. Most of the work of this routine is checking
533** to see if there are indices that can be used to speed up the loop.
534**
535** Terms of the WHERE clause are also used to limit which rows actually
536** make it to the "..." in the middle of the loop. After each "foreach",
537** terms of the WHERE clause that use only terms in that loop and outer
538** loops are evaluated and if false a jump is made around all subsequent
539** inner loops (or around the "..." if the test occurs within the inner-
540** most loop)
541**
542** OUTER JOINS
543**
544** An outer join of tables t1 and t2 is conceptally coded as follows:
545**
546** foreach row1 in t1 do
547** flag = 0
548** foreach row2 in t2 do
549** start:
550** ...
551** flag = 1
552** end
drhe3184742002-06-19 14:27:05 +0000553** if flag==0 then
554** move the row2 cursor to a null row
555** goto start
556** fi
drhc27a1ce2002-06-14 20:58:45 +0000557** end
558**
drhe3184742002-06-19 14:27:05 +0000559** ORDER BY CLAUSE PROCESSING
560**
561** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
562** if there is one. If there is no ORDER BY clause or if this routine
563** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
564**
565** If an index can be used so that the natural output order of the table
566** scan is correct for the ORDER BY clause, then that index is used and
567** *ppOrderBy is set to NULL. This is an optimization that prevents an
568** unnecessary sort of the result set if an index appropriate for the
569** ORDER BY clause already exists.
570**
571** If the where clause loops cannot be arranged to provide the correct
572** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +0000573*/
danielk19774adee202004-05-08 08:23:19 +0000574WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +0000575 Parse *pParse, /* The parser context */
576 SrcList *pTabList, /* A list of all tables to be scanned */
577 Expr *pWhere, /* The WHERE clause */
578 int pushKey, /* If TRUE, leave the table key on the stack */
drhe4e72072004-11-23 01:47:30 +0000579 ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
580 Fetch *pFetch /* Initial location of cursors. NULL otherwise */
drh75897232000-05-29 14:26:00 +0000581){
582 int i; /* Loop counter */
583 WhereInfo *pWInfo; /* Will become the return value of this function */
584 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhd4f5ee22003-07-16 00:54:31 +0000585 int brk, cont = 0; /* Addresses used during code generation */
drh75897232000-05-29 14:26:00 +0000586 int nExpr; /* Number of subexpressions in the WHERE clause */
drh51669862004-12-18 18:40:26 +0000587 Bitmask loopMask; /* One bit set for each outer loop */
drh9012bcb2004-12-19 00:11:35 +0000588 int haveRowid = 0; /* True if the ROWID is on the stack */
drh193bd772004-07-20 18:23:14 +0000589 ExprInfo *pTerm; /* A single term in the WHERE clause; ptr to aExpr[] */
drh6a3ea0e2003-05-02 14:32:12 +0000590 ExprMaskSet maskSet; /* The expression mask set */
drh51669862004-12-18 18:40:26 +0000591 int iDirectEq[BMS]; /* Term of the form ROWID==X for the N-th table */
592 int iDirectLt[BMS]; /* Term of the form ROWID<X or ROWID<=X */
593 int iDirectGt[BMS]; /* Term of the form ROWID>X or ROWID>=X */
drh193bd772004-07-20 18:23:14 +0000594 ExprInfo aExpr[101]; /* The WHERE clause is divided into these terms */
drh9012bcb2004-12-19 00:11:35 +0000595 struct SrcList_item *pTabItem; /* A single entry from pTabList */
596 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh75897232000-05-29 14:26:00 +0000597
drhc27a1ce2002-06-14 20:58:45 +0000598 /* pushKey is only allowed if there is a single table (as in an INSERT or
599 ** UPDATE statement)
600 */
601 assert( pushKey==0 || pTabList->nSrc==1 );
drh83dcb1a2002-06-28 01:02:38 +0000602
603 /* Split the WHERE clause into separate subexpressions where each
604 ** subexpression is separated by an AND operator. If the aExpr[]
605 ** array fills up, the last entry might point to an expression which
606 ** contains additional unfactored AND operators.
607 */
drh6a3ea0e2003-05-02 14:32:12 +0000608 initMaskSet(&maskSet);
drh83dcb1a2002-06-28 01:02:38 +0000609 memset(aExpr, 0, sizeof(aExpr));
610 nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
611 if( nExpr==ARRAYSIZE(aExpr) ){
danielk19774adee202004-05-08 08:23:19 +0000612 sqlite3ErrorMsg(pParse, "WHERE clause too complex - no more "
drhf7a9e1a2004-02-22 18:40:56 +0000613 "than %d terms allowed", (int)ARRAYSIZE(aExpr)-1);
drh83dcb1a2002-06-28 01:02:38 +0000614 return 0;
615 }
drhc27a1ce2002-06-14 20:58:45 +0000616
drh75897232000-05-29 14:26:00 +0000617 /* Allocate and initialize the WhereInfo structure that will become the
618 ** return value.
619 */
drhad3cab52002-05-24 02:04:32 +0000620 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
danielk1977132872b2004-05-10 10:37:18 +0000621 if( sqlite3_malloc_failed ){
drh193bd772004-07-20 18:23:14 +0000622 /* sqliteFree(pWInfo); // Leak memory when malloc fails */
drh75897232000-05-29 14:26:00 +0000623 return 0;
624 }
625 pWInfo->pParse = pParse;
626 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +0000627 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh08192d52002-04-30 19:20:28 +0000628
629 /* Special case: a WHERE clause that is constant. Evaluate the
630 ** expression and either jump over all of the code or fall thru.
631 */
danielk19774adee202004-05-08 08:23:19 +0000632 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
633 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +0000634 pWhere = 0;
drh08192d52002-04-30 19:20:28 +0000635 }
drh75897232000-05-29 14:26:00 +0000636
drh75897232000-05-29 14:26:00 +0000637 /* Analyze all of the subexpressions.
638 */
drh193bd772004-07-20 18:23:14 +0000639 for(pTerm=aExpr, i=0; i<nExpr; i++, pTerm++){
640 TriggerStack *pStack;
641 exprAnalyze(pTabList, &maskSet, pTerm);
drh1d1f3052002-05-21 13:18:25 +0000642
643 /* If we are executing a trigger body, remove all references to
644 ** new.* and old.* tables from the prerequisite masks.
645 */
drh193bd772004-07-20 18:23:14 +0000646 if( (pStack = pParse->trigStack)!=0 ){
drh1d1f3052002-05-21 13:18:25 +0000647 int x;
drh193bd772004-07-20 18:23:14 +0000648 if( (x=pStack->newIdx) >= 0 ){
drh51669862004-12-18 18:40:26 +0000649 Bitmask mask = ~getMask(&maskSet, x);
drh193bd772004-07-20 18:23:14 +0000650 pTerm->prereqRight &= mask;
651 pTerm->prereqLeft &= mask;
652 pTerm->prereqAll &= mask;
drh1d1f3052002-05-21 13:18:25 +0000653 }
drh193bd772004-07-20 18:23:14 +0000654 if( (x=pStack->oldIdx) >= 0 ){
drh51669862004-12-18 18:40:26 +0000655 Bitmask mask = ~getMask(&maskSet, x);
drh193bd772004-07-20 18:23:14 +0000656 pTerm->prereqRight &= mask;
657 pTerm->prereqLeft &= mask;
658 pTerm->prereqAll &= mask;
drh1d1f3052002-05-21 13:18:25 +0000659 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000660 }
drh75897232000-05-29 14:26:00 +0000661 }
662
drh75897232000-05-29 14:26:00 +0000663 /* Figure out what index to use (if any) for each nested loop.
drh6b563442001-11-07 16:48:26 +0000664 ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
drhad3cab52002-05-24 02:04:32 +0000665 ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
drh8aff1012001-12-22 14:49:24 +0000666 ** loop.
667 **
668 ** If terms exist that use the ROWID of any table, then set the
669 ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
670 ** to the index of the term containing the ROWID. We always prefer
671 ** to use a ROWID which can directly access a table rather than an
drh0a36c572002-02-18 22:49:59 +0000672 ** index which requires reading an index first to get the rowid then
673 ** doing a second read of the actual database table.
drh75897232000-05-29 14:26:00 +0000674 **
675 ** Actually, if there are more than 32 tables in the join, only the
drh0a36c572002-02-18 22:49:59 +0000676 ** first 32 tables are candidates for indices. This is (again) due
677 ** to the limit of 32 bits in an integer bitmask.
drh75897232000-05-29 14:26:00 +0000678 */
679 loopMask = 0;
drh9012bcb2004-12-19 00:11:35 +0000680 pTabItem = pTabList->a;
681 pLevel = pWInfo->a;
682 for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++,pTabItem++,pLevel++){
drhc4a3c772001-04-04 11:48:57 +0000683 int j;
drh9012bcb2004-12-19 00:11:35 +0000684 int iCur = pTabItem->iCursor; /* The cursor for this table */
drh51669862004-12-18 18:40:26 +0000685 Bitmask mask = getMask(&maskSet, iCur); /* Cursor mask for this table */
drh9012bcb2004-12-19 00:11:35 +0000686 Table *pTab = pTabItem->pTab;
drh75897232000-05-29 14:26:00 +0000687 Index *pIdx;
688 Index *pBestIdx = 0;
drh487ab3c2001-11-08 00:45:21 +0000689 int bestScore = 0;
drh51669862004-12-18 18:40:26 +0000690 int bestRev = 0;
drh75897232000-05-29 14:26:00 +0000691
drhc4a3c772001-04-04 11:48:57 +0000692 /* Check to see if there is an expression that uses only the
drh8aff1012001-12-22 14:49:24 +0000693 ** ROWID field of this table. For terms of the form ROWID==expr
694 ** set iDirectEq[i] to the index of the term. For terms of the
695 ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
696 ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
drh174b6192002-12-03 02:22:52 +0000697 **
698 ** (Added:) Treat ROWID IN expr like ROWID=expr.
drhc4a3c772001-04-04 11:48:57 +0000699 */
drh9012bcb2004-12-19 00:11:35 +0000700 pLevel->iIdxCur = -1;
drh8aff1012001-12-22 14:49:24 +0000701 iDirectEq[i] = -1;
702 iDirectLt[i] = -1;
703 iDirectGt[i] = -1;
drh193bd772004-07-20 18:23:14 +0000704 for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
705 Expr *pX = pTerm->p;
706 if( pTerm->idxLeft==iCur && pX->pLeft->iColumn<0
707 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight ){
708 switch( pX->op ){
drhd99f7062002-06-08 23:25:08 +0000709 case TK_IN:
drh8aff1012001-12-22 14:49:24 +0000710 case TK_EQ: iDirectEq[i] = j; break;
711 case TK_LE:
712 case TK_LT: iDirectLt[i] = j; break;
713 case TK_GE:
714 case TK_GT: iDirectGt[i] = j; break;
715 }
drhc4a3c772001-04-04 11:48:57 +0000716 }
drhc4a3c772001-04-04 11:48:57 +0000717 }
drhb6c29892004-11-22 19:12:19 +0000718
719 /* If we found a term that tests ROWID with == or IN, that term
720 ** will be used to locate the rows in the database table. There
721 ** is not need to continue into the code below that looks for
722 ** an index. We will always use the ROWID over an index.
723 */
drh8aff1012001-12-22 14:49:24 +0000724 if( iDirectEq[i]>=0 ){
drh6a3ea0e2003-05-02 14:32:12 +0000725 loopMask |= mask;
drh94a11212004-09-25 13:12:14 +0000726 pLevel->pIdx = 0;
drhc4a3c772001-04-04 11:48:57 +0000727 continue;
728 }
729
drh75897232000-05-29 14:26:00 +0000730 /* Do a search for usable indices. Leave pBestIdx pointing to
drh487ab3c2001-11-08 00:45:21 +0000731 ** the "best" index. pBestIdx is left set to NULL if no indices
732 ** are usable.
drh75897232000-05-29 14:26:00 +0000733 **
drh487ab3c2001-11-08 00:45:21 +0000734 ** The best index is determined as follows. For each of the
735 ** left-most terms that is fixed by an equality operator, add
drh51669862004-12-18 18:40:26 +0000736 ** 32 to the score. The right-most term of the index may be
737 ** constrained by an inequality. Add 4 if for an "x<..." constraint
738 ** and add 8 for an "x>..." constraint. If both constraints
739 ** are present, add 12.
740 **
741 ** If the left-most term of the index uses an IN operator
742 ** (ex: "x IN (...)") then add 16 to the score.
743 **
744 ** If an index can be used for sorting, add 2 to the score.
745 ** If an index contains all the terms of a table that are ever
746 ** used by any expression in the SQL statement, then add 1 to
747 ** the score.
drh487ab3c2001-11-08 00:45:21 +0000748 **
749 ** This scoring system is designed so that the score can later be
drh51669862004-12-18 18:40:26 +0000750 ** used to determine how the index is used. If the score&0x1c is 0
751 ** then all constraints are equalities. If score&0x4 is not 0 then
drh487ab3c2001-11-08 00:45:21 +0000752 ** there is an inequality used as a termination key. (ex: "x<...")
drh51669862004-12-18 18:40:26 +0000753 ** If score&0x8 is not 0 then there is an inequality used as the
754 ** start key. (ex: "x>..."). A score or 0x10 is the special case
drhc045ec52002-12-04 20:01:06 +0000755 ** of an IN operator constraint. (ex: "x IN ...").
drhd99f7062002-06-08 23:25:08 +0000756 **
drhc27a1ce2002-06-14 20:58:45 +0000757 ** The IN operator (as in "<expr> IN (...)") is treated the same as
758 ** an equality comparison except that it can only be used on the
759 ** left-most column of an index and other terms of the WHERE clause
760 ** cannot be used in conjunction with the IN operator to help satisfy
761 ** other columns of the index.
drh75897232000-05-29 14:26:00 +0000762 */
763 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh51669862004-12-18 18:40:26 +0000764 Bitmask eqMask = 0; /* Index columns covered by an x=... term */
765 Bitmask ltMask = 0; /* Index columns covered by an x<... term */
766 Bitmask gtMask = 0; /* Index columns covered by an x>... term */
767 Bitmask inMask = 0; /* Index columns covered by an x IN .. term */
768 Bitmask m;
769 int nEq, score, bRev = 0;
drh75897232000-05-29 14:26:00 +0000770
drh51669862004-12-18 18:40:26 +0000771 if( pIdx->nColumn>sizeof(eqMask)*8 ){
772 continue; /* Ignore indices with too many columns to analyze */
773 }
drh193bd772004-07-20 18:23:14 +0000774 for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
drh193bd772004-07-20 18:23:14 +0000775 Expr *pX = pTerm->p;
drh94a11212004-09-25 13:12:14 +0000776 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
drh193bd772004-07-20 18:23:14 +0000777 if( !pColl && pX->pRight ){
778 pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
danielk19770202b292004-06-09 09:55:16 +0000779 }
780 if( !pColl ){
781 pColl = pParse->db->pDfltColl;
782 }
drh193bd772004-07-20 18:23:14 +0000783 if( pTerm->idxLeft==iCur
784 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight ){
785 int iColumn = pX->pLeft->iColumn;
drh75897232000-05-29 14:26:00 +0000786 int k;
danielk1977e014a832004-05-17 10:48:57 +0000787 char idxaff = pIdx->pTable->aCol[iColumn].affinity;
drh967e8b72000-06-21 13:59:10 +0000788 for(k=0; k<pIdx->nColumn; k++){
danielk19770202b292004-06-09 09:55:16 +0000789 /* If the collating sequences or affinities don't match,
790 ** ignore this index. */
791 if( pColl!=pIdx->keyInfo.aColl[k] ) continue;
drh193bd772004-07-20 18:23:14 +0000792 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
danielk19770202b292004-06-09 09:55:16 +0000793 if( pIdx->aiColumn[k]==iColumn ){
drh193bd772004-07-20 18:23:14 +0000794 switch( pX->op ){
drh48185c12002-06-09 01:55:20 +0000795 case TK_IN: {
796 if( k==0 ) inMask |= 1;
797 break;
798 }
drh487ab3c2001-11-08 00:45:21 +0000799 case TK_EQ: {
drh51669862004-12-18 18:40:26 +0000800 eqMask |= ((Bitmask)1)<<k;
drh487ab3c2001-11-08 00:45:21 +0000801 break;
802 }
803 case TK_LE:
804 case TK_LT: {
drh51669862004-12-18 18:40:26 +0000805 ltMask |= ((Bitmask)1)<<k;
drh487ab3c2001-11-08 00:45:21 +0000806 break;
807 }
808 case TK_GE:
809 case TK_GT: {
drh51669862004-12-18 18:40:26 +0000810 gtMask |= ((Bitmask)1)<<k;
drh487ab3c2001-11-08 00:45:21 +0000811 break;
812 }
813 default: {
814 /* CANT_HAPPEN */
815 assert( 0 );
816 break;
817 }
818 }
drh75897232000-05-29 14:26:00 +0000819 break;
820 }
821 }
822 }
drh75897232000-05-29 14:26:00 +0000823 }
drhc045ec52002-12-04 20:01:06 +0000824
825 /* The following loop ends with nEq set to the number of columns
826 ** on the left of the index with == constraints.
827 */
drh487ab3c2001-11-08 00:45:21 +0000828 for(nEq=0; nEq<pIdx->nColumn; nEq++){
drh51669862004-12-18 18:40:26 +0000829 m = (((Bitmask)1)<<(nEq+1))-1;
drh487ab3c2001-11-08 00:45:21 +0000830 if( (m & eqMask)!=m ) break;
831 }
drh51669862004-12-18 18:40:26 +0000832
833 /* Begin assemblying the score
834 */
835 score = nEq*32; /* Base score is 32 times number of == constraints */
836 m = ((Bitmask)1)<<nEq;
837 if( m & ltMask ) score+=4; /* Increase score for a < constraint */
838 if( m & gtMask ) score+=8; /* Increase score for a > constraint */
839 if( score==0 && inMask ) score = 16; /* Default score for IN constraint */
840
841 /* Give bonus points if this index can be used for sorting
842 */
drh9012bcb2004-12-19 00:11:35 +0000843 if( i==0 && score!=16 && ppOrderBy && *ppOrderBy ){
drh51669862004-12-18 18:40:26 +0000844 int base = pTabList->a[0].iCursor;
845 if( isSortingIndex(pParse, pIdx, pTab, base, *ppOrderBy, nEq, &bRev) ){
846 score += 2;
847 }
848 }
849
drh9012bcb2004-12-19 00:11:35 +0000850 /* Check to see if we can get away with using just the index without
851 ** ever reading the table. If that is the case, then add one bonus
852 ** point to the score.
853 */
854 if( score && pTabItem->colUsed < (((Bitmask)1)<<(BMS-1)) ){
855 for(m=0, j=0; j<pIdx->nColumn; j++){
856 int x = pIdx->aiColumn[j];
857 if( x<BMS-1 ){
858 m |= ((Bitmask)1)<<x;
859 }
860 }
861 if( (pTabItem->colUsed & m)==pTabItem->colUsed ){
862 score++;
863 }
864 }
865
drh51669862004-12-18 18:40:26 +0000866 /* If the score for this index is the best we have seen so far, then
867 ** save it
868 */
drh487ab3c2001-11-08 00:45:21 +0000869 if( score>bestScore ){
870 pBestIdx = pIdx;
871 bestScore = score;
drh51669862004-12-18 18:40:26 +0000872 bestRev = bRev;
drh75897232000-05-29 14:26:00 +0000873 }
874 }
drh94a11212004-09-25 13:12:14 +0000875 pLevel->pIdx = pBestIdx;
876 pLevel->score = bestScore;
drh51669862004-12-18 18:40:26 +0000877 pLevel->bRev = bestRev;
drh6a3ea0e2003-05-02 14:32:12 +0000878 loopMask |= mask;
drh6b563442001-11-07 16:48:26 +0000879 if( pBestIdx ){
drh9012bcb2004-12-19 00:11:35 +0000880 pLevel->iIdxCur = pParse->nTab++;
drh6b563442001-11-07 16:48:26 +0000881 }
drh75897232000-05-29 14:26:00 +0000882 }
883
drhe3184742002-06-19 14:27:05 +0000884 /* Check to see if the ORDER BY clause is or can be satisfied by the
885 ** use of an index on the first table.
886 */
887 if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
drh9012bcb2004-12-19 00:11:35 +0000888 Index *pIdx; /* Index derived from the WHERE clause */
889 Table *pTab; /* Left-most table in the FROM clause */
890 int bRev = 0; /* True to reverse the output order */
891 int iCur; /* Btree-cursor that will be used by pTab */
892 WhereLevel *pLevel0 = &pWInfo->a[0];
drhe3184742002-06-19 14:27:05 +0000893
drh9012bcb2004-12-19 00:11:35 +0000894 pTab = pTabList->a[0].pTab;
895 pIdx = pLevel0->pIdx;
896 iCur = pTabList->a[0].iCursor;
897 if( pIdx==0 && sortableByRowid(iCur, *ppOrderBy, &bRev) ){
898 /* The ORDER BY clause specifies ROWID order, which is what we
899 ** were going to be doing anyway...
900 */
901 *ppOrderBy = 0;
902 pLevel0->bRev = bRev;
903 }else if( pLevel0->score==16 ){
904 /* If there is already an IN index on the left-most table,
905 ** it will not give the correct sort order.
906 ** So, pretend that no suitable index is found.
907 */
908 }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
909 /* If the left-most column is accessed using its ROWID, then do
910 ** not try to sort by index. But do delete the ORDER BY clause
911 ** if it is redundant.
912 */
913 }else if( (pLevel0->score&2)!=0 ){
914 /* The index that was selected for searching will cause rows to
915 ** appear in sorted order.
916 */
917 *ppOrderBy = 0;
drh75897232000-05-29 14:26:00 +0000918 }
919 }
920
drh9012bcb2004-12-19 00:11:35 +0000921 /* Open all tables in the pTabList and any indices selected for
922 ** searching those tables.
923 */
924 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
925 pLevel = pWInfo->a;
926 for(i=0, pTabItem=pTabList->a; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
927 Table *pTab;
928 Index *pIx;
929 int iIdxCur = pLevel->iIdxCur;
930
931 pTab = pTabItem->pTab;
932 if( pTab->isTransient || pTab->pSelect ) continue;
933 if( (pLevel->score & 1)==0 ){
934 sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
935 }
936 pLevel->iTabCur = pTabItem->iCursor;
937 if( (pIx = pLevel->pIdx)!=0 ){
938 sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
939 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
940 (char*)&pIx->keyInfo, P3_KEYINFO);
941 }
942 if( (pLevel->score & 1)!=0 ){
943 sqlite3VdbeAddOp(v, OP_KeyAsData, iIdxCur, 1);
944 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
945 }
946 sqlite3CodeVerifySchema(pParse, pTab->iDb);
947 }
948 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
949
drh75897232000-05-29 14:26:00 +0000950 /* Generate the code to do the search
951 */
drh75897232000-05-29 14:26:00 +0000952 loopMask = 0;
drh9012bcb2004-12-19 00:11:35 +0000953 pLevel = pWInfo->a;
954 pTabItem = pTabList->a;
955 for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
drh75897232000-05-29 14:26:00 +0000956 int j, k;
drh9012bcb2004-12-19 00:11:35 +0000957 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
958 Index *pIdx; /* The index we will be using */
959 int iIdxCur; /* The VDBE cursor for the index */
960 int omitTable; /* True if we use the index only */
961
962 pIdx = pLevel->pIdx;
963 iIdxCur = pLevel->iIdxCur;
964 pLevel->inOp = OP_Noop;
965
966 /* Check to see if it is appropriate to omit the use of the table
967 ** here and use its index instead.
968 */
969 omitTable = (pLevel->score&1)!=0;
drh75897232000-05-29 14:26:00 +0000970
drhad2d8302002-05-24 20:31:36 +0000971 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +0000972 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +0000973 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +0000974 */
975 if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
976 if( !pParse->nMem ) pParse->nMem++;
977 pLevel->iLeftJoin = pParse->nMem++;
danielk19770f69c1e2004-05-29 11:24:50 +0000978 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000979 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +0000980 VdbeComment((v, "# init LEFT JOIN no-match flag"));
drhad2d8302002-05-24 20:31:36 +0000981 }
982
drh94a11212004-09-25 13:12:14 +0000983 if( i<ARRAYSIZE(iDirectEq) && (k = iDirectEq[i])>=0 ){
drh8aff1012001-12-22 14:49:24 +0000984 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +0000985 ** equality comparison against the ROWID field. Or
986 ** we reference multiple rows using a "rowid IN (...)"
987 ** construct.
drhc4a3c772001-04-04 11:48:57 +0000988 */
drh8aff1012001-12-22 14:49:24 +0000989 assert( k<nExpr );
drh193bd772004-07-20 18:23:14 +0000990 pTerm = &aExpr[k];
991 assert( pTerm->p!=0 );
drh193bd772004-07-20 18:23:14 +0000992 assert( pTerm->idxLeft==iCur );
drh9012bcb2004-12-19 00:11:35 +0000993 assert( omitTable==0 );
drh94a11212004-09-25 13:12:14 +0000994 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
995 codeEqualityTerm(pParse, pTerm, brk, pLevel);
danielk19774adee202004-05-08 08:23:19 +0000996 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
997 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
danielk19774adee202004-05-08 08:23:19 +0000998 sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
drh9012bcb2004-12-19 00:11:35 +0000999 haveRowid = 0;
drh6b563442001-11-07 16:48:26 +00001000 pLevel->op = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001001 }else if( pIdx!=0 && pLevel->score>3 && (pLevel->score&0x0c)==0 ){
drhc27a1ce2002-06-14 20:58:45 +00001002 /* Case 2: There is an index and all terms of the WHERE clause that
drhb6c29892004-11-22 19:12:19 +00001003 ** refer to the index using the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +00001004 */
drh6b563442001-11-07 16:48:26 +00001005 int start;
drh51669862004-12-18 18:40:26 +00001006 int nColumn = (pLevel->score+16)/32;
danielk19774adee202004-05-08 08:23:19 +00001007 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
drh772ae622004-05-19 13:13:08 +00001008
1009 /* For each column of the index, find the term of the WHERE clause that
1010 ** constraints that column. If the WHERE clause term is X=expr, then
1011 ** evaluation expr and leave the result on the stack */
drh487ab3c2001-11-08 00:45:21 +00001012 for(j=0; j<nColumn; j++){
drh193bd772004-07-20 18:23:14 +00001013 for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
1014 Expr *pX = pTerm->p;
drhd99f7062002-06-08 23:25:08 +00001015 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001016 if( pTerm->idxLeft==iCur
1017 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drhd99f7062002-06-08 23:25:08 +00001018 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +00001019 ){
danielk1977e014a832004-05-17 10:48:57 +00001020 char idxaff = pIdx->pTable->aCol[pX->pLeft->iColumn].affinity;
drh94a11212004-09-25 13:12:14 +00001021 if( sqlite3IndexAffinityOk(pX, idxaff) ){
1022 codeEqualityTerm(pParse, pTerm, brk, pLevel);
1023 break;
drhd99f7062002-06-08 23:25:08 +00001024 }
drh75897232000-05-29 14:26:00 +00001025 }
drh75897232000-05-29 14:26:00 +00001026 }
1027 }
drh6b563442001-11-07 16:48:26 +00001028 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001029 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drh94a11212004-09-25 13:12:14 +00001030 buildIndexProbe(v, nColumn, brk, pIdx);
danielk19773d1bfea2004-05-14 11:00:53 +00001031 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
drh772ae622004-05-19 13:13:08 +00001032
drh772ae622004-05-19 13:13:08 +00001033 /* Generate code (1) to move to the first matching element of the table.
1034 ** Then generate code (2) that jumps to "brk" after the cursor is past
1035 ** the last matching element of the table. The code (1) is executed
1036 ** once to initialize the search, the code (2) is executed before each
1037 ** iteration of the scan to see if the scan has finished. */
drhc045ec52002-12-04 20:01:06 +00001038 if( pLevel->bRev ){
1039 /* Scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001040 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001041 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001042 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001043 pLevel->op = OP_Prev;
1044 }else{
1045 /* Scan in the forward order */
drh9012bcb2004-12-19 00:11:35 +00001046 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001047 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001048 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
drhc045ec52002-12-04 20:01:06 +00001049 pLevel->op = OP_Next;
1050 }
drh9012bcb2004-12-19 00:11:35 +00001051 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001052 sqlite3VdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
drh9012bcb2004-12-19 00:11:35 +00001053 if( omitTable ){
1054 haveRowid = 0;
drh75897232000-05-29 14:26:00 +00001055 }else{
drh9012bcb2004-12-19 00:11:35 +00001056 sqlite3VdbeAddOp(v, OP_IdxRecno, iIdxCur, 0);
1057 haveRowid = 1;
drh75897232000-05-29 14:26:00 +00001058 }
drh9012bcb2004-12-19 00:11:35 +00001059 pLevel->p1 = iIdxCur;
drh6b563442001-11-07 16:48:26 +00001060 pLevel->p2 = start;
drh8aff1012001-12-22 14:49:24 +00001061 }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
1062 /* Case 3: We have an inequality comparison against the ROWID field.
1063 */
1064 int testOp = OP_Noop;
1065 int start;
drhb6c29892004-11-22 19:12:19 +00001066 int bRev = pLevel->bRev;
drh8aff1012001-12-22 14:49:24 +00001067
drh9012bcb2004-12-19 00:11:35 +00001068 assert( omitTable==0 );
danielk19774adee202004-05-08 08:23:19 +00001069 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1070 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drhb6c29892004-11-22 19:12:19 +00001071 if( bRev ){
1072 int t = iDirectGt[i];
1073 iDirectGt[i] = iDirectLt[i];
1074 iDirectLt[i] = t;
1075 }
drh8aff1012001-12-22 14:49:24 +00001076 if( iDirectGt[i]>=0 ){
drh94a11212004-09-25 13:12:14 +00001077 Expr *pX;
drh8aff1012001-12-22 14:49:24 +00001078 k = iDirectGt[i];
1079 assert( k<nExpr );
drh193bd772004-07-20 18:23:14 +00001080 pTerm = &aExpr[k];
drh94a11212004-09-25 13:12:14 +00001081 pX = pTerm->p;
1082 assert( pX!=0 );
drh193bd772004-07-20 18:23:14 +00001083 assert( pTerm->idxLeft==iCur );
drh94a11212004-09-25 13:12:14 +00001084 sqlite3ExprCode(pParse, pX->pRight);
1085 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LT || pX->op==TK_GT, brk);
drhb6c29892004-11-22 19:12:19 +00001086 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
drh193bd772004-07-20 18:23:14 +00001087 disableTerm(pLevel, &pTerm->p);
drh8aff1012001-12-22 14:49:24 +00001088 }else{
drhb6c29892004-11-22 19:12:19 +00001089 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
drh8aff1012001-12-22 14:49:24 +00001090 }
1091 if( iDirectLt[i]>=0 ){
drh94a11212004-09-25 13:12:14 +00001092 Expr *pX;
drh8aff1012001-12-22 14:49:24 +00001093 k = iDirectLt[i];
1094 assert( k<nExpr );
drh193bd772004-07-20 18:23:14 +00001095 pTerm = &aExpr[k];
drh94a11212004-09-25 13:12:14 +00001096 pX = pTerm->p;
1097 assert( pX!=0 );
drh193bd772004-07-20 18:23:14 +00001098 assert( pTerm->idxLeft==iCur );
drh94a11212004-09-25 13:12:14 +00001099 sqlite3ExprCode(pParse, pX->pRight);
drh8aff1012001-12-22 14:49:24 +00001100 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001101 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drh94a11212004-09-25 13:12:14 +00001102 if( pX->op==TK_LT || pX->op==TK_GT ){
drhb6c29892004-11-22 19:12:19 +00001103 testOp = bRev ? OP_Le : OP_Ge;
drh8aff1012001-12-22 14:49:24 +00001104 }else{
drhb6c29892004-11-22 19:12:19 +00001105 testOp = bRev ? OP_Lt : OP_Gt;
drh8aff1012001-12-22 14:49:24 +00001106 }
drh193bd772004-07-20 18:23:14 +00001107 disableTerm(pLevel, &pTerm->p);
drh8aff1012001-12-22 14:49:24 +00001108 }
danielk19774adee202004-05-08 08:23:19 +00001109 start = sqlite3VdbeCurrentAddr(v);
drhb6c29892004-11-22 19:12:19 +00001110 pLevel->op = bRev ? OP_Prev : OP_Next;
drh6a3ea0e2003-05-02 14:32:12 +00001111 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001112 pLevel->p2 = start;
1113 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001114 sqlite3VdbeAddOp(v, OP_Recno, iCur, 0);
1115 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1116 sqlite3VdbeAddOp(v, testOp, 0, brk);
drh8aff1012001-12-22 14:49:24 +00001117 }
drh9012bcb2004-12-19 00:11:35 +00001118 haveRowid = 0;
drh8aff1012001-12-22 14:49:24 +00001119 }else if( pIdx==0 ){
drhc27a1ce2002-06-14 20:58:45 +00001120 /* Case 4: There is no usable index. We must do a complete
drh8aff1012001-12-22 14:49:24 +00001121 ** scan of the entire database table.
1122 */
1123 int start;
drhb6c29892004-11-22 19:12:19 +00001124 int opRewind;
drh8aff1012001-12-22 14:49:24 +00001125
drh9012bcb2004-12-19 00:11:35 +00001126 assert( omitTable==0 );
danielk19774adee202004-05-08 08:23:19 +00001127 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1128 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drhb6c29892004-11-22 19:12:19 +00001129 if( pLevel->bRev ){
1130 opRewind = OP_Last;
1131 pLevel->op = OP_Prev;
1132 }else{
1133 opRewind = OP_Rewind;
1134 pLevel->op = OP_Next;
1135 }
1136 sqlite3VdbeAddOp(v, opRewind, iCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001137 start = sqlite3VdbeCurrentAddr(v);
drh6a3ea0e2003-05-02 14:32:12 +00001138 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001139 pLevel->p2 = start;
drh9012bcb2004-12-19 00:11:35 +00001140 haveRowid = 0;
drh487ab3c2001-11-08 00:45:21 +00001141 }else{
drhc27a1ce2002-06-14 20:58:45 +00001142 /* Case 5: The WHERE clause term that refers to the right-most
1143 ** column of the index is an inequality. For example, if
1144 ** the index is on (x,y,z) and the WHERE clause is of the
1145 ** form "x=5 AND y<10" then this case is used. Only the
1146 ** right-most column can be an inequality - the rest must
1147 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +00001148 **
1149 ** This case is also used when there are no WHERE clause
1150 ** constraints but an index is selected anyway, in order
1151 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +00001152 */
1153 int score = pLevel->score;
drh51669862004-12-18 18:40:26 +00001154 int nEqColumn = score/32;
drh487ab3c2001-11-08 00:45:21 +00001155 int start;
danielk1977f7df9cc2004-06-16 12:02:47 +00001156 int leFlag=0, geFlag=0;
drh487ab3c2001-11-08 00:45:21 +00001157 int testOp;
1158
1159 /* Evaluate the equality constraints
1160 */
1161 for(j=0; j<nEqColumn; j++){
drh94a11212004-09-25 13:12:14 +00001162 int iIdxCol = pIdx->aiColumn[j];
drh193bd772004-07-20 18:23:14 +00001163 for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
drh94a11212004-09-25 13:12:14 +00001164 Expr *pX = pTerm->p;
1165 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001166 if( pTerm->idxLeft==iCur
drh94a11212004-09-25 13:12:14 +00001167 && pX->op==TK_EQ
drh193bd772004-07-20 18:23:14 +00001168 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drh94a11212004-09-25 13:12:14 +00001169 && pX->pLeft->iColumn==iIdxCol
drh487ab3c2001-11-08 00:45:21 +00001170 ){
drh94a11212004-09-25 13:12:14 +00001171 sqlite3ExprCode(pParse, pX->pRight);
drh193bd772004-07-20 18:23:14 +00001172 disableTerm(pLevel, &pTerm->p);
drh487ab3c2001-11-08 00:45:21 +00001173 break;
1174 }
1175 }
1176 }
1177
drhc27a1ce2002-06-14 20:58:45 +00001178 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +00001179 ** used twice: once to make the termination key and once to make the
1180 ** start key.
1181 */
1182 for(j=0; j<nEqColumn; j++){
danielk19774adee202004-05-08 08:23:19 +00001183 sqlite3VdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
drh487ab3c2001-11-08 00:45:21 +00001184 }
1185
drhc045ec52002-12-04 20:01:06 +00001186 /* Labels for the beginning and end of the loop
1187 */
danielk19774adee202004-05-08 08:23:19 +00001188 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1189 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
drhc045ec52002-12-04 20:01:06 +00001190
drh487ab3c2001-11-08 00:45:21 +00001191 /* Generate the termination key. This is the key value that
1192 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +00001193 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +00001194 **
1195 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1196 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +00001197 */
drh51669862004-12-18 18:40:26 +00001198 if( (score & 4)!=0 ){
drh193bd772004-07-20 18:23:14 +00001199 for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
drh94a11212004-09-25 13:12:14 +00001200 Expr *pX = pTerm->p;
1201 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001202 if( pTerm->idxLeft==iCur
drh94a11212004-09-25 13:12:14 +00001203 && (pX->op==TK_LT || pX->op==TK_LE)
drh193bd772004-07-20 18:23:14 +00001204 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drh94a11212004-09-25 13:12:14 +00001205 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh487ab3c2001-11-08 00:45:21 +00001206 ){
drh94a11212004-09-25 13:12:14 +00001207 sqlite3ExprCode(pParse, pX->pRight);
1208 leFlag = pX->op==TK_LE;
drh193bd772004-07-20 18:23:14 +00001209 disableTerm(pLevel, &pTerm->p);
drh487ab3c2001-11-08 00:45:21 +00001210 break;
1211 }
1212 }
1213 testOp = OP_IdxGE;
1214 }else{
1215 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
1216 leFlag = 1;
1217 }
1218 if( testOp!=OP_Noop ){
drh51669862004-12-18 18:40:26 +00001219 int nCol = nEqColumn + ((score & 4)!=0);
drh487ab3c2001-11-08 00:45:21 +00001220 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001221 buildIndexProbe(v, nCol, brk, pIdx);
drhc045ec52002-12-04 20:01:06 +00001222 if( pLevel->bRev ){
drh7cf6e4d2004-05-19 14:56:55 +00001223 int op = leFlag ? OP_MoveLe : OP_MoveLt;
drh9012bcb2004-12-19 00:11:35 +00001224 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001225 }else{
danielk19774adee202004-05-08 08:23:19 +00001226 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001227 }
1228 }else if( pLevel->bRev ){
drh9012bcb2004-12-19 00:11:35 +00001229 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001230 }
1231
1232 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001233 ** bound on the search. There is no start key if there are no
1234 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001235 ** that case, generate a "Rewind" instruction in place of the
1236 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001237 **
1238 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1239 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001240 */
drh51669862004-12-18 18:40:26 +00001241 if( (score & 8)!=0 ){
drh193bd772004-07-20 18:23:14 +00001242 for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
drh94a11212004-09-25 13:12:14 +00001243 Expr *pX = pTerm->p;
1244 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001245 if( pTerm->idxLeft==iCur
drh94a11212004-09-25 13:12:14 +00001246 && (pX->op==TK_GT || pX->op==TK_GE)
drh193bd772004-07-20 18:23:14 +00001247 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drh94a11212004-09-25 13:12:14 +00001248 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh487ab3c2001-11-08 00:45:21 +00001249 ){
drh94a11212004-09-25 13:12:14 +00001250 sqlite3ExprCode(pParse, pX->pRight);
1251 geFlag = pX->op==TK_GE;
drh193bd772004-07-20 18:23:14 +00001252 disableTerm(pLevel, &pTerm->p);
drh487ab3c2001-11-08 00:45:21 +00001253 break;
1254 }
1255 }
drh7900ead2001-11-12 13:51:43 +00001256 }else{
1257 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001258 }
drh51669862004-12-18 18:40:26 +00001259 if( nEqColumn>0 || (score&8)!=0 ){
1260 int nCol = nEqColumn + ((score&8)!=0);
drh94a11212004-09-25 13:12:14 +00001261 buildIndexProbe(v, nCol, brk, pIdx);
drhc045ec52002-12-04 20:01:06 +00001262 if( pLevel->bRev ){
1263 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001264 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001265 testOp = OP_IdxLT;
1266 }else{
drh7cf6e4d2004-05-19 14:56:55 +00001267 int op = geFlag ? OP_MoveGe : OP_MoveGt;
drh9012bcb2004-12-19 00:11:35 +00001268 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001269 }
1270 }else if( pLevel->bRev ){
1271 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001272 }else{
drh9012bcb2004-12-19 00:11:35 +00001273 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001274 }
1275
1276 /* Generate the the top of the loop. If there is a termination
1277 ** key we have to test for that key and abort at the top of the
1278 ** loop.
1279 */
danielk19774adee202004-05-08 08:23:19 +00001280 start = sqlite3VdbeCurrentAddr(v);
drh487ab3c2001-11-08 00:45:21 +00001281 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001282 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001283 sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
danielk19773d1bfea2004-05-14 11:00:53 +00001284 if( (leFlag && !pLevel->bRev) || (!geFlag && pLevel->bRev) ){
1285 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
1286 }
drh487ab3c2001-11-08 00:45:21 +00001287 }
drh9012bcb2004-12-19 00:11:35 +00001288 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
drh51669862004-12-18 18:40:26 +00001289 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEqColumn + ((score&4)!=0), cont);
drh9012bcb2004-12-19 00:11:35 +00001290 if( omitTable ){
1291 haveRowid = 0;
drh487ab3c2001-11-08 00:45:21 +00001292 }else{
drh9012bcb2004-12-19 00:11:35 +00001293 sqlite3VdbeAddOp(v, OP_IdxRecno, iIdxCur, 0);
1294 haveRowid = 1;
drh487ab3c2001-11-08 00:45:21 +00001295 }
1296
1297 /* Record the instruction used to terminate the loop.
1298 */
drhc045ec52002-12-04 20:01:06 +00001299 pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
drh9012bcb2004-12-19 00:11:35 +00001300 pLevel->p1 = iIdxCur;
drh487ab3c2001-11-08 00:45:21 +00001301 pLevel->p2 = start;
drh75897232000-05-29 14:26:00 +00001302 }
drh6a3ea0e2003-05-02 14:32:12 +00001303 loopMask |= getMask(&maskSet, iCur);
drh75897232000-05-29 14:26:00 +00001304
1305 /* Insert code to test every subexpression that can be completely
1306 ** computed using the current set of tables.
1307 */
drh193bd772004-07-20 18:23:14 +00001308 for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
1309 if( pTerm->p==0 ) continue;
1310 if( (pTerm->prereqAll & loopMask)!=pTerm->prereqAll ) continue;
1311 if( pLevel->iLeftJoin && !ExprHasProperty(pTerm->p,EP_FromJoin) ){
drh1f162302002-10-27 19:35:33 +00001312 continue;
1313 }
drh9012bcb2004-12-19 00:11:35 +00001314 if( haveRowid ){
1315 haveRowid = 0;
1316 if( omitTable ){
1317 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1318 }else{
1319 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
1320 }
drh75897232000-05-29 14:26:00 +00001321 }
drh193bd772004-07-20 18:23:14 +00001322 sqlite3ExprIfFalse(pParse, pTerm->p, cont, 1);
1323 pTerm->p = 0;
drh75897232000-05-29 14:26:00 +00001324 }
1325 brk = cont;
drhad2d8302002-05-24 20:31:36 +00001326
1327 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1328 ** at least one row of the right table has matched the left table.
1329 */
1330 if( pLevel->iLeftJoin ){
danielk19774adee202004-05-08 08:23:19 +00001331 pLevel->top = sqlite3VdbeCurrentAddr(v);
1332 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1333 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001334 VdbeComment((v, "# record LEFT JOIN hit"));
drh193bd772004-07-20 18:23:14 +00001335 for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
1336 if( pTerm->p==0 ) continue;
1337 if( (pTerm->prereqAll & loopMask)!=pTerm->prereqAll ) continue;
drh9012bcb2004-12-19 00:11:35 +00001338 if( haveRowid ){
1339 /* Cannot happen. "haveRowid" can only be true if pushKey is true
drh3b167c72002-06-28 12:18:47 +00001340 ** an pushKey can only be true for DELETE and UPDATE and there are
1341 ** no outer joins with DELETE and UPDATE.
1342 */
drh9012bcb2004-12-19 00:11:35 +00001343 assert( 0 );
1344 haveRowid = 0;
drh7cf6e4d2004-05-19 14:56:55 +00001345 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh1cc093c2002-06-24 22:01:57 +00001346 }
drh193bd772004-07-20 18:23:14 +00001347 sqlite3ExprIfFalse(pParse, pTerm->p, cont, 1);
1348 pTerm->p = 0;
drh1cc093c2002-06-24 22:01:57 +00001349 }
drhad2d8302002-05-24 20:31:36 +00001350 }
drh9012bcb2004-12-19 00:11:35 +00001351
1352 if( haveRowid && (i<pTabList->nSrc-1 || !pushKey) ){
1353 haveRowid = 0;
1354 if( omitTable ){
1355 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1356 }else{
1357 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
1358 }
1359 }
drh75897232000-05-29 14:26:00 +00001360 }
1361 pWInfo->iContinue = cont;
drh9012bcb2004-12-19 00:11:35 +00001362 if( pushKey && !haveRowid ){
danielk19774adee202004-05-08 08:23:19 +00001363 sqlite3VdbeAddOp(v, OP_Recno, pTabList->a[0].iCursor, 0);
drh75897232000-05-29 14:26:00 +00001364 }
drh6a3ea0e2003-05-02 14:32:12 +00001365 freeMaskSet(&maskSet);
drh75897232000-05-29 14:26:00 +00001366 return pWInfo;
1367}
1368
1369/*
drhc27a1ce2002-06-14 20:58:45 +00001370** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00001371** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001372*/
danielk19774adee202004-05-08 08:23:19 +00001373void sqlite3WhereEnd(WhereInfo *pWInfo){
drh75897232000-05-29 14:26:00 +00001374 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001375 int i;
drh6b563442001-11-07 16:48:26 +00001376 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001377 SrcList *pTabList = pWInfo->pTabList;
drh9012bcb2004-12-19 00:11:35 +00001378 struct SrcList_item *pTabItem;
drh19a775c2000-06-05 18:54:46 +00001379
drh9012bcb2004-12-19 00:11:35 +00001380 /* Generate loop termination code.
1381 */
drhad3cab52002-05-24 02:04:32 +00001382 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001383 pLevel = &pWInfo->a[i];
danielk19774adee202004-05-08 08:23:19 +00001384 sqlite3VdbeResolveLabel(v, pLevel->cont);
drh6b563442001-11-07 16:48:26 +00001385 if( pLevel->op!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001386 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001387 }
danielk19774adee202004-05-08 08:23:19 +00001388 sqlite3VdbeResolveLabel(v, pLevel->brk);
drhd99f7062002-06-08 23:25:08 +00001389 if( pLevel->inOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001390 sqlite3VdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
drhd99f7062002-06-08 23:25:08 +00001391 }
drhad2d8302002-05-24 20:31:36 +00001392 if( pLevel->iLeftJoin ){
1393 int addr;
danielk19774adee202004-05-08 08:23:19 +00001394 addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh9012bcb2004-12-19 00:11:35 +00001395 sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
danielk19774adee202004-05-08 08:23:19 +00001396 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
drh9012bcb2004-12-19 00:11:35 +00001397 if( pLevel->iIdxCur>=0 ){
1398 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
drh7f09b3e2002-08-13 13:15:49 +00001399 }
danielk19774adee202004-05-08 08:23:19 +00001400 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
drhad2d8302002-05-24 20:31:36 +00001401 }
drh19a775c2000-06-05 18:54:46 +00001402 }
drh9012bcb2004-12-19 00:11:35 +00001403
1404 /* The "break" point is here, just past the end of the outer loop.
1405 ** Set it.
1406 */
danielk19774adee202004-05-08 08:23:19 +00001407 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00001408
1409 /* Close all of the cursors
1410 */
1411 pLevel = pWInfo->a;
1412 pTabItem = pTabList->a;
1413 for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
1414 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00001415 assert( pTab!=0 );
1416 if( pTab->isTransient || pTab->pSelect ) continue;
drh9012bcb2004-12-19 00:11:35 +00001417 if( (pLevel->score & 1)==0 ){
1418 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
1419 }
drh6b563442001-11-07 16:48:26 +00001420 if( pLevel->pIdx!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001421 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
1422 }
1423
1424 /* Make all cursor substitutions for cases where we want to use
1425 ** just the index and never reference the table.
1426 **
1427 ** Calls to the code generator in between sqlite3WhereBegin and
1428 ** sqlite3WhereEnd will have created code that references the table
1429 ** directly. This loop scans all that code looking for opcodes
1430 ** that reference the table and converts them into opcodes that
1431 ** reference the index.
1432 */
1433 if( pLevel->score & 1 ){
1434 int i, j, last;
1435 VdbeOp *pOp;
1436 Index *pIdx = pLevel->pIdx;
1437
1438 assert( pIdx!=0 );
1439 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1440 last = sqlite3VdbeCurrentAddr(v);
1441 for(i=pWInfo->iTop; i<last; i++, pOp++){
1442 if( pOp->p1!=pLevel->iTabCur ) continue;
1443 if( pOp->opcode==OP_Column ){
1444 pOp->p1 = pLevel->iIdxCur;
1445 for(j=0; j<pIdx->nColumn; j++){
1446 if( pOp->p2==pIdx->aiColumn[j] ){
1447 pOp->p2 = j;
1448 break;
1449 }
1450 }
1451 }else if( pOp->opcode==OP_Recno ){
1452 pOp->p1 = pLevel->iIdxCur;
1453 pOp->opcode = OP_IdxRecno;
1454 }
1455 }
drh6b563442001-11-07 16:48:26 +00001456 }
drh19a775c2000-06-05 18:54:46 +00001457 }
drh9012bcb2004-12-19 00:11:35 +00001458
1459 /* Final cleanup
1460 */
drh75897232000-05-29 14:26:00 +00001461 sqliteFree(pWInfo);
1462 return;
1463}