blob: 96d476ec9d5d553e599a1bcb0a14443e958d2305 [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**
drh142e30d2002-08-28 03:00:58 +000016** $Id: where.c,v 1.64 2002/08/28 03:01:01 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 }
drhc330af12002-08-14 03:03:57 +0000184 if( (pOrderBy->a[i].sortOrder & SQLITE_SO_TYPEMASK)!=SQLITE_SO_UNK ){
185 /* Do not sort by index if there is a COLLATE clause */
186 return 0;
187 }
drhe3184742002-06-19 14:27:05 +0000188 p = pOrderBy->a[i].pExpr;
189 if( p->op!=TK_COLUMN || p->iTable!=base ){
190 /* Can not use an index sort on anything that is not a column in the
191 ** left-most table of the FROM clause */
192 return 0;
193 }
194 }
195
196 /* If we get this far, it means the ORDER BY clause consists only of
197 ** ascending columns in the left-most table of the FROM clause. Now
198 ** check for a matching index.
199 */
200 pMatch = 0;
201 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
202 if( pIdx->nColumn<pOrderBy->nExpr ) continue;
203 for(i=0; i<pOrderBy->nExpr; i++){
204 if( pOrderBy->a[i].pExpr->iColumn!=pIdx->aiColumn[i] ) break;
205 }
206 if( i>=pOrderBy->nExpr ){
207 pMatch = pIdx;
208 if( pIdx==pPreferredIdx ) break;
209 }
210 }
211 return pMatch;
212}
213
214/*
215** Generate the beginning of the loop used for WHERE clause processing.
drh75897232000-05-29 14:26:00 +0000216** The return value is a pointer to an (opaque) structure that contains
217** information needed to terminate the loop. Later, the calling routine
218** should invoke sqliteWhereEnd() with the return value of this function
219** in order to complete the WHERE clause processing.
220**
221** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +0000222**
223** The basic idea is to do a nested loop, one loop for each table in
224** the FROM clause of a select. (INSERT and UPDATE statements are the
225** same as a SELECT with only a single table in the FROM clause.) For
226** example, if the SQL is this:
227**
228** SELECT * FROM t1, t2, t3 WHERE ...;
229**
230** Then the code generated is conceptually like the following:
231**
232** foreach row1 in t1 do \ Code generated
233** foreach row2 in t2 do |-- by sqliteWhereBegin()
234** foreach row3 in t3 do /
235** ...
236** end \ Code generated
237** end |-- by sqliteWhereEnd()
238** end /
239**
240** There are Btree cursors associated with each table. t1 uses cursor
241** "base". t2 uses cursor "base+1". And so forth. This routine generates
242** the code to open those cursors. sqliteWhereEnd() generates the code
243** to close them.
244**
245** If the WHERE clause is empty, the foreach loops must each scan their
246** entire tables. Thus a three-way join is an O(N^3) operation. But if
247** the tables have indices and there are terms in the WHERE clause that
248** refer to those indices, a complete table scan can be avoided and the
249** code will run much faster. Most of the work of this routine is checking
250** to see if there are indices that can be used to speed up the loop.
251**
252** Terms of the WHERE clause are also used to limit which rows actually
253** make it to the "..." in the middle of the loop. After each "foreach",
254** terms of the WHERE clause that use only terms in that loop and outer
255** loops are evaluated and if false a jump is made around all subsequent
256** inner loops (or around the "..." if the test occurs within the inner-
257** most loop)
258**
259** OUTER JOINS
260**
261** An outer join of tables t1 and t2 is conceptally coded as follows:
262**
263** foreach row1 in t1 do
264** flag = 0
265** foreach row2 in t2 do
266** start:
267** ...
268** flag = 1
269** end
drhe3184742002-06-19 14:27:05 +0000270** if flag==0 then
271** move the row2 cursor to a null row
272** goto start
273** fi
drhc27a1ce2002-06-14 20:58:45 +0000274** end
275**
drhe3184742002-06-19 14:27:05 +0000276** ORDER BY CLAUSE PROCESSING
277**
278** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
279** if there is one. If there is no ORDER BY clause or if this routine
280** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
281**
282** If an index can be used so that the natural output order of the table
283** scan is correct for the ORDER BY clause, then that index is used and
284** *ppOrderBy is set to NULL. This is an optimization that prevents an
285** unnecessary sort of the result set if an index appropriate for the
286** ORDER BY clause already exists.
287**
288** If the where clause loops cannot be arranged to provide the correct
289** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +0000290*/
291WhereInfo *sqliteWhereBegin(
292 Parse *pParse, /* The parser context */
drh832508b2002-03-02 17:04:07 +0000293 int base, /* VDBE cursor index for left-most table in pTabList */
drhad3cab52002-05-24 02:04:32 +0000294 SrcList *pTabList, /* A list of all tables to be scanned */
drh75897232000-05-29 14:26:00 +0000295 Expr *pWhere, /* The WHERE clause */
drhe3184742002-06-19 14:27:05 +0000296 int pushKey, /* If TRUE, leave the table key on the stack */
297 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +0000298){
299 int i; /* Loop counter */
300 WhereInfo *pWInfo; /* Will become the return value of this function */
301 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
302 int brk, cont; /* Addresses used during code generation */
303 int *aOrder; /* Order in which pTabList entries are searched */
304 int nExpr; /* Number of subexpressions in the WHERE clause */
305 int loopMask; /* One bit set for each outer loop */
306 int haveKey; /* True if KEY is on the stack */
drh8aff1012001-12-22 14:49:24 +0000307 int iDirectEq[32]; /* Term of the form ROWID==X for the N-th table */
308 int iDirectLt[32]; /* Term of the form ROWID<X or ROWID<=X */
309 int iDirectGt[32]; /* Term of the form ROWID>X or ROWID>=X */
drh83dcb1a2002-06-28 01:02:38 +0000310 ExprInfo aExpr[101]; /* The WHERE clause is divided into these expressions */
drh75897232000-05-29 14:26:00 +0000311
drhc27a1ce2002-06-14 20:58:45 +0000312 /* pushKey is only allowed if there is a single table (as in an INSERT or
313 ** UPDATE statement)
314 */
315 assert( pushKey==0 || pTabList->nSrc==1 );
drh83dcb1a2002-06-28 01:02:38 +0000316
317 /* Split the WHERE clause into separate subexpressions where each
318 ** subexpression is separated by an AND operator. If the aExpr[]
319 ** array fills up, the last entry might point to an expression which
320 ** contains additional unfactored AND operators.
321 */
322 memset(aExpr, 0, sizeof(aExpr));
323 nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
324 if( nExpr==ARRAYSIZE(aExpr) ){
325 char zBuf[50];
326 sprintf(zBuf, "%d", ARRAYSIZE(aExpr)-1);
327 sqliteSetString(&pParse->zErrMsg, "WHERE clause too complex - no more "
328 "than ", zBuf, " terms allowed", 0);
329 pParse->nErr++;
330 return 0;
331 }
drhc27a1ce2002-06-14 20:58:45 +0000332
drhe3184742002-06-19 14:27:05 +0000333 /* Allocate space for aOrder[] */
drhad3cab52002-05-24 02:04:32 +0000334 aOrder = sqliteMalloc( sizeof(int) * pTabList->nSrc );
drh75897232000-05-29 14:26:00 +0000335
336 /* Allocate and initialize the WhereInfo structure that will become the
337 ** return value.
338 */
drhad3cab52002-05-24 02:04:32 +0000339 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
drhdaffd0e2001-04-11 14:28:42 +0000340 if( sqlite_malloc_failed ){
drh75897232000-05-29 14:26:00 +0000341 sqliteFree(aOrder);
drhdaffd0e2001-04-11 14:28:42 +0000342 sqliteFree(pWInfo);
drh75897232000-05-29 14:26:00 +0000343 return 0;
344 }
345 pWInfo->pParse = pParse;
346 pWInfo->pTabList = pTabList;
drh832508b2002-03-02 17:04:07 +0000347 pWInfo->base = base;
348 pWInfo->peakNTab = pWInfo->savedNTab = pParse->nTab;
drh08192d52002-04-30 19:20:28 +0000349 pWInfo->iBreak = sqliteVdbeMakeLabel(v);
350
351 /* Special case: a WHERE clause that is constant. Evaluate the
352 ** expression and either jump over all of the code or fall thru.
353 */
354 if( pWhere && sqliteExprIsConstant(pWhere) ){
drhf5905aa2002-05-26 20:54:33 +0000355 sqliteExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +0000356 pWhere = 0;
drh08192d52002-04-30 19:20:28 +0000357 }
drh75897232000-05-29 14:26:00 +0000358
drh75897232000-05-29 14:26:00 +0000359 /* Analyze all of the subexpressions.
360 */
361 for(i=0; i<nExpr; i++){
drh22f70c32002-02-18 01:17:00 +0000362 exprAnalyze(base, &aExpr[i]);
drh1d1f3052002-05-21 13:18:25 +0000363
364 /* If we are executing a trigger body, remove all references to
365 ** new.* and old.* tables from the prerequisite masks.
366 */
367 if( pParse->trigStack ){
368 int x;
369 if( (x = pParse->trigStack->newIdx) >= 0 ){
370 int mask = ~(1 << (x - base));
371 aExpr[i].prereqRight &= mask;
372 aExpr[i].prereqLeft &= mask;
373 aExpr[i].prereqAll &= mask;
374 }
375 if( (x = pParse->trigStack->oldIdx) >= 0 ){
376 int mask = ~(1 << (x - base));
377 aExpr[i].prereqRight &= mask;
378 aExpr[i].prereqLeft &= mask;
379 aExpr[i].prereqAll &= mask;
380 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000381 }
drh75897232000-05-29 14:26:00 +0000382 }
383
384 /* Figure out a good nesting order for the tables. aOrder[0] will
385 ** be the index in pTabList of the outermost table. aOrder[1] will
drhad3cab52002-05-24 02:04:32 +0000386 ** be the first nested loop and so on. aOrder[pTabList->nSrc-1] will
drh75897232000-05-29 14:26:00 +0000387 ** be the innermost loop.
388 **
drh1d1f3052002-05-21 13:18:25 +0000389 ** Someday we will put in a good algorithm here to reorder the loops
drh75897232000-05-29 14:26:00 +0000390 ** for an effiecient query. But for now, just use whatever order the
391 ** tables appear in in the pTabList.
392 */
drhad3cab52002-05-24 02:04:32 +0000393 for(i=0; i<pTabList->nSrc; i++){
drh75897232000-05-29 14:26:00 +0000394 aOrder[i] = i;
395 }
396
397 /* Figure out what index to use (if any) for each nested loop.
drh6b563442001-11-07 16:48:26 +0000398 ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
drhad3cab52002-05-24 02:04:32 +0000399 ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
drh8aff1012001-12-22 14:49:24 +0000400 ** loop.
401 **
402 ** If terms exist that use the ROWID of any table, then set the
403 ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
404 ** to the index of the term containing the ROWID. We always prefer
405 ** to use a ROWID which can directly access a table rather than an
drh0a36c572002-02-18 22:49:59 +0000406 ** index which requires reading an index first to get the rowid then
407 ** doing a second read of the actual database table.
drh75897232000-05-29 14:26:00 +0000408 **
409 ** Actually, if there are more than 32 tables in the join, only the
drh0a36c572002-02-18 22:49:59 +0000410 ** first 32 tables are candidates for indices. This is (again) due
411 ** to the limit of 32 bits in an integer bitmask.
drh75897232000-05-29 14:26:00 +0000412 */
413 loopMask = 0;
drhcb485882002-08-15 13:50:48 +0000414 for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++){
drhc4a3c772001-04-04 11:48:57 +0000415 int j;
drh75897232000-05-29 14:26:00 +0000416 int idx = aOrder[i];
417 Table *pTab = pTabList->a[idx].pTab;
418 Index *pIdx;
419 Index *pBestIdx = 0;
drh487ab3c2001-11-08 00:45:21 +0000420 int bestScore = 0;
drh75897232000-05-29 14:26:00 +0000421
drhc4a3c772001-04-04 11:48:57 +0000422 /* Check to see if there is an expression that uses only the
drh8aff1012001-12-22 14:49:24 +0000423 ** ROWID field of this table. For terms of the form ROWID==expr
424 ** set iDirectEq[i] to the index of the term. For terms of the
425 ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
426 ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
drhc4a3c772001-04-04 11:48:57 +0000427 */
drh8aff1012001-12-22 14:49:24 +0000428 iDirectEq[i] = -1;
429 iDirectLt[i] = -1;
430 iDirectGt[i] = -1;
drhc4a3c772001-04-04 11:48:57 +0000431 for(j=0; j<nExpr; j++){
432 if( aExpr[j].idxLeft==idx && aExpr[j].p->pLeft->iColumn<0
433 && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
drh8aff1012001-12-22 14:49:24 +0000434 switch( aExpr[j].p->op ){
drhd99f7062002-06-08 23:25:08 +0000435 case TK_IN:
drh8aff1012001-12-22 14:49:24 +0000436 case TK_EQ: iDirectEq[i] = j; break;
437 case TK_LE:
438 case TK_LT: iDirectLt[i] = j; break;
439 case TK_GE:
440 case TK_GT: iDirectGt[i] = j; break;
441 }
drhc4a3c772001-04-04 11:48:57 +0000442 }
443 if( aExpr[j].idxRight==idx && aExpr[j].p->pRight->iColumn<0
444 && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
drh8aff1012001-12-22 14:49:24 +0000445 switch( aExpr[j].p->op ){
446 case TK_EQ: iDirectEq[i] = j; break;
447 case TK_LE:
448 case TK_LT: iDirectGt[i] = j; break;
449 case TK_GE:
450 case TK_GT: iDirectLt[i] = j; break;
451 }
drhc4a3c772001-04-04 11:48:57 +0000452 }
453 }
drh8aff1012001-12-22 14:49:24 +0000454 if( iDirectEq[i]>=0 ){
drhc4a3c772001-04-04 11:48:57 +0000455 loopMask |= 1<<idx;
drh6b563442001-11-07 16:48:26 +0000456 pWInfo->a[i].pIdx = 0;
drhc4a3c772001-04-04 11:48:57 +0000457 continue;
458 }
459
drh75897232000-05-29 14:26:00 +0000460 /* Do a search for usable indices. Leave pBestIdx pointing to
drh487ab3c2001-11-08 00:45:21 +0000461 ** the "best" index. pBestIdx is left set to NULL if no indices
462 ** are usable.
drh75897232000-05-29 14:26:00 +0000463 **
drh487ab3c2001-11-08 00:45:21 +0000464 ** The best index is determined as follows. For each of the
465 ** left-most terms that is fixed by an equality operator, add
466 ** 4 to the score. The right-most term of the index may be
467 ** constrained by an inequality. Add 1 if for an "x<..." constraint
468 ** and add 2 for an "x>..." constraint. Chose the index that
469 ** gives the best score.
470 **
471 ** This scoring system is designed so that the score can later be
472 ** used to determine how the index is used. If the score&3 is 0
473 ** then all constraints are equalities. If score&1 is not 0 then
474 ** there is an inequality used as a termination key. (ex: "x<...")
475 ** If score&2 is not 0 then there is an inequality used as the
476 ** start key. (ex: "x>...");
drhd99f7062002-06-08 23:25:08 +0000477 **
drhc27a1ce2002-06-14 20:58:45 +0000478 ** The IN operator (as in "<expr> IN (...)") is treated the same as
479 ** an equality comparison except that it can only be used on the
480 ** left-most column of an index and other terms of the WHERE clause
481 ** cannot be used in conjunction with the IN operator to help satisfy
482 ** other columns of the index.
drh75897232000-05-29 14:26:00 +0000483 */
484 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drhc27a1ce2002-06-14 20:58:45 +0000485 int eqMask = 0; /* Index columns covered by an x=... term */
486 int ltMask = 0; /* Index columns covered by an x<... term */
487 int gtMask = 0; /* Index columns covered by an x>... term */
488 int inMask = 0; /* Index columns covered by an x IN .. term */
drh487ab3c2001-11-08 00:45:21 +0000489 int nEq, m, score;
drh75897232000-05-29 14:26:00 +0000490
drh487ab3c2001-11-08 00:45:21 +0000491 if( pIdx->nColumn>32 ) continue; /* Ignore indices too many columns */
drh75897232000-05-29 14:26:00 +0000492 for(j=0; j<nExpr; j++){
493 if( aExpr[j].idxLeft==idx
494 && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
drh967e8b72000-06-21 13:59:10 +0000495 int iColumn = aExpr[j].p->pLeft->iColumn;
drh75897232000-05-29 14:26:00 +0000496 int k;
drh967e8b72000-06-21 13:59:10 +0000497 for(k=0; k<pIdx->nColumn; k++){
498 if( pIdx->aiColumn[k]==iColumn ){
drh487ab3c2001-11-08 00:45:21 +0000499 switch( aExpr[j].p->op ){
drh48185c12002-06-09 01:55:20 +0000500 case TK_IN: {
501 if( k==0 ) inMask |= 1;
502 break;
503 }
drh487ab3c2001-11-08 00:45:21 +0000504 case TK_EQ: {
505 eqMask |= 1<<k;
506 break;
507 }
508 case TK_LE:
509 case TK_LT: {
510 ltMask |= 1<<k;
511 break;
512 }
513 case TK_GE:
514 case TK_GT: {
515 gtMask |= 1<<k;
516 break;
517 }
518 default: {
519 /* CANT_HAPPEN */
520 assert( 0 );
521 break;
522 }
523 }
drh75897232000-05-29 14:26:00 +0000524 break;
525 }
526 }
527 }
528 if( aExpr[j].idxRight==idx
529 && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
drh967e8b72000-06-21 13:59:10 +0000530 int iColumn = aExpr[j].p->pRight->iColumn;
drh75897232000-05-29 14:26:00 +0000531 int k;
drh967e8b72000-06-21 13:59:10 +0000532 for(k=0; k<pIdx->nColumn; k++){
533 if( pIdx->aiColumn[k]==iColumn ){
drh487ab3c2001-11-08 00:45:21 +0000534 switch( aExpr[j].p->op ){
535 case TK_EQ: {
536 eqMask |= 1<<k;
537 break;
538 }
539 case TK_LE:
540 case TK_LT: {
541 gtMask |= 1<<k;
542 break;
543 }
544 case TK_GE:
545 case TK_GT: {
546 ltMask |= 1<<k;
547 break;
548 }
549 default: {
550 /* CANT_HAPPEN */
551 assert( 0 );
552 break;
553 }
554 }
drh75897232000-05-29 14:26:00 +0000555 break;
556 }
557 }
558 }
559 }
drh487ab3c2001-11-08 00:45:21 +0000560 for(nEq=0; nEq<pIdx->nColumn; nEq++){
561 m = (1<<(nEq+1))-1;
562 if( (m & eqMask)!=m ) break;
563 }
564 score = nEq*4;
565 m = 1<<nEq;
566 if( m & ltMask ) score++;
567 if( m & gtMask ) score+=2;
drh48185c12002-06-09 01:55:20 +0000568 if( score==0 && inMask ) score = 4;
drh487ab3c2001-11-08 00:45:21 +0000569 if( score>bestScore ){
570 pBestIdx = pIdx;
571 bestScore = score;
drh75897232000-05-29 14:26:00 +0000572 }
573 }
drh6b563442001-11-07 16:48:26 +0000574 pWInfo->a[i].pIdx = pBestIdx;
drh487ab3c2001-11-08 00:45:21 +0000575 pWInfo->a[i].score = bestScore;
drh7e391e12000-05-30 20:17:49 +0000576 loopMask |= 1<<idx;
drh6b563442001-11-07 16:48:26 +0000577 if( pBestIdx ){
drh832508b2002-03-02 17:04:07 +0000578 pWInfo->a[i].iCur = pParse->nTab++;
579 pWInfo->peakNTab = pParse->nTab;
drh7f09b3e2002-08-13 13:15:49 +0000580 }else{
581 pWInfo->a[i].iCur = -1;
drh6b563442001-11-07 16:48:26 +0000582 }
drh75897232000-05-29 14:26:00 +0000583 }
584
drhe3184742002-06-19 14:27:05 +0000585 /* Check to see if the ORDER BY clause is or can be satisfied by the
586 ** use of an index on the first table.
587 */
588 if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
589 Index *pSortIdx;
590 Index *pIdx;
591 Table *pTab;
592
593 pTab = pTabList->a[0].pTab;
594 pIdx = pWInfo->a[0].pIdx;
595 if( pIdx && pWInfo->a[0].score==4 ){
596 /* If there is already an index on the left-most column and it is
597 ** an equality index, then either sorting is not helpful, or the
598 ** index is an IN operator, in which case the index does not give
599 ** the correct sort order. Either way, pretend that no suitable
600 ** index is found.
601 */
602 pSortIdx = 0;
603 }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
604 /* If the left-most column is accessed using its ROWID, then do
605 ** not try to sort by index.
606 */
607 pSortIdx = 0;
608 }else{
609 pSortIdx = findSortingIndex(pTab, base, *ppOrderBy, pIdx);
610 }
611 if( pSortIdx && (pIdx==0 || pIdx==pSortIdx) ){
612 if( pIdx==0 ){
613 pWInfo->a[0].pIdx = pSortIdx;
614 pWInfo->a[0].iCur = pParse->nTab++;
615 pWInfo->peakNTab = pParse->nTab;
616 }
617 *ppOrderBy = 0;
618 }
619 }
620
drh6b563442001-11-07 16:48:26 +0000621 /* Open all tables in the pTabList and all indices used by those tables.
drh75897232000-05-29 14:26:00 +0000622 */
drhad3cab52002-05-24 02:04:32 +0000623 for(i=0; i<pTabList->nSrc; i++){
drhf57b3392001-10-08 13:22:32 +0000624 int openOp;
625 Table *pTab;
626
627 pTab = pTabList->a[i].pTab;
drha76b5df2002-02-23 02:32:10 +0000628 if( pTab->isTransient || pTab->pSelect ) continue;
drhf57b3392001-10-08 13:22:32 +0000629 openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
drh99fcd712001-10-13 01:06:47 +0000630 sqliteVdbeAddOp(v, openOp, base+i, pTab->tnum);
631 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drh50e5dad2001-09-15 00:57:28 +0000632 if( i==0 && !pParse->schemaVerified &&
633 (pParse->db->flags & SQLITE_InTrans)==0 ){
drh99fcd712001-10-13 01:06:47 +0000634 sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
drh50e5dad2001-09-15 00:57:28 +0000635 pParse->schemaVerified = 1;
636 }
drh6b563442001-11-07 16:48:26 +0000637 if( pWInfo->a[i].pIdx!=0 ){
638 sqliteVdbeAddOp(v, openOp, pWInfo->a[i].iCur, pWInfo->a[i].pIdx->tnum);
639 sqliteVdbeChangeP3(v, -1, pWInfo->a[i].pIdx->zName, P3_STATIC);
drh75897232000-05-29 14:26:00 +0000640 }
641 }
642
643 /* Generate the code to do the search
644 */
drh75897232000-05-29 14:26:00 +0000645 loopMask = 0;
drhad3cab52002-05-24 02:04:32 +0000646 for(i=0; i<pTabList->nSrc; i++){
drh75897232000-05-29 14:26:00 +0000647 int j, k;
648 int idx = aOrder[i];
drhc4a3c772001-04-04 11:48:57 +0000649 Index *pIdx;
drh6b563442001-11-07 16:48:26 +0000650 WhereLevel *pLevel = &pWInfo->a[i];
drh75897232000-05-29 14:26:00 +0000651
drhad2d8302002-05-24 20:31:36 +0000652 /* If this is the right table of a LEFT OUTER JOIN, allocate and
653 ** initialize a memory cell that record if this table matches any
drhc27a1ce2002-06-14 20:58:45 +0000654 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +0000655 */
656 if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
657 if( !pParse->nMem ) pParse->nMem++;
658 pLevel->iLeftJoin = pParse->nMem++;
659 sqliteVdbeAddOp(v, OP_String, 0, 0);
660 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
661 }
662
drh8aff1012001-12-22 14:49:24 +0000663 pIdx = pLevel->pIdx;
drhd99f7062002-06-08 23:25:08 +0000664 pLevel->inOp = OP_Noop;
drh8aff1012001-12-22 14:49:24 +0000665 if( i<ARRAYSIZE(iDirectEq) && iDirectEq[i]>=0 ){
666 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +0000667 ** equality comparison against the ROWID field. Or
668 ** we reference multiple rows using a "rowid IN (...)"
669 ** construct.
drhc4a3c772001-04-04 11:48:57 +0000670 */
drh8aff1012001-12-22 14:49:24 +0000671 k = iDirectEq[i];
672 assert( k<nExpr );
673 assert( aExpr[k].p!=0 );
674 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
drhd99f7062002-06-08 23:25:08 +0000675 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
drh8aff1012001-12-22 14:49:24 +0000676 if( aExpr[k].idxLeft==idx ){
drhd99f7062002-06-08 23:25:08 +0000677 Expr *pX = aExpr[k].p;
678 if( pX->op!=TK_IN ){
679 sqliteExprCode(pParse, aExpr[k].p->pRight);
680 }else if( pX->pList ){
681 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
682 pLevel->inOp = OP_SetNext;
683 pLevel->inP1 = pX->iTable;
684 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
685 }else{
686 assert( pX->pSelect );
687 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
688 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
689 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
690 pLevel->inOp = OP_Next;
691 pLevel->inP1 = pX->iTable;
692 }
drh8aff1012001-12-22 14:49:24 +0000693 }else{
694 sqliteExprCode(pParse, aExpr[k].p->pLeft);
drhc4a3c772001-04-04 11:48:57 +0000695 }
drh8aff1012001-12-22 14:49:24 +0000696 aExpr[k].p = 0;
drhd99f7062002-06-08 23:25:08 +0000697 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
drhf1351b62002-07-31 19:50:26 +0000698 sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
drhd99f7062002-06-08 23:25:08 +0000699 haveKey = 0;
drh6b125452002-01-28 15:53:03 +0000700 sqliteVdbeAddOp(v, OP_NotExists, base+idx, brk);
drh6b563442001-11-07 16:48:26 +0000701 pLevel->op = OP_Noop;
drhe3184742002-06-19 14:27:05 +0000702 }else if( pIdx!=0 && pLevel->score>0 && pLevel->score%4==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000703 /* Case 2: There is an index and all terms of the WHERE clause that
704 ** refer to the index use the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +0000705 */
drh6b563442001-11-07 16:48:26 +0000706 int start;
drh487ab3c2001-11-08 00:45:21 +0000707 int testOp;
708 int nColumn = pLevel->score/4;
drhd99f7062002-06-08 23:25:08 +0000709 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
drh487ab3c2001-11-08 00:45:21 +0000710 for(j=0; j<nColumn; j++){
drh75897232000-05-29 14:26:00 +0000711 for(k=0; k<nExpr; k++){
drhd99f7062002-06-08 23:25:08 +0000712 Expr *pX = aExpr[k].p;
713 if( pX==0 ) continue;
drh75897232000-05-29 14:26:00 +0000714 if( aExpr[k].idxLeft==idx
715 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
drhd99f7062002-06-08 23:25:08 +0000716 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +0000717 ){
drhd99f7062002-06-08 23:25:08 +0000718 if( pX->op==TK_EQ ){
719 sqliteExprCode(pParse, pX->pRight);
720 aExpr[k].p = 0;
721 break;
722 }
723 if( pX->op==TK_IN && nColumn==1 ){
724 if( pX->pList ){
725 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
726 pLevel->inOp = OP_SetNext;
727 pLevel->inP1 = pX->iTable;
728 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
729 }else{
730 assert( pX->pSelect );
731 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
732 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
733 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
734 pLevel->inOp = OP_Next;
735 pLevel->inP1 = pX->iTable;
736 }
737 aExpr[k].p = 0;
738 break;
739 }
drh75897232000-05-29 14:26:00 +0000740 }
741 if( aExpr[k].idxRight==idx
drh487ab3c2001-11-08 00:45:21 +0000742 && aExpr[k].p->op==TK_EQ
drh75897232000-05-29 14:26:00 +0000743 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
drh967e8b72000-06-21 13:59:10 +0000744 && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +0000745 ){
746 sqliteExprCode(pParse, aExpr[k].p->pLeft);
747 aExpr[k].p = 0;
748 break;
749 }
750 }
751 }
drh6b563442001-11-07 16:48:26 +0000752 pLevel->iMem = pParse->nMem++;
drh6b563442001-11-07 16:48:26 +0000753 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
drh487ab3c2001-11-08 00:45:21 +0000754 sqliteVdbeAddOp(v, OP_MakeKey, nColumn, 0);
drha9e99ae2002-08-13 23:02:57 +0000755 sqliteAddIdxKeyType(v, pIdx);
drh487ab3c2001-11-08 00:45:21 +0000756 if( nColumn==pIdx->nColumn ){
757 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
758 testOp = OP_IdxGT;
759 }else{
760 sqliteVdbeAddOp(v, OP_Dup, 0, 0);
761 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
762 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
763 testOp = OP_IdxGE;
764 }
drh6b563442001-11-07 16:48:26 +0000765 sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
766 start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh487ab3c2001-11-08 00:45:21 +0000767 sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
drh6b563442001-11-07 16:48:26 +0000768 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
drhad3cab52002-05-24 02:04:32 +0000769 if( i==pTabList->nSrc-1 && pushKey ){
drh75897232000-05-29 14:26:00 +0000770 haveKey = 1;
771 }else{
drh99fcd712001-10-13 01:06:47 +0000772 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
drh75897232000-05-29 14:26:00 +0000773 haveKey = 0;
774 }
drh6b563442001-11-07 16:48:26 +0000775 pLevel->op = OP_Next;
776 pLevel->p1 = pLevel->iCur;
777 pLevel->p2 = start;
drh8aff1012001-12-22 14:49:24 +0000778 }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
779 /* Case 3: We have an inequality comparison against the ROWID field.
780 */
781 int testOp = OP_Noop;
782 int start;
783
784 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
785 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
786 if( iDirectGt[i]>=0 ){
787 k = iDirectGt[i];
788 assert( k<nExpr );
789 assert( aExpr[k].p!=0 );
790 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
791 if( aExpr[k].idxLeft==idx ){
792 sqliteExprCode(pParse, aExpr[k].p->pRight);
793 }else{
794 sqliteExprCode(pParse, aExpr[k].p->pLeft);
795 }
drhf1351b62002-07-31 19:50:26 +0000796 sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
drh8aff1012001-12-22 14:49:24 +0000797 if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
798 sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
799 }
800 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, brk);
801 aExpr[k].p = 0;
802 }else{
803 sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
804 }
805 if( iDirectLt[i]>=0 ){
806 k = iDirectLt[i];
807 assert( k<nExpr );
808 assert( aExpr[k].p!=0 );
809 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
810 if( aExpr[k].idxLeft==idx ){
811 sqliteExprCode(pParse, aExpr[k].p->pRight);
812 }else{
813 sqliteExprCode(pParse, aExpr[k].p->pLeft);
814 }
drhf1351b62002-07-31 19:50:26 +0000815 sqliteVdbeAddOp(v, OP_MustBeInt, 1, sqliteVdbeCurrentAddr(v)+1);
drh8aff1012001-12-22 14:49:24 +0000816 pLevel->iMem = pParse->nMem++;
817 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
818 if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
819 testOp = OP_Ge;
820 }else{
821 testOp = OP_Gt;
822 }
823 aExpr[k].p = 0;
824 }
825 start = sqliteVdbeCurrentAddr(v);
826 pLevel->op = OP_Next;
827 pLevel->p1 = base+idx;
828 pLevel->p2 = start;
829 if( testOp!=OP_Noop ){
830 sqliteVdbeAddOp(v, OP_Recno, base+idx, 0);
831 sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
832 sqliteVdbeAddOp(v, testOp, 0, brk);
833 }
834 haveKey = 0;
835 }else if( pIdx==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000836 /* Case 4: There is no usable index. We must do a complete
drh8aff1012001-12-22 14:49:24 +0000837 ** scan of the entire database table.
838 */
839 int start;
840
841 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
842 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
843 sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
844 start = sqliteVdbeCurrentAddr(v);
845 pLevel->op = OP_Next;
846 pLevel->p1 = base+idx;
847 pLevel->p2 = start;
848 haveKey = 0;
drh487ab3c2001-11-08 00:45:21 +0000849 }else{
drhc27a1ce2002-06-14 20:58:45 +0000850 /* Case 5: The WHERE clause term that refers to the right-most
851 ** column of the index is an inequality. For example, if
852 ** the index is on (x,y,z) and the WHERE clause is of the
853 ** form "x=5 AND y<10" then this case is used. Only the
854 ** right-most column can be an inequality - the rest must
855 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +0000856 **
857 ** This case is also used when there are no WHERE clause
858 ** constraints but an index is selected anyway, in order
859 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +0000860 */
861 int score = pLevel->score;
862 int nEqColumn = score/4;
863 int start;
864 int leFlag, geFlag;
865 int testOp;
866
867 /* Evaluate the equality constraints
868 */
869 for(j=0; j<nEqColumn; j++){
870 for(k=0; k<nExpr; k++){
871 if( aExpr[k].p==0 ) continue;
872 if( aExpr[k].idxLeft==idx
873 && aExpr[k].p->op==TK_EQ
874 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
875 && aExpr[k].p->pLeft->iColumn==pIdx->aiColumn[j]
876 ){
877 sqliteExprCode(pParse, aExpr[k].p->pRight);
878 aExpr[k].p = 0;
879 break;
880 }
881 if( aExpr[k].idxRight==idx
882 && aExpr[k].p->op==TK_EQ
883 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
884 && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
885 ){
886 sqliteExprCode(pParse, aExpr[k].p->pLeft);
887 aExpr[k].p = 0;
888 break;
889 }
890 }
891 }
892
drhc27a1ce2002-06-14 20:58:45 +0000893 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +0000894 ** used twice: once to make the termination key and once to make the
895 ** start key.
896 */
897 for(j=0; j<nEqColumn; j++){
898 sqliteVdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
899 }
900
901 /* Generate the termination key. This is the key value that
902 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +0000903 ** are no equality terms and no "X<..." term.
drh487ab3c2001-11-08 00:45:21 +0000904 */
905 if( (score & 1)!=0 ){
906 for(k=0; k<nExpr; k++){
907 Expr *pExpr = aExpr[k].p;
908 if( pExpr==0 ) continue;
909 if( aExpr[k].idxLeft==idx
910 && (pExpr->op==TK_LT || pExpr->op==TK_LE)
911 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
912 && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
913 ){
914 sqliteExprCode(pParse, pExpr->pRight);
915 leFlag = pExpr->op==TK_LE;
916 aExpr[k].p = 0;
917 break;
918 }
919 if( aExpr[k].idxRight==idx
920 && (pExpr->op==TK_GT || pExpr->op==TK_GE)
921 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
922 && pExpr->pRight->iColumn==pIdx->aiColumn[j]
923 ){
924 sqliteExprCode(pParse, pExpr->pLeft);
925 leFlag = pExpr->op==TK_GE;
926 aExpr[k].p = 0;
927 break;
928 }
929 }
930 testOp = OP_IdxGE;
931 }else{
932 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
933 leFlag = 1;
934 }
935 if( testOp!=OP_Noop ){
936 pLevel->iMem = pParse->nMem++;
937 sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + (score & 1), 0);
drha9e99ae2002-08-13 23:02:57 +0000938 sqliteAddIdxKeyType(v, pIdx);
drh487ab3c2001-11-08 00:45:21 +0000939 if( leFlag ){
940 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
941 }
942 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
943 }
944
945 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +0000946 ** bound on the search. There is no start key if there are no
947 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +0000948 ** that case, generate a "Rewind" instruction in place of the
949 ** start key search.
950 */
951 if( (score & 2)!=0 ){
952 for(k=0; k<nExpr; k++){
953 Expr *pExpr = aExpr[k].p;
954 if( pExpr==0 ) continue;
955 if( aExpr[k].idxLeft==idx
956 && (pExpr->op==TK_GT || pExpr->op==TK_GE)
957 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
958 && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
959 ){
960 sqliteExprCode(pParse, pExpr->pRight);
961 geFlag = pExpr->op==TK_GE;
962 aExpr[k].p = 0;
963 break;
964 }
965 if( aExpr[k].idxRight==idx
966 && (pExpr->op==TK_LT || pExpr->op==TK_LE)
967 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
968 && pExpr->pRight->iColumn==pIdx->aiColumn[j]
969 ){
970 sqliteExprCode(pParse, pExpr->pLeft);
971 geFlag = pExpr->op==TK_LE;
972 aExpr[k].p = 0;
973 break;
974 }
975 }
drh7900ead2001-11-12 13:51:43 +0000976 }else{
977 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +0000978 }
979 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
980 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
981 if( nEqColumn>0 || (score&2)!=0 ){
982 sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + ((score&2)!=0), 0);
drha9e99ae2002-08-13 23:02:57 +0000983 sqliteAddIdxKeyType(v, pIdx);
drh487ab3c2001-11-08 00:45:21 +0000984 if( !geFlag ){
985 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
986 }
987 sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
988 }else{
989 sqliteVdbeAddOp(v, OP_Rewind, pLevel->iCur, brk);
990 }
991
992 /* Generate the the top of the loop. If there is a termination
993 ** key we have to test for that key and abort at the top of the
994 ** loop.
995 */
996 start = sqliteVdbeCurrentAddr(v);
997 if( testOp!=OP_Noop ){
998 sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
999 sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
1000 }
1001 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
drhad3cab52002-05-24 02:04:32 +00001002 if( i==pTabList->nSrc-1 && pushKey ){
drh487ab3c2001-11-08 00:45:21 +00001003 haveKey = 1;
1004 }else{
1005 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
1006 haveKey = 0;
1007 }
1008
1009 /* Record the instruction used to terminate the loop.
1010 */
1011 pLevel->op = OP_Next;
1012 pLevel->p1 = pLevel->iCur;
1013 pLevel->p2 = start;
drh75897232000-05-29 14:26:00 +00001014 }
1015 loopMask |= 1<<idx;
1016
1017 /* Insert code to test every subexpression that can be completely
1018 ** computed using the current set of tables.
1019 */
1020 for(j=0; j<nExpr; j++){
1021 if( aExpr[j].p==0 ) continue;
drh3f6b5482002-04-02 13:26:10 +00001022 if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
drh1cc093c2002-06-24 22:01:57 +00001023 if( pLevel->iLeftJoin && aExpr[j].p->isJoinExpr==0 ) continue;
drh75897232000-05-29 14:26:00 +00001024 if( haveKey ){
drh573bd272001-02-19 23:23:38 +00001025 haveKey = 0;
drh99fcd712001-10-13 01:06:47 +00001026 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
drh75897232000-05-29 14:26:00 +00001027 }
drhf5905aa2002-05-26 20:54:33 +00001028 sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
drh75897232000-05-29 14:26:00 +00001029 aExpr[j].p = 0;
1030 }
1031 brk = cont;
drhad2d8302002-05-24 20:31:36 +00001032
1033 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1034 ** at least one row of the right table has matched the left table.
1035 */
1036 if( pLevel->iLeftJoin ){
1037 pLevel->top = sqliteVdbeCurrentAddr(v);
1038 sqliteVdbeAddOp(v, OP_Integer, 1, 0);
1039 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drh1cc093c2002-06-24 22:01:57 +00001040 for(j=0; j<nExpr; j++){
1041 if( aExpr[j].p==0 ) continue;
1042 if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
1043 if( haveKey ){
drh3b167c72002-06-28 12:18:47 +00001044 /* Cannot happen. "haveKey" can only be true if pushKey is true
1045 ** an pushKey can only be true for DELETE and UPDATE and there are
1046 ** no outer joins with DELETE and UPDATE.
1047 */
drh1cc093c2002-06-24 22:01:57 +00001048 haveKey = 0;
1049 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
1050 }
1051 sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
1052 aExpr[j].p = 0;
1053 }
drhad2d8302002-05-24 20:31:36 +00001054 }
drh75897232000-05-29 14:26:00 +00001055 }
1056 pWInfo->iContinue = cont;
1057 if( pushKey && !haveKey ){
drh99fcd712001-10-13 01:06:47 +00001058 sqliteVdbeAddOp(v, OP_Recno, base, 0);
drh75897232000-05-29 14:26:00 +00001059 }
1060 sqliteFree(aOrder);
1061 return pWInfo;
1062}
1063
1064/*
drhc27a1ce2002-06-14 20:58:45 +00001065** Generate the end of the WHERE loop. See comments on
1066** sqliteWhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001067*/
1068void sqliteWhereEnd(WhereInfo *pWInfo){
1069 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001070 int i;
drh19a775c2000-06-05 18:54:46 +00001071 int base = pWInfo->base;
drh6b563442001-11-07 16:48:26 +00001072 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001073 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001074
drhad3cab52002-05-24 02:04:32 +00001075 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001076 pLevel = &pWInfo->a[i];
1077 sqliteVdbeResolveLabel(v, pLevel->cont);
1078 if( pLevel->op!=OP_Noop ){
1079 sqliteVdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001080 }
drh6b563442001-11-07 16:48:26 +00001081 sqliteVdbeResolveLabel(v, pLevel->brk);
drhd99f7062002-06-08 23:25:08 +00001082 if( pLevel->inOp!=OP_Noop ){
1083 sqliteVdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
1084 }
drhad2d8302002-05-24 20:31:36 +00001085 if( pLevel->iLeftJoin ){
1086 int addr;
1087 addr = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh7f09b3e2002-08-13 13:15:49 +00001088 sqliteVdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iCur>=0));
drhad2d8302002-05-24 20:31:36 +00001089 sqliteVdbeAddOp(v, OP_NullRow, base+i, 0);
drh7f09b3e2002-08-13 13:15:49 +00001090 if( pLevel->iCur>=0 ){
1091 sqliteVdbeAddOp(v, OP_NullRow, pLevel->iCur, 0);
1092 }
drhad2d8302002-05-24 20:31:36 +00001093 sqliteVdbeAddOp(v, OP_Goto, 0, pLevel->top);
1094 }
drh19a775c2000-06-05 18:54:46 +00001095 }
drh6b563442001-11-07 16:48:26 +00001096 sqliteVdbeResolveLabel(v, pWInfo->iBreak);
drhad3cab52002-05-24 02:04:32 +00001097 for(i=0; i<pTabList->nSrc; i++){
drh22f70c32002-02-18 01:17:00 +00001098 if( pTabList->a[i].pTab->isTransient ) continue;
drh6b563442001-11-07 16:48:26 +00001099 pLevel = &pWInfo->a[i];
1100 sqliteVdbeAddOp(v, OP_Close, base+i, 0);
1101 if( pLevel->pIdx!=0 ){
1102 sqliteVdbeAddOp(v, OP_Close, pLevel->iCur, 0);
1103 }
drh19a775c2000-06-05 18:54:46 +00001104 }
drh142e30d2002-08-28 03:00:58 +00001105#if 0 /* Never reuse a cursor */
drh832508b2002-03-02 17:04:07 +00001106 if( pWInfo->pParse->nTab==pWInfo->peakNTab ){
1107 pWInfo->pParse->nTab = pWInfo->savedNTab;
1108 }
drh142e30d2002-08-28 03:00:58 +00001109#endif
drh75897232000-05-29 14:26:00 +00001110 sqliteFree(pWInfo);
1111 return;
1112}