blob: d0eb170ab7b8179784d587530e566d650f9dfc4e [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**
drh1cc093c2002-06-24 22:01:57 +000016** $Id: where.c,v 1.55 2002/06/24 22:01:59 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 */
29 short int idxLeft; /* p->pLeft is a column in this table number. -1 if
drh967e8b72000-06-21 13:59:10 +000030 ** p->pLeft is not the column of any table */
drhe3184742002-06-19 14:27:05 +000031 short int idxRight; /* p->pRight is a column in this table number. -1 if
drh967e8b72000-06-21 13:59:10 +000032 ** p->pRight is not the column of any table */
drhe3184742002-06-19 14:27:05 +000033 unsigned prereqLeft; /* Bitmask of tables referenced by p->pLeft */
34 unsigned prereqRight; /* Bitmask of tables referenced by p->pRight */
35 unsigned prereqAll; /* Bitmask of tables referenced by p */
drh75897232000-05-29 14:26:00 +000036};
37
38/*
39** Determine the number of elements in an array.
40*/
41#define ARRAYSIZE(X) (sizeof(X)/sizeof(X[0]))
42
43/*
44** This routine is used to divide the WHERE expression into subexpressions
45** separated by the AND operator.
46**
47** aSlot[] is an array of subexpressions structures.
48** There are nSlot spaces left in this array. This routine attempts to
49** split pExpr into subexpressions and fills aSlot[] with those subexpressions.
50** The return value is the number of slots filled.
51*/
52static int exprSplit(int nSlot, ExprInfo *aSlot, Expr *pExpr){
53 int cnt = 0;
54 if( pExpr==0 || nSlot<1 ) return 0;
55 if( nSlot==1 || pExpr->op!=TK_AND ){
56 aSlot[0].p = pExpr;
57 return 1;
58 }
59 if( pExpr->pLeft->op!=TK_AND ){
60 aSlot[0].p = pExpr->pLeft;
61 cnt = 1 + exprSplit(nSlot-1, &aSlot[1], pExpr->pRight);
62 }else{
63 cnt = exprSplit(nSlot, aSlot, pExpr->pRight);
64 cnt += exprSplit(nSlot-cnt, &aSlot[cnt], pExpr->pLeft);
65 }
66 return cnt;
67}
68
69/*
70** This routine walks (recursively) an expression tree and generates
71** a bitmask indicating which tables are used in that expression
drhe3184742002-06-19 14:27:05 +000072** tree. Bit 0 of the mask is set if table base+0 is used. Bit 1
73** is set if table base+1 is used. And so forth.
drh75897232000-05-29 14:26:00 +000074**
75** In order for this routine to work, the calling function must have
76** previously invoked sqliteExprResolveIds() on the expression. See
77** the header comment on that routine for additional information.
drh19a775c2000-06-05 18:54:46 +000078**
79** "base" is the cursor number (the value of the iTable field) that
drhe3184742002-06-19 14:27:05 +000080** corresponds to the first entry in the list of tables that appear
81** in the FROM clause of a SELECT. For UPDATE and DELETE statements
82** there is just a single table with "base" as the cursor number.
drh75897232000-05-29 14:26:00 +000083*/
drh19a775c2000-06-05 18:54:46 +000084static int exprTableUsage(int base, Expr *p){
drh75897232000-05-29 14:26:00 +000085 unsigned int mask = 0;
86 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +000087 if( p->op==TK_COLUMN ){
drh19a775c2000-06-05 18:54:46 +000088 return 1<< (p->iTable - base);
drh75897232000-05-29 14:26:00 +000089 }
90 if( p->pRight ){
drh19a775c2000-06-05 18:54:46 +000091 mask = exprTableUsage(base, p->pRight);
drh75897232000-05-29 14:26:00 +000092 }
93 if( p->pLeft ){
drh19a775c2000-06-05 18:54:46 +000094 mask |= exprTableUsage(base, p->pLeft);
drh75897232000-05-29 14:26:00 +000095 }
drhdd579122002-04-02 01:58:57 +000096 if( p->pList ){
97 int i;
98 for(i=0; i<p->pList->nExpr; i++){
99 mask |= exprTableUsage(base, p->pList->a[i].pExpr);
100 }
101 }
drh75897232000-05-29 14:26:00 +0000102 return mask;
103}
104
105/*
drh487ab3c2001-11-08 00:45:21 +0000106** Return TRUE if the given operator is one of the operators that is
107** allowed for an indexable WHERE clause. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000108** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000109*/
110static int allowedOp(int op){
111 switch( op ){
112 case TK_LT:
113 case TK_LE:
114 case TK_GT:
115 case TK_GE:
116 case TK_EQ:
drhd99f7062002-06-08 23:25:08 +0000117 case TK_IN:
drh487ab3c2001-11-08 00:45:21 +0000118 return 1;
119 default:
120 return 0;
121 }
122}
123
124/*
drh75897232000-05-29 14:26:00 +0000125** The input to this routine is an ExprInfo structure with only the
126** "p" field filled in. The job of this routine is to analyze the
127** subexpression and populate all the other fields of the ExprInfo
128** structure.
drh19a775c2000-06-05 18:54:46 +0000129**
130** "base" is the cursor number (the value of the iTable field) that
drh832508b2002-03-02 17:04:07 +0000131** corresponds to the first entry in the table list.
drh75897232000-05-29 14:26:00 +0000132*/
drh19a775c2000-06-05 18:54:46 +0000133static void exprAnalyze(int base, ExprInfo *pInfo){
drh75897232000-05-29 14:26:00 +0000134 Expr *pExpr = pInfo->p;
drh19a775c2000-06-05 18:54:46 +0000135 pInfo->prereqLeft = exprTableUsage(base, pExpr->pLeft);
136 pInfo->prereqRight = exprTableUsage(base, pExpr->pRight);
drh3f6b5482002-04-02 13:26:10 +0000137 pInfo->prereqAll = exprTableUsage(base, pExpr);
drh75897232000-05-29 14:26:00 +0000138 pInfo->indexable = 0;
139 pInfo->idxLeft = -1;
140 pInfo->idxRight = -1;
drh487ab3c2001-11-08 00:45:21 +0000141 if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
drhd99f7062002-06-08 23:25:08 +0000142 if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
drh19a775c2000-06-05 18:54:46 +0000143 pInfo->idxRight = pExpr->pRight->iTable - base;
drh75897232000-05-29 14:26:00 +0000144 pInfo->indexable = 1;
145 }
drh967e8b72000-06-21 13:59:10 +0000146 if( pExpr->pLeft->op==TK_COLUMN ){
drh19a775c2000-06-05 18:54:46 +0000147 pInfo->idxLeft = pExpr->pLeft->iTable - base;
drh75897232000-05-29 14:26:00 +0000148 pInfo->indexable = 1;
149 }
150 }
151}
152
153/*
drhe3184742002-06-19 14:27:05 +0000154** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
155** left-most table in the FROM clause of that same SELECT statement and
156** the table has a cursor number of "base".
157**
158** This routine attempts to find an index for pTab that generates the
159** correct record sequence for the given ORDER BY clause. The return value
160** is a pointer to an index that does the job. NULL is returned if the
161** table has no index that will generate the correct sort order.
162**
163** If there are two or more indices that generate the correct sort order
164** and pPreferredIdx is one of those indices, then return pPreferredIdx.
165*/
166static Index *findSortingIndex(
167 Table *pTab, /* The table to be sorted */
168 int base, /* Cursor number for pTab */
169 ExprList *pOrderBy, /* The ORDER BY clause */
170 Index *pPreferredIdx /* Use this index, if possible and not NULL */
171){
172 int i;
173 Index *pMatch;
174 Index *pIdx;
175
176 assert( pOrderBy!=0 );
177 assert( pOrderBy->nExpr>0 );
178 for(i=0; i<pOrderBy->nExpr; i++){
179 Expr *p;
180 if( (pOrderBy->a[i].sortOrder & SQLITE_SO_DIRMASK)!=SQLITE_SO_ASC ){
181 /* Indices can only be used for ascending sort order */
182 return 0;
183 }
184 p = pOrderBy->a[i].pExpr;
185 if( p->op!=TK_COLUMN || p->iTable!=base ){
186 /* Can not use an index sort on anything that is not a column in the
187 ** left-most table of the FROM clause */
188 return 0;
189 }
190 }
191
192 /* If we get this far, it means the ORDER BY clause consists only of
193 ** ascending columns in the left-most table of the FROM clause. Now
194 ** check for a matching index.
195 */
196 pMatch = 0;
197 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
198 if( pIdx->nColumn<pOrderBy->nExpr ) continue;
199 for(i=0; i<pOrderBy->nExpr; i++){
200 if( pOrderBy->a[i].pExpr->iColumn!=pIdx->aiColumn[i] ) break;
201 }
202 if( i>=pOrderBy->nExpr ){
203 pMatch = pIdx;
204 if( pIdx==pPreferredIdx ) break;
205 }
206 }
207 return pMatch;
208}
209
210/*
211** Generate the beginning of the loop used for WHERE clause processing.
drh75897232000-05-29 14:26:00 +0000212** The return value is a pointer to an (opaque) structure that contains
213** information needed to terminate the loop. Later, the calling routine
214** should invoke sqliteWhereEnd() with the return value of this function
215** in order to complete the WHERE clause processing.
216**
217** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +0000218**
219** The basic idea is to do a nested loop, one loop for each table in
220** the FROM clause of a select. (INSERT and UPDATE statements are the
221** same as a SELECT with only a single table in the FROM clause.) For
222** example, if the SQL is this:
223**
224** SELECT * FROM t1, t2, t3 WHERE ...;
225**
226** Then the code generated is conceptually like the following:
227**
228** foreach row1 in t1 do \ Code generated
229** foreach row2 in t2 do |-- by sqliteWhereBegin()
230** foreach row3 in t3 do /
231** ...
232** end \ Code generated
233** end |-- by sqliteWhereEnd()
234** end /
235**
236** There are Btree cursors associated with each table. t1 uses cursor
237** "base". t2 uses cursor "base+1". And so forth. This routine generates
238** the code to open those cursors. sqliteWhereEnd() generates the code
239** to close them.
240**
241** If the WHERE clause is empty, the foreach loops must each scan their
242** entire tables. Thus a three-way join is an O(N^3) operation. But if
243** the tables have indices and there are terms in the WHERE clause that
244** refer to those indices, a complete table scan can be avoided and the
245** code will run much faster. Most of the work of this routine is checking
246** to see if there are indices that can be used to speed up the loop.
247**
248** Terms of the WHERE clause are also used to limit which rows actually
249** make it to the "..." in the middle of the loop. After each "foreach",
250** terms of the WHERE clause that use only terms in that loop and outer
251** loops are evaluated and if false a jump is made around all subsequent
252** inner loops (or around the "..." if the test occurs within the inner-
253** most loop)
254**
255** OUTER JOINS
256**
257** An outer join of tables t1 and t2 is conceptally coded as follows:
258**
259** foreach row1 in t1 do
260** flag = 0
261** foreach row2 in t2 do
262** start:
263** ...
264** flag = 1
265** end
drhe3184742002-06-19 14:27:05 +0000266** if flag==0 then
267** move the row2 cursor to a null row
268** goto start
269** fi
drhc27a1ce2002-06-14 20:58:45 +0000270** end
271**
drhe3184742002-06-19 14:27:05 +0000272** ORDER BY CLAUSE PROCESSING
273**
274** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
275** if there is one. If there is no ORDER BY clause or if this routine
276** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
277**
278** If an index can be used so that the natural output order of the table
279** scan is correct for the ORDER BY clause, then that index is used and
280** *ppOrderBy is set to NULL. This is an optimization that prevents an
281** unnecessary sort of the result set if an index appropriate for the
282** ORDER BY clause already exists.
283**
284** If the where clause loops cannot be arranged to provide the correct
285** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +0000286*/
287WhereInfo *sqliteWhereBegin(
288 Parse *pParse, /* The parser context */
drh832508b2002-03-02 17:04:07 +0000289 int base, /* VDBE cursor index for left-most table in pTabList */
drhad3cab52002-05-24 02:04:32 +0000290 SrcList *pTabList, /* A list of all tables to be scanned */
drh75897232000-05-29 14:26:00 +0000291 Expr *pWhere, /* The WHERE clause */
drhe3184742002-06-19 14:27:05 +0000292 int pushKey, /* If TRUE, leave the table key on the stack */
293 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +0000294){
295 int i; /* Loop counter */
296 WhereInfo *pWInfo; /* Will become the return value of this function */
297 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
298 int brk, cont; /* Addresses used during code generation */
299 int *aOrder; /* Order in which pTabList entries are searched */
300 int nExpr; /* Number of subexpressions in the WHERE clause */
301 int loopMask; /* One bit set for each outer loop */
302 int haveKey; /* True if KEY is on the stack */
drhc4a3c772001-04-04 11:48:57 +0000303 int aDirect[32]; /* If TRUE, then index this table using ROWID */
drh8aff1012001-12-22 14:49:24 +0000304 int iDirectEq[32]; /* Term of the form ROWID==X for the N-th table */
305 int iDirectLt[32]; /* Term of the form ROWID<X or ROWID<=X */
306 int iDirectGt[32]; /* Term of the form ROWID>X or ROWID>=X */
drh75897232000-05-29 14:26:00 +0000307 ExprInfo aExpr[50]; /* The WHERE clause is divided into these expressions */
308
drhc27a1ce2002-06-14 20:58:45 +0000309 /* pushKey is only allowed if there is a single table (as in an INSERT or
310 ** UPDATE statement)
311 */
312 assert( pushKey==0 || pTabList->nSrc==1 );
313
drhe3184742002-06-19 14:27:05 +0000314 /* Allocate space for aOrder[] */
drhad3cab52002-05-24 02:04:32 +0000315 aOrder = sqliteMalloc( sizeof(int) * pTabList->nSrc );
drh75897232000-05-29 14:26:00 +0000316
317 /* Allocate and initialize the WhereInfo structure that will become the
318 ** return value.
319 */
drhad3cab52002-05-24 02:04:32 +0000320 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
drhdaffd0e2001-04-11 14:28:42 +0000321 if( sqlite_malloc_failed ){
drh75897232000-05-29 14:26:00 +0000322 sqliteFree(aOrder);
drhdaffd0e2001-04-11 14:28:42 +0000323 sqliteFree(pWInfo);
drh75897232000-05-29 14:26:00 +0000324 return 0;
325 }
326 pWInfo->pParse = pParse;
327 pWInfo->pTabList = pTabList;
drh832508b2002-03-02 17:04:07 +0000328 pWInfo->base = base;
329 pWInfo->peakNTab = pWInfo->savedNTab = pParse->nTab;
drh08192d52002-04-30 19:20:28 +0000330 pWInfo->iBreak = sqliteVdbeMakeLabel(v);
331
332 /* Special case: a WHERE clause that is constant. Evaluate the
333 ** expression and either jump over all of the code or fall thru.
334 */
335 if( pWhere && sqliteExprIsConstant(pWhere) ){
drhf5905aa2002-05-26 20:54:33 +0000336 sqliteExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +0000337 pWhere = 0;
drh08192d52002-04-30 19:20:28 +0000338 }
drh75897232000-05-29 14:26:00 +0000339
340 /* Split the WHERE clause into as many as 32 separate subexpressions
341 ** where each subexpression is separated by an AND operator. Any additional
342 ** subexpressions are attached in the aExpr[32] and will not enter
343 ** into the query optimizer computations. 32 is chosen as the cutoff
344 ** since that is the number of bits in an integer that we use for an
345 ** expression-used mask.
346 */
347 memset(aExpr, 0, sizeof(aExpr));
348 nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
349
350 /* Analyze all of the subexpressions.
351 */
352 for(i=0; i<nExpr; i++){
drh22f70c32002-02-18 01:17:00 +0000353 exprAnalyze(base, &aExpr[i]);
drh1d1f3052002-05-21 13:18:25 +0000354
355 /* If we are executing a trigger body, remove all references to
356 ** new.* and old.* tables from the prerequisite masks.
357 */
358 if( pParse->trigStack ){
359 int x;
360 if( (x = pParse->trigStack->newIdx) >= 0 ){
361 int mask = ~(1 << (x - base));
362 aExpr[i].prereqRight &= mask;
363 aExpr[i].prereqLeft &= mask;
364 aExpr[i].prereqAll &= mask;
365 }
366 if( (x = pParse->trigStack->oldIdx) >= 0 ){
367 int mask = ~(1 << (x - base));
368 aExpr[i].prereqRight &= mask;
369 aExpr[i].prereqLeft &= mask;
370 aExpr[i].prereqAll &= mask;
371 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000372 }
drh75897232000-05-29 14:26:00 +0000373 }
374
375 /* Figure out a good nesting order for the tables. aOrder[0] will
376 ** be the index in pTabList of the outermost table. aOrder[1] will
drhad3cab52002-05-24 02:04:32 +0000377 ** be the first nested loop and so on. aOrder[pTabList->nSrc-1] will
drh75897232000-05-29 14:26:00 +0000378 ** be the innermost loop.
379 **
drh1d1f3052002-05-21 13:18:25 +0000380 ** Someday we will put in a good algorithm here to reorder the loops
drh75897232000-05-29 14:26:00 +0000381 ** for an effiecient query. But for now, just use whatever order the
382 ** tables appear in in the pTabList.
383 */
drhad3cab52002-05-24 02:04:32 +0000384 for(i=0; i<pTabList->nSrc; i++){
drh75897232000-05-29 14:26:00 +0000385 aOrder[i] = i;
386 }
387
388 /* Figure out what index to use (if any) for each nested loop.
drh6b563442001-11-07 16:48:26 +0000389 ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
drhad3cab52002-05-24 02:04:32 +0000390 ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
drh8aff1012001-12-22 14:49:24 +0000391 ** loop.
392 **
393 ** If terms exist that use the ROWID of any table, then set the
394 ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
395 ** to the index of the term containing the ROWID. We always prefer
396 ** to use a ROWID which can directly access a table rather than an
drh0a36c572002-02-18 22:49:59 +0000397 ** index which requires reading an index first to get the rowid then
398 ** doing a second read of the actual database table.
drh75897232000-05-29 14:26:00 +0000399 **
400 ** Actually, if there are more than 32 tables in the join, only the
drh0a36c572002-02-18 22:49:59 +0000401 ** first 32 tables are candidates for indices. This is (again) due
402 ** to the limit of 32 bits in an integer bitmask.
drh75897232000-05-29 14:26:00 +0000403 */
404 loopMask = 0;
drhad3cab52002-05-24 02:04:32 +0000405 for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(aDirect); i++){
drhc4a3c772001-04-04 11:48:57 +0000406 int j;
drh75897232000-05-29 14:26:00 +0000407 int idx = aOrder[i];
408 Table *pTab = pTabList->a[idx].pTab;
409 Index *pIdx;
410 Index *pBestIdx = 0;
drh487ab3c2001-11-08 00:45:21 +0000411 int bestScore = 0;
drh75897232000-05-29 14:26:00 +0000412
drhc4a3c772001-04-04 11:48:57 +0000413 /* Check to see if there is an expression that uses only the
drh8aff1012001-12-22 14:49:24 +0000414 ** ROWID field of this table. For terms of the form ROWID==expr
415 ** set iDirectEq[i] to the index of the term. For terms of the
416 ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
417 ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
drhc4a3c772001-04-04 11:48:57 +0000418 */
drh8aff1012001-12-22 14:49:24 +0000419 iDirectEq[i] = -1;
420 iDirectLt[i] = -1;
421 iDirectGt[i] = -1;
drhc4a3c772001-04-04 11:48:57 +0000422 for(j=0; j<nExpr; j++){
423 if( aExpr[j].idxLeft==idx && aExpr[j].p->pLeft->iColumn<0
424 && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
drh8aff1012001-12-22 14:49:24 +0000425 switch( aExpr[j].p->op ){
drhd99f7062002-06-08 23:25:08 +0000426 case TK_IN:
drh8aff1012001-12-22 14:49:24 +0000427 case TK_EQ: iDirectEq[i] = j; break;
428 case TK_LE:
429 case TK_LT: iDirectLt[i] = j; break;
430 case TK_GE:
431 case TK_GT: iDirectGt[i] = j; break;
432 }
drhc4a3c772001-04-04 11:48:57 +0000433 }
434 if( aExpr[j].idxRight==idx && aExpr[j].p->pRight->iColumn<0
435 && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
drh8aff1012001-12-22 14:49:24 +0000436 switch( aExpr[j].p->op ){
437 case TK_EQ: iDirectEq[i] = j; break;
438 case TK_LE:
439 case TK_LT: iDirectGt[i] = j; break;
440 case TK_GE:
441 case TK_GT: iDirectLt[i] = j; break;
442 }
drhc4a3c772001-04-04 11:48:57 +0000443 }
444 }
drh8aff1012001-12-22 14:49:24 +0000445 if( iDirectEq[i]>=0 ){
drhc4a3c772001-04-04 11:48:57 +0000446 loopMask |= 1<<idx;
drh6b563442001-11-07 16:48:26 +0000447 pWInfo->a[i].pIdx = 0;
drhc4a3c772001-04-04 11:48:57 +0000448 continue;
449 }
450
drh75897232000-05-29 14:26:00 +0000451 /* Do a search for usable indices. Leave pBestIdx pointing to
drh487ab3c2001-11-08 00:45:21 +0000452 ** the "best" index. pBestIdx is left set to NULL if no indices
453 ** are usable.
drh75897232000-05-29 14:26:00 +0000454 **
drh487ab3c2001-11-08 00:45:21 +0000455 ** The best index is determined as follows. For each of the
456 ** left-most terms that is fixed by an equality operator, add
457 ** 4 to the score. The right-most term of the index may be
458 ** constrained by an inequality. Add 1 if for an "x<..." constraint
459 ** and add 2 for an "x>..." constraint. Chose the index that
460 ** gives the best score.
461 **
462 ** This scoring system is designed so that the score can later be
463 ** used to determine how the index is used. If the score&3 is 0
464 ** then all constraints are equalities. If score&1 is not 0 then
465 ** there is an inequality used as a termination key. (ex: "x<...")
466 ** If score&2 is not 0 then there is an inequality used as the
467 ** start key. (ex: "x>...");
drhd99f7062002-06-08 23:25:08 +0000468 **
drhc27a1ce2002-06-14 20:58:45 +0000469 ** The IN operator (as in "<expr> IN (...)") is treated the same as
470 ** an equality comparison except that it can only be used on the
471 ** left-most column of an index and other terms of the WHERE clause
472 ** cannot be used in conjunction with the IN operator to help satisfy
473 ** other columns of the index.
drh75897232000-05-29 14:26:00 +0000474 */
475 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drhc27a1ce2002-06-14 20:58:45 +0000476 int eqMask = 0; /* Index columns covered by an x=... term */
477 int ltMask = 0; /* Index columns covered by an x<... term */
478 int gtMask = 0; /* Index columns covered by an x>... term */
479 int inMask = 0; /* Index columns covered by an x IN .. term */
drh487ab3c2001-11-08 00:45:21 +0000480 int nEq, m, score;
drh75897232000-05-29 14:26:00 +0000481
drh74e24cd2002-01-09 03:19:59 +0000482 if( pIdx->isDropped ) continue; /* Ignore dropped indices */
drh487ab3c2001-11-08 00:45:21 +0000483 if( pIdx->nColumn>32 ) continue; /* Ignore indices too many columns */
drh75897232000-05-29 14:26:00 +0000484 for(j=0; j<nExpr; j++){
485 if( aExpr[j].idxLeft==idx
486 && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
drh967e8b72000-06-21 13:59:10 +0000487 int iColumn = aExpr[j].p->pLeft->iColumn;
drh75897232000-05-29 14:26:00 +0000488 int k;
drh967e8b72000-06-21 13:59:10 +0000489 for(k=0; k<pIdx->nColumn; k++){
490 if( pIdx->aiColumn[k]==iColumn ){
drh487ab3c2001-11-08 00:45:21 +0000491 switch( aExpr[j].p->op ){
drh48185c12002-06-09 01:55:20 +0000492 case TK_IN: {
493 if( k==0 ) inMask |= 1;
494 break;
495 }
drh487ab3c2001-11-08 00:45:21 +0000496 case TK_EQ: {
497 eqMask |= 1<<k;
498 break;
499 }
500 case TK_LE:
501 case TK_LT: {
502 ltMask |= 1<<k;
503 break;
504 }
505 case TK_GE:
506 case TK_GT: {
507 gtMask |= 1<<k;
508 break;
509 }
510 default: {
511 /* CANT_HAPPEN */
512 assert( 0 );
513 break;
514 }
515 }
drh75897232000-05-29 14:26:00 +0000516 break;
517 }
518 }
519 }
520 if( aExpr[j].idxRight==idx
521 && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
drh967e8b72000-06-21 13:59:10 +0000522 int iColumn = aExpr[j].p->pRight->iColumn;
drh75897232000-05-29 14:26:00 +0000523 int k;
drh967e8b72000-06-21 13:59:10 +0000524 for(k=0; k<pIdx->nColumn; k++){
525 if( pIdx->aiColumn[k]==iColumn ){
drh487ab3c2001-11-08 00:45:21 +0000526 switch( aExpr[j].p->op ){
527 case TK_EQ: {
528 eqMask |= 1<<k;
529 break;
530 }
531 case TK_LE:
532 case TK_LT: {
533 gtMask |= 1<<k;
534 break;
535 }
536 case TK_GE:
537 case TK_GT: {
538 ltMask |= 1<<k;
539 break;
540 }
541 default: {
542 /* CANT_HAPPEN */
543 assert( 0 );
544 break;
545 }
546 }
drh75897232000-05-29 14:26:00 +0000547 break;
548 }
549 }
550 }
551 }
drh487ab3c2001-11-08 00:45:21 +0000552 for(nEq=0; nEq<pIdx->nColumn; nEq++){
553 m = (1<<(nEq+1))-1;
554 if( (m & eqMask)!=m ) break;
555 }
556 score = nEq*4;
557 m = 1<<nEq;
558 if( m & ltMask ) score++;
559 if( m & gtMask ) score+=2;
drh48185c12002-06-09 01:55:20 +0000560 if( score==0 && inMask ) score = 4;
drh487ab3c2001-11-08 00:45:21 +0000561 if( score>bestScore ){
562 pBestIdx = pIdx;
563 bestScore = score;
drh75897232000-05-29 14:26:00 +0000564 }
565 }
drh6b563442001-11-07 16:48:26 +0000566 pWInfo->a[i].pIdx = pBestIdx;
drh487ab3c2001-11-08 00:45:21 +0000567 pWInfo->a[i].score = bestScore;
drh7e391e12000-05-30 20:17:49 +0000568 loopMask |= 1<<idx;
drh6b563442001-11-07 16:48:26 +0000569 if( pBestIdx ){
drh832508b2002-03-02 17:04:07 +0000570 pWInfo->a[i].iCur = pParse->nTab++;
571 pWInfo->peakNTab = pParse->nTab;
drh6b563442001-11-07 16:48:26 +0000572 }
drh75897232000-05-29 14:26:00 +0000573 }
574
drhe3184742002-06-19 14:27:05 +0000575 /* Check to see if the ORDER BY clause is or can be satisfied by the
576 ** use of an index on the first table.
577 */
578 if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
579 Index *pSortIdx;
580 Index *pIdx;
581 Table *pTab;
582
583 pTab = pTabList->a[0].pTab;
584 pIdx = pWInfo->a[0].pIdx;
585 if( pIdx && pWInfo->a[0].score==4 ){
586 /* If there is already an index on the left-most column and it is
587 ** an equality index, then either sorting is not helpful, or the
588 ** index is an IN operator, in which case the index does not give
589 ** the correct sort order. Either way, pretend that no suitable
590 ** index is found.
591 */
592 pSortIdx = 0;
593 }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
594 /* If the left-most column is accessed using its ROWID, then do
595 ** not try to sort by index.
596 */
597 pSortIdx = 0;
598 }else{
599 pSortIdx = findSortingIndex(pTab, base, *ppOrderBy, pIdx);
600 }
601 if( pSortIdx && (pIdx==0 || pIdx==pSortIdx) ){
602 if( pIdx==0 ){
603 pWInfo->a[0].pIdx = pSortIdx;
604 pWInfo->a[0].iCur = pParse->nTab++;
605 pWInfo->peakNTab = pParse->nTab;
606 }
607 *ppOrderBy = 0;
608 }
609 }
610
drh6b563442001-11-07 16:48:26 +0000611 /* Open all tables in the pTabList and all indices used by those tables.
drh75897232000-05-29 14:26:00 +0000612 */
drhad3cab52002-05-24 02:04:32 +0000613 for(i=0; i<pTabList->nSrc; i++){
drhf57b3392001-10-08 13:22:32 +0000614 int openOp;
615 Table *pTab;
616
617 pTab = pTabList->a[i].pTab;
drha76b5df2002-02-23 02:32:10 +0000618 if( pTab->isTransient || pTab->pSelect ) continue;
drhf57b3392001-10-08 13:22:32 +0000619 openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
drh99fcd712001-10-13 01:06:47 +0000620 sqliteVdbeAddOp(v, openOp, base+i, pTab->tnum);
621 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drh50e5dad2001-09-15 00:57:28 +0000622 if( i==0 && !pParse->schemaVerified &&
623 (pParse->db->flags & SQLITE_InTrans)==0 ){
drh99fcd712001-10-13 01:06:47 +0000624 sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
drh50e5dad2001-09-15 00:57:28 +0000625 pParse->schemaVerified = 1;
626 }
drh6b563442001-11-07 16:48:26 +0000627 if( pWInfo->a[i].pIdx!=0 ){
628 sqliteVdbeAddOp(v, openOp, pWInfo->a[i].iCur, pWInfo->a[i].pIdx->tnum);
629 sqliteVdbeChangeP3(v, -1, pWInfo->a[i].pIdx->zName, P3_STATIC);
drh75897232000-05-29 14:26:00 +0000630 }
631 }
632
633 /* Generate the code to do the search
634 */
drh75897232000-05-29 14:26:00 +0000635 loopMask = 0;
drhad3cab52002-05-24 02:04:32 +0000636 for(i=0; i<pTabList->nSrc; i++){
drh75897232000-05-29 14:26:00 +0000637 int j, k;
638 int idx = aOrder[i];
drhc4a3c772001-04-04 11:48:57 +0000639 Index *pIdx;
drh6b563442001-11-07 16:48:26 +0000640 WhereLevel *pLevel = &pWInfo->a[i];
drh75897232000-05-29 14:26:00 +0000641
drhad2d8302002-05-24 20:31:36 +0000642 /* If this is the right table of a LEFT OUTER JOIN, allocate and
643 ** initialize a memory cell that record if this table matches any
drhc27a1ce2002-06-14 20:58:45 +0000644 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +0000645 */
646 if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
647 if( !pParse->nMem ) pParse->nMem++;
648 pLevel->iLeftJoin = pParse->nMem++;
649 sqliteVdbeAddOp(v, OP_String, 0, 0);
650 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
651 }
652
drh8aff1012001-12-22 14:49:24 +0000653 pIdx = pLevel->pIdx;
drhd99f7062002-06-08 23:25:08 +0000654 pLevel->inOp = OP_Noop;
drh8aff1012001-12-22 14:49:24 +0000655 if( i<ARRAYSIZE(iDirectEq) && iDirectEq[i]>=0 ){
656 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +0000657 ** equality comparison against the ROWID field. Or
658 ** we reference multiple rows using a "rowid IN (...)"
659 ** construct.
drhc4a3c772001-04-04 11:48:57 +0000660 */
drh8aff1012001-12-22 14:49:24 +0000661 k = iDirectEq[i];
662 assert( k<nExpr );
663 assert( aExpr[k].p!=0 );
664 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
drhd99f7062002-06-08 23:25:08 +0000665 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
drh8aff1012001-12-22 14:49:24 +0000666 if( aExpr[k].idxLeft==idx ){
drhd99f7062002-06-08 23:25:08 +0000667 Expr *pX = aExpr[k].p;
668 if( pX->op!=TK_IN ){
669 sqliteExprCode(pParse, aExpr[k].p->pRight);
670 }else if( pX->pList ){
671 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
672 pLevel->inOp = OP_SetNext;
673 pLevel->inP1 = pX->iTable;
674 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
675 }else{
676 assert( pX->pSelect );
677 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
678 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
679 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
680 pLevel->inOp = OP_Next;
681 pLevel->inP1 = pX->iTable;
682 }
drh8aff1012001-12-22 14:49:24 +0000683 }else{
684 sqliteExprCode(pParse, aExpr[k].p->pLeft);
drhc4a3c772001-04-04 11:48:57 +0000685 }
drh8aff1012001-12-22 14:49:24 +0000686 aExpr[k].p = 0;
drhd99f7062002-06-08 23:25:08 +0000687 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
drh8aff1012001-12-22 14:49:24 +0000688 sqliteVdbeAddOp(v, OP_MustBeInt, 0, brk);
drhd99f7062002-06-08 23:25:08 +0000689 haveKey = 0;
drh6b125452002-01-28 15:53:03 +0000690 sqliteVdbeAddOp(v, OP_NotExists, base+idx, brk);
drh6b563442001-11-07 16:48:26 +0000691 pLevel->op = OP_Noop;
drhe3184742002-06-19 14:27:05 +0000692 }else if( pIdx!=0 && pLevel->score>0 && pLevel->score%4==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000693 /* Case 2: There is an index and all terms of the WHERE clause that
694 ** refer to the index use the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +0000695 */
drh6b563442001-11-07 16:48:26 +0000696 int start;
drh487ab3c2001-11-08 00:45:21 +0000697 int testOp;
698 int nColumn = pLevel->score/4;
drhd99f7062002-06-08 23:25:08 +0000699 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
drh487ab3c2001-11-08 00:45:21 +0000700 for(j=0; j<nColumn; j++){
drh75897232000-05-29 14:26:00 +0000701 for(k=0; k<nExpr; k++){
drhd99f7062002-06-08 23:25:08 +0000702 Expr *pX = aExpr[k].p;
703 if( pX==0 ) continue;
drh75897232000-05-29 14:26:00 +0000704 if( aExpr[k].idxLeft==idx
705 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
drhd99f7062002-06-08 23:25:08 +0000706 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +0000707 ){
drhd99f7062002-06-08 23:25:08 +0000708 if( pX->op==TK_EQ ){
709 sqliteExprCode(pParse, pX->pRight);
710 aExpr[k].p = 0;
711 break;
712 }
713 if( pX->op==TK_IN && nColumn==1 ){
714 if( pX->pList ){
715 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
716 pLevel->inOp = OP_SetNext;
717 pLevel->inP1 = pX->iTable;
718 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
719 }else{
720 assert( pX->pSelect );
721 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
722 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
723 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
724 pLevel->inOp = OP_Next;
725 pLevel->inP1 = pX->iTable;
726 }
727 aExpr[k].p = 0;
728 break;
729 }
drh75897232000-05-29 14:26:00 +0000730 }
731 if( aExpr[k].idxRight==idx
drh487ab3c2001-11-08 00:45:21 +0000732 && aExpr[k].p->op==TK_EQ
drh75897232000-05-29 14:26:00 +0000733 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
drh967e8b72000-06-21 13:59:10 +0000734 && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +0000735 ){
736 sqliteExprCode(pParse, aExpr[k].p->pLeft);
737 aExpr[k].p = 0;
738 break;
739 }
740 }
741 }
drh6b563442001-11-07 16:48:26 +0000742 pLevel->iMem = pParse->nMem++;
drh6b563442001-11-07 16:48:26 +0000743 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
drh487ab3c2001-11-08 00:45:21 +0000744 sqliteVdbeAddOp(v, OP_MakeKey, nColumn, 0);
745 if( nColumn==pIdx->nColumn ){
746 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
747 testOp = OP_IdxGT;
748 }else{
749 sqliteVdbeAddOp(v, OP_Dup, 0, 0);
750 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
751 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
752 testOp = OP_IdxGE;
753 }
drh6b563442001-11-07 16:48:26 +0000754 sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
755 start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh487ab3c2001-11-08 00:45:21 +0000756 sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
drh6b563442001-11-07 16:48:26 +0000757 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
drhad3cab52002-05-24 02:04:32 +0000758 if( i==pTabList->nSrc-1 && pushKey ){
drh75897232000-05-29 14:26:00 +0000759 haveKey = 1;
760 }else{
drh99fcd712001-10-13 01:06:47 +0000761 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
drh75897232000-05-29 14:26:00 +0000762 haveKey = 0;
763 }
drh6b563442001-11-07 16:48:26 +0000764 pLevel->op = OP_Next;
765 pLevel->p1 = pLevel->iCur;
766 pLevel->p2 = start;
drh8aff1012001-12-22 14:49:24 +0000767 }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
768 /* Case 3: We have an inequality comparison against the ROWID field.
769 */
770 int testOp = OP_Noop;
771 int start;
772
773 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
774 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
775 if( iDirectGt[i]>=0 ){
776 k = iDirectGt[i];
777 assert( k<nExpr );
778 assert( aExpr[k].p!=0 );
779 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
780 if( aExpr[k].idxLeft==idx ){
781 sqliteExprCode(pParse, aExpr[k].p->pRight);
782 }else{
783 sqliteExprCode(pParse, aExpr[k].p->pLeft);
784 }
785 sqliteVdbeAddOp(v, OP_MustBeInt, 0, brk);
786 if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
787 sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
788 }
789 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, brk);
790 aExpr[k].p = 0;
791 }else{
792 sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
793 }
794 if( iDirectLt[i]>=0 ){
795 k = iDirectLt[i];
796 assert( k<nExpr );
797 assert( aExpr[k].p!=0 );
798 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
799 if( aExpr[k].idxLeft==idx ){
800 sqliteExprCode(pParse, aExpr[k].p->pRight);
801 }else{
802 sqliteExprCode(pParse, aExpr[k].p->pLeft);
803 }
804 sqliteVdbeAddOp(v, OP_MustBeInt, 0, sqliteVdbeCurrentAddr(v)+1);
805 pLevel->iMem = pParse->nMem++;
806 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
807 if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
808 testOp = OP_Ge;
809 }else{
810 testOp = OP_Gt;
811 }
812 aExpr[k].p = 0;
813 }
814 start = sqliteVdbeCurrentAddr(v);
815 pLevel->op = OP_Next;
816 pLevel->p1 = base+idx;
817 pLevel->p2 = start;
818 if( testOp!=OP_Noop ){
819 sqliteVdbeAddOp(v, OP_Recno, base+idx, 0);
820 sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
821 sqliteVdbeAddOp(v, testOp, 0, brk);
822 }
823 haveKey = 0;
824 }else if( pIdx==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000825 /* Case 4: There is no usable index. We must do a complete
drh8aff1012001-12-22 14:49:24 +0000826 ** scan of the entire database table.
827 */
828 int start;
829
830 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
831 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
832 sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
833 start = sqliteVdbeCurrentAddr(v);
834 pLevel->op = OP_Next;
835 pLevel->p1 = base+idx;
836 pLevel->p2 = start;
837 haveKey = 0;
drh487ab3c2001-11-08 00:45:21 +0000838 }else{
drhc27a1ce2002-06-14 20:58:45 +0000839 /* Case 5: The WHERE clause term that refers to the right-most
840 ** column of the index is an inequality. For example, if
841 ** the index is on (x,y,z) and the WHERE clause is of the
842 ** form "x=5 AND y<10" then this case is used. Only the
843 ** right-most column can be an inequality - the rest must
844 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +0000845 **
846 ** This case is also used when there are no WHERE clause
847 ** constraints but an index is selected anyway, in order
848 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +0000849 */
850 int score = pLevel->score;
851 int nEqColumn = score/4;
852 int start;
853 int leFlag, geFlag;
854 int testOp;
855
856 /* Evaluate the equality constraints
857 */
858 for(j=0; j<nEqColumn; j++){
859 for(k=0; k<nExpr; k++){
860 if( aExpr[k].p==0 ) continue;
861 if( aExpr[k].idxLeft==idx
862 && aExpr[k].p->op==TK_EQ
863 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
864 && aExpr[k].p->pLeft->iColumn==pIdx->aiColumn[j]
865 ){
866 sqliteExprCode(pParse, aExpr[k].p->pRight);
867 aExpr[k].p = 0;
868 break;
869 }
870 if( aExpr[k].idxRight==idx
871 && aExpr[k].p->op==TK_EQ
872 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
873 && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
874 ){
875 sqliteExprCode(pParse, aExpr[k].p->pLeft);
876 aExpr[k].p = 0;
877 break;
878 }
879 }
880 }
881
drhc27a1ce2002-06-14 20:58:45 +0000882 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +0000883 ** used twice: once to make the termination key and once to make the
884 ** start key.
885 */
886 for(j=0; j<nEqColumn; j++){
887 sqliteVdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
888 }
889
890 /* Generate the termination key. This is the key value that
891 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +0000892 ** are no equality terms and no "X<..." term.
drh487ab3c2001-11-08 00:45:21 +0000893 */
894 if( (score & 1)!=0 ){
895 for(k=0; k<nExpr; k++){
896 Expr *pExpr = aExpr[k].p;
897 if( pExpr==0 ) continue;
898 if( aExpr[k].idxLeft==idx
899 && (pExpr->op==TK_LT || pExpr->op==TK_LE)
900 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
901 && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
902 ){
903 sqliteExprCode(pParse, pExpr->pRight);
904 leFlag = pExpr->op==TK_LE;
905 aExpr[k].p = 0;
906 break;
907 }
908 if( aExpr[k].idxRight==idx
909 && (pExpr->op==TK_GT || pExpr->op==TK_GE)
910 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
911 && pExpr->pRight->iColumn==pIdx->aiColumn[j]
912 ){
913 sqliteExprCode(pParse, pExpr->pLeft);
914 leFlag = pExpr->op==TK_GE;
915 aExpr[k].p = 0;
916 break;
917 }
918 }
919 testOp = OP_IdxGE;
920 }else{
921 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
922 leFlag = 1;
923 }
924 if( testOp!=OP_Noop ){
925 pLevel->iMem = pParse->nMem++;
926 sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + (score & 1), 0);
927 if( leFlag ){
928 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
929 }
930 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
931 }
932
933 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +0000934 ** bound on the search. There is no start key if there are no
935 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +0000936 ** that case, generate a "Rewind" instruction in place of the
937 ** start key search.
938 */
939 if( (score & 2)!=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_GT || pExpr->op==TK_GE)
945 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
946 && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
947 ){
948 sqliteExprCode(pParse, pExpr->pRight);
949 geFlag = pExpr->op==TK_GE;
950 aExpr[k].p = 0;
951 break;
952 }
953 if( aExpr[k].idxRight==idx
954 && (pExpr->op==TK_LT || pExpr->op==TK_LE)
955 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
956 && pExpr->pRight->iColumn==pIdx->aiColumn[j]
957 ){
958 sqliteExprCode(pParse, pExpr->pLeft);
959 geFlag = pExpr->op==TK_LE;
960 aExpr[k].p = 0;
961 break;
962 }
963 }
drh7900ead2001-11-12 13:51:43 +0000964 }else{
965 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +0000966 }
967 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
968 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
969 if( nEqColumn>0 || (score&2)!=0 ){
970 sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + ((score&2)!=0), 0);
971 if( !geFlag ){
972 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
973 }
974 sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
975 }else{
976 sqliteVdbeAddOp(v, OP_Rewind, pLevel->iCur, brk);
977 }
978
979 /* Generate the the top of the loop. If there is a termination
980 ** key we have to test for that key and abort at the top of the
981 ** loop.
982 */
983 start = sqliteVdbeCurrentAddr(v);
984 if( testOp!=OP_Noop ){
985 sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
986 sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
987 }
988 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
drhad3cab52002-05-24 02:04:32 +0000989 if( i==pTabList->nSrc-1 && pushKey ){
drh487ab3c2001-11-08 00:45:21 +0000990 haveKey = 1;
991 }else{
992 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
993 haveKey = 0;
994 }
995
996 /* Record the instruction used to terminate the loop.
997 */
998 pLevel->op = OP_Next;
999 pLevel->p1 = pLevel->iCur;
1000 pLevel->p2 = start;
drh75897232000-05-29 14:26:00 +00001001 }
1002 loopMask |= 1<<idx;
1003
1004 /* Insert code to test every subexpression that can be completely
1005 ** computed using the current set of tables.
1006 */
1007 for(j=0; j<nExpr; j++){
1008 if( aExpr[j].p==0 ) continue;
drh3f6b5482002-04-02 13:26:10 +00001009 if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
drh1cc093c2002-06-24 22:01:57 +00001010 if( pLevel->iLeftJoin && aExpr[j].p->isJoinExpr==0 ) continue;
drh75897232000-05-29 14:26:00 +00001011 if( haveKey ){
drh573bd272001-02-19 23:23:38 +00001012 haveKey = 0;
drh99fcd712001-10-13 01:06:47 +00001013 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
drh75897232000-05-29 14:26:00 +00001014 }
drhf5905aa2002-05-26 20:54:33 +00001015 sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
drh75897232000-05-29 14:26:00 +00001016 aExpr[j].p = 0;
1017 }
1018 brk = cont;
drhad2d8302002-05-24 20:31:36 +00001019
1020 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1021 ** at least one row of the right table has matched the left table.
1022 */
1023 if( pLevel->iLeftJoin ){
1024 pLevel->top = sqliteVdbeCurrentAddr(v);
1025 sqliteVdbeAddOp(v, OP_Integer, 1, 0);
1026 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drh1cc093c2002-06-24 22:01:57 +00001027 for(j=0; j<nExpr; j++){
1028 if( aExpr[j].p==0 ) continue;
1029 if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
1030 if( haveKey ){
1031 haveKey = 0;
1032 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
1033 }
1034 sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
1035 aExpr[j].p = 0;
1036 }
drhad2d8302002-05-24 20:31:36 +00001037 }
drh75897232000-05-29 14:26:00 +00001038 }
1039 pWInfo->iContinue = cont;
1040 if( pushKey && !haveKey ){
drh99fcd712001-10-13 01:06:47 +00001041 sqliteVdbeAddOp(v, OP_Recno, base, 0);
drh75897232000-05-29 14:26:00 +00001042 }
1043 sqliteFree(aOrder);
1044 return pWInfo;
1045}
1046
1047/*
drhc27a1ce2002-06-14 20:58:45 +00001048** Generate the end of the WHERE loop. See comments on
1049** sqliteWhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001050*/
1051void sqliteWhereEnd(WhereInfo *pWInfo){
1052 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001053 int i;
drh19a775c2000-06-05 18:54:46 +00001054 int base = pWInfo->base;
drh6b563442001-11-07 16:48:26 +00001055 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001056 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001057
drhad3cab52002-05-24 02:04:32 +00001058 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001059 pLevel = &pWInfo->a[i];
1060 sqliteVdbeResolveLabel(v, pLevel->cont);
1061 if( pLevel->op!=OP_Noop ){
1062 sqliteVdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001063 }
drh6b563442001-11-07 16:48:26 +00001064 sqliteVdbeResolveLabel(v, pLevel->brk);
drhd99f7062002-06-08 23:25:08 +00001065 if( pLevel->inOp!=OP_Noop ){
1066 sqliteVdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
1067 }
drhad2d8302002-05-24 20:31:36 +00001068 if( pLevel->iLeftJoin ){
1069 int addr;
1070 addr = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drhbf5cd972002-06-24 12:20:23 +00001071 sqliteVdbeAddOp(v, OP_NotNull, 1, addr+4);
drhad2d8302002-05-24 20:31:36 +00001072 sqliteVdbeAddOp(v, OP_NullRow, base+i, 0);
1073 sqliteVdbeAddOp(v, OP_Goto, 0, pLevel->top);
1074 }
drh19a775c2000-06-05 18:54:46 +00001075 }
drh6b563442001-11-07 16:48:26 +00001076 sqliteVdbeResolveLabel(v, pWInfo->iBreak);
drhad3cab52002-05-24 02:04:32 +00001077 for(i=0; i<pTabList->nSrc; i++){
drh22f70c32002-02-18 01:17:00 +00001078 if( pTabList->a[i].pTab->isTransient ) continue;
drh6b563442001-11-07 16:48:26 +00001079 pLevel = &pWInfo->a[i];
1080 sqliteVdbeAddOp(v, OP_Close, base+i, 0);
1081 if( pLevel->pIdx!=0 ){
1082 sqliteVdbeAddOp(v, OP_Close, pLevel->iCur, 0);
1083 }
drh19a775c2000-06-05 18:54:46 +00001084 }
drh832508b2002-03-02 17:04:07 +00001085 if( pWInfo->pParse->nTab==pWInfo->peakNTab ){
1086 pWInfo->pParse->nTab = pWInfo->savedNTab;
1087 }
drh75897232000-05-29 14:26:00 +00001088 sqliteFree(pWInfo);
1089 return;
1090}