blob: ee7580021c672eba417e89e91c05a1abe631b3eb [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**
drhfd159812003-01-11 14:25:39 +000016** $Id: where.c,v 1.70 2003/01/11 14:25:40 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{
65 cnt = exprSplit(nSlot, aSlot, pExpr->pRight);
66 cnt += exprSplit(nSlot-cnt, &aSlot[cnt], pExpr->pLeft);
67 }
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 */
328 int *aOrder; /* Order in which pTabList entries are searched */
329 int nExpr; /* Number of subexpressions in the WHERE clause */
330 int loopMask; /* One bit set for each outer loop */
331 int haveKey; /* True if KEY is on the stack */
drh8aff1012001-12-22 14:49:24 +0000332 int iDirectEq[32]; /* Term of the form ROWID==X for the N-th table */
333 int iDirectLt[32]; /* Term of the form ROWID<X or ROWID<=X */
334 int iDirectGt[32]; /* Term of the form ROWID>X or ROWID>=X */
drh83dcb1a2002-06-28 01:02:38 +0000335 ExprInfo aExpr[101]; /* The WHERE clause is divided into these expressions */
drh75897232000-05-29 14:26:00 +0000336
drhc27a1ce2002-06-14 20:58:45 +0000337 /* pushKey is only allowed if there is a single table (as in an INSERT or
338 ** UPDATE statement)
339 */
340 assert( pushKey==0 || pTabList->nSrc==1 );
drh83dcb1a2002-06-28 01:02:38 +0000341
342 /* Split the WHERE clause into separate subexpressions where each
343 ** subexpression is separated by an AND operator. If the aExpr[]
344 ** array fills up, the last entry might point to an expression which
345 ** contains additional unfactored AND operators.
346 */
347 memset(aExpr, 0, sizeof(aExpr));
348 nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
349 if( nExpr==ARRAYSIZE(aExpr) ){
350 char zBuf[50];
drhfd159812003-01-11 14:25:39 +0000351 sprintf(zBuf, "%d", (int)ARRAYSIZE(aExpr)-1);
drh83dcb1a2002-06-28 01:02:38 +0000352 sqliteSetString(&pParse->zErrMsg, "WHERE clause too complex - no more "
353 "than ", zBuf, " terms allowed", 0);
354 pParse->nErr++;
355 return 0;
356 }
drhc27a1ce2002-06-14 20:58:45 +0000357
drhe3184742002-06-19 14:27:05 +0000358 /* Allocate space for aOrder[] */
drhad3cab52002-05-24 02:04:32 +0000359 aOrder = sqliteMalloc( sizeof(int) * pTabList->nSrc );
drh75897232000-05-29 14:26:00 +0000360
361 /* Allocate and initialize the WhereInfo structure that will become the
362 ** return value.
363 */
drhad3cab52002-05-24 02:04:32 +0000364 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
drhdaffd0e2001-04-11 14:28:42 +0000365 if( sqlite_malloc_failed ){
drh75897232000-05-29 14:26:00 +0000366 sqliteFree(aOrder);
drhdaffd0e2001-04-11 14:28:42 +0000367 sqliteFree(pWInfo);
drh75897232000-05-29 14:26:00 +0000368 return 0;
369 }
370 pWInfo->pParse = pParse;
371 pWInfo->pTabList = pTabList;
drh832508b2002-03-02 17:04:07 +0000372 pWInfo->base = base;
373 pWInfo->peakNTab = pWInfo->savedNTab = pParse->nTab;
drh08192d52002-04-30 19:20:28 +0000374 pWInfo->iBreak = sqliteVdbeMakeLabel(v);
375
376 /* Special case: a WHERE clause that is constant. Evaluate the
377 ** expression and either jump over all of the code or fall thru.
378 */
379 if( pWhere && sqliteExprIsConstant(pWhere) ){
drhf5905aa2002-05-26 20:54:33 +0000380 sqliteExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +0000381 pWhere = 0;
drh08192d52002-04-30 19:20:28 +0000382 }
drh75897232000-05-29 14:26:00 +0000383
drh75897232000-05-29 14:26:00 +0000384 /* Analyze all of the subexpressions.
385 */
386 for(i=0; i<nExpr; i++){
drh22f70c32002-02-18 01:17:00 +0000387 exprAnalyze(base, &aExpr[i]);
drh1d1f3052002-05-21 13:18:25 +0000388
389 /* If we are executing a trigger body, remove all references to
390 ** new.* and old.* tables from the prerequisite masks.
391 */
392 if( pParse->trigStack ){
393 int x;
394 if( (x = pParse->trigStack->newIdx) >= 0 ){
395 int mask = ~(1 << (x - base));
396 aExpr[i].prereqRight &= mask;
397 aExpr[i].prereqLeft &= mask;
398 aExpr[i].prereqAll &= mask;
399 }
400 if( (x = pParse->trigStack->oldIdx) >= 0 ){
401 int mask = ~(1 << (x - base));
402 aExpr[i].prereqRight &= mask;
403 aExpr[i].prereqLeft &= mask;
404 aExpr[i].prereqAll &= mask;
405 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000406 }
drh75897232000-05-29 14:26:00 +0000407 }
408
409 /* Figure out a good nesting order for the tables. aOrder[0] will
410 ** be the index in pTabList of the outermost table. aOrder[1] will
drhad3cab52002-05-24 02:04:32 +0000411 ** be the first nested loop and so on. aOrder[pTabList->nSrc-1] will
drh75897232000-05-29 14:26:00 +0000412 ** be the innermost loop.
413 **
drh1d1f3052002-05-21 13:18:25 +0000414 ** Someday we will put in a good algorithm here to reorder the loops
drh75897232000-05-29 14:26:00 +0000415 ** for an effiecient query. But for now, just use whatever order the
416 ** tables appear in in the pTabList.
417 */
drhad3cab52002-05-24 02:04:32 +0000418 for(i=0; i<pTabList->nSrc; i++){
drh75897232000-05-29 14:26:00 +0000419 aOrder[i] = i;
420 }
421
422 /* Figure out what index to use (if any) for each nested loop.
drh6b563442001-11-07 16:48:26 +0000423 ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
drhad3cab52002-05-24 02:04:32 +0000424 ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
drh8aff1012001-12-22 14:49:24 +0000425 ** loop.
426 **
427 ** If terms exist that use the ROWID of any table, then set the
428 ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
429 ** to the index of the term containing the ROWID. We always prefer
430 ** to use a ROWID which can directly access a table rather than an
drh0a36c572002-02-18 22:49:59 +0000431 ** index which requires reading an index first to get the rowid then
432 ** doing a second read of the actual database table.
drh75897232000-05-29 14:26:00 +0000433 **
434 ** Actually, if there are more than 32 tables in the join, only the
drh0a36c572002-02-18 22:49:59 +0000435 ** first 32 tables are candidates for indices. This is (again) due
436 ** to the limit of 32 bits in an integer bitmask.
drh75897232000-05-29 14:26:00 +0000437 */
438 loopMask = 0;
drhcb485882002-08-15 13:50:48 +0000439 for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++){
drhc4a3c772001-04-04 11:48:57 +0000440 int j;
drh75897232000-05-29 14:26:00 +0000441 int idx = aOrder[i];
442 Table *pTab = pTabList->a[idx].pTab;
443 Index *pIdx;
444 Index *pBestIdx = 0;
drh487ab3c2001-11-08 00:45:21 +0000445 int bestScore = 0;
drh75897232000-05-29 14:26:00 +0000446
drhc4a3c772001-04-04 11:48:57 +0000447 /* Check to see if there is an expression that uses only the
drh8aff1012001-12-22 14:49:24 +0000448 ** ROWID field of this table. For terms of the form ROWID==expr
449 ** set iDirectEq[i] to the index of the term. For terms of the
450 ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
451 ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
drh174b6192002-12-03 02:22:52 +0000452 **
453 ** (Added:) Treat ROWID IN expr like ROWID=expr.
drhc4a3c772001-04-04 11:48:57 +0000454 */
drhc8f8b632002-09-30 12:36:26 +0000455 pWInfo->a[i].iCur = -1;
drh8aff1012001-12-22 14:49:24 +0000456 iDirectEq[i] = -1;
457 iDirectLt[i] = -1;
458 iDirectGt[i] = -1;
drhc4a3c772001-04-04 11:48:57 +0000459 for(j=0; j<nExpr; j++){
460 if( aExpr[j].idxLeft==idx && aExpr[j].p->pLeft->iColumn<0
461 && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
drh8aff1012001-12-22 14:49:24 +0000462 switch( aExpr[j].p->op ){
drhd99f7062002-06-08 23:25:08 +0000463 case TK_IN:
drh8aff1012001-12-22 14:49:24 +0000464 case TK_EQ: iDirectEq[i] = j; break;
465 case TK_LE:
466 case TK_LT: iDirectLt[i] = j; break;
467 case TK_GE:
468 case TK_GT: iDirectGt[i] = j; break;
469 }
drhc4a3c772001-04-04 11:48:57 +0000470 }
471 if( aExpr[j].idxRight==idx && aExpr[j].p->pRight->iColumn<0
472 && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
drh8aff1012001-12-22 14:49:24 +0000473 switch( aExpr[j].p->op ){
474 case TK_EQ: iDirectEq[i] = j; break;
475 case TK_LE:
476 case TK_LT: iDirectGt[i] = j; break;
477 case TK_GE:
478 case TK_GT: iDirectLt[i] = j; break;
479 }
drhc4a3c772001-04-04 11:48:57 +0000480 }
481 }
drh8aff1012001-12-22 14:49:24 +0000482 if( iDirectEq[i]>=0 ){
drhc4a3c772001-04-04 11:48:57 +0000483 loopMask |= 1<<idx;
drh6b563442001-11-07 16:48:26 +0000484 pWInfo->a[i].pIdx = 0;
drhc4a3c772001-04-04 11:48:57 +0000485 continue;
486 }
487
drh75897232000-05-29 14:26:00 +0000488 /* Do a search for usable indices. Leave pBestIdx pointing to
drh487ab3c2001-11-08 00:45:21 +0000489 ** the "best" index. pBestIdx is left set to NULL if no indices
490 ** are usable.
drh75897232000-05-29 14:26:00 +0000491 **
drh487ab3c2001-11-08 00:45:21 +0000492 ** The best index is determined as follows. For each of the
493 ** left-most terms that is fixed by an equality operator, add
drhc045ec52002-12-04 20:01:06 +0000494 ** 8 to the score. The right-most term of the index may be
drh487ab3c2001-11-08 00:45:21 +0000495 ** constrained by an inequality. Add 1 if for an "x<..." constraint
496 ** and add 2 for an "x>..." constraint. Chose the index that
497 ** gives the best score.
498 **
499 ** This scoring system is designed so that the score can later be
drhc045ec52002-12-04 20:01:06 +0000500 ** used to determine how the index is used. If the score&7 is 0
drh487ab3c2001-11-08 00:45:21 +0000501 ** then all constraints are equalities. If score&1 is not 0 then
502 ** there is an inequality used as a termination key. (ex: "x<...")
503 ** If score&2 is not 0 then there is an inequality used as the
drhc045ec52002-12-04 20:01:06 +0000504 ** start key. (ex: "x>..."). A score or 4 is the special case
505 ** of an IN operator constraint. (ex: "x IN ...").
drhd99f7062002-06-08 23:25:08 +0000506 **
drhc27a1ce2002-06-14 20:58:45 +0000507 ** The IN operator (as in "<expr> IN (...)") is treated the same as
508 ** an equality comparison except that it can only be used on the
509 ** left-most column of an index and other terms of the WHERE clause
510 ** cannot be used in conjunction with the IN operator to help satisfy
511 ** other columns of the index.
drh75897232000-05-29 14:26:00 +0000512 */
513 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drhc27a1ce2002-06-14 20:58:45 +0000514 int eqMask = 0; /* Index columns covered by an x=... term */
515 int ltMask = 0; /* Index columns covered by an x<... term */
516 int gtMask = 0; /* Index columns covered by an x>... term */
517 int inMask = 0; /* Index columns covered by an x IN .. term */
drh487ab3c2001-11-08 00:45:21 +0000518 int nEq, m, score;
drh75897232000-05-29 14:26:00 +0000519
drh487ab3c2001-11-08 00:45:21 +0000520 if( pIdx->nColumn>32 ) continue; /* Ignore indices too many columns */
drh75897232000-05-29 14:26:00 +0000521 for(j=0; j<nExpr; j++){
522 if( aExpr[j].idxLeft==idx
523 && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
drh967e8b72000-06-21 13:59:10 +0000524 int iColumn = aExpr[j].p->pLeft->iColumn;
drh75897232000-05-29 14:26:00 +0000525 int k;
drh967e8b72000-06-21 13:59:10 +0000526 for(k=0; k<pIdx->nColumn; k++){
527 if( pIdx->aiColumn[k]==iColumn ){
drh487ab3c2001-11-08 00:45:21 +0000528 switch( aExpr[j].p->op ){
drh48185c12002-06-09 01:55:20 +0000529 case TK_IN: {
530 if( k==0 ) inMask |= 1;
531 break;
532 }
drh487ab3c2001-11-08 00:45:21 +0000533 case TK_EQ: {
534 eqMask |= 1<<k;
535 break;
536 }
537 case TK_LE:
538 case TK_LT: {
539 ltMask |= 1<<k;
540 break;
541 }
542 case TK_GE:
543 case TK_GT: {
544 gtMask |= 1<<k;
545 break;
546 }
547 default: {
548 /* CANT_HAPPEN */
549 assert( 0 );
550 break;
551 }
552 }
drh75897232000-05-29 14:26:00 +0000553 break;
554 }
555 }
556 }
557 if( aExpr[j].idxRight==idx
558 && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
drh967e8b72000-06-21 13:59:10 +0000559 int iColumn = aExpr[j].p->pRight->iColumn;
drh75897232000-05-29 14:26:00 +0000560 int k;
drh967e8b72000-06-21 13:59:10 +0000561 for(k=0; k<pIdx->nColumn; k++){
562 if( pIdx->aiColumn[k]==iColumn ){
drh487ab3c2001-11-08 00:45:21 +0000563 switch( aExpr[j].p->op ){
564 case TK_EQ: {
565 eqMask |= 1<<k;
566 break;
567 }
568 case TK_LE:
569 case TK_LT: {
570 gtMask |= 1<<k;
571 break;
572 }
573 case TK_GE:
574 case TK_GT: {
575 ltMask |= 1<<k;
576 break;
577 }
578 default: {
579 /* CANT_HAPPEN */
580 assert( 0 );
581 break;
582 }
583 }
drh75897232000-05-29 14:26:00 +0000584 break;
585 }
586 }
587 }
588 }
drhc045ec52002-12-04 20:01:06 +0000589
590 /* The following loop ends with nEq set to the number of columns
591 ** on the left of the index with == constraints.
592 */
drh487ab3c2001-11-08 00:45:21 +0000593 for(nEq=0; nEq<pIdx->nColumn; nEq++){
594 m = (1<<(nEq+1))-1;
595 if( (m & eqMask)!=m ) break;
596 }
drhc045ec52002-12-04 20:01:06 +0000597 score = nEq*8; /* Base score is 8 times number of == constraints */
drh487ab3c2001-11-08 00:45:21 +0000598 m = 1<<nEq;
drhc045ec52002-12-04 20:01:06 +0000599 if( m & ltMask ) score++; /* Increase score for a < constraint */
600 if( m & gtMask ) score+=2; /* Increase score for a > constraint */
601 if( score==0 && inMask ) score = 4; /* Default score for IN constraint */
drh487ab3c2001-11-08 00:45:21 +0000602 if( score>bestScore ){
603 pBestIdx = pIdx;
604 bestScore = score;
drh75897232000-05-29 14:26:00 +0000605 }
606 }
drh6b563442001-11-07 16:48:26 +0000607 pWInfo->a[i].pIdx = pBestIdx;
drh487ab3c2001-11-08 00:45:21 +0000608 pWInfo->a[i].score = bestScore;
drhc045ec52002-12-04 20:01:06 +0000609 pWInfo->a[i].bRev = 0;
drh7e391e12000-05-30 20:17:49 +0000610 loopMask |= 1<<idx;
drh6b563442001-11-07 16:48:26 +0000611 if( pBestIdx ){
drh832508b2002-03-02 17:04:07 +0000612 pWInfo->a[i].iCur = pParse->nTab++;
613 pWInfo->peakNTab = pParse->nTab;
drh6b563442001-11-07 16:48:26 +0000614 }
drh75897232000-05-29 14:26:00 +0000615 }
616
drhe3184742002-06-19 14:27:05 +0000617 /* Check to see if the ORDER BY clause is or can be satisfied by the
618 ** use of an index on the first table.
619 */
620 if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
621 Index *pSortIdx;
622 Index *pIdx;
623 Table *pTab;
drhc045ec52002-12-04 20:01:06 +0000624 int bRev = 0;
drhe3184742002-06-19 14:27:05 +0000625
626 pTab = pTabList->a[0].pTab;
627 pIdx = pWInfo->a[0].pIdx;
628 if( pIdx && pWInfo->a[0].score==4 ){
drhc045ec52002-12-04 20:01:06 +0000629 /* If there is already an IN index on the left-most table,
630 ** it will not give the correct sort order.
631 ** So, pretend that no suitable index is found.
drhe3184742002-06-19 14:27:05 +0000632 */
633 pSortIdx = 0;
634 }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
635 /* If the left-most column is accessed using its ROWID, then do
636 ** not try to sort by index.
637 */
638 pSortIdx = 0;
639 }else{
drhdd4852c2002-12-04 21:50:16 +0000640 int nEqCol = (pWInfo->a[0].score+4)/8;
641 pSortIdx = findSortingIndex(pTab, base, *ppOrderBy, pIdx, nEqCol, &bRev);
drhe3184742002-06-19 14:27:05 +0000642 }
643 if( pSortIdx && (pIdx==0 || pIdx==pSortIdx) ){
644 if( pIdx==0 ){
645 pWInfo->a[0].pIdx = pSortIdx;
646 pWInfo->a[0].iCur = pParse->nTab++;
647 pWInfo->peakNTab = pParse->nTab;
648 }
drhc045ec52002-12-04 20:01:06 +0000649 pWInfo->a[0].bRev = bRev;
drhe3184742002-06-19 14:27:05 +0000650 *ppOrderBy = 0;
651 }
652 }
653
drh6b563442001-11-07 16:48:26 +0000654 /* Open all tables in the pTabList and all indices used by those tables.
drh75897232000-05-29 14:26:00 +0000655 */
drhad3cab52002-05-24 02:04:32 +0000656 for(i=0; i<pTabList->nSrc; i++){
drhf57b3392001-10-08 13:22:32 +0000657 int openOp;
658 Table *pTab;
659
660 pTab = pTabList->a[i].pTab;
drha76b5df2002-02-23 02:32:10 +0000661 if( pTab->isTransient || pTab->pSelect ) continue;
drhf57b3392001-10-08 13:22:32 +0000662 openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
drh99fcd712001-10-13 01:06:47 +0000663 sqliteVdbeAddOp(v, openOp, base+i, pTab->tnum);
664 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drh50e5dad2001-09-15 00:57:28 +0000665 if( i==0 && !pParse->schemaVerified &&
666 (pParse->db->flags & SQLITE_InTrans)==0 ){
drh99fcd712001-10-13 01:06:47 +0000667 sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
drh50e5dad2001-09-15 00:57:28 +0000668 pParse->schemaVerified = 1;
669 }
drh6b563442001-11-07 16:48:26 +0000670 if( pWInfo->a[i].pIdx!=0 ){
671 sqliteVdbeAddOp(v, openOp, pWInfo->a[i].iCur, pWInfo->a[i].pIdx->tnum);
672 sqliteVdbeChangeP3(v, -1, pWInfo->a[i].pIdx->zName, P3_STATIC);
drh75897232000-05-29 14:26:00 +0000673 }
674 }
675
676 /* Generate the code to do the search
677 */
drh75897232000-05-29 14:26:00 +0000678 loopMask = 0;
drhad3cab52002-05-24 02:04:32 +0000679 for(i=0; i<pTabList->nSrc; i++){
drh75897232000-05-29 14:26:00 +0000680 int j, k;
681 int idx = aOrder[i];
drhc4a3c772001-04-04 11:48:57 +0000682 Index *pIdx;
drh6b563442001-11-07 16:48:26 +0000683 WhereLevel *pLevel = &pWInfo->a[i];
drh75897232000-05-29 14:26:00 +0000684
drhad2d8302002-05-24 20:31:36 +0000685 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +0000686 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +0000687 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +0000688 */
689 if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
690 if( !pParse->nMem ) pParse->nMem++;
691 pLevel->iLeftJoin = pParse->nMem++;
692 sqliteVdbeAddOp(v, OP_String, 0, 0);
693 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
694 }
695
drh8aff1012001-12-22 14:49:24 +0000696 pIdx = pLevel->pIdx;
drhd99f7062002-06-08 23:25:08 +0000697 pLevel->inOp = OP_Noop;
drh8aff1012001-12-22 14:49:24 +0000698 if( i<ARRAYSIZE(iDirectEq) && iDirectEq[i]>=0 ){
699 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +0000700 ** equality comparison against the ROWID field. Or
701 ** we reference multiple rows using a "rowid IN (...)"
702 ** construct.
drhc4a3c772001-04-04 11:48:57 +0000703 */
drh8aff1012001-12-22 14:49:24 +0000704 k = iDirectEq[i];
705 assert( k<nExpr );
706 assert( aExpr[k].p!=0 );
707 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
drhd99f7062002-06-08 23:25:08 +0000708 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
drh8aff1012001-12-22 14:49:24 +0000709 if( aExpr[k].idxLeft==idx ){
drhd99f7062002-06-08 23:25:08 +0000710 Expr *pX = aExpr[k].p;
711 if( pX->op!=TK_IN ){
712 sqliteExprCode(pParse, aExpr[k].p->pRight);
713 }else if( pX->pList ){
714 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
715 pLevel->inOp = OP_SetNext;
716 pLevel->inP1 = pX->iTable;
717 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
718 }else{
719 assert( pX->pSelect );
720 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
721 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
722 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
723 pLevel->inOp = OP_Next;
724 pLevel->inP1 = pX->iTable;
725 }
drh8aff1012001-12-22 14:49:24 +0000726 }else{
727 sqliteExprCode(pParse, aExpr[k].p->pLeft);
drhc4a3c772001-04-04 11:48:57 +0000728 }
drh8aff1012001-12-22 14:49:24 +0000729 aExpr[k].p = 0;
drhd99f7062002-06-08 23:25:08 +0000730 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
drhf1351b62002-07-31 19:50:26 +0000731 sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
drhd99f7062002-06-08 23:25:08 +0000732 haveKey = 0;
drh6b125452002-01-28 15:53:03 +0000733 sqliteVdbeAddOp(v, OP_NotExists, base+idx, brk);
drh6b563442001-11-07 16:48:26 +0000734 pLevel->op = OP_Noop;
drhe3184742002-06-19 14:27:05 +0000735 }else if( pIdx!=0 && pLevel->score>0 && pLevel->score%4==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000736 /* Case 2: There is an index and all terms of the WHERE clause that
737 ** refer to the index use the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +0000738 */
drh6b563442001-11-07 16:48:26 +0000739 int start;
drh487ab3c2001-11-08 00:45:21 +0000740 int testOp;
drhc045ec52002-12-04 20:01:06 +0000741 int nColumn = (pLevel->score+4)/8;
drhd99f7062002-06-08 23:25:08 +0000742 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
drh487ab3c2001-11-08 00:45:21 +0000743 for(j=0; j<nColumn; j++){
drh75897232000-05-29 14:26:00 +0000744 for(k=0; k<nExpr; k++){
drhd99f7062002-06-08 23:25:08 +0000745 Expr *pX = aExpr[k].p;
746 if( pX==0 ) continue;
drh75897232000-05-29 14:26:00 +0000747 if( aExpr[k].idxLeft==idx
748 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
drhd99f7062002-06-08 23:25:08 +0000749 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +0000750 ){
drhd99f7062002-06-08 23:25:08 +0000751 if( pX->op==TK_EQ ){
752 sqliteExprCode(pParse, pX->pRight);
753 aExpr[k].p = 0;
754 break;
755 }
756 if( pX->op==TK_IN && nColumn==1 ){
757 if( pX->pList ){
758 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
759 pLevel->inOp = OP_SetNext;
760 pLevel->inP1 = pX->iTable;
761 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
762 }else{
763 assert( pX->pSelect );
764 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
765 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
766 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
767 pLevel->inOp = OP_Next;
768 pLevel->inP1 = pX->iTable;
769 }
770 aExpr[k].p = 0;
771 break;
772 }
drh75897232000-05-29 14:26:00 +0000773 }
774 if( aExpr[k].idxRight==idx
drh487ab3c2001-11-08 00:45:21 +0000775 && aExpr[k].p->op==TK_EQ
drh75897232000-05-29 14:26:00 +0000776 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
drh967e8b72000-06-21 13:59:10 +0000777 && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +0000778 ){
779 sqliteExprCode(pParse, aExpr[k].p->pLeft);
780 aExpr[k].p = 0;
781 break;
782 }
783 }
784 }
drh6b563442001-11-07 16:48:26 +0000785 pLevel->iMem = pParse->nMem++;
drh6b563442001-11-07 16:48:26 +0000786 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
drh487ab3c2001-11-08 00:45:21 +0000787 sqliteVdbeAddOp(v, OP_MakeKey, nColumn, 0);
drha9e99ae2002-08-13 23:02:57 +0000788 sqliteAddIdxKeyType(v, pIdx);
drhc045ec52002-12-04 20:01:06 +0000789 if( nColumn==pIdx->nColumn || pLevel->bRev ){
drh487ab3c2001-11-08 00:45:21 +0000790 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
791 testOp = OP_IdxGT;
792 }else{
793 sqliteVdbeAddOp(v, OP_Dup, 0, 0);
794 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
795 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
796 testOp = OP_IdxGE;
797 }
drhc045ec52002-12-04 20:01:06 +0000798 if( pLevel->bRev ){
799 /* Scan in reverse order */
800 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
801 sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
802 start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
803 sqliteVdbeAddOp(v, OP_IdxLT, pLevel->iCur, brk);
804 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
805 pLevel->op = OP_Prev;
806 }else{
807 /* Scan in the forward order */
808 sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
809 start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
810 sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
811 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
812 pLevel->op = OP_Next;
813 }
drhad3cab52002-05-24 02:04:32 +0000814 if( i==pTabList->nSrc-1 && pushKey ){
drh75897232000-05-29 14:26:00 +0000815 haveKey = 1;
816 }else{
drh99fcd712001-10-13 01:06:47 +0000817 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
drh75897232000-05-29 14:26:00 +0000818 haveKey = 0;
819 }
drh6b563442001-11-07 16:48:26 +0000820 pLevel->p1 = pLevel->iCur;
821 pLevel->p2 = start;
drh8aff1012001-12-22 14:49:24 +0000822 }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
823 /* Case 3: We have an inequality comparison against the ROWID field.
824 */
825 int testOp = OP_Noop;
826 int start;
827
828 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
829 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
830 if( iDirectGt[i]>=0 ){
831 k = iDirectGt[i];
832 assert( k<nExpr );
833 assert( aExpr[k].p!=0 );
834 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
835 if( aExpr[k].idxLeft==idx ){
836 sqliteExprCode(pParse, aExpr[k].p->pRight);
837 }else{
838 sqliteExprCode(pParse, aExpr[k].p->pLeft);
839 }
drhf1351b62002-07-31 19:50:26 +0000840 sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
drh8aff1012001-12-22 14:49:24 +0000841 if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
842 sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
843 }
844 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, brk);
845 aExpr[k].p = 0;
846 }else{
847 sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
848 }
849 if( iDirectLt[i]>=0 ){
850 k = iDirectLt[i];
851 assert( k<nExpr );
852 assert( aExpr[k].p!=0 );
853 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
854 if( aExpr[k].idxLeft==idx ){
855 sqliteExprCode(pParse, aExpr[k].p->pRight);
856 }else{
857 sqliteExprCode(pParse, aExpr[k].p->pLeft);
858 }
drhf1351b62002-07-31 19:50:26 +0000859 sqliteVdbeAddOp(v, OP_MustBeInt, 1, sqliteVdbeCurrentAddr(v)+1);
drh8aff1012001-12-22 14:49:24 +0000860 pLevel->iMem = pParse->nMem++;
861 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
862 if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
863 testOp = OP_Ge;
864 }else{
865 testOp = OP_Gt;
866 }
867 aExpr[k].p = 0;
868 }
869 start = sqliteVdbeCurrentAddr(v);
870 pLevel->op = OP_Next;
871 pLevel->p1 = base+idx;
872 pLevel->p2 = start;
873 if( testOp!=OP_Noop ){
874 sqliteVdbeAddOp(v, OP_Recno, base+idx, 0);
875 sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
876 sqliteVdbeAddOp(v, testOp, 0, brk);
877 }
878 haveKey = 0;
879 }else if( pIdx==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000880 /* Case 4: There is no usable index. We must do a complete
drh8aff1012001-12-22 14:49:24 +0000881 ** scan of the entire database table.
882 */
883 int start;
884
885 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
886 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
887 sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
888 start = sqliteVdbeCurrentAddr(v);
889 pLevel->op = OP_Next;
890 pLevel->p1 = base+idx;
891 pLevel->p2 = start;
892 haveKey = 0;
drh487ab3c2001-11-08 00:45:21 +0000893 }else{
drhc27a1ce2002-06-14 20:58:45 +0000894 /* Case 5: The WHERE clause term that refers to the right-most
895 ** column of the index is an inequality. For example, if
896 ** the index is on (x,y,z) and the WHERE clause is of the
897 ** form "x=5 AND y<10" then this case is used. Only the
898 ** right-most column can be an inequality - the rest must
899 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +0000900 **
901 ** This case is also used when there are no WHERE clause
902 ** constraints but an index is selected anyway, in order
903 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +0000904 */
905 int score = pLevel->score;
drhc045ec52002-12-04 20:01:06 +0000906 int nEqColumn = score/8;
drh487ab3c2001-11-08 00:45:21 +0000907 int start;
908 int leFlag, geFlag;
909 int testOp;
910
911 /* Evaluate the equality constraints
912 */
913 for(j=0; j<nEqColumn; j++){
914 for(k=0; k<nExpr; k++){
915 if( aExpr[k].p==0 ) continue;
916 if( aExpr[k].idxLeft==idx
917 && aExpr[k].p->op==TK_EQ
918 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
919 && aExpr[k].p->pLeft->iColumn==pIdx->aiColumn[j]
920 ){
921 sqliteExprCode(pParse, aExpr[k].p->pRight);
922 aExpr[k].p = 0;
923 break;
924 }
925 if( aExpr[k].idxRight==idx
926 && aExpr[k].p->op==TK_EQ
927 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
928 && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
929 ){
930 sqliteExprCode(pParse, aExpr[k].p->pLeft);
931 aExpr[k].p = 0;
932 break;
933 }
934 }
935 }
936
drhc27a1ce2002-06-14 20:58:45 +0000937 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +0000938 ** used twice: once to make the termination key and once to make the
939 ** start key.
940 */
941 for(j=0; j<nEqColumn; j++){
942 sqliteVdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
943 }
944
drhc045ec52002-12-04 20:01:06 +0000945 /* Labels for the beginning and end of the loop
946 */
947 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
948 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
949
drh487ab3c2001-11-08 00:45:21 +0000950 /* Generate the termination key. This is the key value that
951 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +0000952 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +0000953 **
954 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
955 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +0000956 */
957 if( (score & 1)!=0 ){
958 for(k=0; k<nExpr; k++){
959 Expr *pExpr = aExpr[k].p;
960 if( pExpr==0 ) continue;
961 if( aExpr[k].idxLeft==idx
962 && (pExpr->op==TK_LT || pExpr->op==TK_LE)
963 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
964 && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
965 ){
966 sqliteExprCode(pParse, pExpr->pRight);
967 leFlag = pExpr->op==TK_LE;
968 aExpr[k].p = 0;
969 break;
970 }
971 if( aExpr[k].idxRight==idx
972 && (pExpr->op==TK_GT || pExpr->op==TK_GE)
973 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
974 && pExpr->pRight->iColumn==pIdx->aiColumn[j]
975 ){
976 sqliteExprCode(pParse, pExpr->pLeft);
977 leFlag = pExpr->op==TK_GE;
978 aExpr[k].p = 0;
979 break;
980 }
981 }
982 testOp = OP_IdxGE;
983 }else{
984 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
985 leFlag = 1;
986 }
987 if( testOp!=OP_Noop ){
988 pLevel->iMem = pParse->nMem++;
989 sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + (score & 1), 0);
drha9e99ae2002-08-13 23:02:57 +0000990 sqliteAddIdxKeyType(v, pIdx);
drh487ab3c2001-11-08 00:45:21 +0000991 if( leFlag ){
992 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
993 }
drhc045ec52002-12-04 20:01:06 +0000994 if( pLevel->bRev ){
995 sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
996 }else{
997 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
998 }
999 }else if( pLevel->bRev ){
1000 sqliteVdbeAddOp(v, OP_Last, pLevel->iCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001001 }
1002
1003 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001004 ** bound on the search. There is no start key if there are no
1005 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001006 ** that case, generate a "Rewind" instruction in place of the
1007 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001008 **
1009 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1010 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001011 */
1012 if( (score & 2)!=0 ){
1013 for(k=0; k<nExpr; k++){
1014 Expr *pExpr = aExpr[k].p;
1015 if( pExpr==0 ) continue;
1016 if( aExpr[k].idxLeft==idx
1017 && (pExpr->op==TK_GT || pExpr->op==TK_GE)
1018 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
1019 && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
1020 ){
1021 sqliteExprCode(pParse, pExpr->pRight);
1022 geFlag = pExpr->op==TK_GE;
1023 aExpr[k].p = 0;
1024 break;
1025 }
1026 if( aExpr[k].idxRight==idx
1027 && (pExpr->op==TK_LT || pExpr->op==TK_LE)
1028 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
1029 && pExpr->pRight->iColumn==pIdx->aiColumn[j]
1030 ){
1031 sqliteExprCode(pParse, pExpr->pLeft);
1032 geFlag = pExpr->op==TK_LE;
1033 aExpr[k].p = 0;
1034 break;
1035 }
1036 }
drh7900ead2001-11-12 13:51:43 +00001037 }else{
1038 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001039 }
drh487ab3c2001-11-08 00:45:21 +00001040 if( nEqColumn>0 || (score&2)!=0 ){
1041 sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + ((score&2)!=0), 0);
drha9e99ae2002-08-13 23:02:57 +00001042 sqliteAddIdxKeyType(v, pIdx);
drh487ab3c2001-11-08 00:45:21 +00001043 if( !geFlag ){
1044 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
1045 }
drhc045ec52002-12-04 20:01:06 +00001046 if( pLevel->bRev ){
1047 pLevel->iMem = pParse->nMem++;
1048 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
1049 testOp = OP_IdxLT;
1050 }else{
1051 sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
1052 }
1053 }else if( pLevel->bRev ){
1054 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001055 }else{
1056 sqliteVdbeAddOp(v, OP_Rewind, pLevel->iCur, brk);
1057 }
1058
1059 /* Generate the the top of the loop. If there is a termination
1060 ** key we have to test for that key and abort at the top of the
1061 ** loop.
1062 */
1063 start = sqliteVdbeCurrentAddr(v);
1064 if( testOp!=OP_Noop ){
1065 sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1066 sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
1067 }
1068 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
drhad3cab52002-05-24 02:04:32 +00001069 if( i==pTabList->nSrc-1 && pushKey ){
drh487ab3c2001-11-08 00:45:21 +00001070 haveKey = 1;
1071 }else{
1072 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
1073 haveKey = 0;
1074 }
1075
1076 /* Record the instruction used to terminate the loop.
1077 */
drhc045ec52002-12-04 20:01:06 +00001078 pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
drh487ab3c2001-11-08 00:45:21 +00001079 pLevel->p1 = pLevel->iCur;
1080 pLevel->p2 = start;
drh75897232000-05-29 14:26:00 +00001081 }
1082 loopMask |= 1<<idx;
1083
1084 /* Insert code to test every subexpression that can be completely
1085 ** computed using the current set of tables.
1086 */
1087 for(j=0; j<nExpr; j++){
1088 if( aExpr[j].p==0 ) continue;
drh3f6b5482002-04-02 13:26:10 +00001089 if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
drh1f162302002-10-27 19:35:33 +00001090 if( pLevel->iLeftJoin && !ExprHasProperty(aExpr[j].p,EP_FromJoin) ){
1091 continue;
1092 }
drh75897232000-05-29 14:26:00 +00001093 if( haveKey ){
drh573bd272001-02-19 23:23:38 +00001094 haveKey = 0;
drh99fcd712001-10-13 01:06:47 +00001095 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
drh75897232000-05-29 14:26:00 +00001096 }
drhf5905aa2002-05-26 20:54:33 +00001097 sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
drh75897232000-05-29 14:26:00 +00001098 aExpr[j].p = 0;
1099 }
1100 brk = cont;
drhad2d8302002-05-24 20:31:36 +00001101
1102 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1103 ** at least one row of the right table has matched the left table.
1104 */
1105 if( pLevel->iLeftJoin ){
1106 pLevel->top = sqliteVdbeCurrentAddr(v);
1107 sqliteVdbeAddOp(v, OP_Integer, 1, 0);
1108 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drh1cc093c2002-06-24 22:01:57 +00001109 for(j=0; j<nExpr; j++){
1110 if( aExpr[j].p==0 ) continue;
1111 if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
1112 if( haveKey ){
drh3b167c72002-06-28 12:18:47 +00001113 /* Cannot happen. "haveKey" can only be true if pushKey is true
1114 ** an pushKey can only be true for DELETE and UPDATE and there are
1115 ** no outer joins with DELETE and UPDATE.
1116 */
drh1cc093c2002-06-24 22:01:57 +00001117 haveKey = 0;
1118 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
1119 }
1120 sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
1121 aExpr[j].p = 0;
1122 }
drhad2d8302002-05-24 20:31:36 +00001123 }
drh75897232000-05-29 14:26:00 +00001124 }
1125 pWInfo->iContinue = cont;
1126 if( pushKey && !haveKey ){
drh99fcd712001-10-13 01:06:47 +00001127 sqliteVdbeAddOp(v, OP_Recno, base, 0);
drh75897232000-05-29 14:26:00 +00001128 }
1129 sqliteFree(aOrder);
1130 return pWInfo;
1131}
1132
1133/*
drhc27a1ce2002-06-14 20:58:45 +00001134** Generate the end of the WHERE loop. See comments on
1135** sqliteWhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001136*/
1137void sqliteWhereEnd(WhereInfo *pWInfo){
1138 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001139 int i;
drh19a775c2000-06-05 18:54:46 +00001140 int base = pWInfo->base;
drh6b563442001-11-07 16:48:26 +00001141 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001142 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001143
drhad3cab52002-05-24 02:04:32 +00001144 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001145 pLevel = &pWInfo->a[i];
1146 sqliteVdbeResolveLabel(v, pLevel->cont);
1147 if( pLevel->op!=OP_Noop ){
1148 sqliteVdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001149 }
drh6b563442001-11-07 16:48:26 +00001150 sqliteVdbeResolveLabel(v, pLevel->brk);
drhd99f7062002-06-08 23:25:08 +00001151 if( pLevel->inOp!=OP_Noop ){
1152 sqliteVdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
1153 }
drhad2d8302002-05-24 20:31:36 +00001154 if( pLevel->iLeftJoin ){
1155 int addr;
1156 addr = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh7f09b3e2002-08-13 13:15:49 +00001157 sqliteVdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iCur>=0));
drhad2d8302002-05-24 20:31:36 +00001158 sqliteVdbeAddOp(v, OP_NullRow, base+i, 0);
drh7f09b3e2002-08-13 13:15:49 +00001159 if( pLevel->iCur>=0 ){
1160 sqliteVdbeAddOp(v, OP_NullRow, pLevel->iCur, 0);
1161 }
drhad2d8302002-05-24 20:31:36 +00001162 sqliteVdbeAddOp(v, OP_Goto, 0, pLevel->top);
1163 }
drh19a775c2000-06-05 18:54:46 +00001164 }
drh6b563442001-11-07 16:48:26 +00001165 sqliteVdbeResolveLabel(v, pWInfo->iBreak);
drhad3cab52002-05-24 02:04:32 +00001166 for(i=0; i<pTabList->nSrc; i++){
drh22f70c32002-02-18 01:17:00 +00001167 if( pTabList->a[i].pTab->isTransient ) continue;
drh6b563442001-11-07 16:48:26 +00001168 pLevel = &pWInfo->a[i];
1169 sqliteVdbeAddOp(v, OP_Close, base+i, 0);
1170 if( pLevel->pIdx!=0 ){
1171 sqliteVdbeAddOp(v, OP_Close, pLevel->iCur, 0);
1172 }
drh19a775c2000-06-05 18:54:46 +00001173 }
drh142e30d2002-08-28 03:00:58 +00001174#if 0 /* Never reuse a cursor */
drh832508b2002-03-02 17:04:07 +00001175 if( pWInfo->pParse->nTab==pWInfo->peakNTab ){
1176 pWInfo->pParse->nTab = pWInfo->savedNTab;
1177 }
drh142e30d2002-08-28 03:00:58 +00001178#endif
drh75897232000-05-29 14:26:00 +00001179 sqliteFree(pWInfo);
1180 return;
1181}