blob: 7fa6f4171628ab70a4560af34e599477ade022ae [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
13** the WHERE clause of SQL statements. Also found here are subroutines
14** to generate VDBE code to evaluate expressions.
15**
drhdcd997e2003-01-31 17:21:49 +000016** $Id: where.c,v 1.72 2003/01/31 17:21:50 drh Exp $
drh75897232000-05-29 14:26:00 +000017*/
18#include "sqliteInt.h"
19
20/*
21** The query generator uses an array of instances of this structure to
22** help it analyze the subexpressions of the WHERE clause. Each WHERE
23** clause subexpression is separated from the others by an AND operator.
24*/
25typedef struct ExprInfo ExprInfo;
26struct ExprInfo {
27 Expr *p; /* Pointer to the subexpression */
drhe3184742002-06-19 14:27:05 +000028 u8 indexable; /* True if this subexprssion is usable by an index */
drh1f162302002-10-27 19:35:33 +000029 u8 oracle8join; /* -1 if left side contains "(+)". +1 if right side
30 ** contains "(+)". 0 if neither contains "(+)" */
drhe3184742002-06-19 14:27:05 +000031 short int idxLeft; /* p->pLeft is a column in this table number. -1 if
drh967e8b72000-06-21 13:59:10 +000032 ** p->pLeft is not the column of any table */
drhe3184742002-06-19 14:27:05 +000033 short int idxRight; /* p->pRight is a column in this table number. -1 if
drh967e8b72000-06-21 13:59:10 +000034 ** p->pRight is not the column of any table */
drhe3184742002-06-19 14:27:05 +000035 unsigned prereqLeft; /* Bitmask of tables referenced by p->pLeft */
36 unsigned prereqRight; /* Bitmask of tables referenced by p->pRight */
37 unsigned prereqAll; /* Bitmask of tables referenced by p */
drh75897232000-05-29 14:26:00 +000038};
39
40/*
41** Determine the number of elements in an array.
42*/
43#define ARRAYSIZE(X) (sizeof(X)/sizeof(X[0]))
44
45/*
46** This routine is used to divide the WHERE expression into subexpressions
47** separated by the AND operator.
48**
49** aSlot[] is an array of subexpressions structures.
50** There are nSlot spaces left in this array. This routine attempts to
51** split pExpr into subexpressions and fills aSlot[] with those subexpressions.
52** The return value is the number of slots filled.
53*/
54static int exprSplit(int nSlot, ExprInfo *aSlot, Expr *pExpr){
55 int cnt = 0;
56 if( pExpr==0 || nSlot<1 ) return 0;
57 if( nSlot==1 || pExpr->op!=TK_AND ){
58 aSlot[0].p = pExpr;
59 return 1;
60 }
61 if( pExpr->pLeft->op!=TK_AND ){
62 aSlot[0].p = pExpr->pLeft;
63 cnt = 1 + exprSplit(nSlot-1, &aSlot[1], pExpr->pRight);
64 }else{
drhdcd997e2003-01-31 17:21:49 +000065 cnt = exprSplit(nSlot, aSlot, pExpr->pLeft);
66 cnt += exprSplit(nSlot-cnt, &aSlot[cnt], pExpr->pRight);
drh75897232000-05-29 14:26:00 +000067 }
68 return cnt;
69}
70
71/*
72** This routine walks (recursively) an expression tree and generates
73** a bitmask indicating which tables are used in that expression
drhe3184742002-06-19 14:27:05 +000074** tree. Bit 0 of the mask is set if table base+0 is used. Bit 1
75** is set if table base+1 is used. And so forth.
drh75897232000-05-29 14:26:00 +000076**
77** In order for this routine to work, the calling function must have
78** previously invoked sqliteExprResolveIds() on the expression. See
79** the header comment on that routine for additional information.
drh19a775c2000-06-05 18:54:46 +000080**
81** "base" is the cursor number (the value of the iTable field) that
drhe3184742002-06-19 14:27:05 +000082** corresponds to the first entry in the list of tables that appear
83** in the FROM clause of a SELECT. For UPDATE and DELETE statements
84** there is just a single table with "base" as the cursor number.
drh75897232000-05-29 14:26:00 +000085*/
drh19a775c2000-06-05 18:54:46 +000086static int exprTableUsage(int base, Expr *p){
drh75897232000-05-29 14:26:00 +000087 unsigned int mask = 0;
88 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +000089 if( p->op==TK_COLUMN ){
drh19a775c2000-06-05 18:54:46 +000090 return 1<< (p->iTable - base);
drh75897232000-05-29 14:26:00 +000091 }
92 if( p->pRight ){
drh19a775c2000-06-05 18:54:46 +000093 mask = exprTableUsage(base, p->pRight);
drh75897232000-05-29 14:26:00 +000094 }
95 if( p->pLeft ){
drh19a775c2000-06-05 18:54:46 +000096 mask |= exprTableUsage(base, p->pLeft);
drh75897232000-05-29 14:26:00 +000097 }
drhdd579122002-04-02 01:58:57 +000098 if( p->pList ){
99 int i;
100 for(i=0; i<p->pList->nExpr; i++){
101 mask |= exprTableUsage(base, p->pList->a[i].pExpr);
102 }
103 }
drh75897232000-05-29 14:26:00 +0000104 return mask;
105}
106
107/*
drh487ab3c2001-11-08 00:45:21 +0000108** Return TRUE if the given operator is one of the operators that is
109** allowed for an indexable WHERE clause. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000110** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000111*/
112static int allowedOp(int op){
113 switch( op ){
114 case TK_LT:
115 case TK_LE:
116 case TK_GT:
117 case TK_GE:
118 case TK_EQ:
drhd99f7062002-06-08 23:25:08 +0000119 case TK_IN:
drh487ab3c2001-11-08 00:45:21 +0000120 return 1;
121 default:
122 return 0;
123 }
124}
125
126/*
drh75897232000-05-29 14:26:00 +0000127** The input to this routine is an ExprInfo structure with only the
128** "p" field filled in. The job of this routine is to analyze the
129** subexpression and populate all the other fields of the ExprInfo
130** structure.
drh19a775c2000-06-05 18:54:46 +0000131**
132** "base" is the cursor number (the value of the iTable field) that
drh832508b2002-03-02 17:04:07 +0000133** corresponds to the first entry in the table list.
drh75897232000-05-29 14:26:00 +0000134*/
drh19a775c2000-06-05 18:54:46 +0000135static void exprAnalyze(int base, ExprInfo *pInfo){
drh75897232000-05-29 14:26:00 +0000136 Expr *pExpr = pInfo->p;
drh19a775c2000-06-05 18:54:46 +0000137 pInfo->prereqLeft = exprTableUsage(base, pExpr->pLeft);
138 pInfo->prereqRight = exprTableUsage(base, pExpr->pRight);
drh3f6b5482002-04-02 13:26:10 +0000139 pInfo->prereqAll = exprTableUsage(base, pExpr);
drh75897232000-05-29 14:26:00 +0000140 pInfo->indexable = 0;
141 pInfo->idxLeft = -1;
142 pInfo->idxRight = -1;
drh487ab3c2001-11-08 00:45:21 +0000143 if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
drhd99f7062002-06-08 23:25:08 +0000144 if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
drh19a775c2000-06-05 18:54:46 +0000145 pInfo->idxRight = pExpr->pRight->iTable - base;
drh75897232000-05-29 14:26:00 +0000146 pInfo->indexable = 1;
147 }
drh967e8b72000-06-21 13:59:10 +0000148 if( pExpr->pLeft->op==TK_COLUMN ){
drh19a775c2000-06-05 18:54:46 +0000149 pInfo->idxLeft = pExpr->pLeft->iTable - base;
drh75897232000-05-29 14:26:00 +0000150 pInfo->indexable = 1;
151 }
152 }
153}
154
155/*
drhe3184742002-06-19 14:27:05 +0000156** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
157** left-most table in the FROM clause of that same SELECT statement and
158** the table has a cursor number of "base".
159**
160** This routine attempts to find an index for pTab that generates the
161** correct record sequence for the given ORDER BY clause. The return value
162** is a pointer to an index that does the job. NULL is returned if the
163** table has no index that will generate the correct sort order.
164**
165** If there are two or more indices that generate the correct sort order
166** and pPreferredIdx is one of those indices, then return pPreferredIdx.
drhdd4852c2002-12-04 21:50:16 +0000167**
168** nEqCol is the number of columns of pPreferredIdx that are used as
169** equality constraints. Any index returned must have exactly this same
170** set of columns. The ORDER BY clause only matches index columns beyond the
171** the first nEqCol columns.
172**
173** All terms of the ORDER BY clause must be either ASC or DESC. The
174** *pbRev value is set to 1 if the ORDER BY clause is all DESC and it is
175** set to 0 if the ORDER BY clause is all ASC.
drhe3184742002-06-19 14:27:05 +0000176*/
177static Index *findSortingIndex(
178 Table *pTab, /* The table to be sorted */
179 int base, /* Cursor number for pTab */
180 ExprList *pOrderBy, /* The ORDER BY clause */
drhc045ec52002-12-04 20:01:06 +0000181 Index *pPreferredIdx, /* Use this index, if possible and not NULL */
drhdd4852c2002-12-04 21:50:16 +0000182 int nEqCol, /* Number of index columns used with == constraints */
drhc045ec52002-12-04 20:01:06 +0000183 int *pbRev /* Set to 1 if ORDER BY is DESC */
drhe3184742002-06-19 14:27:05 +0000184){
drhdd4852c2002-12-04 21:50:16 +0000185 int i, j;
drhe3184742002-06-19 14:27:05 +0000186 Index *pMatch;
187 Index *pIdx;
drhc045ec52002-12-04 20:01:06 +0000188 int sortOrder;
drhe3184742002-06-19 14:27:05 +0000189
190 assert( pOrderBy!=0 );
191 assert( pOrderBy->nExpr>0 );
drhc045ec52002-12-04 20:01:06 +0000192 sortOrder = pOrderBy->a[0].sortOrder & SQLITE_SO_DIRMASK;
drhe3184742002-06-19 14:27:05 +0000193 for(i=0; i<pOrderBy->nExpr; i++){
194 Expr *p;
drhc045ec52002-12-04 20:01:06 +0000195 if( (pOrderBy->a[i].sortOrder & SQLITE_SO_DIRMASK)!=sortOrder ){
196 /* Indices can only be used if all ORDER BY terms are either
197 ** DESC or ASC. Indices cannot be used on a mixture. */
drhe3184742002-06-19 14:27:05 +0000198 return 0;
199 }
drhc330af12002-08-14 03:03:57 +0000200 if( (pOrderBy->a[i].sortOrder & SQLITE_SO_TYPEMASK)!=SQLITE_SO_UNK ){
201 /* Do not sort by index if there is a COLLATE clause */
202 return 0;
203 }
drhe3184742002-06-19 14:27:05 +0000204 p = pOrderBy->a[i].pExpr;
205 if( p->op!=TK_COLUMN || p->iTable!=base ){
206 /* Can not use an index sort on anything that is not a column in the
207 ** left-most table of the FROM clause */
208 return 0;
209 }
210 }
drhc045ec52002-12-04 20:01:06 +0000211
drhe3184742002-06-19 14:27:05 +0000212 /* If we get this far, it means the ORDER BY clause consists only of
213 ** ascending columns in the left-most table of the FROM clause. Now
214 ** check for a matching index.
215 */
216 pMatch = 0;
217 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drhdd4852c2002-12-04 21:50:16 +0000218 int nExpr = pOrderBy->nExpr;
219 if( pIdx->nColumn < nEqCol || pIdx->nColumn < nExpr ) continue;
220 for(i=j=0; i<nEqCol; i++){
221 if( pPreferredIdx->aiColumn[i]!=pIdx->aiColumn[i] ) break;
222 if( j<nExpr && pOrderBy->a[j].pExpr->iColumn==pIdx->aiColumn[i] ){ j++; }
drhe3184742002-06-19 14:27:05 +0000223 }
drhdd4852c2002-12-04 21:50:16 +0000224 if( i<nEqCol ) continue;
225 for(i=0; i+j<nExpr; i++){
226 if( pOrderBy->a[i+j].pExpr->iColumn!=pIdx->aiColumn[i+nEqCol] ) break;
227 }
228 if( i+j>=nExpr ){
drhe3184742002-06-19 14:27:05 +0000229 pMatch = pIdx;
230 if( pIdx==pPreferredIdx ) break;
231 }
232 }
drhc045ec52002-12-04 20:01:06 +0000233 if( pMatch && pbRev ){
234 *pbRev = sortOrder==SQLITE_SO_DESC;
235 }
drhe3184742002-06-19 14:27:05 +0000236 return pMatch;
237}
238
239/*
240** Generate the beginning of the loop used for WHERE clause processing.
drh75897232000-05-29 14:26:00 +0000241** The return value is a pointer to an (opaque) structure that contains
242** information needed to terminate the loop. Later, the calling routine
243** should invoke sqliteWhereEnd() with the return value of this function
244** in order to complete the WHERE clause processing.
245**
246** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +0000247**
248** The basic idea is to do a nested loop, one loop for each table in
249** the FROM clause of a select. (INSERT and UPDATE statements are the
250** same as a SELECT with only a single table in the FROM clause.) For
251** example, if the SQL is this:
252**
253** SELECT * FROM t1, t2, t3 WHERE ...;
254**
255** Then the code generated is conceptually like the following:
256**
257** foreach row1 in t1 do \ Code generated
258** foreach row2 in t2 do |-- by sqliteWhereBegin()
259** foreach row3 in t3 do /
260** ...
261** end \ Code generated
262** end |-- by sqliteWhereEnd()
263** end /
264**
265** There are Btree cursors associated with each table. t1 uses cursor
266** "base". t2 uses cursor "base+1". And so forth. This routine generates
267** the code to open those cursors. sqliteWhereEnd() generates the code
268** to close them.
269**
270** If the WHERE clause is empty, the foreach loops must each scan their
271** entire tables. Thus a three-way join is an O(N^3) operation. But if
272** the tables have indices and there are terms in the WHERE clause that
273** refer to those indices, a complete table scan can be avoided and the
274** code will run much faster. Most of the work of this routine is checking
275** to see if there are indices that can be used to speed up the loop.
276**
277** Terms of the WHERE clause are also used to limit which rows actually
278** make it to the "..." in the middle of the loop. After each "foreach",
279** terms of the WHERE clause that use only terms in that loop and outer
280** loops are evaluated and if false a jump is made around all subsequent
281** inner loops (or around the "..." if the test occurs within the inner-
282** most loop)
283**
284** OUTER JOINS
285**
286** An outer join of tables t1 and t2 is conceptally coded as follows:
287**
288** foreach row1 in t1 do
289** flag = 0
290** foreach row2 in t2 do
291** start:
292** ...
293** flag = 1
294** end
drhe3184742002-06-19 14:27:05 +0000295** if flag==0 then
296** move the row2 cursor to a null row
297** goto start
298** fi
drhc27a1ce2002-06-14 20:58:45 +0000299** end
300**
drhe3184742002-06-19 14:27:05 +0000301** ORDER BY CLAUSE PROCESSING
302**
303** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
304** if there is one. If there is no ORDER BY clause or if this routine
305** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
306**
307** If an index can be used so that the natural output order of the table
308** scan is correct for the ORDER BY clause, then that index is used and
309** *ppOrderBy is set to NULL. This is an optimization that prevents an
310** unnecessary sort of the result set if an index appropriate for the
311** ORDER BY clause already exists.
312**
313** If the where clause loops cannot be arranged to provide the correct
314** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +0000315*/
316WhereInfo *sqliteWhereBegin(
317 Parse *pParse, /* The parser context */
drh832508b2002-03-02 17:04:07 +0000318 int base, /* VDBE cursor index for left-most table in pTabList */
drhad3cab52002-05-24 02:04:32 +0000319 SrcList *pTabList, /* A list of all tables to be scanned */
drh75897232000-05-29 14:26:00 +0000320 Expr *pWhere, /* The WHERE clause */
drhe3184742002-06-19 14:27:05 +0000321 int pushKey, /* If TRUE, leave the table key on the stack */
322 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +0000323){
324 int i; /* Loop counter */
325 WhereInfo *pWInfo; /* Will become the return value of this function */
326 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
327 int brk, cont; /* Addresses used during code generation */
drh75897232000-05-29 14:26:00 +0000328 int nExpr; /* Number of subexpressions in the WHERE clause */
329 int loopMask; /* One bit set for each outer loop */
330 int haveKey; /* True if KEY is on the stack */
drh8aff1012001-12-22 14:49:24 +0000331 int iDirectEq[32]; /* Term of the form ROWID==X for the N-th table */
332 int iDirectLt[32]; /* Term of the form ROWID<X or ROWID<=X */
333 int iDirectGt[32]; /* Term of the form ROWID>X or ROWID>=X */
drh83dcb1a2002-06-28 01:02:38 +0000334 ExprInfo aExpr[101]; /* The WHERE clause is divided into these expressions */
drh75897232000-05-29 14:26:00 +0000335
drhc27a1ce2002-06-14 20:58:45 +0000336 /* pushKey is only allowed if there is a single table (as in an INSERT or
337 ** UPDATE statement)
338 */
339 assert( pushKey==0 || pTabList->nSrc==1 );
drh83dcb1a2002-06-28 01:02:38 +0000340
341 /* Split the WHERE clause into separate subexpressions where each
342 ** subexpression is separated by an AND operator. If the aExpr[]
343 ** array fills up, the last entry might point to an expression which
344 ** contains additional unfactored AND operators.
345 */
346 memset(aExpr, 0, sizeof(aExpr));
347 nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
348 if( nExpr==ARRAYSIZE(aExpr) ){
349 char zBuf[50];
drhfd159812003-01-11 14:25:39 +0000350 sprintf(zBuf, "%d", (int)ARRAYSIZE(aExpr)-1);
drh83dcb1a2002-06-28 01:02:38 +0000351 sqliteSetString(&pParse->zErrMsg, "WHERE clause too complex - no more "
352 "than ", zBuf, " terms allowed", 0);
353 pParse->nErr++;
354 return 0;
355 }
drhc27a1ce2002-06-14 20:58:45 +0000356
drh75897232000-05-29 14:26:00 +0000357 /* Allocate and initialize the WhereInfo structure that will become the
358 ** return value.
359 */
drhad3cab52002-05-24 02:04:32 +0000360 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
drhdaffd0e2001-04-11 14:28:42 +0000361 if( sqlite_malloc_failed ){
drhdaffd0e2001-04-11 14:28:42 +0000362 sqliteFree(pWInfo);
drh75897232000-05-29 14:26:00 +0000363 return 0;
364 }
365 pWInfo->pParse = pParse;
366 pWInfo->pTabList = pTabList;
drh832508b2002-03-02 17:04:07 +0000367 pWInfo->base = base;
368 pWInfo->peakNTab = pWInfo->savedNTab = pParse->nTab;
drh08192d52002-04-30 19:20:28 +0000369 pWInfo->iBreak = sqliteVdbeMakeLabel(v);
370
371 /* Special case: a WHERE clause that is constant. Evaluate the
372 ** expression and either jump over all of the code or fall thru.
373 */
374 if( pWhere && sqliteExprIsConstant(pWhere) ){
drhf5905aa2002-05-26 20:54:33 +0000375 sqliteExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +0000376 pWhere = 0;
drh08192d52002-04-30 19:20:28 +0000377 }
drh75897232000-05-29 14:26:00 +0000378
drh75897232000-05-29 14:26:00 +0000379 /* Analyze all of the subexpressions.
380 */
381 for(i=0; i<nExpr; i++){
drh22f70c32002-02-18 01:17:00 +0000382 exprAnalyze(base, &aExpr[i]);
drh1d1f3052002-05-21 13:18:25 +0000383
384 /* If we are executing a trigger body, remove all references to
385 ** new.* and old.* tables from the prerequisite masks.
386 */
387 if( pParse->trigStack ){
388 int x;
389 if( (x = pParse->trigStack->newIdx) >= 0 ){
390 int mask = ~(1 << (x - base));
391 aExpr[i].prereqRight &= mask;
392 aExpr[i].prereqLeft &= mask;
393 aExpr[i].prereqAll &= mask;
394 }
395 if( (x = pParse->trigStack->oldIdx) >= 0 ){
396 int mask = ~(1 << (x - base));
397 aExpr[i].prereqRight &= mask;
398 aExpr[i].prereqLeft &= mask;
399 aExpr[i].prereqAll &= mask;
400 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000401 }
drh75897232000-05-29 14:26:00 +0000402 }
403
drh75897232000-05-29 14:26:00 +0000404 /* Figure out what index to use (if any) for each nested loop.
drh6b563442001-11-07 16:48:26 +0000405 ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
drhad3cab52002-05-24 02:04:32 +0000406 ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
drh8aff1012001-12-22 14:49:24 +0000407 ** loop.
408 **
409 ** If terms exist that use the ROWID of any table, then set the
410 ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
411 ** to the index of the term containing the ROWID. We always prefer
412 ** to use a ROWID which can directly access a table rather than an
drh0a36c572002-02-18 22:49:59 +0000413 ** index which requires reading an index first to get the rowid then
414 ** doing a second read of the actual database table.
drh75897232000-05-29 14:26:00 +0000415 **
416 ** Actually, if there are more than 32 tables in the join, only the
drh0a36c572002-02-18 22:49:59 +0000417 ** first 32 tables are candidates for indices. This is (again) due
418 ** to the limit of 32 bits in an integer bitmask.
drh75897232000-05-29 14:26:00 +0000419 */
420 loopMask = 0;
drhcb485882002-08-15 13:50:48 +0000421 for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++){
drhc4a3c772001-04-04 11:48:57 +0000422 int j;
drhfa9e0df2003-01-11 15:02:44 +0000423 int idx = i;
drh75897232000-05-29 14:26:00 +0000424 Table *pTab = pTabList->a[idx].pTab;
425 Index *pIdx;
426 Index *pBestIdx = 0;
drh487ab3c2001-11-08 00:45:21 +0000427 int bestScore = 0;
drh75897232000-05-29 14:26:00 +0000428
drhc4a3c772001-04-04 11:48:57 +0000429 /* Check to see if there is an expression that uses only the
drh8aff1012001-12-22 14:49:24 +0000430 ** ROWID field of this table. For terms of the form ROWID==expr
431 ** set iDirectEq[i] to the index of the term. For terms of the
432 ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
433 ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
drh174b6192002-12-03 02:22:52 +0000434 **
435 ** (Added:) Treat ROWID IN expr like ROWID=expr.
drhc4a3c772001-04-04 11:48:57 +0000436 */
drhc8f8b632002-09-30 12:36:26 +0000437 pWInfo->a[i].iCur = -1;
drh8aff1012001-12-22 14:49:24 +0000438 iDirectEq[i] = -1;
439 iDirectLt[i] = -1;
440 iDirectGt[i] = -1;
drhc4a3c772001-04-04 11:48:57 +0000441 for(j=0; j<nExpr; j++){
442 if( aExpr[j].idxLeft==idx && aExpr[j].p->pLeft->iColumn<0
443 && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
drh8aff1012001-12-22 14:49:24 +0000444 switch( aExpr[j].p->op ){
drhd99f7062002-06-08 23:25:08 +0000445 case TK_IN:
drh8aff1012001-12-22 14:49:24 +0000446 case TK_EQ: iDirectEq[i] = j; break;
447 case TK_LE:
448 case TK_LT: iDirectLt[i] = j; break;
449 case TK_GE:
450 case TK_GT: iDirectGt[i] = j; break;
451 }
drhc4a3c772001-04-04 11:48:57 +0000452 }
453 if( aExpr[j].idxRight==idx && aExpr[j].p->pRight->iColumn<0
454 && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
drh8aff1012001-12-22 14:49:24 +0000455 switch( aExpr[j].p->op ){
456 case TK_EQ: iDirectEq[i] = j; break;
457 case TK_LE:
458 case TK_LT: iDirectGt[i] = j; break;
459 case TK_GE:
460 case TK_GT: iDirectLt[i] = j; break;
461 }
drhc4a3c772001-04-04 11:48:57 +0000462 }
463 }
drh8aff1012001-12-22 14:49:24 +0000464 if( iDirectEq[i]>=0 ){
drhc4a3c772001-04-04 11:48:57 +0000465 loopMask |= 1<<idx;
drh6b563442001-11-07 16:48:26 +0000466 pWInfo->a[i].pIdx = 0;
drhc4a3c772001-04-04 11:48:57 +0000467 continue;
468 }
469
drh75897232000-05-29 14:26:00 +0000470 /* Do a search for usable indices. Leave pBestIdx pointing to
drh487ab3c2001-11-08 00:45:21 +0000471 ** the "best" index. pBestIdx is left set to NULL if no indices
472 ** are usable.
drh75897232000-05-29 14:26:00 +0000473 **
drh487ab3c2001-11-08 00:45:21 +0000474 ** The best index is determined as follows. For each of the
475 ** left-most terms that is fixed by an equality operator, add
drhc045ec52002-12-04 20:01:06 +0000476 ** 8 to the score. The right-most term of the index may be
drh487ab3c2001-11-08 00:45:21 +0000477 ** constrained by an inequality. Add 1 if for an "x<..." constraint
478 ** and add 2 for an "x>..." constraint. Chose the index that
479 ** gives the best score.
480 **
481 ** This scoring system is designed so that the score can later be
drhc045ec52002-12-04 20:01:06 +0000482 ** used to determine how the index is used. If the score&7 is 0
drh487ab3c2001-11-08 00:45:21 +0000483 ** then all constraints are equalities. If score&1 is not 0 then
484 ** there is an inequality used as a termination key. (ex: "x<...")
485 ** If score&2 is not 0 then there is an inequality used as the
drhc045ec52002-12-04 20:01:06 +0000486 ** start key. (ex: "x>..."). A score or 4 is the special case
487 ** of an IN operator constraint. (ex: "x IN ...").
drhd99f7062002-06-08 23:25:08 +0000488 **
drhc27a1ce2002-06-14 20:58:45 +0000489 ** The IN operator (as in "<expr> IN (...)") is treated the same as
490 ** an equality comparison except that it can only be used on the
491 ** left-most column of an index and other terms of the WHERE clause
492 ** cannot be used in conjunction with the IN operator to help satisfy
493 ** other columns of the index.
drh75897232000-05-29 14:26:00 +0000494 */
495 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drhc27a1ce2002-06-14 20:58:45 +0000496 int eqMask = 0; /* Index columns covered by an x=... term */
497 int ltMask = 0; /* Index columns covered by an x<... term */
498 int gtMask = 0; /* Index columns covered by an x>... term */
499 int inMask = 0; /* Index columns covered by an x IN .. term */
drh487ab3c2001-11-08 00:45:21 +0000500 int nEq, m, score;
drh75897232000-05-29 14:26:00 +0000501
drh487ab3c2001-11-08 00:45:21 +0000502 if( pIdx->nColumn>32 ) continue; /* Ignore indices too many columns */
drh75897232000-05-29 14:26:00 +0000503 for(j=0; j<nExpr; j++){
504 if( aExpr[j].idxLeft==idx
505 && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
drh967e8b72000-06-21 13:59:10 +0000506 int iColumn = aExpr[j].p->pLeft->iColumn;
drh75897232000-05-29 14:26:00 +0000507 int k;
drh967e8b72000-06-21 13:59:10 +0000508 for(k=0; k<pIdx->nColumn; k++){
509 if( pIdx->aiColumn[k]==iColumn ){
drh487ab3c2001-11-08 00:45:21 +0000510 switch( aExpr[j].p->op ){
drh48185c12002-06-09 01:55:20 +0000511 case TK_IN: {
512 if( k==0 ) inMask |= 1;
513 break;
514 }
drh487ab3c2001-11-08 00:45:21 +0000515 case TK_EQ: {
516 eqMask |= 1<<k;
517 break;
518 }
519 case TK_LE:
520 case TK_LT: {
521 ltMask |= 1<<k;
522 break;
523 }
524 case TK_GE:
525 case TK_GT: {
526 gtMask |= 1<<k;
527 break;
528 }
529 default: {
530 /* CANT_HAPPEN */
531 assert( 0 );
532 break;
533 }
534 }
drh75897232000-05-29 14:26:00 +0000535 break;
536 }
537 }
538 }
539 if( aExpr[j].idxRight==idx
540 && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
drh967e8b72000-06-21 13:59:10 +0000541 int iColumn = aExpr[j].p->pRight->iColumn;
drh75897232000-05-29 14:26:00 +0000542 int k;
drh967e8b72000-06-21 13:59:10 +0000543 for(k=0; k<pIdx->nColumn; k++){
544 if( pIdx->aiColumn[k]==iColumn ){
drh487ab3c2001-11-08 00:45:21 +0000545 switch( aExpr[j].p->op ){
546 case TK_EQ: {
547 eqMask |= 1<<k;
548 break;
549 }
550 case TK_LE:
551 case TK_LT: {
552 gtMask |= 1<<k;
553 break;
554 }
555 case TK_GE:
556 case TK_GT: {
557 ltMask |= 1<<k;
558 break;
559 }
560 default: {
561 /* CANT_HAPPEN */
562 assert( 0 );
563 break;
564 }
565 }
drh75897232000-05-29 14:26:00 +0000566 break;
567 }
568 }
569 }
570 }
drhc045ec52002-12-04 20:01:06 +0000571
572 /* The following loop ends with nEq set to the number of columns
573 ** on the left of the index with == constraints.
574 */
drh487ab3c2001-11-08 00:45:21 +0000575 for(nEq=0; nEq<pIdx->nColumn; nEq++){
576 m = (1<<(nEq+1))-1;
577 if( (m & eqMask)!=m ) break;
578 }
drhc045ec52002-12-04 20:01:06 +0000579 score = nEq*8; /* Base score is 8 times number of == constraints */
drh487ab3c2001-11-08 00:45:21 +0000580 m = 1<<nEq;
drhc045ec52002-12-04 20:01:06 +0000581 if( m & ltMask ) score++; /* Increase score for a < constraint */
582 if( m & gtMask ) score+=2; /* Increase score for a > constraint */
583 if( score==0 && inMask ) score = 4; /* Default score for IN constraint */
drh487ab3c2001-11-08 00:45:21 +0000584 if( score>bestScore ){
585 pBestIdx = pIdx;
586 bestScore = score;
drh75897232000-05-29 14:26:00 +0000587 }
588 }
drh6b563442001-11-07 16:48:26 +0000589 pWInfo->a[i].pIdx = pBestIdx;
drh487ab3c2001-11-08 00:45:21 +0000590 pWInfo->a[i].score = bestScore;
drhc045ec52002-12-04 20:01:06 +0000591 pWInfo->a[i].bRev = 0;
drh7e391e12000-05-30 20:17:49 +0000592 loopMask |= 1<<idx;
drh6b563442001-11-07 16:48:26 +0000593 if( pBestIdx ){
drh832508b2002-03-02 17:04:07 +0000594 pWInfo->a[i].iCur = pParse->nTab++;
595 pWInfo->peakNTab = pParse->nTab;
drh6b563442001-11-07 16:48:26 +0000596 }
drh75897232000-05-29 14:26:00 +0000597 }
598
drhe3184742002-06-19 14:27:05 +0000599 /* Check to see if the ORDER BY clause is or can be satisfied by the
600 ** use of an index on the first table.
601 */
602 if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
603 Index *pSortIdx;
604 Index *pIdx;
605 Table *pTab;
drhc045ec52002-12-04 20:01:06 +0000606 int bRev = 0;
drhe3184742002-06-19 14:27:05 +0000607
608 pTab = pTabList->a[0].pTab;
609 pIdx = pWInfo->a[0].pIdx;
610 if( pIdx && pWInfo->a[0].score==4 ){
drhc045ec52002-12-04 20:01:06 +0000611 /* If there is already an IN index on the left-most table,
612 ** it will not give the correct sort order.
613 ** So, pretend that no suitable index is found.
drhe3184742002-06-19 14:27:05 +0000614 */
615 pSortIdx = 0;
616 }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
617 /* If the left-most column is accessed using its ROWID, then do
618 ** not try to sort by index.
619 */
620 pSortIdx = 0;
621 }else{
drhdd4852c2002-12-04 21:50:16 +0000622 int nEqCol = (pWInfo->a[0].score+4)/8;
623 pSortIdx = findSortingIndex(pTab, base, *ppOrderBy, pIdx, nEqCol, &bRev);
drhe3184742002-06-19 14:27:05 +0000624 }
625 if( pSortIdx && (pIdx==0 || pIdx==pSortIdx) ){
626 if( pIdx==0 ){
627 pWInfo->a[0].pIdx = pSortIdx;
628 pWInfo->a[0].iCur = pParse->nTab++;
629 pWInfo->peakNTab = pParse->nTab;
630 }
drhc045ec52002-12-04 20:01:06 +0000631 pWInfo->a[0].bRev = bRev;
drhe3184742002-06-19 14:27:05 +0000632 *ppOrderBy = 0;
633 }
634 }
635
drh6b563442001-11-07 16:48:26 +0000636 /* Open all tables in the pTabList and all indices used by those tables.
drh75897232000-05-29 14:26:00 +0000637 */
drhad3cab52002-05-24 02:04:32 +0000638 for(i=0; i<pTabList->nSrc; i++){
drhf57b3392001-10-08 13:22:32 +0000639 int openOp;
640 Table *pTab;
641
642 pTab = pTabList->a[i].pTab;
drha76b5df2002-02-23 02:32:10 +0000643 if( pTab->isTransient || pTab->pSelect ) continue;
drhf57b3392001-10-08 13:22:32 +0000644 openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
drh99fcd712001-10-13 01:06:47 +0000645 sqliteVdbeAddOp(v, openOp, base+i, pTab->tnum);
646 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drh50e5dad2001-09-15 00:57:28 +0000647 if( i==0 && !pParse->schemaVerified &&
648 (pParse->db->flags & SQLITE_InTrans)==0 ){
drh99fcd712001-10-13 01:06:47 +0000649 sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
drh50e5dad2001-09-15 00:57:28 +0000650 pParse->schemaVerified = 1;
651 }
drh6b563442001-11-07 16:48:26 +0000652 if( pWInfo->a[i].pIdx!=0 ){
653 sqliteVdbeAddOp(v, openOp, pWInfo->a[i].iCur, pWInfo->a[i].pIdx->tnum);
654 sqliteVdbeChangeP3(v, -1, pWInfo->a[i].pIdx->zName, P3_STATIC);
drh75897232000-05-29 14:26:00 +0000655 }
656 }
657
658 /* Generate the code to do the search
659 */
drh75897232000-05-29 14:26:00 +0000660 loopMask = 0;
drhad3cab52002-05-24 02:04:32 +0000661 for(i=0; i<pTabList->nSrc; i++){
drh75897232000-05-29 14:26:00 +0000662 int j, k;
drhfa9e0df2003-01-11 15:02:44 +0000663 int idx = i;
drhc4a3c772001-04-04 11:48:57 +0000664 Index *pIdx;
drh6b563442001-11-07 16:48:26 +0000665 WhereLevel *pLevel = &pWInfo->a[i];
drh75897232000-05-29 14:26:00 +0000666
drhad2d8302002-05-24 20:31:36 +0000667 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +0000668 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +0000669 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +0000670 */
671 if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
672 if( !pParse->nMem ) pParse->nMem++;
673 pLevel->iLeftJoin = pParse->nMem++;
674 sqliteVdbeAddOp(v, OP_String, 0, 0);
675 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
676 }
677
drh8aff1012001-12-22 14:49:24 +0000678 pIdx = pLevel->pIdx;
drhd99f7062002-06-08 23:25:08 +0000679 pLevel->inOp = OP_Noop;
drh8aff1012001-12-22 14:49:24 +0000680 if( i<ARRAYSIZE(iDirectEq) && iDirectEq[i]>=0 ){
681 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +0000682 ** equality comparison against the ROWID field. Or
683 ** we reference multiple rows using a "rowid IN (...)"
684 ** construct.
drhc4a3c772001-04-04 11:48:57 +0000685 */
drh8aff1012001-12-22 14:49:24 +0000686 k = iDirectEq[i];
687 assert( k<nExpr );
688 assert( aExpr[k].p!=0 );
689 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
drhd99f7062002-06-08 23:25:08 +0000690 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
drh8aff1012001-12-22 14:49:24 +0000691 if( aExpr[k].idxLeft==idx ){
drhd99f7062002-06-08 23:25:08 +0000692 Expr *pX = aExpr[k].p;
693 if( pX->op!=TK_IN ){
694 sqliteExprCode(pParse, aExpr[k].p->pRight);
695 }else if( pX->pList ){
696 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
697 pLevel->inOp = OP_SetNext;
698 pLevel->inP1 = pX->iTable;
699 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
700 }else{
701 assert( pX->pSelect );
702 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
703 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
704 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
705 pLevel->inOp = OP_Next;
706 pLevel->inP1 = pX->iTable;
707 }
drh8aff1012001-12-22 14:49:24 +0000708 }else{
709 sqliteExprCode(pParse, aExpr[k].p->pLeft);
drhc4a3c772001-04-04 11:48:57 +0000710 }
drh8aff1012001-12-22 14:49:24 +0000711 aExpr[k].p = 0;
drhd99f7062002-06-08 23:25:08 +0000712 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
drhf1351b62002-07-31 19:50:26 +0000713 sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
drhd99f7062002-06-08 23:25:08 +0000714 haveKey = 0;
drh6b125452002-01-28 15:53:03 +0000715 sqliteVdbeAddOp(v, OP_NotExists, base+idx, brk);
drh6b563442001-11-07 16:48:26 +0000716 pLevel->op = OP_Noop;
drhe3184742002-06-19 14:27:05 +0000717 }else if( pIdx!=0 && pLevel->score>0 && pLevel->score%4==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000718 /* Case 2: There is an index and all terms of the WHERE clause that
719 ** refer to the index use the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +0000720 */
drh6b563442001-11-07 16:48:26 +0000721 int start;
drh487ab3c2001-11-08 00:45:21 +0000722 int testOp;
drhc045ec52002-12-04 20:01:06 +0000723 int nColumn = (pLevel->score+4)/8;
drhd99f7062002-06-08 23:25:08 +0000724 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
drh487ab3c2001-11-08 00:45:21 +0000725 for(j=0; j<nColumn; j++){
drh75897232000-05-29 14:26:00 +0000726 for(k=0; k<nExpr; k++){
drhd99f7062002-06-08 23:25:08 +0000727 Expr *pX = aExpr[k].p;
728 if( pX==0 ) continue;
drh75897232000-05-29 14:26:00 +0000729 if( aExpr[k].idxLeft==idx
730 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
drhd99f7062002-06-08 23:25:08 +0000731 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +0000732 ){
drhd99f7062002-06-08 23:25:08 +0000733 if( pX->op==TK_EQ ){
734 sqliteExprCode(pParse, pX->pRight);
735 aExpr[k].p = 0;
736 break;
737 }
738 if( pX->op==TK_IN && nColumn==1 ){
739 if( pX->pList ){
740 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
741 pLevel->inOp = OP_SetNext;
742 pLevel->inP1 = pX->iTable;
743 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
744 }else{
745 assert( pX->pSelect );
746 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
747 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
748 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
749 pLevel->inOp = OP_Next;
750 pLevel->inP1 = pX->iTable;
751 }
752 aExpr[k].p = 0;
753 break;
754 }
drh75897232000-05-29 14:26:00 +0000755 }
756 if( aExpr[k].idxRight==idx
drh487ab3c2001-11-08 00:45:21 +0000757 && aExpr[k].p->op==TK_EQ
drh75897232000-05-29 14:26:00 +0000758 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
drh967e8b72000-06-21 13:59:10 +0000759 && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +0000760 ){
761 sqliteExprCode(pParse, aExpr[k].p->pLeft);
762 aExpr[k].p = 0;
763 break;
764 }
765 }
766 }
drh6b563442001-11-07 16:48:26 +0000767 pLevel->iMem = pParse->nMem++;
drh6b563442001-11-07 16:48:26 +0000768 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
drh487ab3c2001-11-08 00:45:21 +0000769 sqliteVdbeAddOp(v, OP_MakeKey, nColumn, 0);
drha9e99ae2002-08-13 23:02:57 +0000770 sqliteAddIdxKeyType(v, pIdx);
drhc045ec52002-12-04 20:01:06 +0000771 if( nColumn==pIdx->nColumn || pLevel->bRev ){
drh487ab3c2001-11-08 00:45:21 +0000772 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
773 testOp = OP_IdxGT;
774 }else{
775 sqliteVdbeAddOp(v, OP_Dup, 0, 0);
776 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
777 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
778 testOp = OP_IdxGE;
779 }
drhc045ec52002-12-04 20:01:06 +0000780 if( pLevel->bRev ){
781 /* Scan in reverse order */
782 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
783 sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
784 start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
785 sqliteVdbeAddOp(v, OP_IdxLT, pLevel->iCur, brk);
786 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
787 pLevel->op = OP_Prev;
788 }else{
789 /* Scan in the forward order */
790 sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
791 start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
792 sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
793 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
794 pLevel->op = OP_Next;
795 }
drhad3cab52002-05-24 02:04:32 +0000796 if( i==pTabList->nSrc-1 && pushKey ){
drh75897232000-05-29 14:26:00 +0000797 haveKey = 1;
798 }else{
drh99fcd712001-10-13 01:06:47 +0000799 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
drh75897232000-05-29 14:26:00 +0000800 haveKey = 0;
801 }
drh6b563442001-11-07 16:48:26 +0000802 pLevel->p1 = pLevel->iCur;
803 pLevel->p2 = start;
drh8aff1012001-12-22 14:49:24 +0000804 }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
805 /* Case 3: We have an inequality comparison against the ROWID field.
806 */
807 int testOp = OP_Noop;
808 int start;
809
810 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
811 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
812 if( iDirectGt[i]>=0 ){
813 k = iDirectGt[i];
814 assert( k<nExpr );
815 assert( aExpr[k].p!=0 );
816 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
817 if( aExpr[k].idxLeft==idx ){
818 sqliteExprCode(pParse, aExpr[k].p->pRight);
819 }else{
820 sqliteExprCode(pParse, aExpr[k].p->pLeft);
821 }
drhf1351b62002-07-31 19:50:26 +0000822 sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
drh8aff1012001-12-22 14:49:24 +0000823 if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
824 sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
825 }
826 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, brk);
827 aExpr[k].p = 0;
828 }else{
829 sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
830 }
831 if( iDirectLt[i]>=0 ){
832 k = iDirectLt[i];
833 assert( k<nExpr );
834 assert( aExpr[k].p!=0 );
835 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
836 if( aExpr[k].idxLeft==idx ){
837 sqliteExprCode(pParse, aExpr[k].p->pRight);
838 }else{
839 sqliteExprCode(pParse, aExpr[k].p->pLeft);
840 }
drhf1351b62002-07-31 19:50:26 +0000841 sqliteVdbeAddOp(v, OP_MustBeInt, 1, sqliteVdbeCurrentAddr(v)+1);
drh8aff1012001-12-22 14:49:24 +0000842 pLevel->iMem = pParse->nMem++;
843 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
844 if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
845 testOp = OP_Ge;
846 }else{
847 testOp = OP_Gt;
848 }
849 aExpr[k].p = 0;
850 }
851 start = sqliteVdbeCurrentAddr(v);
852 pLevel->op = OP_Next;
853 pLevel->p1 = base+idx;
854 pLevel->p2 = start;
855 if( testOp!=OP_Noop ){
856 sqliteVdbeAddOp(v, OP_Recno, base+idx, 0);
857 sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
858 sqliteVdbeAddOp(v, testOp, 0, brk);
859 }
860 haveKey = 0;
861 }else if( pIdx==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000862 /* Case 4: There is no usable index. We must do a complete
drh8aff1012001-12-22 14:49:24 +0000863 ** scan of the entire database table.
864 */
865 int start;
866
867 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
868 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
869 sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
870 start = sqliteVdbeCurrentAddr(v);
871 pLevel->op = OP_Next;
872 pLevel->p1 = base+idx;
873 pLevel->p2 = start;
874 haveKey = 0;
drh487ab3c2001-11-08 00:45:21 +0000875 }else{
drhc27a1ce2002-06-14 20:58:45 +0000876 /* Case 5: The WHERE clause term that refers to the right-most
877 ** column of the index is an inequality. For example, if
878 ** the index is on (x,y,z) and the WHERE clause is of the
879 ** form "x=5 AND y<10" then this case is used. Only the
880 ** right-most column can be an inequality - the rest must
881 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +0000882 **
883 ** This case is also used when there are no WHERE clause
884 ** constraints but an index is selected anyway, in order
885 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +0000886 */
887 int score = pLevel->score;
drhc045ec52002-12-04 20:01:06 +0000888 int nEqColumn = score/8;
drh487ab3c2001-11-08 00:45:21 +0000889 int start;
890 int leFlag, geFlag;
891 int testOp;
892
893 /* Evaluate the equality constraints
894 */
895 for(j=0; j<nEqColumn; j++){
896 for(k=0; k<nExpr; k++){
897 if( aExpr[k].p==0 ) continue;
898 if( aExpr[k].idxLeft==idx
899 && aExpr[k].p->op==TK_EQ
900 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
901 && aExpr[k].p->pLeft->iColumn==pIdx->aiColumn[j]
902 ){
903 sqliteExprCode(pParse, aExpr[k].p->pRight);
904 aExpr[k].p = 0;
905 break;
906 }
907 if( aExpr[k].idxRight==idx
908 && aExpr[k].p->op==TK_EQ
909 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
910 && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
911 ){
912 sqliteExprCode(pParse, aExpr[k].p->pLeft);
913 aExpr[k].p = 0;
914 break;
915 }
916 }
917 }
918
drhc27a1ce2002-06-14 20:58:45 +0000919 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +0000920 ** used twice: once to make the termination key and once to make the
921 ** start key.
922 */
923 for(j=0; j<nEqColumn; j++){
924 sqliteVdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
925 }
926
drhc045ec52002-12-04 20:01:06 +0000927 /* Labels for the beginning and end of the loop
928 */
929 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
930 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
931
drh487ab3c2001-11-08 00:45:21 +0000932 /* Generate the termination key. This is the key value that
933 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +0000934 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +0000935 **
936 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
937 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +0000938 */
939 if( (score & 1)!=0 ){
940 for(k=0; k<nExpr; k++){
941 Expr *pExpr = aExpr[k].p;
942 if( pExpr==0 ) continue;
943 if( aExpr[k].idxLeft==idx
944 && (pExpr->op==TK_LT || pExpr->op==TK_LE)
945 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
946 && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
947 ){
948 sqliteExprCode(pParse, pExpr->pRight);
949 leFlag = pExpr->op==TK_LE;
950 aExpr[k].p = 0;
951 break;
952 }
953 if( aExpr[k].idxRight==idx
954 && (pExpr->op==TK_GT || pExpr->op==TK_GE)
955 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
956 && pExpr->pRight->iColumn==pIdx->aiColumn[j]
957 ){
958 sqliteExprCode(pParse, pExpr->pLeft);
959 leFlag = pExpr->op==TK_GE;
960 aExpr[k].p = 0;
961 break;
962 }
963 }
964 testOp = OP_IdxGE;
965 }else{
966 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
967 leFlag = 1;
968 }
969 if( testOp!=OP_Noop ){
970 pLevel->iMem = pParse->nMem++;
971 sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + (score & 1), 0);
drha9e99ae2002-08-13 23:02:57 +0000972 sqliteAddIdxKeyType(v, pIdx);
drh487ab3c2001-11-08 00:45:21 +0000973 if( leFlag ){
974 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
975 }
drhc045ec52002-12-04 20:01:06 +0000976 if( pLevel->bRev ){
977 sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
978 }else{
979 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
980 }
981 }else if( pLevel->bRev ){
982 sqliteVdbeAddOp(v, OP_Last, pLevel->iCur, brk);
drh487ab3c2001-11-08 00:45:21 +0000983 }
984
985 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +0000986 ** bound on the search. There is no start key if there are no
987 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +0000988 ** that case, generate a "Rewind" instruction in place of the
989 ** start key search.
drhc045ec52002-12-04 20:01:06 +0000990 **
991 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
992 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +0000993 */
994 if( (score & 2)!=0 ){
995 for(k=0; k<nExpr; k++){
996 Expr *pExpr = aExpr[k].p;
997 if( pExpr==0 ) continue;
998 if( aExpr[k].idxLeft==idx
999 && (pExpr->op==TK_GT || pExpr->op==TK_GE)
1000 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
1001 && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
1002 ){
1003 sqliteExprCode(pParse, pExpr->pRight);
1004 geFlag = pExpr->op==TK_GE;
1005 aExpr[k].p = 0;
1006 break;
1007 }
1008 if( aExpr[k].idxRight==idx
1009 && (pExpr->op==TK_LT || pExpr->op==TK_LE)
1010 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
1011 && pExpr->pRight->iColumn==pIdx->aiColumn[j]
1012 ){
1013 sqliteExprCode(pParse, pExpr->pLeft);
1014 geFlag = pExpr->op==TK_LE;
1015 aExpr[k].p = 0;
1016 break;
1017 }
1018 }
drh7900ead2001-11-12 13:51:43 +00001019 }else{
1020 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001021 }
drh487ab3c2001-11-08 00:45:21 +00001022 if( nEqColumn>0 || (score&2)!=0 ){
1023 sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + ((score&2)!=0), 0);
drha9e99ae2002-08-13 23:02:57 +00001024 sqliteAddIdxKeyType(v, pIdx);
drh487ab3c2001-11-08 00:45:21 +00001025 if( !geFlag ){
1026 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
1027 }
drhc045ec52002-12-04 20:01:06 +00001028 if( pLevel->bRev ){
1029 pLevel->iMem = pParse->nMem++;
1030 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
1031 testOp = OP_IdxLT;
1032 }else{
1033 sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
1034 }
1035 }else if( pLevel->bRev ){
1036 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001037 }else{
1038 sqliteVdbeAddOp(v, OP_Rewind, pLevel->iCur, brk);
1039 }
1040
1041 /* Generate the the top of the loop. If there is a termination
1042 ** key we have to test for that key and abort at the top of the
1043 ** loop.
1044 */
1045 start = sqliteVdbeCurrentAddr(v);
1046 if( testOp!=OP_Noop ){
1047 sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1048 sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
1049 }
1050 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
drhad3cab52002-05-24 02:04:32 +00001051 if( i==pTabList->nSrc-1 && pushKey ){
drh487ab3c2001-11-08 00:45:21 +00001052 haveKey = 1;
1053 }else{
1054 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
1055 haveKey = 0;
1056 }
1057
1058 /* Record the instruction used to terminate the loop.
1059 */
drhc045ec52002-12-04 20:01:06 +00001060 pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
drh487ab3c2001-11-08 00:45:21 +00001061 pLevel->p1 = pLevel->iCur;
1062 pLevel->p2 = start;
drh75897232000-05-29 14:26:00 +00001063 }
1064 loopMask |= 1<<idx;
1065
1066 /* Insert code to test every subexpression that can be completely
1067 ** computed using the current set of tables.
1068 */
1069 for(j=0; j<nExpr; j++){
1070 if( aExpr[j].p==0 ) continue;
drh3f6b5482002-04-02 13:26:10 +00001071 if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
drh1f162302002-10-27 19:35:33 +00001072 if( pLevel->iLeftJoin && !ExprHasProperty(aExpr[j].p,EP_FromJoin) ){
1073 continue;
1074 }
drh75897232000-05-29 14:26:00 +00001075 if( haveKey ){
drh573bd272001-02-19 23:23:38 +00001076 haveKey = 0;
drh99fcd712001-10-13 01:06:47 +00001077 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
drh75897232000-05-29 14:26:00 +00001078 }
drhf5905aa2002-05-26 20:54:33 +00001079 sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
drh75897232000-05-29 14:26:00 +00001080 aExpr[j].p = 0;
1081 }
1082 brk = cont;
drhad2d8302002-05-24 20:31:36 +00001083
1084 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1085 ** at least one row of the right table has matched the left table.
1086 */
1087 if( pLevel->iLeftJoin ){
1088 pLevel->top = sqliteVdbeCurrentAddr(v);
1089 sqliteVdbeAddOp(v, OP_Integer, 1, 0);
1090 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drh1cc093c2002-06-24 22:01:57 +00001091 for(j=0; j<nExpr; j++){
1092 if( aExpr[j].p==0 ) continue;
1093 if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
1094 if( haveKey ){
drh3b167c72002-06-28 12:18:47 +00001095 /* Cannot happen. "haveKey" can only be true if pushKey is true
1096 ** an pushKey can only be true for DELETE and UPDATE and there are
1097 ** no outer joins with DELETE and UPDATE.
1098 */
drh1cc093c2002-06-24 22:01:57 +00001099 haveKey = 0;
1100 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
1101 }
1102 sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
1103 aExpr[j].p = 0;
1104 }
drhad2d8302002-05-24 20:31:36 +00001105 }
drh75897232000-05-29 14:26:00 +00001106 }
1107 pWInfo->iContinue = cont;
1108 if( pushKey && !haveKey ){
drh99fcd712001-10-13 01:06:47 +00001109 sqliteVdbeAddOp(v, OP_Recno, base, 0);
drh75897232000-05-29 14:26:00 +00001110 }
drh75897232000-05-29 14:26:00 +00001111 return pWInfo;
1112}
1113
1114/*
drhc27a1ce2002-06-14 20:58:45 +00001115** Generate the end of the WHERE loop. See comments on
1116** sqliteWhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001117*/
1118void sqliteWhereEnd(WhereInfo *pWInfo){
1119 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001120 int i;
drh19a775c2000-06-05 18:54:46 +00001121 int base = pWInfo->base;
drh6b563442001-11-07 16:48:26 +00001122 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001123 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001124
drhad3cab52002-05-24 02:04:32 +00001125 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001126 pLevel = &pWInfo->a[i];
1127 sqliteVdbeResolveLabel(v, pLevel->cont);
1128 if( pLevel->op!=OP_Noop ){
1129 sqliteVdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001130 }
drh6b563442001-11-07 16:48:26 +00001131 sqliteVdbeResolveLabel(v, pLevel->brk);
drhd99f7062002-06-08 23:25:08 +00001132 if( pLevel->inOp!=OP_Noop ){
1133 sqliteVdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
1134 }
drhad2d8302002-05-24 20:31:36 +00001135 if( pLevel->iLeftJoin ){
1136 int addr;
1137 addr = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh7f09b3e2002-08-13 13:15:49 +00001138 sqliteVdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iCur>=0));
drhad2d8302002-05-24 20:31:36 +00001139 sqliteVdbeAddOp(v, OP_NullRow, base+i, 0);
drh7f09b3e2002-08-13 13:15:49 +00001140 if( pLevel->iCur>=0 ){
1141 sqliteVdbeAddOp(v, OP_NullRow, pLevel->iCur, 0);
1142 }
drhad2d8302002-05-24 20:31:36 +00001143 sqliteVdbeAddOp(v, OP_Goto, 0, pLevel->top);
1144 }
drh19a775c2000-06-05 18:54:46 +00001145 }
drh6b563442001-11-07 16:48:26 +00001146 sqliteVdbeResolveLabel(v, pWInfo->iBreak);
drhad3cab52002-05-24 02:04:32 +00001147 for(i=0; i<pTabList->nSrc; i++){
drh22f70c32002-02-18 01:17:00 +00001148 if( pTabList->a[i].pTab->isTransient ) continue;
drh6b563442001-11-07 16:48:26 +00001149 pLevel = &pWInfo->a[i];
1150 sqliteVdbeAddOp(v, OP_Close, base+i, 0);
1151 if( pLevel->pIdx!=0 ){
1152 sqliteVdbeAddOp(v, OP_Close, pLevel->iCur, 0);
1153 }
drh19a775c2000-06-05 18:54:46 +00001154 }
drh142e30d2002-08-28 03:00:58 +00001155#if 0 /* Never reuse a cursor */
drh832508b2002-03-02 17:04:07 +00001156 if( pWInfo->pParse->nTab==pWInfo->peakNTab ){
1157 pWInfo->pParse->nTab = pWInfo->savedNTab;
1158 }
drh142e30d2002-08-28 03:00:58 +00001159#endif
drh75897232000-05-29 14:26:00 +00001160 sqliteFree(pWInfo);
1161 return;
1162}