blob: 7470a669ce187137da224284a55b56a68b05f4c7 [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**
drh1f162302002-10-27 19:35:33 +000016** $Id: where.c,v 1.66 2002/10/27 19:35:35 drh Exp $
drh75897232000-05-29 14:26:00 +000017*/
18#include "sqliteInt.h"
19
20/*
21** The query generator uses an array of instances of this structure to
22** help it analyze the subexpressions of the WHERE clause. Each WHERE
23** clause subexpression is separated from the others by an AND operator.
24*/
25typedef struct ExprInfo ExprInfo;
26struct ExprInfo {
27 Expr *p; /* Pointer to the subexpression */
drhe3184742002-06-19 14:27:05 +000028 u8 indexable; /* True if this subexprssion is usable by an index */
drh1f162302002-10-27 19:35:33 +000029 u8 oracle8join; /* -1 if left side contains "(+)". +1 if right side
30 ** contains "(+)". 0 if neither contains "(+)" */
drhe3184742002-06-19 14:27:05 +000031 short int idxLeft; /* p->pLeft is a column in this table number. -1 if
drh967e8b72000-06-21 13:59:10 +000032 ** p->pLeft is not the column of any table */
drhe3184742002-06-19 14:27:05 +000033 short int idxRight; /* p->pRight is a column in this table number. -1 if
drh967e8b72000-06-21 13:59:10 +000034 ** p->pRight is not the column of any table */
drhe3184742002-06-19 14:27:05 +000035 unsigned prereqLeft; /* Bitmask of tables referenced by p->pLeft */
36 unsigned prereqRight; /* Bitmask of tables referenced by p->pRight */
37 unsigned prereqAll; /* Bitmask of tables referenced by p */
drh75897232000-05-29 14:26:00 +000038};
39
40/*
41** Determine the number of elements in an array.
42*/
43#define ARRAYSIZE(X) (sizeof(X)/sizeof(X[0]))
44
45/*
46** This routine is used to divide the WHERE expression into subexpressions
47** separated by the AND operator.
48**
49** aSlot[] is an array of subexpressions structures.
50** There are nSlot spaces left in this array. This routine attempts to
51** split pExpr into subexpressions and fills aSlot[] with those subexpressions.
52** The return value is the number of slots filled.
53*/
54static int exprSplit(int nSlot, ExprInfo *aSlot, Expr *pExpr){
55 int cnt = 0;
56 if( pExpr==0 || nSlot<1 ) return 0;
57 if( nSlot==1 || pExpr->op!=TK_AND ){
58 aSlot[0].p = pExpr;
59 return 1;
60 }
61 if( pExpr->pLeft->op!=TK_AND ){
62 aSlot[0].p = pExpr->pLeft;
63 cnt = 1 + exprSplit(nSlot-1, &aSlot[1], pExpr->pRight);
64 }else{
65 cnt = exprSplit(nSlot, aSlot, pExpr->pRight);
66 cnt += exprSplit(nSlot-cnt, &aSlot[cnt], pExpr->pLeft);
67 }
68 return cnt;
69}
70
71/*
72** This routine walks (recursively) an expression tree and generates
73** a bitmask indicating which tables are used in that expression
drhe3184742002-06-19 14:27:05 +000074** tree. Bit 0 of the mask is set if table base+0 is used. Bit 1
75** is set if table base+1 is used. And so forth.
drh75897232000-05-29 14:26:00 +000076**
77** In order for this routine to work, the calling function must have
78** previously invoked sqliteExprResolveIds() on the expression. See
79** the header comment on that routine for additional information.
drh19a775c2000-06-05 18:54:46 +000080**
81** "base" is the cursor number (the value of the iTable field) that
drhe3184742002-06-19 14:27:05 +000082** corresponds to the first entry in the list of tables that appear
83** in the FROM clause of a SELECT. For UPDATE and DELETE statements
84** there is just a single table with "base" as the cursor number.
drh75897232000-05-29 14:26:00 +000085*/
drh19a775c2000-06-05 18:54:46 +000086static int exprTableUsage(int base, Expr *p){
drh75897232000-05-29 14:26:00 +000087 unsigned int mask = 0;
88 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +000089 if( p->op==TK_COLUMN ){
drh19a775c2000-06-05 18:54:46 +000090 return 1<< (p->iTable - base);
drh75897232000-05-29 14:26:00 +000091 }
92 if( p->pRight ){
drh19a775c2000-06-05 18:54:46 +000093 mask = exprTableUsage(base, p->pRight);
drh75897232000-05-29 14:26:00 +000094 }
95 if( p->pLeft ){
drh19a775c2000-06-05 18:54:46 +000096 mask |= exprTableUsage(base, p->pLeft);
drh75897232000-05-29 14:26:00 +000097 }
drhdd579122002-04-02 01:58:57 +000098 if( p->pList ){
99 int i;
100 for(i=0; i<p->pList->nExpr; i++){
101 mask |= exprTableUsage(base, p->pList->a[i].pExpr);
102 }
103 }
drh75897232000-05-29 14:26:00 +0000104 return mask;
105}
106
107/*
drh487ab3c2001-11-08 00:45:21 +0000108** Return TRUE if the given operator is one of the operators that is
109** allowed for an indexable WHERE clause. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000110** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000111*/
112static int allowedOp(int op){
113 switch( op ){
114 case TK_LT:
115 case TK_LE:
116 case TK_GT:
117 case TK_GE:
118 case TK_EQ:
drhd99f7062002-06-08 23:25:08 +0000119 case TK_IN:
drh487ab3c2001-11-08 00:45:21 +0000120 return 1;
121 default:
122 return 0;
123 }
124}
125
126/*
drh75897232000-05-29 14:26:00 +0000127** The input to this routine is an ExprInfo structure with only the
128** "p" field filled in. The job of this routine is to analyze the
129** subexpression and populate all the other fields of the ExprInfo
130** structure.
drh19a775c2000-06-05 18:54:46 +0000131**
132** "base" is the cursor number (the value of the iTable field) that
drh832508b2002-03-02 17:04:07 +0000133** corresponds to the first entry in the table list.
drh75897232000-05-29 14:26:00 +0000134*/
drh19a775c2000-06-05 18:54:46 +0000135static void exprAnalyze(int base, ExprInfo *pInfo){
drh75897232000-05-29 14:26:00 +0000136 Expr *pExpr = pInfo->p;
drh19a775c2000-06-05 18:54:46 +0000137 pInfo->prereqLeft = exprTableUsage(base, pExpr->pLeft);
138 pInfo->prereqRight = exprTableUsage(base, pExpr->pRight);
drh3f6b5482002-04-02 13:26:10 +0000139 pInfo->prereqAll = exprTableUsage(base, pExpr);
drh75897232000-05-29 14:26:00 +0000140 pInfo->indexable = 0;
141 pInfo->idxLeft = -1;
142 pInfo->idxRight = -1;
drh487ab3c2001-11-08 00:45:21 +0000143 if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
drhd99f7062002-06-08 23:25:08 +0000144 if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
drh19a775c2000-06-05 18:54:46 +0000145 pInfo->idxRight = pExpr->pRight->iTable - base;
drh75897232000-05-29 14:26:00 +0000146 pInfo->indexable = 1;
147 }
drh967e8b72000-06-21 13:59:10 +0000148 if( pExpr->pLeft->op==TK_COLUMN ){
drh19a775c2000-06-05 18:54:46 +0000149 pInfo->idxLeft = pExpr->pLeft->iTable - base;
drh75897232000-05-29 14:26:00 +0000150 pInfo->indexable = 1;
151 }
152 }
153}
154
155/*
drhe3184742002-06-19 14:27:05 +0000156** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
157** left-most table in the FROM clause of that same SELECT statement and
158** the table has a cursor number of "base".
159**
160** This routine attempts to find an index for pTab that generates the
161** correct record sequence for the given ORDER BY clause. The return value
162** is a pointer to an index that does the job. NULL is returned if the
163** table has no index that will generate the correct sort order.
164**
165** If there are two or more indices that generate the correct sort order
166** and pPreferredIdx is one of those indices, then return pPreferredIdx.
167*/
168static Index *findSortingIndex(
169 Table *pTab, /* The table to be sorted */
170 int base, /* Cursor number for pTab */
171 ExprList *pOrderBy, /* The ORDER BY clause */
172 Index *pPreferredIdx /* Use this index, if possible and not NULL */
173){
174 int i;
175 Index *pMatch;
176 Index *pIdx;
177
178 assert( pOrderBy!=0 );
179 assert( pOrderBy->nExpr>0 );
180 for(i=0; i<pOrderBy->nExpr; i++){
181 Expr *p;
182 if( (pOrderBy->a[i].sortOrder & SQLITE_SO_DIRMASK)!=SQLITE_SO_ASC ){
183 /* Indices can only be used for ascending sort order */
184 return 0;
185 }
drhc330af12002-08-14 03:03:57 +0000186 if( (pOrderBy->a[i].sortOrder & SQLITE_SO_TYPEMASK)!=SQLITE_SO_UNK ){
187 /* Do not sort by index if there is a COLLATE clause */
188 return 0;
189 }
drhe3184742002-06-19 14:27:05 +0000190 p = pOrderBy->a[i].pExpr;
191 if( p->op!=TK_COLUMN || p->iTable!=base ){
192 /* Can not use an index sort on anything that is not a column in the
193 ** left-most table of the FROM clause */
194 return 0;
195 }
196 }
197
198 /* If we get this far, it means the ORDER BY clause consists only of
199 ** ascending columns in the left-most table of the FROM clause. Now
200 ** check for a matching index.
201 */
202 pMatch = 0;
203 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
204 if( pIdx->nColumn<pOrderBy->nExpr ) continue;
205 for(i=0; i<pOrderBy->nExpr; i++){
206 if( pOrderBy->a[i].pExpr->iColumn!=pIdx->aiColumn[i] ) break;
207 }
208 if( i>=pOrderBy->nExpr ){
209 pMatch = pIdx;
210 if( pIdx==pPreferredIdx ) break;
211 }
212 }
213 return pMatch;
214}
215
216/*
217** Generate the beginning of the loop used for WHERE clause processing.
drh75897232000-05-29 14:26:00 +0000218** The return value is a pointer to an (opaque) structure that contains
219** information needed to terminate the loop. Later, the calling routine
220** should invoke sqliteWhereEnd() with the return value of this function
221** in order to complete the WHERE clause processing.
222**
223** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +0000224**
225** The basic idea is to do a nested loop, one loop for each table in
226** the FROM clause of a select. (INSERT and UPDATE statements are the
227** same as a SELECT with only a single table in the FROM clause.) For
228** example, if the SQL is this:
229**
230** SELECT * FROM t1, t2, t3 WHERE ...;
231**
232** Then the code generated is conceptually like the following:
233**
234** foreach row1 in t1 do \ Code generated
235** foreach row2 in t2 do |-- by sqliteWhereBegin()
236** foreach row3 in t3 do /
237** ...
238** end \ Code generated
239** end |-- by sqliteWhereEnd()
240** end /
241**
242** There are Btree cursors associated with each table. t1 uses cursor
243** "base". t2 uses cursor "base+1". And so forth. This routine generates
244** the code to open those cursors. sqliteWhereEnd() generates the code
245** to close them.
246**
247** If the WHERE clause is empty, the foreach loops must each scan their
248** entire tables. Thus a three-way join is an O(N^3) operation. But if
249** the tables have indices and there are terms in the WHERE clause that
250** refer to those indices, a complete table scan can be avoided and the
251** code will run much faster. Most of the work of this routine is checking
252** to see if there are indices that can be used to speed up the loop.
253**
254** Terms of the WHERE clause are also used to limit which rows actually
255** make it to the "..." in the middle of the loop. After each "foreach",
256** terms of the WHERE clause that use only terms in that loop and outer
257** loops are evaluated and if false a jump is made around all subsequent
258** inner loops (or around the "..." if the test occurs within the inner-
259** most loop)
260**
261** OUTER JOINS
262**
263** An outer join of tables t1 and t2 is conceptally coded as follows:
264**
265** foreach row1 in t1 do
266** flag = 0
267** foreach row2 in t2 do
268** start:
269** ...
270** flag = 1
271** end
drhe3184742002-06-19 14:27:05 +0000272** if flag==0 then
273** move the row2 cursor to a null row
274** goto start
275** fi
drhc27a1ce2002-06-14 20:58:45 +0000276** end
277**
drhe3184742002-06-19 14:27:05 +0000278** ORDER BY CLAUSE PROCESSING
279**
280** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
281** if there is one. If there is no ORDER BY clause or if this routine
282** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
283**
284** If an index can be used so that the natural output order of the table
285** scan is correct for the ORDER BY clause, then that index is used and
286** *ppOrderBy is set to NULL. This is an optimization that prevents an
287** unnecessary sort of the result set if an index appropriate for the
288** ORDER BY clause already exists.
289**
290** If the where clause loops cannot be arranged to provide the correct
291** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +0000292*/
293WhereInfo *sqliteWhereBegin(
294 Parse *pParse, /* The parser context */
drh832508b2002-03-02 17:04:07 +0000295 int base, /* VDBE cursor index for left-most table in pTabList */
drhad3cab52002-05-24 02:04:32 +0000296 SrcList *pTabList, /* A list of all tables to be scanned */
drh75897232000-05-29 14:26:00 +0000297 Expr *pWhere, /* The WHERE clause */
drhe3184742002-06-19 14:27:05 +0000298 int pushKey, /* If TRUE, leave the table key on the stack */
299 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +0000300){
301 int i; /* Loop counter */
302 WhereInfo *pWInfo; /* Will become the return value of this function */
303 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
304 int brk, cont; /* Addresses used during code generation */
305 int *aOrder; /* Order in which pTabList entries are searched */
306 int nExpr; /* Number of subexpressions in the WHERE clause */
307 int loopMask; /* One bit set for each outer loop */
308 int haveKey; /* True if KEY is on the stack */
drh8aff1012001-12-22 14:49:24 +0000309 int iDirectEq[32]; /* Term of the form ROWID==X for the N-th table */
310 int iDirectLt[32]; /* Term of the form ROWID<X or ROWID<=X */
311 int iDirectGt[32]; /* Term of the form ROWID>X or ROWID>=X */
drh83dcb1a2002-06-28 01:02:38 +0000312 ExprInfo aExpr[101]; /* The WHERE clause is divided into these expressions */
drh75897232000-05-29 14:26:00 +0000313
drhc27a1ce2002-06-14 20:58:45 +0000314 /* pushKey is only allowed if there is a single table (as in an INSERT or
315 ** UPDATE statement)
316 */
317 assert( pushKey==0 || pTabList->nSrc==1 );
drh83dcb1a2002-06-28 01:02:38 +0000318
319 /* Split the WHERE clause into separate subexpressions where each
320 ** subexpression is separated by an AND operator. If the aExpr[]
321 ** array fills up, the last entry might point to an expression which
322 ** contains additional unfactored AND operators.
323 */
324 memset(aExpr, 0, sizeof(aExpr));
325 nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
326 if( nExpr==ARRAYSIZE(aExpr) ){
327 char zBuf[50];
328 sprintf(zBuf, "%d", ARRAYSIZE(aExpr)-1);
329 sqliteSetString(&pParse->zErrMsg, "WHERE clause too complex - no more "
330 "than ", zBuf, " terms allowed", 0);
331 pParse->nErr++;
332 return 0;
333 }
drhc27a1ce2002-06-14 20:58:45 +0000334
drhe3184742002-06-19 14:27:05 +0000335 /* Allocate space for aOrder[] */
drhad3cab52002-05-24 02:04:32 +0000336 aOrder = sqliteMalloc( sizeof(int) * pTabList->nSrc );
drh75897232000-05-29 14:26:00 +0000337
338 /* Allocate and initialize the WhereInfo structure that will become the
339 ** return value.
340 */
drhad3cab52002-05-24 02:04:32 +0000341 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
drhdaffd0e2001-04-11 14:28:42 +0000342 if( sqlite_malloc_failed ){
drh75897232000-05-29 14:26:00 +0000343 sqliteFree(aOrder);
drhdaffd0e2001-04-11 14:28:42 +0000344 sqliteFree(pWInfo);
drh75897232000-05-29 14:26:00 +0000345 return 0;
346 }
347 pWInfo->pParse = pParse;
348 pWInfo->pTabList = pTabList;
drh832508b2002-03-02 17:04:07 +0000349 pWInfo->base = base;
350 pWInfo->peakNTab = pWInfo->savedNTab = pParse->nTab;
drh08192d52002-04-30 19:20:28 +0000351 pWInfo->iBreak = sqliteVdbeMakeLabel(v);
352
353 /* Special case: a WHERE clause that is constant. Evaluate the
354 ** expression and either jump over all of the code or fall thru.
355 */
356 if( pWhere && sqliteExprIsConstant(pWhere) ){
drhf5905aa2002-05-26 20:54:33 +0000357 sqliteExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +0000358 pWhere = 0;
drh08192d52002-04-30 19:20:28 +0000359 }
drh75897232000-05-29 14:26:00 +0000360
drh75897232000-05-29 14:26:00 +0000361 /* Analyze all of the subexpressions.
362 */
363 for(i=0; i<nExpr; i++){
drh22f70c32002-02-18 01:17:00 +0000364 exprAnalyze(base, &aExpr[i]);
drh1d1f3052002-05-21 13:18:25 +0000365
366 /* If we are executing a trigger body, remove all references to
367 ** new.* and old.* tables from the prerequisite masks.
368 */
369 if( pParse->trigStack ){
370 int x;
371 if( (x = pParse->trigStack->newIdx) >= 0 ){
372 int mask = ~(1 << (x - base));
373 aExpr[i].prereqRight &= mask;
374 aExpr[i].prereqLeft &= mask;
375 aExpr[i].prereqAll &= mask;
376 }
377 if( (x = pParse->trigStack->oldIdx) >= 0 ){
378 int mask = ~(1 << (x - base));
379 aExpr[i].prereqRight &= mask;
380 aExpr[i].prereqLeft &= mask;
381 aExpr[i].prereqAll &= mask;
382 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000383 }
drh75897232000-05-29 14:26:00 +0000384 }
385
386 /* Figure out a good nesting order for the tables. aOrder[0] will
387 ** be the index in pTabList of the outermost table. aOrder[1] will
drhad3cab52002-05-24 02:04:32 +0000388 ** be the first nested loop and so on. aOrder[pTabList->nSrc-1] will
drh75897232000-05-29 14:26:00 +0000389 ** be the innermost loop.
390 **
drh1d1f3052002-05-21 13:18:25 +0000391 ** Someday we will put in a good algorithm here to reorder the loops
drh75897232000-05-29 14:26:00 +0000392 ** for an effiecient query. But for now, just use whatever order the
393 ** tables appear in in the pTabList.
394 */
drhad3cab52002-05-24 02:04:32 +0000395 for(i=0; i<pTabList->nSrc; i++){
drh75897232000-05-29 14:26:00 +0000396 aOrder[i] = i;
397 }
398
399 /* Figure out what index to use (if any) for each nested loop.
drh6b563442001-11-07 16:48:26 +0000400 ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
drhad3cab52002-05-24 02:04:32 +0000401 ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
drh8aff1012001-12-22 14:49:24 +0000402 ** loop.
403 **
404 ** If terms exist that use the ROWID of any table, then set the
405 ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
406 ** to the index of the term containing the ROWID. We always prefer
407 ** to use a ROWID which can directly access a table rather than an
drh0a36c572002-02-18 22:49:59 +0000408 ** index which requires reading an index first to get the rowid then
409 ** doing a second read of the actual database table.
drh75897232000-05-29 14:26:00 +0000410 **
411 ** Actually, if there are more than 32 tables in the join, only the
drh0a36c572002-02-18 22:49:59 +0000412 ** first 32 tables are candidates for indices. This is (again) due
413 ** to the limit of 32 bits in an integer bitmask.
drh75897232000-05-29 14:26:00 +0000414 */
415 loopMask = 0;
drhcb485882002-08-15 13:50:48 +0000416 for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++){
drhc4a3c772001-04-04 11:48:57 +0000417 int j;
drh75897232000-05-29 14:26:00 +0000418 int idx = aOrder[i];
419 Table *pTab = pTabList->a[idx].pTab;
420 Index *pIdx;
421 Index *pBestIdx = 0;
drh487ab3c2001-11-08 00:45:21 +0000422 int bestScore = 0;
drh75897232000-05-29 14:26:00 +0000423
drhc4a3c772001-04-04 11:48:57 +0000424 /* Check to see if there is an expression that uses only the
drh8aff1012001-12-22 14:49:24 +0000425 ** ROWID field of this table. For terms of the form ROWID==expr
426 ** set iDirectEq[i] to the index of the term. For terms of the
427 ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
428 ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
drhc4a3c772001-04-04 11:48:57 +0000429 */
drhc8f8b632002-09-30 12:36:26 +0000430 pWInfo->a[i].iCur = -1;
drh8aff1012001-12-22 14:49:24 +0000431 iDirectEq[i] = -1;
432 iDirectLt[i] = -1;
433 iDirectGt[i] = -1;
drhc4a3c772001-04-04 11:48:57 +0000434 for(j=0; j<nExpr; j++){
435 if( aExpr[j].idxLeft==idx && aExpr[j].p->pLeft->iColumn<0
436 && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
drh8aff1012001-12-22 14:49:24 +0000437 switch( aExpr[j].p->op ){
drhd99f7062002-06-08 23:25:08 +0000438 case TK_IN:
drh8aff1012001-12-22 14:49:24 +0000439 case TK_EQ: iDirectEq[i] = j; break;
440 case TK_LE:
441 case TK_LT: iDirectLt[i] = j; break;
442 case TK_GE:
443 case TK_GT: iDirectGt[i] = j; break;
444 }
drhc4a3c772001-04-04 11:48:57 +0000445 }
446 if( aExpr[j].idxRight==idx && aExpr[j].p->pRight->iColumn<0
447 && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
drh8aff1012001-12-22 14:49:24 +0000448 switch( aExpr[j].p->op ){
449 case TK_EQ: iDirectEq[i] = j; break;
450 case TK_LE:
451 case TK_LT: iDirectGt[i] = j; break;
452 case TK_GE:
453 case TK_GT: iDirectLt[i] = j; break;
454 }
drhc4a3c772001-04-04 11:48:57 +0000455 }
456 }
drh8aff1012001-12-22 14:49:24 +0000457 if( iDirectEq[i]>=0 ){
drhc4a3c772001-04-04 11:48:57 +0000458 loopMask |= 1<<idx;
drh6b563442001-11-07 16:48:26 +0000459 pWInfo->a[i].pIdx = 0;
drhc4a3c772001-04-04 11:48:57 +0000460 continue;
461 }
462
drh75897232000-05-29 14:26:00 +0000463 /* Do a search for usable indices. Leave pBestIdx pointing to
drh487ab3c2001-11-08 00:45:21 +0000464 ** the "best" index. pBestIdx is left set to NULL if no indices
465 ** are usable.
drh75897232000-05-29 14:26:00 +0000466 **
drh487ab3c2001-11-08 00:45:21 +0000467 ** The best index is determined as follows. For each of the
468 ** left-most terms that is fixed by an equality operator, add
469 ** 4 to the score. The right-most term of the index may be
470 ** constrained by an inequality. Add 1 if for an "x<..." constraint
471 ** and add 2 for an "x>..." constraint. Chose the index that
472 ** gives the best score.
473 **
474 ** This scoring system is designed so that the score can later be
475 ** used to determine how the index is used. If the score&3 is 0
476 ** then all constraints are equalities. If score&1 is not 0 then
477 ** there is an inequality used as a termination key. (ex: "x<...")
478 ** If score&2 is not 0 then there is an inequality used as the
479 ** start key. (ex: "x>...");
drhd99f7062002-06-08 23:25:08 +0000480 **
drhc27a1ce2002-06-14 20:58:45 +0000481 ** The IN operator (as in "<expr> IN (...)") is treated the same as
482 ** an equality comparison except that it can only be used on the
483 ** left-most column of an index and other terms of the WHERE clause
484 ** cannot be used in conjunction with the IN operator to help satisfy
485 ** other columns of the index.
drh75897232000-05-29 14:26:00 +0000486 */
487 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drhc27a1ce2002-06-14 20:58:45 +0000488 int eqMask = 0; /* Index columns covered by an x=... term */
489 int ltMask = 0; /* Index columns covered by an x<... term */
490 int gtMask = 0; /* Index columns covered by an x>... term */
491 int inMask = 0; /* Index columns covered by an x IN .. term */
drh487ab3c2001-11-08 00:45:21 +0000492 int nEq, m, score;
drh75897232000-05-29 14:26:00 +0000493
drh487ab3c2001-11-08 00:45:21 +0000494 if( pIdx->nColumn>32 ) continue; /* Ignore indices too many columns */
drh75897232000-05-29 14:26:00 +0000495 for(j=0; j<nExpr; j++){
496 if( aExpr[j].idxLeft==idx
497 && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
drh967e8b72000-06-21 13:59:10 +0000498 int iColumn = aExpr[j].p->pLeft->iColumn;
drh75897232000-05-29 14:26:00 +0000499 int k;
drh967e8b72000-06-21 13:59:10 +0000500 for(k=0; k<pIdx->nColumn; k++){
501 if( pIdx->aiColumn[k]==iColumn ){
drh487ab3c2001-11-08 00:45:21 +0000502 switch( aExpr[j].p->op ){
drh48185c12002-06-09 01:55:20 +0000503 case TK_IN: {
504 if( k==0 ) inMask |= 1;
505 break;
506 }
drh487ab3c2001-11-08 00:45:21 +0000507 case TK_EQ: {
508 eqMask |= 1<<k;
509 break;
510 }
511 case TK_LE:
512 case TK_LT: {
513 ltMask |= 1<<k;
514 break;
515 }
516 case TK_GE:
517 case TK_GT: {
518 gtMask |= 1<<k;
519 break;
520 }
521 default: {
522 /* CANT_HAPPEN */
523 assert( 0 );
524 break;
525 }
526 }
drh75897232000-05-29 14:26:00 +0000527 break;
528 }
529 }
530 }
531 if( aExpr[j].idxRight==idx
532 && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
drh967e8b72000-06-21 13:59:10 +0000533 int iColumn = aExpr[j].p->pRight->iColumn;
drh75897232000-05-29 14:26:00 +0000534 int k;
drh967e8b72000-06-21 13:59:10 +0000535 for(k=0; k<pIdx->nColumn; k++){
536 if( pIdx->aiColumn[k]==iColumn ){
drh487ab3c2001-11-08 00:45:21 +0000537 switch( aExpr[j].p->op ){
538 case TK_EQ: {
539 eqMask |= 1<<k;
540 break;
541 }
542 case TK_LE:
543 case TK_LT: {
544 gtMask |= 1<<k;
545 break;
546 }
547 case TK_GE:
548 case TK_GT: {
549 ltMask |= 1<<k;
550 break;
551 }
552 default: {
553 /* CANT_HAPPEN */
554 assert( 0 );
555 break;
556 }
557 }
drh75897232000-05-29 14:26:00 +0000558 break;
559 }
560 }
561 }
562 }
drh487ab3c2001-11-08 00:45:21 +0000563 for(nEq=0; nEq<pIdx->nColumn; nEq++){
564 m = (1<<(nEq+1))-1;
565 if( (m & eqMask)!=m ) break;
566 }
567 score = nEq*4;
568 m = 1<<nEq;
569 if( m & ltMask ) score++;
570 if( m & gtMask ) score+=2;
drh48185c12002-06-09 01:55:20 +0000571 if( score==0 && inMask ) score = 4;
drh487ab3c2001-11-08 00:45:21 +0000572 if( score>bestScore ){
573 pBestIdx = pIdx;
574 bestScore = score;
drh75897232000-05-29 14:26:00 +0000575 }
576 }
drh6b563442001-11-07 16:48:26 +0000577 pWInfo->a[i].pIdx = pBestIdx;
drh487ab3c2001-11-08 00:45:21 +0000578 pWInfo->a[i].score = bestScore;
drh7e391e12000-05-30 20:17:49 +0000579 loopMask |= 1<<idx;
drh6b563442001-11-07 16:48:26 +0000580 if( pBestIdx ){
drh832508b2002-03-02 17:04:07 +0000581 pWInfo->a[i].iCur = pParse->nTab++;
582 pWInfo->peakNTab = pParse->nTab;
drh6b563442001-11-07 16:48:26 +0000583 }
drh75897232000-05-29 14:26:00 +0000584 }
585
drhe3184742002-06-19 14:27:05 +0000586 /* Check to see if the ORDER BY clause is or can be satisfied by the
587 ** use of an index on the first table.
588 */
589 if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
590 Index *pSortIdx;
591 Index *pIdx;
592 Table *pTab;
593
594 pTab = pTabList->a[0].pTab;
595 pIdx = pWInfo->a[0].pIdx;
596 if( pIdx && pWInfo->a[0].score==4 ){
597 /* If there is already an index on the left-most column and it is
598 ** an equality index, then either sorting is not helpful, or the
599 ** index is an IN operator, in which case the index does not give
600 ** the correct sort order. Either way, pretend that no suitable
601 ** index is found.
602 */
603 pSortIdx = 0;
604 }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
605 /* If the left-most column is accessed using its ROWID, then do
606 ** not try to sort by index.
607 */
608 pSortIdx = 0;
609 }else{
610 pSortIdx = findSortingIndex(pTab, base, *ppOrderBy, pIdx);
611 }
612 if( pSortIdx && (pIdx==0 || pIdx==pSortIdx) ){
613 if( pIdx==0 ){
614 pWInfo->a[0].pIdx = pSortIdx;
615 pWInfo->a[0].iCur = pParse->nTab++;
616 pWInfo->peakNTab = pParse->nTab;
617 }
618 *ppOrderBy = 0;
619 }
620 }
621
drh6b563442001-11-07 16:48:26 +0000622 /* Open all tables in the pTabList and all indices used by those tables.
drh75897232000-05-29 14:26:00 +0000623 */
drhad3cab52002-05-24 02:04:32 +0000624 for(i=0; i<pTabList->nSrc; i++){
drhf57b3392001-10-08 13:22:32 +0000625 int openOp;
626 Table *pTab;
627
628 pTab = pTabList->a[i].pTab;
drha76b5df2002-02-23 02:32:10 +0000629 if( pTab->isTransient || pTab->pSelect ) continue;
drhf57b3392001-10-08 13:22:32 +0000630 openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
drh99fcd712001-10-13 01:06:47 +0000631 sqliteVdbeAddOp(v, openOp, base+i, pTab->tnum);
632 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drh50e5dad2001-09-15 00:57:28 +0000633 if( i==0 && !pParse->schemaVerified &&
634 (pParse->db->flags & SQLITE_InTrans)==0 ){
drh99fcd712001-10-13 01:06:47 +0000635 sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
drh50e5dad2001-09-15 00:57:28 +0000636 pParse->schemaVerified = 1;
637 }
drh6b563442001-11-07 16:48:26 +0000638 if( pWInfo->a[i].pIdx!=0 ){
639 sqliteVdbeAddOp(v, openOp, pWInfo->a[i].iCur, pWInfo->a[i].pIdx->tnum);
640 sqliteVdbeChangeP3(v, -1, pWInfo->a[i].pIdx->zName, P3_STATIC);
drh75897232000-05-29 14:26:00 +0000641 }
642 }
643
644 /* Generate the code to do the search
645 */
drh75897232000-05-29 14:26:00 +0000646 loopMask = 0;
drhad3cab52002-05-24 02:04:32 +0000647 for(i=0; i<pTabList->nSrc; i++){
drh75897232000-05-29 14:26:00 +0000648 int j, k;
649 int idx = aOrder[i];
drhc4a3c772001-04-04 11:48:57 +0000650 Index *pIdx;
drh6b563442001-11-07 16:48:26 +0000651 WhereLevel *pLevel = &pWInfo->a[i];
drh75897232000-05-29 14:26:00 +0000652
drhad2d8302002-05-24 20:31:36 +0000653 /* If this is the right table of a LEFT OUTER JOIN, allocate and
654 ** initialize a memory cell that record if this table matches any
drhc27a1ce2002-06-14 20:58:45 +0000655 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +0000656 */
657 if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
658 if( !pParse->nMem ) pParse->nMem++;
659 pLevel->iLeftJoin = pParse->nMem++;
660 sqliteVdbeAddOp(v, OP_String, 0, 0);
661 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
662 }
663
drh8aff1012001-12-22 14:49:24 +0000664 pIdx = pLevel->pIdx;
drhd99f7062002-06-08 23:25:08 +0000665 pLevel->inOp = OP_Noop;
drh8aff1012001-12-22 14:49:24 +0000666 if( i<ARRAYSIZE(iDirectEq) && iDirectEq[i]>=0 ){
667 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +0000668 ** equality comparison against the ROWID field. Or
669 ** we reference multiple rows using a "rowid IN (...)"
670 ** construct.
drhc4a3c772001-04-04 11:48:57 +0000671 */
drh8aff1012001-12-22 14:49:24 +0000672 k = iDirectEq[i];
673 assert( k<nExpr );
674 assert( aExpr[k].p!=0 );
675 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
drhd99f7062002-06-08 23:25:08 +0000676 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
drh8aff1012001-12-22 14:49:24 +0000677 if( aExpr[k].idxLeft==idx ){
drhd99f7062002-06-08 23:25:08 +0000678 Expr *pX = aExpr[k].p;
679 if( pX->op!=TK_IN ){
680 sqliteExprCode(pParse, aExpr[k].p->pRight);
681 }else if( pX->pList ){
682 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
683 pLevel->inOp = OP_SetNext;
684 pLevel->inP1 = pX->iTable;
685 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
686 }else{
687 assert( pX->pSelect );
688 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
689 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
690 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
691 pLevel->inOp = OP_Next;
692 pLevel->inP1 = pX->iTable;
693 }
drh8aff1012001-12-22 14:49:24 +0000694 }else{
695 sqliteExprCode(pParse, aExpr[k].p->pLeft);
drhc4a3c772001-04-04 11:48:57 +0000696 }
drh8aff1012001-12-22 14:49:24 +0000697 aExpr[k].p = 0;
drhd99f7062002-06-08 23:25:08 +0000698 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
drhf1351b62002-07-31 19:50:26 +0000699 sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
drhd99f7062002-06-08 23:25:08 +0000700 haveKey = 0;
drh6b125452002-01-28 15:53:03 +0000701 sqliteVdbeAddOp(v, OP_NotExists, base+idx, brk);
drh6b563442001-11-07 16:48:26 +0000702 pLevel->op = OP_Noop;
drhe3184742002-06-19 14:27:05 +0000703 }else if( pIdx!=0 && pLevel->score>0 && pLevel->score%4==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000704 /* Case 2: There is an index and all terms of the WHERE clause that
705 ** refer to the index use the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +0000706 */
drh6b563442001-11-07 16:48:26 +0000707 int start;
drh487ab3c2001-11-08 00:45:21 +0000708 int testOp;
709 int nColumn = pLevel->score/4;
drhd99f7062002-06-08 23:25:08 +0000710 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
drh487ab3c2001-11-08 00:45:21 +0000711 for(j=0; j<nColumn; j++){
drh75897232000-05-29 14:26:00 +0000712 for(k=0; k<nExpr; k++){
drhd99f7062002-06-08 23:25:08 +0000713 Expr *pX = aExpr[k].p;
714 if( pX==0 ) continue;
drh75897232000-05-29 14:26:00 +0000715 if( aExpr[k].idxLeft==idx
716 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
drhd99f7062002-06-08 23:25:08 +0000717 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +0000718 ){
drhd99f7062002-06-08 23:25:08 +0000719 if( pX->op==TK_EQ ){
720 sqliteExprCode(pParse, pX->pRight);
721 aExpr[k].p = 0;
722 break;
723 }
724 if( pX->op==TK_IN && nColumn==1 ){
725 if( pX->pList ){
726 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
727 pLevel->inOp = OP_SetNext;
728 pLevel->inP1 = pX->iTable;
729 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
730 }else{
731 assert( pX->pSelect );
732 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
733 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
734 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
735 pLevel->inOp = OP_Next;
736 pLevel->inP1 = pX->iTable;
737 }
738 aExpr[k].p = 0;
739 break;
740 }
drh75897232000-05-29 14:26:00 +0000741 }
742 if( aExpr[k].idxRight==idx
drh487ab3c2001-11-08 00:45:21 +0000743 && aExpr[k].p->op==TK_EQ
drh75897232000-05-29 14:26:00 +0000744 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
drh967e8b72000-06-21 13:59:10 +0000745 && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +0000746 ){
747 sqliteExprCode(pParse, aExpr[k].p->pLeft);
748 aExpr[k].p = 0;
749 break;
750 }
751 }
752 }
drh6b563442001-11-07 16:48:26 +0000753 pLevel->iMem = pParse->nMem++;
drh6b563442001-11-07 16:48:26 +0000754 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
drh487ab3c2001-11-08 00:45:21 +0000755 sqliteVdbeAddOp(v, OP_MakeKey, nColumn, 0);
drha9e99ae2002-08-13 23:02:57 +0000756 sqliteAddIdxKeyType(v, pIdx);
drh487ab3c2001-11-08 00:45:21 +0000757 if( nColumn==pIdx->nColumn ){
758 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
759 testOp = OP_IdxGT;
760 }else{
761 sqliteVdbeAddOp(v, OP_Dup, 0, 0);
762 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
763 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
764 testOp = OP_IdxGE;
765 }
drh6b563442001-11-07 16:48:26 +0000766 sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
767 start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh487ab3c2001-11-08 00:45:21 +0000768 sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
drh6b563442001-11-07 16:48:26 +0000769 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
drhad3cab52002-05-24 02:04:32 +0000770 if( i==pTabList->nSrc-1 && pushKey ){
drh75897232000-05-29 14:26:00 +0000771 haveKey = 1;
772 }else{
drh99fcd712001-10-13 01:06:47 +0000773 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
drh75897232000-05-29 14:26:00 +0000774 haveKey = 0;
775 }
drh6b563442001-11-07 16:48:26 +0000776 pLevel->op = OP_Next;
777 pLevel->p1 = pLevel->iCur;
778 pLevel->p2 = start;
drh8aff1012001-12-22 14:49:24 +0000779 }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
780 /* Case 3: We have an inequality comparison against the ROWID field.
781 */
782 int testOp = OP_Noop;
783 int start;
784
785 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
786 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
787 if( iDirectGt[i]>=0 ){
788 k = iDirectGt[i];
789 assert( k<nExpr );
790 assert( aExpr[k].p!=0 );
791 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
792 if( aExpr[k].idxLeft==idx ){
793 sqliteExprCode(pParse, aExpr[k].p->pRight);
794 }else{
795 sqliteExprCode(pParse, aExpr[k].p->pLeft);
796 }
drhf1351b62002-07-31 19:50:26 +0000797 sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
drh8aff1012001-12-22 14:49:24 +0000798 if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
799 sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
800 }
801 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, brk);
802 aExpr[k].p = 0;
803 }else{
804 sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
805 }
806 if( iDirectLt[i]>=0 ){
807 k = iDirectLt[i];
808 assert( k<nExpr );
809 assert( aExpr[k].p!=0 );
810 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
811 if( aExpr[k].idxLeft==idx ){
812 sqliteExprCode(pParse, aExpr[k].p->pRight);
813 }else{
814 sqliteExprCode(pParse, aExpr[k].p->pLeft);
815 }
drhf1351b62002-07-31 19:50:26 +0000816 sqliteVdbeAddOp(v, OP_MustBeInt, 1, sqliteVdbeCurrentAddr(v)+1);
drh8aff1012001-12-22 14:49:24 +0000817 pLevel->iMem = pParse->nMem++;
818 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
819 if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
820 testOp = OP_Ge;
821 }else{
822 testOp = OP_Gt;
823 }
824 aExpr[k].p = 0;
825 }
826 start = sqliteVdbeCurrentAddr(v);
827 pLevel->op = OP_Next;
828 pLevel->p1 = base+idx;
829 pLevel->p2 = start;
830 if( testOp!=OP_Noop ){
831 sqliteVdbeAddOp(v, OP_Recno, base+idx, 0);
832 sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
833 sqliteVdbeAddOp(v, testOp, 0, brk);
834 }
835 haveKey = 0;
836 }else if( pIdx==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000837 /* Case 4: There is no usable index. We must do a complete
drh8aff1012001-12-22 14:49:24 +0000838 ** scan of the entire database table.
839 */
840 int start;
841
842 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
843 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
844 sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
845 start = sqliteVdbeCurrentAddr(v);
846 pLevel->op = OP_Next;
847 pLevel->p1 = base+idx;
848 pLevel->p2 = start;
849 haveKey = 0;
drh487ab3c2001-11-08 00:45:21 +0000850 }else{
drhc27a1ce2002-06-14 20:58:45 +0000851 /* Case 5: The WHERE clause term that refers to the right-most
852 ** column of the index is an inequality. For example, if
853 ** the index is on (x,y,z) and the WHERE clause is of the
854 ** form "x=5 AND y<10" then this case is used. Only the
855 ** right-most column can be an inequality - the rest must
856 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +0000857 **
858 ** This case is also used when there are no WHERE clause
859 ** constraints but an index is selected anyway, in order
860 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +0000861 */
862 int score = pLevel->score;
863 int nEqColumn = score/4;
864 int start;
865 int leFlag, geFlag;
866 int testOp;
867
868 /* Evaluate the equality constraints
869 */
870 for(j=0; j<nEqColumn; j++){
871 for(k=0; k<nExpr; k++){
872 if( aExpr[k].p==0 ) continue;
873 if( aExpr[k].idxLeft==idx
874 && aExpr[k].p->op==TK_EQ
875 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
876 && aExpr[k].p->pLeft->iColumn==pIdx->aiColumn[j]
877 ){
878 sqliteExprCode(pParse, aExpr[k].p->pRight);
879 aExpr[k].p = 0;
880 break;
881 }
882 if( aExpr[k].idxRight==idx
883 && aExpr[k].p->op==TK_EQ
884 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
885 && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
886 ){
887 sqliteExprCode(pParse, aExpr[k].p->pLeft);
888 aExpr[k].p = 0;
889 break;
890 }
891 }
892 }
893
drhc27a1ce2002-06-14 20:58:45 +0000894 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +0000895 ** used twice: once to make the termination key and once to make the
896 ** start key.
897 */
898 for(j=0; j<nEqColumn; j++){
899 sqliteVdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
900 }
901
902 /* Generate the termination key. This is the key value that
903 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +0000904 ** are no equality terms and no "X<..." term.
drh487ab3c2001-11-08 00:45:21 +0000905 */
906 if( (score & 1)!=0 ){
907 for(k=0; k<nExpr; k++){
908 Expr *pExpr = aExpr[k].p;
909 if( pExpr==0 ) continue;
910 if( aExpr[k].idxLeft==idx
911 && (pExpr->op==TK_LT || pExpr->op==TK_LE)
912 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
913 && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
914 ){
915 sqliteExprCode(pParse, pExpr->pRight);
916 leFlag = pExpr->op==TK_LE;
917 aExpr[k].p = 0;
918 break;
919 }
920 if( aExpr[k].idxRight==idx
921 && (pExpr->op==TK_GT || pExpr->op==TK_GE)
922 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
923 && pExpr->pRight->iColumn==pIdx->aiColumn[j]
924 ){
925 sqliteExprCode(pParse, pExpr->pLeft);
926 leFlag = pExpr->op==TK_GE;
927 aExpr[k].p = 0;
928 break;
929 }
930 }
931 testOp = OP_IdxGE;
932 }else{
933 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
934 leFlag = 1;
935 }
936 if( testOp!=OP_Noop ){
937 pLevel->iMem = pParse->nMem++;
938 sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + (score & 1), 0);
drha9e99ae2002-08-13 23:02:57 +0000939 sqliteAddIdxKeyType(v, pIdx);
drh487ab3c2001-11-08 00:45:21 +0000940 if( leFlag ){
941 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
942 }
943 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
944 }
945
946 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +0000947 ** bound on the search. There is no start key if there are no
948 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +0000949 ** that case, generate a "Rewind" instruction in place of the
950 ** start key search.
951 */
952 if( (score & 2)!=0 ){
953 for(k=0; k<nExpr; k++){
954 Expr *pExpr = aExpr[k].p;
955 if( pExpr==0 ) continue;
956 if( aExpr[k].idxLeft==idx
957 && (pExpr->op==TK_GT || pExpr->op==TK_GE)
958 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
959 && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
960 ){
961 sqliteExprCode(pParse, pExpr->pRight);
962 geFlag = pExpr->op==TK_GE;
963 aExpr[k].p = 0;
964 break;
965 }
966 if( aExpr[k].idxRight==idx
967 && (pExpr->op==TK_LT || pExpr->op==TK_LE)
968 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
969 && pExpr->pRight->iColumn==pIdx->aiColumn[j]
970 ){
971 sqliteExprCode(pParse, pExpr->pLeft);
972 geFlag = pExpr->op==TK_LE;
973 aExpr[k].p = 0;
974 break;
975 }
976 }
drh7900ead2001-11-12 13:51:43 +0000977 }else{
978 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +0000979 }
980 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
981 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
982 if( nEqColumn>0 || (score&2)!=0 ){
983 sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + ((score&2)!=0), 0);
drha9e99ae2002-08-13 23:02:57 +0000984 sqliteAddIdxKeyType(v, pIdx);
drh487ab3c2001-11-08 00:45:21 +0000985 if( !geFlag ){
986 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
987 }
988 sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
989 }else{
990 sqliteVdbeAddOp(v, OP_Rewind, pLevel->iCur, brk);
991 }
992
993 /* Generate the the top of the loop. If there is a termination
994 ** key we have to test for that key and abort at the top of the
995 ** loop.
996 */
997 start = sqliteVdbeCurrentAddr(v);
998 if( testOp!=OP_Noop ){
999 sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1000 sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
1001 }
1002 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
drhad3cab52002-05-24 02:04:32 +00001003 if( i==pTabList->nSrc-1 && pushKey ){
drh487ab3c2001-11-08 00:45:21 +00001004 haveKey = 1;
1005 }else{
1006 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
1007 haveKey = 0;
1008 }
1009
1010 /* Record the instruction used to terminate the loop.
1011 */
1012 pLevel->op = OP_Next;
1013 pLevel->p1 = pLevel->iCur;
1014 pLevel->p2 = start;
drh75897232000-05-29 14:26:00 +00001015 }
1016 loopMask |= 1<<idx;
1017
1018 /* Insert code to test every subexpression that can be completely
1019 ** computed using the current set of tables.
1020 */
1021 for(j=0; j<nExpr; j++){
1022 if( aExpr[j].p==0 ) continue;
drh3f6b5482002-04-02 13:26:10 +00001023 if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
drh1f162302002-10-27 19:35:33 +00001024 if( pLevel->iLeftJoin && !ExprHasProperty(aExpr[j].p,EP_FromJoin) ){
1025 continue;
1026 }
drh75897232000-05-29 14:26:00 +00001027 if( haveKey ){
drh573bd272001-02-19 23:23:38 +00001028 haveKey = 0;
drh99fcd712001-10-13 01:06:47 +00001029 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
drh75897232000-05-29 14:26:00 +00001030 }
drhf5905aa2002-05-26 20:54:33 +00001031 sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
drh75897232000-05-29 14:26:00 +00001032 aExpr[j].p = 0;
1033 }
1034 brk = cont;
drhad2d8302002-05-24 20:31:36 +00001035
1036 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1037 ** at least one row of the right table has matched the left table.
1038 */
1039 if( pLevel->iLeftJoin ){
1040 pLevel->top = sqliteVdbeCurrentAddr(v);
1041 sqliteVdbeAddOp(v, OP_Integer, 1, 0);
1042 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drh1cc093c2002-06-24 22:01:57 +00001043 for(j=0; j<nExpr; j++){
1044 if( aExpr[j].p==0 ) continue;
1045 if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
1046 if( haveKey ){
drh3b167c72002-06-28 12:18:47 +00001047 /* Cannot happen. "haveKey" can only be true if pushKey is true
1048 ** an pushKey can only be true for DELETE and UPDATE and there are
1049 ** no outer joins with DELETE and UPDATE.
1050 */
drh1cc093c2002-06-24 22:01:57 +00001051 haveKey = 0;
1052 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
1053 }
1054 sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
1055 aExpr[j].p = 0;
1056 }
drhad2d8302002-05-24 20:31:36 +00001057 }
drh75897232000-05-29 14:26:00 +00001058 }
1059 pWInfo->iContinue = cont;
1060 if( pushKey && !haveKey ){
drh99fcd712001-10-13 01:06:47 +00001061 sqliteVdbeAddOp(v, OP_Recno, base, 0);
drh75897232000-05-29 14:26:00 +00001062 }
1063 sqliteFree(aOrder);
1064 return pWInfo;
1065}
1066
1067/*
drhc27a1ce2002-06-14 20:58:45 +00001068** Generate the end of the WHERE loop. See comments on
1069** sqliteWhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001070*/
1071void sqliteWhereEnd(WhereInfo *pWInfo){
1072 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001073 int i;
drh19a775c2000-06-05 18:54:46 +00001074 int base = pWInfo->base;
drh6b563442001-11-07 16:48:26 +00001075 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001076 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001077
drhad3cab52002-05-24 02:04:32 +00001078 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001079 pLevel = &pWInfo->a[i];
1080 sqliteVdbeResolveLabel(v, pLevel->cont);
1081 if( pLevel->op!=OP_Noop ){
1082 sqliteVdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001083 }
drh6b563442001-11-07 16:48:26 +00001084 sqliteVdbeResolveLabel(v, pLevel->brk);
drhd99f7062002-06-08 23:25:08 +00001085 if( pLevel->inOp!=OP_Noop ){
1086 sqliteVdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
1087 }
drhad2d8302002-05-24 20:31:36 +00001088 if( pLevel->iLeftJoin ){
1089 int addr;
1090 addr = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh7f09b3e2002-08-13 13:15:49 +00001091 sqliteVdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iCur>=0));
drhad2d8302002-05-24 20:31:36 +00001092 sqliteVdbeAddOp(v, OP_NullRow, base+i, 0);
drh7f09b3e2002-08-13 13:15:49 +00001093 if( pLevel->iCur>=0 ){
1094 sqliteVdbeAddOp(v, OP_NullRow, pLevel->iCur, 0);
1095 }
drhad2d8302002-05-24 20:31:36 +00001096 sqliteVdbeAddOp(v, OP_Goto, 0, pLevel->top);
1097 }
drh19a775c2000-06-05 18:54:46 +00001098 }
drh6b563442001-11-07 16:48:26 +00001099 sqliteVdbeResolveLabel(v, pWInfo->iBreak);
drhad3cab52002-05-24 02:04:32 +00001100 for(i=0; i<pTabList->nSrc; i++){
drh22f70c32002-02-18 01:17:00 +00001101 if( pTabList->a[i].pTab->isTransient ) continue;
drh6b563442001-11-07 16:48:26 +00001102 pLevel = &pWInfo->a[i];
1103 sqliteVdbeAddOp(v, OP_Close, base+i, 0);
1104 if( pLevel->pIdx!=0 ){
1105 sqliteVdbeAddOp(v, OP_Close, pLevel->iCur, 0);
1106 }
drh19a775c2000-06-05 18:54:46 +00001107 }
drh142e30d2002-08-28 03:00:58 +00001108#if 0 /* Never reuse a cursor */
drh832508b2002-03-02 17:04:07 +00001109 if( pWInfo->pParse->nTab==pWInfo->peakNTab ){
1110 pWInfo->pParse->nTab = pWInfo->savedNTab;
1111 }
drh142e30d2002-08-28 03:00:58 +00001112#endif
drh75897232000-05-29 14:26:00 +00001113 sqliteFree(pWInfo);
1114 return;
1115}