blob: 14f39190049cb833de6fd905455980f3878b6bc4 [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**
drh9170dd72005-07-08 17:13:46 +000019** $Id: where.c,v 1.142 2005/07/08 17:13:47 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*/
danielk1977b3bce662005-01-29 08:32:43 +0000194static Bitmask exprListTableUsage(ExprMaskSet *, ExprList *);
drh51669862004-12-18 18:40:26 +0000195static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
196 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000197 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000198 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000199 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000200 return mask;
drh75897232000-05-29 14:26:00 +0000201 }
danielk1977b3bce662005-01-29 08:32:43 +0000202 mask = exprTableUsage(pMaskSet, p->pRight);
203 mask |= exprTableUsage(pMaskSet, p->pLeft);
204 mask |= exprListTableUsage(pMaskSet, p->pList);
205 if( p->pSelect ){
206 Select *pS = p->pSelect;
207 mask |= exprListTableUsage(pMaskSet, pS->pEList);
208 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
209 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
210 mask |= exprTableUsage(pMaskSet, pS->pWhere);
211 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drh75897232000-05-29 14:26:00 +0000212 }
danielk1977b3bce662005-01-29 08:32:43 +0000213 return mask;
214}
215static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
216 int i;
217 Bitmask mask = 0;
218 if( pList ){
219 for(i=0; i<pList->nExpr; i++){
220 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000221 }
222 }
drh75897232000-05-29 14:26:00 +0000223 return mask;
224}
225
226/*
drh487ab3c2001-11-08 00:45:21 +0000227** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000228** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000229** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000230*/
231static int allowedOp(int op){
drh9a432672004-10-04 13:38:09 +0000232 assert( TK_GT==TK_LE-1 && TK_LE==TK_LT-1 && TK_LT==TK_GE-1 && TK_EQ==TK_GT-1);
233 return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
drh487ab3c2001-11-08 00:45:21 +0000234}
235
236/*
drh51669862004-12-18 18:40:26 +0000237** Swap two objects of type T.
drh193bd772004-07-20 18:23:14 +0000238*/
239#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
240
241/*
242** Return the index in the SrcList that uses cursor iCur. If iCur is
243** used by the first entry in SrcList return 0. If iCur is used by
244** the second entry return 1. And so forth.
245**
246** SrcList is the set of tables in the FROM clause in the order that
247** they will be processed. The value returned here gives us an index
248** of which tables will be processed first.
249*/
250static int tableOrder(SrcList *pList, int iCur){
251 int i;
drh51669862004-12-18 18:40:26 +0000252 struct SrcList_item *pItem;
253 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
254 if( pItem->iCursor==iCur ) return i;
drh193bd772004-07-20 18:23:14 +0000255 }
256 return -1;
257}
258
259/*
drh75897232000-05-29 14:26:00 +0000260** The input to this routine is an ExprInfo structure with only the
261** "p" field filled in. The job of this routine is to analyze the
262** subexpression and populate all the other fields of the ExprInfo
263** structure.
264*/
drh193bd772004-07-20 18:23:14 +0000265static void exprAnalyze(SrcList *pSrc, ExprMaskSet *pMaskSet, ExprInfo *pInfo){
drh75897232000-05-29 14:26:00 +0000266 Expr *pExpr = pInfo->p;
drh6a3ea0e2003-05-02 14:32:12 +0000267 pInfo->prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
268 pInfo->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
269 pInfo->prereqAll = exprTableUsage(pMaskSet, pExpr);
drh75897232000-05-29 14:26:00 +0000270 pInfo->indexable = 0;
271 pInfo->idxLeft = -1;
272 pInfo->idxRight = -1;
drh487ab3c2001-11-08 00:45:21 +0000273 if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
drhd99f7062002-06-08 23:25:08 +0000274 if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
drh6a3ea0e2003-05-02 14:32:12 +0000275 pInfo->idxRight = pExpr->pRight->iTable;
drh75897232000-05-29 14:26:00 +0000276 pInfo->indexable = 1;
277 }
drh967e8b72000-06-21 13:59:10 +0000278 if( pExpr->pLeft->op==TK_COLUMN ){
drh6a3ea0e2003-05-02 14:32:12 +0000279 pInfo->idxLeft = pExpr->pLeft->iTable;
drh75897232000-05-29 14:26:00 +0000280 pInfo->indexable = 1;
281 }
282 }
drh193bd772004-07-20 18:23:14 +0000283 if( pInfo->indexable ){
284 assert( pInfo->idxLeft!=pInfo->idxRight );
285
286 /* We want the expression to be of the form "X = expr", not "expr = X".
287 ** So flip it over if necessary. If the expression is "X = Y", then
288 ** we want Y to come from an earlier table than X.
289 **
290 ** The collating sequence rule is to always choose the left expression.
291 ** So if we do a flip, we also have to move the collating sequence.
292 */
293 if( tableOrder(pSrc,pInfo->idxLeft)<tableOrder(pSrc,pInfo->idxRight) ){
294 assert( pExpr->op!=TK_IN );
295 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
296 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
drh9a432672004-10-04 13:38:09 +0000297 if( pExpr->op>=TK_GT ){
298 assert( TK_LT==TK_GT+2 );
299 assert( TK_GE==TK_LE+2 );
300 assert( TK_GT>TK_EQ );
301 assert( TK_GT<TK_LE );
302 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
303 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000304 }
305 SWAP(unsigned, pInfo->prereqLeft, pInfo->prereqRight);
306 SWAP(short int, pInfo->idxLeft, pInfo->idxRight);
307 }
308 }
309
drh75897232000-05-29 14:26:00 +0000310}
311
312/*
drh51669862004-12-18 18:40:26 +0000313** This routine decides if pIdx can be used to satisfy the ORDER BY
314** clause. If it can, it returns 1. If pIdx cannot satisfy the
315** ORDER BY clause, this routine returns 0.
316**
317** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
318** left-most table in the FROM clause of that same SELECT statement and
319** the table has a cursor number of "base". pIdx is an index on pTab.
320**
321** nEqCol is the number of columns of pIdx that are used as equality
322** constraints. Any of these columns may be missing from the ORDER BY
323** clause and the match can still be a success.
324**
325** If the index is UNIQUE, then the ORDER BY clause is allowed to have
326** additional terms past the end of the index and the match will still
327** be a success.
328**
329** All terms of the ORDER BY that match against the index must be either
330** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
331** index do not need to satisfy this constraint.) The *pbRev value is
332** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
333** the ORDER BY clause is all ASC.
334*/
335static int isSortingIndex(
336 Parse *pParse, /* Parsing context */
337 Index *pIdx, /* The index we are testing */
338 Table *pTab, /* The table to be sorted */
339 int base, /* Cursor number for pTab */
340 ExprList *pOrderBy, /* The ORDER BY clause */
341 int nEqCol, /* Number of index columns with == constraints */
342 int *pbRev /* Set to 1 if ORDER BY is DESC */
343){
344 int i, j; /* Loop counters */
345 int sortOrder; /* Which direction we are sorting */
346 int nTerm; /* Number of ORDER BY terms */
347 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
348 sqlite3 *db = pParse->db;
349
350 assert( pOrderBy!=0 );
351 nTerm = pOrderBy->nExpr;
352 assert( nTerm>0 );
353
354 /* Match terms of the ORDER BY clause against columns of
355 ** the index.
356 */
357 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
358 Expr *pExpr; /* The expression of the ORDER BY pTerm */
359 CollSeq *pColl; /* The collating sequence of pExpr */
360
361 pExpr = pTerm->pExpr;
362 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
363 /* Can not use an index sort on anything that is not a column in the
364 ** left-most table of the FROM clause */
365 return 0;
366 }
367 pColl = sqlite3ExprCollSeq(pParse, pExpr);
368 if( !pColl ) pColl = db->pDfltColl;
drh9012bcb2004-12-19 00:11:35 +0000369 if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
370 /* Term j of the ORDER BY clause does not match column i of the index */
371 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +0000372 /* If an index column that is constrained by == fails to match an
373 ** ORDER BY term, that is OK. Just ignore that column of the index
374 */
375 continue;
376 }else{
377 /* If an index column fails to match and is not constrained by ==
378 ** then the index cannot satisfy the ORDER BY constraint.
379 */
380 return 0;
381 }
382 }
383 if( i>nEqCol ){
384 if( pTerm->sortOrder!=sortOrder ){
385 /* Indices can only be used if all ORDER BY terms past the
386 ** equality constraints are all either DESC or ASC. */
387 return 0;
388 }
389 }else{
390 sortOrder = pTerm->sortOrder;
391 }
392 j++;
393 pTerm++;
394 }
395
396 /* The index can be used for sorting if all terms of the ORDER BY clause
397 ** or covered or if we ran out of index columns and the it is a UNIQUE
398 ** index.
399 */
400 if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
401 *pbRev = sortOrder==SQLITE_SO_DESC;
402 return 1;
403 }
404 return 0;
405}
406
407/*
drhb6c29892004-11-22 19:12:19 +0000408** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
409** by sorting in order of ROWID. Return true if so and set *pbRev to be
410** true for reverse ROWID and false for forward ROWID order.
411*/
412static int sortableByRowid(
413 int base, /* Cursor number for table to be sorted */
414 ExprList *pOrderBy, /* The ORDER BY clause */
415 int *pbRev /* Set to 1 if ORDER BY is DESC */
416){
417 Expr *p;
418
419 assert( pOrderBy!=0 );
420 assert( pOrderBy->nExpr>0 );
421 p = pOrderBy->a[0].pExpr;
422 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
423 *pbRev = pOrderBy->a[0].sortOrder;
424 return 1;
425 }
426 return 0;
427}
428
429
430/*
drh2ffb1182004-07-19 19:14:01 +0000431** Disable a term in the WHERE clause. Except, do not disable the term
432** if it controls a LEFT OUTER JOIN and it did not originate in the ON
433** or USING clause of that join.
434**
435** Consider the term t2.z='ok' in the following queries:
436**
437** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
438** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
439** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
440**
drh23bf66d2004-12-14 03:34:34 +0000441** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +0000442** in the ON clause. The term is disabled in (3) because it is not part
443** of a LEFT OUTER JOIN. In (1), the term is not disabled.
444**
445** Disabling a term causes that term to not be tested in the inner loop
446** of the join. Disabling is an optimization. We would get the correct
447** results if nothing were ever disabled, but joins might run a little
448** slower. The trick is to disable as much as we can without disabling
449** too much. If we disabled in (1), we'd get the wrong answer.
450** See ticket #813.
451*/
452static void disableTerm(WhereLevel *pLevel, Expr **ppExpr){
453 Expr *pExpr = *ppExpr;
454 if( pLevel->iLeftJoin==0 || ExprHasProperty(pExpr, EP_FromJoin) ){
455 *ppExpr = 0;
456 }
457}
458
459/*
drh94a11212004-09-25 13:12:14 +0000460** Generate code that builds a probe for an index. Details:
461**
462** * Check the top nColumn entries on the stack. If any
463** of those entries are NULL, jump immediately to brk,
464** which is the loop exit, since no index entry will match
465** if any part of the key is NULL.
466**
467** * Construct a probe entry from the top nColumn entries in
468** the stack with affinities appropriate for index pIdx.
469*/
470static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
471 sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
472 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
473 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
474 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
475 sqlite3IndexAffinityStr(v, pIdx);
476}
477
478/*
479** Generate code for an equality term of the WHERE clause. An equality
480** term can be either X=expr or X IN (...). pTerm is the X.
481*/
482static void codeEqualityTerm(
483 Parse *pParse, /* The parsing context */
484 ExprInfo *pTerm, /* The term of the WHERE clause to be coded */
485 int brk, /* Jump here to abandon the loop */
486 WhereLevel *pLevel /* When level of the FROM clause we are working on */
487){
488 Expr *pX = pTerm->p;
489 if( pX->op!=TK_IN ){
490 assert( pX->op==TK_EQ );
491 sqlite3ExprCode(pParse, pX->pRight);
danielk1977b3bce662005-01-29 08:32:43 +0000492#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +0000493 }else{
danielk1977b3bce662005-01-29 08:32:43 +0000494 int iTab;
drh94a11212004-09-25 13:12:14 +0000495 Vdbe *v = pParse->pVdbe;
danielk1977b3bce662005-01-29 08:32:43 +0000496
497 sqlite3CodeSubselect(pParse, pX);
498 iTab = pX->iTable;
drh94a11212004-09-25 13:12:14 +0000499 sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
danielk1977b3bce662005-01-29 08:32:43 +0000500 VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
drh9012bcb2004-12-19 00:11:35 +0000501 pLevel->inP2 = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
drh94a11212004-09-25 13:12:14 +0000502 pLevel->inOp = OP_Next;
503 pLevel->inP1 = iTab;
danielk1977b3bce662005-01-29 08:32:43 +0000504#endif
drh94a11212004-09-25 13:12:14 +0000505 }
506 disableTerm(pLevel, &pTerm->p);
507}
508
drh51669862004-12-18 18:40:26 +0000509/*
drh9170dd72005-07-08 17:13:46 +0000510** The number of bits in a Bitmask. "BMS" means "BitMask Size".
drh51669862004-12-18 18:40:26 +0000511*/
512#define BMS (sizeof(Bitmask)*8-1)
513
drh94a11212004-09-25 13:12:14 +0000514
515/*
drhe3184742002-06-19 14:27:05 +0000516** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +0000517** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +0000518** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +0000519** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +0000520** in order to complete the WHERE clause processing.
521**
522** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +0000523**
524** The basic idea is to do a nested loop, one loop for each table in
525** the FROM clause of a select. (INSERT and UPDATE statements are the
526** same as a SELECT with only a single table in the FROM clause.) For
527** example, if the SQL is this:
528**
529** SELECT * FROM t1, t2, t3 WHERE ...;
530**
531** Then the code generated is conceptually like the following:
532**
533** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000534** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +0000535** foreach row3 in t3 do /
536** ...
537** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000538** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +0000539** end /
540**
541** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +0000542** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
543** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +0000544** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +0000545**
drhe6f85e72004-12-25 01:03:13 +0000546** The code that sqlite3WhereBegin() generates leaves the cursors named
547** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +0000548** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +0000549** data from the various tables of the loop.
550**
drhc27a1ce2002-06-14 20:58:45 +0000551** If the WHERE clause is empty, the foreach loops must each scan their
552** entire tables. Thus a three-way join is an O(N^3) operation. But if
553** the tables have indices and there are terms in the WHERE clause that
554** refer to those indices, a complete table scan can be avoided and the
555** code will run much faster. Most of the work of this routine is checking
556** to see if there are indices that can be used to speed up the loop.
557**
558** Terms of the WHERE clause are also used to limit which rows actually
559** make it to the "..." in the middle of the loop. After each "foreach",
560** terms of the WHERE clause that use only terms in that loop and outer
561** loops are evaluated and if false a jump is made around all subsequent
562** inner loops (or around the "..." if the test occurs within the inner-
563** most loop)
564**
565** OUTER JOINS
566**
567** An outer join of tables t1 and t2 is conceptally coded as follows:
568**
569** foreach row1 in t1 do
570** flag = 0
571** foreach row2 in t2 do
572** start:
573** ...
574** flag = 1
575** end
drhe3184742002-06-19 14:27:05 +0000576** if flag==0 then
577** move the row2 cursor to a null row
578** goto start
579** fi
drhc27a1ce2002-06-14 20:58:45 +0000580** end
581**
drhe3184742002-06-19 14:27:05 +0000582** ORDER BY CLAUSE PROCESSING
583**
584** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
585** if there is one. If there is no ORDER BY clause or if this routine
586** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
587**
588** If an index can be used so that the natural output order of the table
589** scan is correct for the ORDER BY clause, then that index is used and
590** *ppOrderBy is set to NULL. This is an optimization that prevents an
591** unnecessary sort of the result set if an index appropriate for the
592** ORDER BY clause already exists.
593**
594** If the where clause loops cannot be arranged to provide the correct
595** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +0000596*/
danielk19774adee202004-05-08 08:23:19 +0000597WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +0000598 Parse *pParse, /* The parser context */
599 SrcList *pTabList, /* A list of all tables to be scanned */
600 Expr *pWhere, /* The WHERE clause */
drhf8db1bc2005-04-22 02:38:37 +0000601 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +0000602){
603 int i; /* Loop counter */
604 WhereInfo *pWInfo; /* Will become the return value of this function */
605 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhd4f5ee22003-07-16 00:54:31 +0000606 int brk, cont = 0; /* Addresses used during code generation */
drh75897232000-05-29 14:26:00 +0000607 int nExpr; /* Number of subexpressions in the WHERE clause */
drh51669862004-12-18 18:40:26 +0000608 Bitmask loopMask; /* One bit set for each outer loop */
drh193bd772004-07-20 18:23:14 +0000609 ExprInfo *pTerm; /* A single term in the WHERE clause; ptr to aExpr[] */
drh6a3ea0e2003-05-02 14:32:12 +0000610 ExprMaskSet maskSet; /* The expression mask set */
drh51669862004-12-18 18:40:26 +0000611 int iDirectEq[BMS]; /* Term of the form ROWID==X for the N-th table */
612 int iDirectLt[BMS]; /* Term of the form ROWID<X or ROWID<=X */
613 int iDirectGt[BMS]; /* Term of the form ROWID>X or ROWID>=X */
drh193bd772004-07-20 18:23:14 +0000614 ExprInfo aExpr[101]; /* The WHERE clause is divided into these terms */
drh9012bcb2004-12-19 00:11:35 +0000615 struct SrcList_item *pTabItem; /* A single entry from pTabList */
616 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh75897232000-05-29 14:26:00 +0000617
drh1398ad32005-01-19 23:24:50 +0000618 /* The number of terms in the FROM clause is limited by the number of
619 ** bits in a Bitmask
620 */
621 if( pTabList->nSrc>sizeof(Bitmask)*8 ){
622 sqlite3ErrorMsg(pParse, "at most %d tables in a join",
623 sizeof(Bitmask)*8);
624 return 0;
625 }
626
drh83dcb1a2002-06-28 01:02:38 +0000627 /* Split the WHERE clause into separate subexpressions where each
628 ** subexpression is separated by an AND operator. If the aExpr[]
629 ** array fills up, the last entry might point to an expression which
630 ** contains additional unfactored AND operators.
631 */
drh6a3ea0e2003-05-02 14:32:12 +0000632 initMaskSet(&maskSet);
drh83dcb1a2002-06-28 01:02:38 +0000633 memset(aExpr, 0, sizeof(aExpr));
634 nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
635 if( nExpr==ARRAYSIZE(aExpr) ){
danielk19774adee202004-05-08 08:23:19 +0000636 sqlite3ErrorMsg(pParse, "WHERE clause too complex - no more "
drhf7a9e1a2004-02-22 18:40:56 +0000637 "than %d terms allowed", (int)ARRAYSIZE(aExpr)-1);
drh83dcb1a2002-06-28 01:02:38 +0000638 return 0;
639 }
drh1398ad32005-01-19 23:24:50 +0000640
drh75897232000-05-29 14:26:00 +0000641 /* Allocate and initialize the WhereInfo structure that will become the
642 ** return value.
643 */
drhad3cab52002-05-24 02:04:32 +0000644 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
danielk1977132872b2004-05-10 10:37:18 +0000645 if( sqlite3_malloc_failed ){
danielk1977d5d56522005-03-16 12:15:20 +0000646 sqliteFree(pWInfo); /* Avoid leaking memory when malloc fails */
drh75897232000-05-29 14:26:00 +0000647 return 0;
648 }
649 pWInfo->pParse = pParse;
650 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +0000651 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh08192d52002-04-30 19:20:28 +0000652
653 /* Special case: a WHERE clause that is constant. Evaluate the
654 ** expression and either jump over all of the code or fall thru.
655 */
danielk19774adee202004-05-08 08:23:19 +0000656 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
657 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +0000658 pWhere = 0;
drh08192d52002-04-30 19:20:28 +0000659 }
drh75897232000-05-29 14:26:00 +0000660
drh75897232000-05-29 14:26:00 +0000661 /* Analyze all of the subexpressions.
662 */
drh1398ad32005-01-19 23:24:50 +0000663 for(i=0; i<pTabList->nSrc; i++){
664 createMask(&maskSet, pTabList->a[i].iCursor);
665 }
drh193bd772004-07-20 18:23:14 +0000666 for(pTerm=aExpr, i=0; i<nExpr; i++, pTerm++){
drh193bd772004-07-20 18:23:14 +0000667 exprAnalyze(pTabList, &maskSet, pTerm);
drh75897232000-05-29 14:26:00 +0000668 }
669
drh75897232000-05-29 14:26:00 +0000670 /* Figure out what index to use (if any) for each nested loop.
drh6b563442001-11-07 16:48:26 +0000671 ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
drhad3cab52002-05-24 02:04:32 +0000672 ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
drh8aff1012001-12-22 14:49:24 +0000673 ** loop.
674 **
675 ** If terms exist that use the ROWID of any table, then set the
676 ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
677 ** to the index of the term containing the ROWID. We always prefer
678 ** to use a ROWID which can directly access a table rather than an
drh0a36c572002-02-18 22:49:59 +0000679 ** index which requires reading an index first to get the rowid then
680 ** doing a second read of the actual database table.
drh75897232000-05-29 14:26:00 +0000681 **
682 ** Actually, if there are more than 32 tables in the join, only the
drh0a36c572002-02-18 22:49:59 +0000683 ** first 32 tables are candidates for indices. This is (again) due
684 ** to the limit of 32 bits in an integer bitmask.
drh75897232000-05-29 14:26:00 +0000685 */
686 loopMask = 0;
drh9012bcb2004-12-19 00:11:35 +0000687 pTabItem = pTabList->a;
688 pLevel = pWInfo->a;
689 for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++,pTabItem++,pLevel++){
drhc4a3c772001-04-04 11:48:57 +0000690 int j;
drh9012bcb2004-12-19 00:11:35 +0000691 int iCur = pTabItem->iCursor; /* The cursor for this table */
drh51669862004-12-18 18:40:26 +0000692 Bitmask mask = getMask(&maskSet, iCur); /* Cursor mask for this table */
drh9012bcb2004-12-19 00:11:35 +0000693 Table *pTab = pTabItem->pTab;
drh75897232000-05-29 14:26:00 +0000694 Index *pIdx;
695 Index *pBestIdx = 0;
drh487ab3c2001-11-08 00:45:21 +0000696 int bestScore = 0;
drh51669862004-12-18 18:40:26 +0000697 int bestRev = 0;
drh75897232000-05-29 14:26:00 +0000698
drhc4a3c772001-04-04 11:48:57 +0000699 /* Check to see if there is an expression that uses only the
drh8aff1012001-12-22 14:49:24 +0000700 ** ROWID field of this table. For terms of the form ROWID==expr
701 ** set iDirectEq[i] to the index of the term. For terms of the
702 ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
703 ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
drh174b6192002-12-03 02:22:52 +0000704 **
705 ** (Added:) Treat ROWID IN expr like ROWID=expr.
drhc4a3c772001-04-04 11:48:57 +0000706 */
drh9012bcb2004-12-19 00:11:35 +0000707 pLevel->iIdxCur = -1;
drh8aff1012001-12-22 14:49:24 +0000708 iDirectEq[i] = -1;
709 iDirectLt[i] = -1;
710 iDirectGt[i] = -1;
drh193bd772004-07-20 18:23:14 +0000711 for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
712 Expr *pX = pTerm->p;
713 if( pTerm->idxLeft==iCur && pX->pLeft->iColumn<0
714 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight ){
715 switch( pX->op ){
drhd99f7062002-06-08 23:25:08 +0000716 case TK_IN:
drh8aff1012001-12-22 14:49:24 +0000717 case TK_EQ: iDirectEq[i] = j; break;
718 case TK_LE:
719 case TK_LT: iDirectLt[i] = j; break;
720 case TK_GE:
721 case TK_GT: iDirectGt[i] = j; break;
722 }
drhc4a3c772001-04-04 11:48:57 +0000723 }
drhc4a3c772001-04-04 11:48:57 +0000724 }
drhb6c29892004-11-22 19:12:19 +0000725
726 /* If we found a term that tests ROWID with == or IN, that term
727 ** will be used to locate the rows in the database table. There
drh7bac7002005-07-01 11:38:44 +0000728 ** is no need to continue into the code below that looks for
drhb6c29892004-11-22 19:12:19 +0000729 ** an index. We will always use the ROWID over an index.
730 */
drh8aff1012001-12-22 14:49:24 +0000731 if( iDirectEq[i]>=0 ){
drh6a3ea0e2003-05-02 14:32:12 +0000732 loopMask |= mask;
drh94a11212004-09-25 13:12:14 +0000733 pLevel->pIdx = 0;
drhc4a3c772001-04-04 11:48:57 +0000734 continue;
735 }
736
drh75897232000-05-29 14:26:00 +0000737 /* Do a search for usable indices. Leave pBestIdx pointing to
drh487ab3c2001-11-08 00:45:21 +0000738 ** the "best" index. pBestIdx is left set to NULL if no indices
739 ** are usable.
drh75897232000-05-29 14:26:00 +0000740 **
drhacf3b982005-01-03 01:27:18 +0000741 ** The best index is the one with the highest score. The score
742 ** for the index is determined as follows. For each of the
drh487ab3c2001-11-08 00:45:21 +0000743 ** left-most terms that is fixed by an equality operator, add
drh51669862004-12-18 18:40:26 +0000744 ** 32 to the score. The right-most term of the index may be
745 ** constrained by an inequality. Add 4 if for an "x<..." constraint
746 ** and add 8 for an "x>..." constraint. If both constraints
747 ** are present, add 12.
748 **
749 ** If the left-most term of the index uses an IN operator
750 ** (ex: "x IN (...)") then add 16 to the score.
751 **
752 ** If an index can be used for sorting, add 2 to the score.
753 ** If an index contains all the terms of a table that are ever
754 ** used by any expression in the SQL statement, then add 1 to
755 ** the score.
drh487ab3c2001-11-08 00:45:21 +0000756 **
757 ** This scoring system is designed so that the score can later be
drh51669862004-12-18 18:40:26 +0000758 ** used to determine how the index is used. If the score&0x1c is 0
759 ** then all constraints are equalities. If score&0x4 is not 0 then
drh487ab3c2001-11-08 00:45:21 +0000760 ** there is an inequality used as a termination key. (ex: "x<...")
drh51669862004-12-18 18:40:26 +0000761 ** If score&0x8 is not 0 then there is an inequality used as the
762 ** start key. (ex: "x>..."). A score or 0x10 is the special case
drhc045ec52002-12-04 20:01:06 +0000763 ** of an IN operator constraint. (ex: "x IN ...").
drhd99f7062002-06-08 23:25:08 +0000764 **
drhc27a1ce2002-06-14 20:58:45 +0000765 ** The IN operator (as in "<expr> IN (...)") is treated the same as
766 ** an equality comparison except that it can only be used on the
767 ** left-most column of an index and other terms of the WHERE clause
768 ** cannot be used in conjunction with the IN operator to help satisfy
769 ** other columns of the index.
drh75897232000-05-29 14:26:00 +0000770 */
771 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh51669862004-12-18 18:40:26 +0000772 Bitmask eqMask = 0; /* Index columns covered by an x=... term */
773 Bitmask ltMask = 0; /* Index columns covered by an x<... term */
774 Bitmask gtMask = 0; /* Index columns covered by an x>... term */
775 Bitmask inMask = 0; /* Index columns covered by an x IN .. term */
776 Bitmask m;
777 int nEq, score, bRev = 0;
drh75897232000-05-29 14:26:00 +0000778
drh51669862004-12-18 18:40:26 +0000779 if( pIdx->nColumn>sizeof(eqMask)*8 ){
780 continue; /* Ignore indices with too many columns to analyze */
781 }
drh193bd772004-07-20 18:23:14 +0000782 for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
drh193bd772004-07-20 18:23:14 +0000783 Expr *pX = pTerm->p;
drh94a11212004-09-25 13:12:14 +0000784 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
drh193bd772004-07-20 18:23:14 +0000785 if( !pColl && pX->pRight ){
786 pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
danielk19770202b292004-06-09 09:55:16 +0000787 }
788 if( !pColl ){
789 pColl = pParse->db->pDfltColl;
790 }
drh193bd772004-07-20 18:23:14 +0000791 if( pTerm->idxLeft==iCur
792 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight ){
793 int iColumn = pX->pLeft->iColumn;
drh75897232000-05-29 14:26:00 +0000794 int k;
drhdd9f8b42005-05-19 01:26:14 +0000795 char idxaff = iColumn>=0 ? pIdx->pTable->aCol[iColumn].affinity : 0;
drh967e8b72000-06-21 13:59:10 +0000796 for(k=0; k<pIdx->nColumn; k++){
danielk19770202b292004-06-09 09:55:16 +0000797 /* If the collating sequences or affinities don't match,
798 ** ignore this index. */
799 if( pColl!=pIdx->keyInfo.aColl[k] ) continue;
drh193bd772004-07-20 18:23:14 +0000800 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
danielk19770202b292004-06-09 09:55:16 +0000801 if( pIdx->aiColumn[k]==iColumn ){
drh193bd772004-07-20 18:23:14 +0000802 switch( pX->op ){
drh48185c12002-06-09 01:55:20 +0000803 case TK_IN: {
804 if( k==0 ) inMask |= 1;
805 break;
806 }
drh487ab3c2001-11-08 00:45:21 +0000807 case TK_EQ: {
drh51669862004-12-18 18:40:26 +0000808 eqMask |= ((Bitmask)1)<<k;
drh487ab3c2001-11-08 00:45:21 +0000809 break;
810 }
811 case TK_LE:
812 case TK_LT: {
drh51669862004-12-18 18:40:26 +0000813 ltMask |= ((Bitmask)1)<<k;
drh487ab3c2001-11-08 00:45:21 +0000814 break;
815 }
816 case TK_GE:
817 case TK_GT: {
drh51669862004-12-18 18:40:26 +0000818 gtMask |= ((Bitmask)1)<<k;
drh487ab3c2001-11-08 00:45:21 +0000819 break;
820 }
821 default: {
822 /* CANT_HAPPEN */
823 assert( 0 );
824 break;
825 }
826 }
drh75897232000-05-29 14:26:00 +0000827 break;
828 }
829 }
830 }
drh75897232000-05-29 14:26:00 +0000831 }
drhc045ec52002-12-04 20:01:06 +0000832
833 /* The following loop ends with nEq set to the number of columns
834 ** on the left of the index with == constraints.
835 */
drh487ab3c2001-11-08 00:45:21 +0000836 for(nEq=0; nEq<pIdx->nColumn; nEq++){
drh51669862004-12-18 18:40:26 +0000837 m = (((Bitmask)1)<<(nEq+1))-1;
drh487ab3c2001-11-08 00:45:21 +0000838 if( (m & eqMask)!=m ) break;
839 }
drh51669862004-12-18 18:40:26 +0000840
drh7bac7002005-07-01 11:38:44 +0000841 /* Begin assembling the score
drh51669862004-12-18 18:40:26 +0000842 */
843 score = nEq*32; /* Base score is 32 times number of == constraints */
844 m = ((Bitmask)1)<<nEq;
845 if( m & ltMask ) score+=4; /* Increase score for a < constraint */
846 if( m & gtMask ) score+=8; /* Increase score for a > constraint */
847 if( score==0 && inMask ) score = 16; /* Default score for IN constraint */
848
849 /* Give bonus points if this index can be used for sorting
850 */
drh9012bcb2004-12-19 00:11:35 +0000851 if( i==0 && score!=16 && ppOrderBy && *ppOrderBy ){
drh51669862004-12-18 18:40:26 +0000852 int base = pTabList->a[0].iCursor;
853 if( isSortingIndex(pParse, pIdx, pTab, base, *ppOrderBy, nEq, &bRev) ){
854 score += 2;
855 }
856 }
857
drh9012bcb2004-12-19 00:11:35 +0000858 /* Check to see if we can get away with using just the index without
859 ** ever reading the table. If that is the case, then add one bonus
860 ** point to the score.
861 */
862 if( score && pTabItem->colUsed < (((Bitmask)1)<<(BMS-1)) ){
863 for(m=0, j=0; j<pIdx->nColumn; j++){
864 int x = pIdx->aiColumn[j];
865 if( x<BMS-1 ){
866 m |= ((Bitmask)1)<<x;
867 }
868 }
869 if( (pTabItem->colUsed & m)==pTabItem->colUsed ){
870 score++;
871 }
872 }
873
drh51669862004-12-18 18:40:26 +0000874 /* If the score for this index is the best we have seen so far, then
875 ** save it
876 */
drh487ab3c2001-11-08 00:45:21 +0000877 if( score>bestScore ){
878 pBestIdx = pIdx;
879 bestScore = score;
drh51669862004-12-18 18:40:26 +0000880 bestRev = bRev;
drh75897232000-05-29 14:26:00 +0000881 }
882 }
drh94a11212004-09-25 13:12:14 +0000883 pLevel->pIdx = pBestIdx;
884 pLevel->score = bestScore;
drh51669862004-12-18 18:40:26 +0000885 pLevel->bRev = bestRev;
drh6a3ea0e2003-05-02 14:32:12 +0000886 loopMask |= mask;
drh6b563442001-11-07 16:48:26 +0000887 if( pBestIdx ){
drh9012bcb2004-12-19 00:11:35 +0000888 pLevel->iIdxCur = pParse->nTab++;
drh6b563442001-11-07 16:48:26 +0000889 }
drh75897232000-05-29 14:26:00 +0000890 }
891
drhe3184742002-06-19 14:27:05 +0000892 /* Check to see if the ORDER BY clause is or can be satisfied by the
893 ** use of an index on the first table.
894 */
895 if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
drh9012bcb2004-12-19 00:11:35 +0000896 Index *pIdx; /* Index derived from the WHERE clause */
897 Table *pTab; /* Left-most table in the FROM clause */
898 int bRev = 0; /* True to reverse the output order */
899 int iCur; /* Btree-cursor that will be used by pTab */
900 WhereLevel *pLevel0 = &pWInfo->a[0];
drhe3184742002-06-19 14:27:05 +0000901
drh9012bcb2004-12-19 00:11:35 +0000902 pTab = pTabList->a[0].pTab;
903 pIdx = pLevel0->pIdx;
904 iCur = pTabList->a[0].iCursor;
905 if( pIdx==0 && sortableByRowid(iCur, *ppOrderBy, &bRev) ){
906 /* The ORDER BY clause specifies ROWID order, which is what we
907 ** were going to be doing anyway...
908 */
909 *ppOrderBy = 0;
910 pLevel0->bRev = bRev;
911 }else if( pLevel0->score==16 ){
912 /* If there is already an IN index on the left-most table,
913 ** it will not give the correct sort order.
914 ** So, pretend that no suitable index is found.
915 */
916 }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
917 /* If the left-most column is accessed using its ROWID, then do
918 ** not try to sort by index. But do delete the ORDER BY clause
919 ** if it is redundant.
920 */
921 }else if( (pLevel0->score&2)!=0 ){
922 /* The index that was selected for searching will cause rows to
923 ** appear in sorted order.
924 */
925 *ppOrderBy = 0;
drh75897232000-05-29 14:26:00 +0000926 }
927 }
928
drh9012bcb2004-12-19 00:11:35 +0000929 /* Open all tables in the pTabList and any indices selected for
930 ** searching those tables.
931 */
932 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
933 pLevel = pWInfo->a;
934 for(i=0, pTabItem=pTabList->a; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
935 Table *pTab;
936 Index *pIx;
937 int iIdxCur = pLevel->iIdxCur;
938
939 pTab = pTabItem->pTab;
940 if( pTab->isTransient || pTab->pSelect ) continue;
941 if( (pLevel->score & 1)==0 ){
942 sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
943 }
944 pLevel->iTabCur = pTabItem->iCursor;
945 if( (pIx = pLevel->pIdx)!=0 ){
946 sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
947 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
948 (char*)&pIx->keyInfo, P3_KEYINFO);
949 }
950 if( (pLevel->score & 1)!=0 ){
drh9012bcb2004-12-19 00:11:35 +0000951 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
952 }
953 sqlite3CodeVerifySchema(pParse, pTab->iDb);
954 }
955 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
956
drh75897232000-05-29 14:26:00 +0000957 /* Generate the code to do the search
958 */
drh75897232000-05-29 14:26:00 +0000959 loopMask = 0;
drh9012bcb2004-12-19 00:11:35 +0000960 pLevel = pWInfo->a;
961 pTabItem = pTabList->a;
962 for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
drh75897232000-05-29 14:26:00 +0000963 int j, k;
drh9012bcb2004-12-19 00:11:35 +0000964 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
965 Index *pIdx; /* The index we will be using */
966 int iIdxCur; /* The VDBE cursor for the index */
967 int omitTable; /* True if we use the index only */
968
969 pIdx = pLevel->pIdx;
970 iIdxCur = pLevel->iIdxCur;
971 pLevel->inOp = OP_Noop;
972
973 /* Check to see if it is appropriate to omit the use of the table
974 ** here and use its index instead.
975 */
976 omitTable = (pLevel->score&1)!=0;
drh75897232000-05-29 14:26:00 +0000977
drhad2d8302002-05-24 20:31:36 +0000978 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +0000979 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +0000980 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +0000981 */
982 if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
983 if( !pParse->nMem ) pParse->nMem++;
984 pLevel->iLeftJoin = pParse->nMem++;
drhf0863fe2005-06-12 21:35:51 +0000985 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000986 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +0000987 VdbeComment((v, "# init LEFT JOIN no-match flag"));
drhad2d8302002-05-24 20:31:36 +0000988 }
989
drh94a11212004-09-25 13:12:14 +0000990 if( i<ARRAYSIZE(iDirectEq) && (k = iDirectEq[i])>=0 ){
drh8aff1012001-12-22 14:49:24 +0000991 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +0000992 ** equality comparison against the ROWID field. Or
993 ** we reference multiple rows using a "rowid IN (...)"
994 ** construct.
drhc4a3c772001-04-04 11:48:57 +0000995 */
drh8aff1012001-12-22 14:49:24 +0000996 assert( k<nExpr );
drh193bd772004-07-20 18:23:14 +0000997 pTerm = &aExpr[k];
998 assert( pTerm->p!=0 );
drh193bd772004-07-20 18:23:14 +0000999 assert( pTerm->idxLeft==iCur );
drh9012bcb2004-12-19 00:11:35 +00001000 assert( omitTable==0 );
drh94a11212004-09-25 13:12:14 +00001001 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1002 codeEqualityTerm(pParse, pTerm, brk, pLevel);
danielk19774adee202004-05-08 08:23:19 +00001003 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1004 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
danielk19774adee202004-05-08 08:23:19 +00001005 sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001006 VdbeComment((v, "pk"));
drh6b563442001-11-07 16:48:26 +00001007 pLevel->op = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001008 }else if( pIdx!=0 && pLevel->score>3 && (pLevel->score&0x0c)==0 ){
drhc27a1ce2002-06-14 20:58:45 +00001009 /* Case 2: There is an index and all terms of the WHERE clause that
drhb6c29892004-11-22 19:12:19 +00001010 ** refer to the index using the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +00001011 */
drh6b563442001-11-07 16:48:26 +00001012 int start;
drh51669862004-12-18 18:40:26 +00001013 int nColumn = (pLevel->score+16)/32;
danielk19774adee202004-05-08 08:23:19 +00001014 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
drh772ae622004-05-19 13:13:08 +00001015
1016 /* For each column of the index, find the term of the WHERE clause that
1017 ** constraints that column. If the WHERE clause term is X=expr, then
1018 ** evaluation expr and leave the result on the stack */
drh487ab3c2001-11-08 00:45:21 +00001019 for(j=0; j<nColumn; j++){
drh193bd772004-07-20 18:23:14 +00001020 for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
1021 Expr *pX = pTerm->p;
drhd99f7062002-06-08 23:25:08 +00001022 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001023 if( pTerm->idxLeft==iCur
1024 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drhd99f7062002-06-08 23:25:08 +00001025 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drhac931eb2005-01-11 18:13:56 +00001026 && (pX->op==TK_EQ || pX->op==TK_IN)
drh75897232000-05-29 14:26:00 +00001027 ){
danielk1977e014a832004-05-17 10:48:57 +00001028 char idxaff = pIdx->pTable->aCol[pX->pLeft->iColumn].affinity;
drh94a11212004-09-25 13:12:14 +00001029 if( sqlite3IndexAffinityOk(pX, idxaff) ){
1030 codeEqualityTerm(pParse, pTerm, brk, pLevel);
1031 break;
drhd99f7062002-06-08 23:25:08 +00001032 }
drh75897232000-05-29 14:26:00 +00001033 }
drh75897232000-05-29 14:26:00 +00001034 }
1035 }
drh6b563442001-11-07 16:48:26 +00001036 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001037 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drh94a11212004-09-25 13:12:14 +00001038 buildIndexProbe(v, nColumn, brk, pIdx);
danielk19773d1bfea2004-05-14 11:00:53 +00001039 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
drh772ae622004-05-19 13:13:08 +00001040
drh772ae622004-05-19 13:13:08 +00001041 /* Generate code (1) to move to the first matching element of the table.
1042 ** Then generate code (2) that jumps to "brk" after the cursor is past
1043 ** the last matching element of the table. The code (1) is executed
1044 ** once to initialize the search, the code (2) is executed before each
1045 ** iteration of the scan to see if the scan has finished. */
drhc045ec52002-12-04 20:01:06 +00001046 if( pLevel->bRev ){
1047 /* Scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001048 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001049 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001050 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001051 pLevel->op = OP_Prev;
1052 }else{
1053 /* Scan in the forward order */
drh9012bcb2004-12-19 00:11:35 +00001054 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001055 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001056 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
drhc045ec52002-12-04 20:01:06 +00001057 pLevel->op = OP_Next;
1058 }
drh9012bcb2004-12-19 00:11:35 +00001059 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001060 sqlite3VdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
drhe6f85e72004-12-25 01:03:13 +00001061 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001062 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001063 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh75897232000-05-29 14:26:00 +00001064 }
drh9012bcb2004-12-19 00:11:35 +00001065 pLevel->p1 = iIdxCur;
drh6b563442001-11-07 16:48:26 +00001066 pLevel->p2 = start;
drh8aff1012001-12-22 14:49:24 +00001067 }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
1068 /* Case 3: We have an inequality comparison against the ROWID field.
1069 */
1070 int testOp = OP_Noop;
1071 int start;
drhb6c29892004-11-22 19:12:19 +00001072 int bRev = pLevel->bRev;
drh8aff1012001-12-22 14:49:24 +00001073
drh9012bcb2004-12-19 00:11:35 +00001074 assert( omitTable==0 );
danielk19774adee202004-05-08 08:23:19 +00001075 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1076 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drhb6c29892004-11-22 19:12:19 +00001077 if( bRev ){
1078 int t = iDirectGt[i];
1079 iDirectGt[i] = iDirectLt[i];
1080 iDirectLt[i] = t;
1081 }
drh8aff1012001-12-22 14:49:24 +00001082 if( iDirectGt[i]>=0 ){
drh94a11212004-09-25 13:12:14 +00001083 Expr *pX;
drh8aff1012001-12-22 14:49:24 +00001084 k = iDirectGt[i];
1085 assert( k<nExpr );
drh193bd772004-07-20 18:23:14 +00001086 pTerm = &aExpr[k];
drh94a11212004-09-25 13:12:14 +00001087 pX = pTerm->p;
1088 assert( pX!=0 );
drh193bd772004-07-20 18:23:14 +00001089 assert( pTerm->idxLeft==iCur );
drh94a11212004-09-25 13:12:14 +00001090 sqlite3ExprCode(pParse, pX->pRight);
danielk1977d0a69322005-02-02 01:10:44 +00001091 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
drhb6c29892004-11-22 19:12:19 +00001092 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001093 VdbeComment((v, "pk"));
drh193bd772004-07-20 18:23:14 +00001094 disableTerm(pLevel, &pTerm->p);
drh8aff1012001-12-22 14:49:24 +00001095 }else{
drhb6c29892004-11-22 19:12:19 +00001096 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
drh8aff1012001-12-22 14:49:24 +00001097 }
1098 if( iDirectLt[i]>=0 ){
drh94a11212004-09-25 13:12:14 +00001099 Expr *pX;
drh8aff1012001-12-22 14:49:24 +00001100 k = iDirectLt[i];
1101 assert( k<nExpr );
drh193bd772004-07-20 18:23:14 +00001102 pTerm = &aExpr[k];
drh94a11212004-09-25 13:12:14 +00001103 pX = pTerm->p;
1104 assert( pX!=0 );
drh193bd772004-07-20 18:23:14 +00001105 assert( pTerm->idxLeft==iCur );
drh94a11212004-09-25 13:12:14 +00001106 sqlite3ExprCode(pParse, pX->pRight);
drh8aff1012001-12-22 14:49:24 +00001107 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001108 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drh94a11212004-09-25 13:12:14 +00001109 if( pX->op==TK_LT || pX->op==TK_GT ){
drhb6c29892004-11-22 19:12:19 +00001110 testOp = bRev ? OP_Le : OP_Ge;
drh8aff1012001-12-22 14:49:24 +00001111 }else{
drhb6c29892004-11-22 19:12:19 +00001112 testOp = bRev ? OP_Lt : OP_Gt;
drh8aff1012001-12-22 14:49:24 +00001113 }
drh193bd772004-07-20 18:23:14 +00001114 disableTerm(pLevel, &pTerm->p);
drh8aff1012001-12-22 14:49:24 +00001115 }
danielk19774adee202004-05-08 08:23:19 +00001116 start = sqlite3VdbeCurrentAddr(v);
drhb6c29892004-11-22 19:12:19 +00001117 pLevel->op = bRev ? OP_Prev : OP_Next;
drh6a3ea0e2003-05-02 14:32:12 +00001118 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001119 pLevel->p2 = start;
1120 if( testOp!=OP_Noop ){
drhf0863fe2005-06-12 21:35:51 +00001121 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001122 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drhf0863fe2005-06-12 21:35:51 +00001123 sqlite3VdbeAddOp(v, testOp, 'n', brk);
drh8aff1012001-12-22 14:49:24 +00001124 }
drh8aff1012001-12-22 14:49:24 +00001125 }else if( pIdx==0 ){
drhc27a1ce2002-06-14 20:58:45 +00001126 /* Case 4: There is no usable index. We must do a complete
drh8aff1012001-12-22 14:49:24 +00001127 ** scan of the entire database table.
1128 */
1129 int start;
drhb6c29892004-11-22 19:12:19 +00001130 int opRewind;
drh8aff1012001-12-22 14:49:24 +00001131
drh9012bcb2004-12-19 00:11:35 +00001132 assert( omitTable==0 );
danielk19774adee202004-05-08 08:23:19 +00001133 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1134 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drhb6c29892004-11-22 19:12:19 +00001135 if( pLevel->bRev ){
1136 opRewind = OP_Last;
1137 pLevel->op = OP_Prev;
1138 }else{
1139 opRewind = OP_Rewind;
1140 pLevel->op = OP_Next;
1141 }
1142 sqlite3VdbeAddOp(v, opRewind, iCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001143 start = sqlite3VdbeCurrentAddr(v);
drh6a3ea0e2003-05-02 14:32:12 +00001144 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001145 pLevel->p2 = start;
drh487ab3c2001-11-08 00:45:21 +00001146 }else{
drhc27a1ce2002-06-14 20:58:45 +00001147 /* Case 5: The WHERE clause term that refers to the right-most
1148 ** column of the index is an inequality. For example, if
1149 ** the index is on (x,y,z) and the WHERE clause is of the
1150 ** form "x=5 AND y<10" then this case is used. Only the
1151 ** right-most column can be an inequality - the rest must
1152 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +00001153 **
1154 ** This case is also used when there are no WHERE clause
1155 ** constraints but an index is selected anyway, in order
1156 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +00001157 */
1158 int score = pLevel->score;
drh51669862004-12-18 18:40:26 +00001159 int nEqColumn = score/32;
drh487ab3c2001-11-08 00:45:21 +00001160 int start;
danielk1977f7df9cc2004-06-16 12:02:47 +00001161 int leFlag=0, geFlag=0;
drh487ab3c2001-11-08 00:45:21 +00001162 int testOp;
1163
1164 /* Evaluate the equality constraints
1165 */
1166 for(j=0; j<nEqColumn; j++){
drh94a11212004-09-25 13:12:14 +00001167 int iIdxCol = pIdx->aiColumn[j];
drh193bd772004-07-20 18:23:14 +00001168 for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
drh94a11212004-09-25 13:12:14 +00001169 Expr *pX = pTerm->p;
1170 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001171 if( pTerm->idxLeft==iCur
drh94a11212004-09-25 13:12:14 +00001172 && pX->op==TK_EQ
drh193bd772004-07-20 18:23:14 +00001173 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drh94a11212004-09-25 13:12:14 +00001174 && pX->pLeft->iColumn==iIdxCol
drh487ab3c2001-11-08 00:45:21 +00001175 ){
drh94a11212004-09-25 13:12:14 +00001176 sqlite3ExprCode(pParse, pX->pRight);
drh193bd772004-07-20 18:23:14 +00001177 disableTerm(pLevel, &pTerm->p);
drh487ab3c2001-11-08 00:45:21 +00001178 break;
1179 }
1180 }
1181 }
1182
drhc27a1ce2002-06-14 20:58:45 +00001183 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +00001184 ** used twice: once to make the termination key and once to make the
1185 ** start key.
1186 */
1187 for(j=0; j<nEqColumn; j++){
danielk19774adee202004-05-08 08:23:19 +00001188 sqlite3VdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
drh487ab3c2001-11-08 00:45:21 +00001189 }
1190
drhc045ec52002-12-04 20:01:06 +00001191 /* Labels for the beginning and end of the loop
1192 */
danielk19774adee202004-05-08 08:23:19 +00001193 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1194 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
drhc045ec52002-12-04 20:01:06 +00001195
drh487ab3c2001-11-08 00:45:21 +00001196 /* Generate the termination key. This is the key value that
1197 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +00001198 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +00001199 **
1200 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1201 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +00001202 */
drh51669862004-12-18 18:40:26 +00001203 if( (score & 4)!=0 ){
drh193bd772004-07-20 18:23:14 +00001204 for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
drh94a11212004-09-25 13:12:14 +00001205 Expr *pX = pTerm->p;
1206 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001207 if( pTerm->idxLeft==iCur
drh94a11212004-09-25 13:12:14 +00001208 && (pX->op==TK_LT || pX->op==TK_LE)
drh193bd772004-07-20 18:23:14 +00001209 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drh94a11212004-09-25 13:12:14 +00001210 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh487ab3c2001-11-08 00:45:21 +00001211 ){
drh94a11212004-09-25 13:12:14 +00001212 sqlite3ExprCode(pParse, pX->pRight);
1213 leFlag = pX->op==TK_LE;
drh193bd772004-07-20 18:23:14 +00001214 disableTerm(pLevel, &pTerm->p);
drh487ab3c2001-11-08 00:45:21 +00001215 break;
1216 }
1217 }
1218 testOp = OP_IdxGE;
1219 }else{
1220 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
1221 leFlag = 1;
1222 }
1223 if( testOp!=OP_Noop ){
drh51669862004-12-18 18:40:26 +00001224 int nCol = nEqColumn + ((score & 4)!=0);
drh487ab3c2001-11-08 00:45:21 +00001225 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001226 buildIndexProbe(v, nCol, brk, pIdx);
drhc045ec52002-12-04 20:01:06 +00001227 if( pLevel->bRev ){
drh7cf6e4d2004-05-19 14:56:55 +00001228 int op = leFlag ? OP_MoveLe : OP_MoveLt;
drh9012bcb2004-12-19 00:11:35 +00001229 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001230 }else{
danielk19774adee202004-05-08 08:23:19 +00001231 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001232 }
1233 }else if( pLevel->bRev ){
drh9012bcb2004-12-19 00:11:35 +00001234 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001235 }
1236
1237 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001238 ** bound on the search. There is no start key if there are no
1239 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001240 ** that case, generate a "Rewind" instruction in place of the
1241 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001242 **
1243 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1244 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001245 */
drh51669862004-12-18 18:40:26 +00001246 if( (score & 8)!=0 ){
drh193bd772004-07-20 18:23:14 +00001247 for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
drh94a11212004-09-25 13:12:14 +00001248 Expr *pX = pTerm->p;
1249 if( pX==0 ) continue;
drh193bd772004-07-20 18:23:14 +00001250 if( pTerm->idxLeft==iCur
drh94a11212004-09-25 13:12:14 +00001251 && (pX->op==TK_GT || pX->op==TK_GE)
drh193bd772004-07-20 18:23:14 +00001252 && (pTerm->prereqRight & loopMask)==pTerm->prereqRight
drh94a11212004-09-25 13:12:14 +00001253 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh487ab3c2001-11-08 00:45:21 +00001254 ){
drh94a11212004-09-25 13:12:14 +00001255 sqlite3ExprCode(pParse, pX->pRight);
1256 geFlag = pX->op==TK_GE;
drh193bd772004-07-20 18:23:14 +00001257 disableTerm(pLevel, &pTerm->p);
drh487ab3c2001-11-08 00:45:21 +00001258 break;
1259 }
1260 }
drh7900ead2001-11-12 13:51:43 +00001261 }else{
1262 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001263 }
drh51669862004-12-18 18:40:26 +00001264 if( nEqColumn>0 || (score&8)!=0 ){
1265 int nCol = nEqColumn + ((score&8)!=0);
drh94a11212004-09-25 13:12:14 +00001266 buildIndexProbe(v, nCol, brk, pIdx);
drhc045ec52002-12-04 20:01:06 +00001267 if( pLevel->bRev ){
1268 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001269 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001270 testOp = OP_IdxLT;
1271 }else{
drh7cf6e4d2004-05-19 14:56:55 +00001272 int op = geFlag ? OP_MoveGe : OP_MoveGt;
drh9012bcb2004-12-19 00:11:35 +00001273 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001274 }
1275 }else if( pLevel->bRev ){
1276 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001277 }else{
drh9012bcb2004-12-19 00:11:35 +00001278 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001279 }
1280
1281 /* Generate the the top of the loop. If there is a termination
1282 ** key we have to test for that key and abort at the top of the
1283 ** loop.
1284 */
danielk19774adee202004-05-08 08:23:19 +00001285 start = sqlite3VdbeCurrentAddr(v);
drh487ab3c2001-11-08 00:45:21 +00001286 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001287 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001288 sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
danielk19773d1bfea2004-05-14 11:00:53 +00001289 if( (leFlag && !pLevel->bRev) || (!geFlag && pLevel->bRev) ){
1290 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
1291 }
drh487ab3c2001-11-08 00:45:21 +00001292 }
drh9012bcb2004-12-19 00:11:35 +00001293 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
drh51669862004-12-18 18:40:26 +00001294 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEqColumn + ((score&4)!=0), cont);
drhe6f85e72004-12-25 01:03:13 +00001295 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001296 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001297 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh487ab3c2001-11-08 00:45:21 +00001298 }
1299
1300 /* Record the instruction used to terminate the loop.
1301 */
drhc045ec52002-12-04 20:01:06 +00001302 pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
drh9012bcb2004-12-19 00:11:35 +00001303 pLevel->p1 = iIdxCur;
drh487ab3c2001-11-08 00:45:21 +00001304 pLevel->p2 = start;
drh75897232000-05-29 14:26:00 +00001305 }
drh6a3ea0e2003-05-02 14:32:12 +00001306 loopMask |= getMask(&maskSet, iCur);
drh75897232000-05-29 14:26:00 +00001307
1308 /* Insert code to test every subexpression that can be completely
1309 ** computed using the current set of tables.
1310 */
drh193bd772004-07-20 18:23:14 +00001311 for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
drh392e5972005-07-08 14:14:22 +00001312 Expr *pE = pTerm->p;
1313 if( pE==0 || ExprHasProperty(pE, EP_OptOnly) ) continue;
drh193bd772004-07-20 18:23:14 +00001314 if( (pTerm->prereqAll & loopMask)!=pTerm->prereqAll ) continue;
drh392e5972005-07-08 14:14:22 +00001315 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
drh1f162302002-10-27 19:35:33 +00001316 continue;
1317 }
drh392e5972005-07-08 14:14:22 +00001318 sqlite3ExprIfFalse(pParse, pE, cont, 1);
drh193bd772004-07-20 18:23:14 +00001319 pTerm->p = 0;
drh75897232000-05-29 14:26:00 +00001320 }
1321 brk = cont;
drhad2d8302002-05-24 20:31:36 +00001322
1323 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1324 ** at least one row of the right table has matched the left table.
1325 */
1326 if( pLevel->iLeftJoin ){
danielk19774adee202004-05-08 08:23:19 +00001327 pLevel->top = sqlite3VdbeCurrentAddr(v);
1328 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1329 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001330 VdbeComment((v, "# record LEFT JOIN hit"));
drh193bd772004-07-20 18:23:14 +00001331 for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
drh392e5972005-07-08 14:14:22 +00001332 Expr *pE = pTerm->p;
1333 if( pE==0 || ExprHasProperty(pE, EP_OptOnly) ) continue;
drh193bd772004-07-20 18:23:14 +00001334 if( (pTerm->prereqAll & loopMask)!=pTerm->prereqAll ) continue;
drh392e5972005-07-08 14:14:22 +00001335 sqlite3ExprIfFalse(pParse, pE, cont, 1);
drh193bd772004-07-20 18:23:14 +00001336 pTerm->p = 0;
drh1cc093c2002-06-24 22:01:57 +00001337 }
drhad2d8302002-05-24 20:31:36 +00001338 }
drh75897232000-05-29 14:26:00 +00001339 }
1340 pWInfo->iContinue = cont;
drh6a3ea0e2003-05-02 14:32:12 +00001341 freeMaskSet(&maskSet);
drh75897232000-05-29 14:26:00 +00001342 return pWInfo;
1343}
1344
1345/*
drhc27a1ce2002-06-14 20:58:45 +00001346** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00001347** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001348*/
danielk19774adee202004-05-08 08:23:19 +00001349void sqlite3WhereEnd(WhereInfo *pWInfo){
drh75897232000-05-29 14:26:00 +00001350 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001351 int i;
drh6b563442001-11-07 16:48:26 +00001352 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001353 SrcList *pTabList = pWInfo->pTabList;
drh9012bcb2004-12-19 00:11:35 +00001354 struct SrcList_item *pTabItem;
drh19a775c2000-06-05 18:54:46 +00001355
drh9012bcb2004-12-19 00:11:35 +00001356 /* Generate loop termination code.
1357 */
drhad3cab52002-05-24 02:04:32 +00001358 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001359 pLevel = &pWInfo->a[i];
danielk19774adee202004-05-08 08:23:19 +00001360 sqlite3VdbeResolveLabel(v, pLevel->cont);
drh6b563442001-11-07 16:48:26 +00001361 if( pLevel->op!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001362 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001363 }
danielk19774adee202004-05-08 08:23:19 +00001364 sqlite3VdbeResolveLabel(v, pLevel->brk);
drhd99f7062002-06-08 23:25:08 +00001365 if( pLevel->inOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001366 sqlite3VdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
drhd99f7062002-06-08 23:25:08 +00001367 }
drhad2d8302002-05-24 20:31:36 +00001368 if( pLevel->iLeftJoin ){
1369 int addr;
danielk19774adee202004-05-08 08:23:19 +00001370 addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh9012bcb2004-12-19 00:11:35 +00001371 sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
danielk19774adee202004-05-08 08:23:19 +00001372 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
drh9012bcb2004-12-19 00:11:35 +00001373 if( pLevel->iIdxCur>=0 ){
1374 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
drh7f09b3e2002-08-13 13:15:49 +00001375 }
danielk19774adee202004-05-08 08:23:19 +00001376 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
drhad2d8302002-05-24 20:31:36 +00001377 }
drh19a775c2000-06-05 18:54:46 +00001378 }
drh9012bcb2004-12-19 00:11:35 +00001379
1380 /* The "break" point is here, just past the end of the outer loop.
1381 ** Set it.
1382 */
danielk19774adee202004-05-08 08:23:19 +00001383 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00001384
drhacf3b982005-01-03 01:27:18 +00001385 /* Close all of the cursors that were opend by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00001386 */
1387 pLevel = pWInfo->a;
1388 pTabItem = pTabList->a;
1389 for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
1390 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00001391 assert( pTab!=0 );
1392 if( pTab->isTransient || pTab->pSelect ) continue;
drh9012bcb2004-12-19 00:11:35 +00001393 if( (pLevel->score & 1)==0 ){
1394 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
1395 }
drh6b563442001-11-07 16:48:26 +00001396 if( pLevel->pIdx!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001397 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
1398 }
1399
drhacf3b982005-01-03 01:27:18 +00001400 /* Make cursor substitutions for cases where we want to use
drh9012bcb2004-12-19 00:11:35 +00001401 ** just the index and never reference the table.
1402 **
1403 ** Calls to the code generator in between sqlite3WhereBegin and
1404 ** sqlite3WhereEnd will have created code that references the table
1405 ** directly. This loop scans all that code looking for opcodes
1406 ** that reference the table and converts them into opcodes that
1407 ** reference the index.
1408 */
1409 if( pLevel->score & 1 ){
1410 int i, j, last;
1411 VdbeOp *pOp;
1412 Index *pIdx = pLevel->pIdx;
1413
1414 assert( pIdx!=0 );
1415 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1416 last = sqlite3VdbeCurrentAddr(v);
1417 for(i=pWInfo->iTop; i<last; i++, pOp++){
1418 if( pOp->p1!=pLevel->iTabCur ) continue;
1419 if( pOp->opcode==OP_Column ){
1420 pOp->p1 = pLevel->iIdxCur;
1421 for(j=0; j<pIdx->nColumn; j++){
1422 if( pOp->p2==pIdx->aiColumn[j] ){
1423 pOp->p2 = j;
1424 break;
1425 }
1426 }
drhf0863fe2005-06-12 21:35:51 +00001427 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00001428 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00001429 pOp->opcode = OP_IdxRowid;
danielk19776c18b6e2005-01-30 09:17:58 +00001430 }else if( pOp->opcode==OP_NullRow ){
1431 pOp->opcode = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001432 }
1433 }
drh6b563442001-11-07 16:48:26 +00001434 }
drh19a775c2000-06-05 18:54:46 +00001435 }
drh9012bcb2004-12-19 00:11:35 +00001436
1437 /* Final cleanup
1438 */
drh75897232000-05-29 14:26:00 +00001439 sqliteFree(pWInfo);
1440 return;
1441}