blob: fe4758de25c9765c22523980f78e244fc9286278 [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**
drhc045ec52002-12-04 20:01:06 +000016** $Id: where.c,v 1.68 2002/12/04 20:01:06 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 */
drhc045ec52002-12-04 20:01:06 +0000172 Index *pPreferredIdx, /* Use this index, if possible and not NULL */
173 int *pbRev /* Set to 1 if ORDER BY is DESC */
drhe3184742002-06-19 14:27:05 +0000174){
175 int i;
176 Index *pMatch;
177 Index *pIdx;
drhc045ec52002-12-04 20:01:06 +0000178 int sortOrder;
drhe3184742002-06-19 14:27:05 +0000179
180 assert( pOrderBy!=0 );
181 assert( pOrderBy->nExpr>0 );
drhc045ec52002-12-04 20:01:06 +0000182 sortOrder = pOrderBy->a[0].sortOrder & SQLITE_SO_DIRMASK;
drhe3184742002-06-19 14:27:05 +0000183 for(i=0; i<pOrderBy->nExpr; i++){
184 Expr *p;
drhc045ec52002-12-04 20:01:06 +0000185 if( (pOrderBy->a[i].sortOrder & SQLITE_SO_DIRMASK)!=sortOrder ){
186 /* Indices can only be used if all ORDER BY terms are either
187 ** DESC or ASC. Indices cannot be used on a mixture. */
drhe3184742002-06-19 14:27:05 +0000188 return 0;
189 }
drhc330af12002-08-14 03:03:57 +0000190 if( (pOrderBy->a[i].sortOrder & SQLITE_SO_TYPEMASK)!=SQLITE_SO_UNK ){
191 /* Do not sort by index if there is a COLLATE clause */
192 return 0;
193 }
drhe3184742002-06-19 14:27:05 +0000194 p = pOrderBy->a[i].pExpr;
195 if( p->op!=TK_COLUMN || p->iTable!=base ){
196 /* Can not use an index sort on anything that is not a column in the
197 ** left-most table of the FROM clause */
198 return 0;
199 }
200 }
drhc045ec52002-12-04 20:01:06 +0000201
drhe3184742002-06-19 14:27:05 +0000202 /* If we get this far, it means the ORDER BY clause consists only of
203 ** ascending columns in the left-most table of the FROM clause. Now
204 ** check for a matching index.
205 */
206 pMatch = 0;
207 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
208 if( pIdx->nColumn<pOrderBy->nExpr ) continue;
209 for(i=0; i<pOrderBy->nExpr; i++){
210 if( pOrderBy->a[i].pExpr->iColumn!=pIdx->aiColumn[i] ) break;
211 }
212 if( i>=pOrderBy->nExpr ){
213 pMatch = pIdx;
214 if( pIdx==pPreferredIdx ) break;
215 }
216 }
drhc045ec52002-12-04 20:01:06 +0000217 if( pMatch && pbRev ){
218 *pbRev = sortOrder==SQLITE_SO_DESC;
219 }
drhe3184742002-06-19 14:27:05 +0000220 return pMatch;
221}
222
223/*
224** Generate the beginning of the loop used for WHERE clause processing.
drh75897232000-05-29 14:26:00 +0000225** The return value is a pointer to an (opaque) structure that contains
226** information needed to terminate the loop. Later, the calling routine
227** should invoke sqliteWhereEnd() with the return value of this function
228** in order to complete the WHERE clause processing.
229**
230** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +0000231**
232** The basic idea is to do a nested loop, one loop for each table in
233** the FROM clause of a select. (INSERT and UPDATE statements are the
234** same as a SELECT with only a single table in the FROM clause.) For
235** example, if the SQL is this:
236**
237** SELECT * FROM t1, t2, t3 WHERE ...;
238**
239** Then the code generated is conceptually like the following:
240**
241** foreach row1 in t1 do \ Code generated
242** foreach row2 in t2 do |-- by sqliteWhereBegin()
243** foreach row3 in t3 do /
244** ...
245** end \ Code generated
246** end |-- by sqliteWhereEnd()
247** end /
248**
249** There are Btree cursors associated with each table. t1 uses cursor
250** "base". t2 uses cursor "base+1". And so forth. This routine generates
251** the code to open those cursors. sqliteWhereEnd() generates the code
252** to close them.
253**
254** If the WHERE clause is empty, the foreach loops must each scan their
255** entire tables. Thus a three-way join is an O(N^3) operation. But if
256** the tables have indices and there are terms in the WHERE clause that
257** refer to those indices, a complete table scan can be avoided and the
258** code will run much faster. Most of the work of this routine is checking
259** to see if there are indices that can be used to speed up the loop.
260**
261** Terms of the WHERE clause are also used to limit which rows actually
262** make it to the "..." in the middle of the loop. After each "foreach",
263** terms of the WHERE clause that use only terms in that loop and outer
264** loops are evaluated and if false a jump is made around all subsequent
265** inner loops (or around the "..." if the test occurs within the inner-
266** most loop)
267**
268** OUTER JOINS
269**
270** An outer join of tables t1 and t2 is conceptally coded as follows:
271**
272** foreach row1 in t1 do
273** flag = 0
274** foreach row2 in t2 do
275** start:
276** ...
277** flag = 1
278** end
drhe3184742002-06-19 14:27:05 +0000279** if flag==0 then
280** move the row2 cursor to a null row
281** goto start
282** fi
drhc27a1ce2002-06-14 20:58:45 +0000283** end
284**
drhe3184742002-06-19 14:27:05 +0000285** ORDER BY CLAUSE PROCESSING
286**
287** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
288** if there is one. If there is no ORDER BY clause or if this routine
289** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
290**
291** If an index can be used so that the natural output order of the table
292** scan is correct for the ORDER BY clause, then that index is used and
293** *ppOrderBy is set to NULL. This is an optimization that prevents an
294** unnecessary sort of the result set if an index appropriate for the
295** ORDER BY clause already exists.
296**
297** If the where clause loops cannot be arranged to provide the correct
298** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +0000299*/
300WhereInfo *sqliteWhereBegin(
301 Parse *pParse, /* The parser context */
drh832508b2002-03-02 17:04:07 +0000302 int base, /* VDBE cursor index for left-most table in pTabList */
drhad3cab52002-05-24 02:04:32 +0000303 SrcList *pTabList, /* A list of all tables to be scanned */
drh75897232000-05-29 14:26:00 +0000304 Expr *pWhere, /* The WHERE clause */
drhe3184742002-06-19 14:27:05 +0000305 int pushKey, /* If TRUE, leave the table key on the stack */
306 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +0000307){
308 int i; /* Loop counter */
309 WhereInfo *pWInfo; /* Will become the return value of this function */
310 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
311 int brk, cont; /* Addresses used during code generation */
312 int *aOrder; /* Order in which pTabList entries are searched */
313 int nExpr; /* Number of subexpressions in the WHERE clause */
314 int loopMask; /* One bit set for each outer loop */
315 int haveKey; /* True if KEY is on the stack */
drh8aff1012001-12-22 14:49:24 +0000316 int iDirectEq[32]; /* Term of the form ROWID==X for the N-th table */
317 int iDirectLt[32]; /* Term of the form ROWID<X or ROWID<=X */
318 int iDirectGt[32]; /* Term of the form ROWID>X or ROWID>=X */
drh83dcb1a2002-06-28 01:02:38 +0000319 ExprInfo aExpr[101]; /* The WHERE clause is divided into these expressions */
drh75897232000-05-29 14:26:00 +0000320
drhc27a1ce2002-06-14 20:58:45 +0000321 /* pushKey is only allowed if there is a single table (as in an INSERT or
322 ** UPDATE statement)
323 */
324 assert( pushKey==0 || pTabList->nSrc==1 );
drh83dcb1a2002-06-28 01:02:38 +0000325
326 /* Split the WHERE clause into separate subexpressions where each
327 ** subexpression is separated by an AND operator. If the aExpr[]
328 ** array fills up, the last entry might point to an expression which
329 ** contains additional unfactored AND operators.
330 */
331 memset(aExpr, 0, sizeof(aExpr));
332 nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
333 if( nExpr==ARRAYSIZE(aExpr) ){
334 char zBuf[50];
335 sprintf(zBuf, "%d", ARRAYSIZE(aExpr)-1);
336 sqliteSetString(&pParse->zErrMsg, "WHERE clause too complex - no more "
337 "than ", zBuf, " terms allowed", 0);
338 pParse->nErr++;
339 return 0;
340 }
drhc27a1ce2002-06-14 20:58:45 +0000341
drhe3184742002-06-19 14:27:05 +0000342 /* Allocate space for aOrder[] */
drhad3cab52002-05-24 02:04:32 +0000343 aOrder = sqliteMalloc( sizeof(int) * pTabList->nSrc );
drh75897232000-05-29 14:26:00 +0000344
345 /* Allocate and initialize the WhereInfo structure that will become the
346 ** return value.
347 */
drhad3cab52002-05-24 02:04:32 +0000348 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
drhdaffd0e2001-04-11 14:28:42 +0000349 if( sqlite_malloc_failed ){
drh75897232000-05-29 14:26:00 +0000350 sqliteFree(aOrder);
drhdaffd0e2001-04-11 14:28:42 +0000351 sqliteFree(pWInfo);
drh75897232000-05-29 14:26:00 +0000352 return 0;
353 }
354 pWInfo->pParse = pParse;
355 pWInfo->pTabList = pTabList;
drh832508b2002-03-02 17:04:07 +0000356 pWInfo->base = base;
357 pWInfo->peakNTab = pWInfo->savedNTab = pParse->nTab;
drh08192d52002-04-30 19:20:28 +0000358 pWInfo->iBreak = sqliteVdbeMakeLabel(v);
359
360 /* Special case: a WHERE clause that is constant. Evaluate the
361 ** expression and either jump over all of the code or fall thru.
362 */
363 if( pWhere && sqliteExprIsConstant(pWhere) ){
drhf5905aa2002-05-26 20:54:33 +0000364 sqliteExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +0000365 pWhere = 0;
drh08192d52002-04-30 19:20:28 +0000366 }
drh75897232000-05-29 14:26:00 +0000367
drh75897232000-05-29 14:26:00 +0000368 /* Analyze all of the subexpressions.
369 */
370 for(i=0; i<nExpr; i++){
drh22f70c32002-02-18 01:17:00 +0000371 exprAnalyze(base, &aExpr[i]);
drh1d1f3052002-05-21 13:18:25 +0000372
373 /* If we are executing a trigger body, remove all references to
374 ** new.* and old.* tables from the prerequisite masks.
375 */
376 if( pParse->trigStack ){
377 int x;
378 if( (x = pParse->trigStack->newIdx) >= 0 ){
379 int mask = ~(1 << (x - base));
380 aExpr[i].prereqRight &= mask;
381 aExpr[i].prereqLeft &= mask;
382 aExpr[i].prereqAll &= mask;
383 }
384 if( (x = pParse->trigStack->oldIdx) >= 0 ){
385 int mask = ~(1 << (x - base));
386 aExpr[i].prereqRight &= mask;
387 aExpr[i].prereqLeft &= mask;
388 aExpr[i].prereqAll &= mask;
389 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000390 }
drh75897232000-05-29 14:26:00 +0000391 }
392
393 /* Figure out a good nesting order for the tables. aOrder[0] will
394 ** be the index in pTabList of the outermost table. aOrder[1] will
drhad3cab52002-05-24 02:04:32 +0000395 ** be the first nested loop and so on. aOrder[pTabList->nSrc-1] will
drh75897232000-05-29 14:26:00 +0000396 ** be the innermost loop.
397 **
drh1d1f3052002-05-21 13:18:25 +0000398 ** Someday we will put in a good algorithm here to reorder the loops
drh75897232000-05-29 14:26:00 +0000399 ** for an effiecient query. But for now, just use whatever order the
400 ** tables appear in in the pTabList.
401 */
drhad3cab52002-05-24 02:04:32 +0000402 for(i=0; i<pTabList->nSrc; i++){
drh75897232000-05-29 14:26:00 +0000403 aOrder[i] = i;
404 }
405
406 /* Figure out what index to use (if any) for each nested loop.
drh6b563442001-11-07 16:48:26 +0000407 ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
drhad3cab52002-05-24 02:04:32 +0000408 ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
drh8aff1012001-12-22 14:49:24 +0000409 ** loop.
410 **
411 ** If terms exist that use the ROWID of any table, then set the
412 ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
413 ** to the index of the term containing the ROWID. We always prefer
414 ** to use a ROWID which can directly access a table rather than an
drh0a36c572002-02-18 22:49:59 +0000415 ** index which requires reading an index first to get the rowid then
416 ** doing a second read of the actual database table.
drh75897232000-05-29 14:26:00 +0000417 **
418 ** Actually, if there are more than 32 tables in the join, only the
drh0a36c572002-02-18 22:49:59 +0000419 ** first 32 tables are candidates for indices. This is (again) due
420 ** to the limit of 32 bits in an integer bitmask.
drh75897232000-05-29 14:26:00 +0000421 */
422 loopMask = 0;
drhcb485882002-08-15 13:50:48 +0000423 for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++){
drhc4a3c772001-04-04 11:48:57 +0000424 int j;
drh75897232000-05-29 14:26:00 +0000425 int idx = aOrder[i];
426 Table *pTab = pTabList->a[idx].pTab;
427 Index *pIdx;
428 Index *pBestIdx = 0;
drh487ab3c2001-11-08 00:45:21 +0000429 int bestScore = 0;
drh75897232000-05-29 14:26:00 +0000430
drhc4a3c772001-04-04 11:48:57 +0000431 /* Check to see if there is an expression that uses only the
drh8aff1012001-12-22 14:49:24 +0000432 ** ROWID field of this table. For terms of the form ROWID==expr
433 ** set iDirectEq[i] to the index of the term. For terms of the
434 ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
435 ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
drh174b6192002-12-03 02:22:52 +0000436 **
437 ** (Added:) Treat ROWID IN expr like ROWID=expr.
drhc4a3c772001-04-04 11:48:57 +0000438 */
drhc8f8b632002-09-30 12:36:26 +0000439 pWInfo->a[i].iCur = -1;
drh8aff1012001-12-22 14:49:24 +0000440 iDirectEq[i] = -1;
441 iDirectLt[i] = -1;
442 iDirectGt[i] = -1;
drhc4a3c772001-04-04 11:48:57 +0000443 for(j=0; j<nExpr; j++){
444 if( aExpr[j].idxLeft==idx && aExpr[j].p->pLeft->iColumn<0
445 && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
drh8aff1012001-12-22 14:49:24 +0000446 switch( aExpr[j].p->op ){
drhd99f7062002-06-08 23:25:08 +0000447 case TK_IN:
drh8aff1012001-12-22 14:49:24 +0000448 case TK_EQ: iDirectEq[i] = j; break;
449 case TK_LE:
450 case TK_LT: iDirectLt[i] = j; break;
451 case TK_GE:
452 case TK_GT: iDirectGt[i] = j; break;
453 }
drhc4a3c772001-04-04 11:48:57 +0000454 }
455 if( aExpr[j].idxRight==idx && aExpr[j].p->pRight->iColumn<0
456 && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
drh8aff1012001-12-22 14:49:24 +0000457 switch( aExpr[j].p->op ){
458 case TK_EQ: iDirectEq[i] = j; break;
459 case TK_LE:
460 case TK_LT: iDirectGt[i] = j; break;
461 case TK_GE:
462 case TK_GT: iDirectLt[i] = j; break;
463 }
drhc4a3c772001-04-04 11:48:57 +0000464 }
465 }
drh8aff1012001-12-22 14:49:24 +0000466 if( iDirectEq[i]>=0 ){
drhc4a3c772001-04-04 11:48:57 +0000467 loopMask |= 1<<idx;
drh6b563442001-11-07 16:48:26 +0000468 pWInfo->a[i].pIdx = 0;
drhc4a3c772001-04-04 11:48:57 +0000469 continue;
470 }
471
drh75897232000-05-29 14:26:00 +0000472 /* Do a search for usable indices. Leave pBestIdx pointing to
drh487ab3c2001-11-08 00:45:21 +0000473 ** the "best" index. pBestIdx is left set to NULL if no indices
474 ** are usable.
drh75897232000-05-29 14:26:00 +0000475 **
drh487ab3c2001-11-08 00:45:21 +0000476 ** The best index is determined as follows. For each of the
477 ** left-most terms that is fixed by an equality operator, add
drhc045ec52002-12-04 20:01:06 +0000478 ** 8 to the score. The right-most term of the index may be
drh487ab3c2001-11-08 00:45:21 +0000479 ** constrained by an inequality. Add 1 if for an "x<..." constraint
480 ** and add 2 for an "x>..." constraint. Chose the index that
481 ** gives the best score.
482 **
483 ** This scoring system is designed so that the score can later be
drhc045ec52002-12-04 20:01:06 +0000484 ** used to determine how the index is used. If the score&7 is 0
drh487ab3c2001-11-08 00:45:21 +0000485 ** then all constraints are equalities. If score&1 is not 0 then
486 ** there is an inequality used as a termination key. (ex: "x<...")
487 ** If score&2 is not 0 then there is an inequality used as the
drhc045ec52002-12-04 20:01:06 +0000488 ** start key. (ex: "x>..."). A score or 4 is the special case
489 ** of an IN operator constraint. (ex: "x IN ...").
drhd99f7062002-06-08 23:25:08 +0000490 **
drhc27a1ce2002-06-14 20:58:45 +0000491 ** The IN operator (as in "<expr> IN (...)") is treated the same as
492 ** an equality comparison except that it can only be used on the
493 ** left-most column of an index and other terms of the WHERE clause
494 ** cannot be used in conjunction with the IN operator to help satisfy
495 ** other columns of the index.
drh75897232000-05-29 14:26:00 +0000496 */
497 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drhc27a1ce2002-06-14 20:58:45 +0000498 int eqMask = 0; /* Index columns covered by an x=... term */
499 int ltMask = 0; /* Index columns covered by an x<... term */
500 int gtMask = 0; /* Index columns covered by an x>... term */
501 int inMask = 0; /* Index columns covered by an x IN .. term */
drh487ab3c2001-11-08 00:45:21 +0000502 int nEq, m, score;
drh75897232000-05-29 14:26:00 +0000503
drh487ab3c2001-11-08 00:45:21 +0000504 if( pIdx->nColumn>32 ) continue; /* Ignore indices too many columns */
drh75897232000-05-29 14:26:00 +0000505 for(j=0; j<nExpr; j++){
506 if( aExpr[j].idxLeft==idx
507 && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
drh967e8b72000-06-21 13:59:10 +0000508 int iColumn = aExpr[j].p->pLeft->iColumn;
drh75897232000-05-29 14:26:00 +0000509 int k;
drh967e8b72000-06-21 13:59:10 +0000510 for(k=0; k<pIdx->nColumn; k++){
511 if( pIdx->aiColumn[k]==iColumn ){
drh487ab3c2001-11-08 00:45:21 +0000512 switch( aExpr[j].p->op ){
drh48185c12002-06-09 01:55:20 +0000513 case TK_IN: {
514 if( k==0 ) inMask |= 1;
515 break;
516 }
drh487ab3c2001-11-08 00:45:21 +0000517 case TK_EQ: {
518 eqMask |= 1<<k;
519 break;
520 }
521 case TK_LE:
522 case TK_LT: {
523 ltMask |= 1<<k;
524 break;
525 }
526 case TK_GE:
527 case TK_GT: {
528 gtMask |= 1<<k;
529 break;
530 }
531 default: {
532 /* CANT_HAPPEN */
533 assert( 0 );
534 break;
535 }
536 }
drh75897232000-05-29 14:26:00 +0000537 break;
538 }
539 }
540 }
541 if( aExpr[j].idxRight==idx
542 && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
drh967e8b72000-06-21 13:59:10 +0000543 int iColumn = aExpr[j].p->pRight->iColumn;
drh75897232000-05-29 14:26:00 +0000544 int k;
drh967e8b72000-06-21 13:59:10 +0000545 for(k=0; k<pIdx->nColumn; k++){
546 if( pIdx->aiColumn[k]==iColumn ){
drh487ab3c2001-11-08 00:45:21 +0000547 switch( aExpr[j].p->op ){
548 case TK_EQ: {
549 eqMask |= 1<<k;
550 break;
551 }
552 case TK_LE:
553 case TK_LT: {
554 gtMask |= 1<<k;
555 break;
556 }
557 case TK_GE:
558 case TK_GT: {
559 ltMask |= 1<<k;
560 break;
561 }
562 default: {
563 /* CANT_HAPPEN */
564 assert( 0 );
565 break;
566 }
567 }
drh75897232000-05-29 14:26:00 +0000568 break;
569 }
570 }
571 }
572 }
drhc045ec52002-12-04 20:01:06 +0000573
574 /* The following loop ends with nEq set to the number of columns
575 ** on the left of the index with == constraints.
576 */
drh487ab3c2001-11-08 00:45:21 +0000577 for(nEq=0; nEq<pIdx->nColumn; nEq++){
578 m = (1<<(nEq+1))-1;
579 if( (m & eqMask)!=m ) break;
580 }
drhc045ec52002-12-04 20:01:06 +0000581 score = nEq*8; /* Base score is 8 times number of == constraints */
drh487ab3c2001-11-08 00:45:21 +0000582 m = 1<<nEq;
drhc045ec52002-12-04 20:01:06 +0000583 if( m & ltMask ) score++; /* Increase score for a < constraint */
584 if( m & gtMask ) score+=2; /* Increase score for a > constraint */
585 if( score==0 && inMask ) score = 4; /* Default score for IN constraint */
drh487ab3c2001-11-08 00:45:21 +0000586 if( score>bestScore ){
587 pBestIdx = pIdx;
588 bestScore = score;
drh75897232000-05-29 14:26:00 +0000589 }
590 }
drh6b563442001-11-07 16:48:26 +0000591 pWInfo->a[i].pIdx = pBestIdx;
drh487ab3c2001-11-08 00:45:21 +0000592 pWInfo->a[i].score = bestScore;
drhc045ec52002-12-04 20:01:06 +0000593 pWInfo->a[i].bRev = 0;
drh7e391e12000-05-30 20:17:49 +0000594 loopMask |= 1<<idx;
drh6b563442001-11-07 16:48:26 +0000595 if( pBestIdx ){
drh832508b2002-03-02 17:04:07 +0000596 pWInfo->a[i].iCur = pParse->nTab++;
597 pWInfo->peakNTab = pParse->nTab;
drh6b563442001-11-07 16:48:26 +0000598 }
drh75897232000-05-29 14:26:00 +0000599 }
600
drhe3184742002-06-19 14:27:05 +0000601 /* Check to see if the ORDER BY clause is or can be satisfied by the
602 ** use of an index on the first table.
603 */
604 if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
605 Index *pSortIdx;
606 Index *pIdx;
607 Table *pTab;
drhc045ec52002-12-04 20:01:06 +0000608 int bRev = 0;
drhe3184742002-06-19 14:27:05 +0000609
610 pTab = pTabList->a[0].pTab;
611 pIdx = pWInfo->a[0].pIdx;
612 if( pIdx && pWInfo->a[0].score==4 ){
drhc045ec52002-12-04 20:01:06 +0000613 /* If there is already an IN index on the left-most table,
614 ** it will not give the correct sort order.
615 ** So, pretend that no suitable index is found.
drhe3184742002-06-19 14:27:05 +0000616 */
617 pSortIdx = 0;
618 }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
619 /* If the left-most column is accessed using its ROWID, then do
620 ** not try to sort by index.
621 */
622 pSortIdx = 0;
623 }else{
drhc045ec52002-12-04 20:01:06 +0000624 pSortIdx = findSortingIndex(pTab, base, *ppOrderBy, pIdx, &bRev);
drhe3184742002-06-19 14:27:05 +0000625 }
626 if( pSortIdx && (pIdx==0 || pIdx==pSortIdx) ){
627 if( pIdx==0 ){
628 pWInfo->a[0].pIdx = pSortIdx;
629 pWInfo->a[0].iCur = pParse->nTab++;
630 pWInfo->peakNTab = pParse->nTab;
631 }
drhc045ec52002-12-04 20:01:06 +0000632 pWInfo->a[0].bRev = bRev;
drhe3184742002-06-19 14:27:05 +0000633 *ppOrderBy = 0;
634 }
635 }
636
drh6b563442001-11-07 16:48:26 +0000637 /* Open all tables in the pTabList and all indices used by those tables.
drh75897232000-05-29 14:26:00 +0000638 */
drhad3cab52002-05-24 02:04:32 +0000639 for(i=0; i<pTabList->nSrc; i++){
drhf57b3392001-10-08 13:22:32 +0000640 int openOp;
641 Table *pTab;
642
643 pTab = pTabList->a[i].pTab;
drha76b5df2002-02-23 02:32:10 +0000644 if( pTab->isTransient || pTab->pSelect ) continue;
drhf57b3392001-10-08 13:22:32 +0000645 openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
drh99fcd712001-10-13 01:06:47 +0000646 sqliteVdbeAddOp(v, openOp, base+i, pTab->tnum);
647 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drh50e5dad2001-09-15 00:57:28 +0000648 if( i==0 && !pParse->schemaVerified &&
649 (pParse->db->flags & SQLITE_InTrans)==0 ){
drh99fcd712001-10-13 01:06:47 +0000650 sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
drh50e5dad2001-09-15 00:57:28 +0000651 pParse->schemaVerified = 1;
652 }
drh6b563442001-11-07 16:48:26 +0000653 if( pWInfo->a[i].pIdx!=0 ){
654 sqliteVdbeAddOp(v, openOp, pWInfo->a[i].iCur, pWInfo->a[i].pIdx->tnum);
655 sqliteVdbeChangeP3(v, -1, pWInfo->a[i].pIdx->zName, P3_STATIC);
drh75897232000-05-29 14:26:00 +0000656 }
657 }
658
659 /* Generate the code to do the search
660 */
drh75897232000-05-29 14:26:00 +0000661 loopMask = 0;
drhad3cab52002-05-24 02:04:32 +0000662 for(i=0; i<pTabList->nSrc; i++){
drh75897232000-05-29 14:26:00 +0000663 int j, k;
664 int idx = aOrder[i];
drhc4a3c772001-04-04 11:48:57 +0000665 Index *pIdx;
drh6b563442001-11-07 16:48:26 +0000666 WhereLevel *pLevel = &pWInfo->a[i];
drh75897232000-05-29 14:26:00 +0000667
drhad2d8302002-05-24 20:31:36 +0000668 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +0000669 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +0000670 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +0000671 */
672 if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
673 if( !pParse->nMem ) pParse->nMem++;
674 pLevel->iLeftJoin = pParse->nMem++;
675 sqliteVdbeAddOp(v, OP_String, 0, 0);
676 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
677 }
678
drh8aff1012001-12-22 14:49:24 +0000679 pIdx = pLevel->pIdx;
drhd99f7062002-06-08 23:25:08 +0000680 pLevel->inOp = OP_Noop;
drh8aff1012001-12-22 14:49:24 +0000681 if( i<ARRAYSIZE(iDirectEq) && iDirectEq[i]>=0 ){
682 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +0000683 ** equality comparison against the ROWID field. Or
684 ** we reference multiple rows using a "rowid IN (...)"
685 ** construct.
drhc4a3c772001-04-04 11:48:57 +0000686 */
drh8aff1012001-12-22 14:49:24 +0000687 k = iDirectEq[i];
688 assert( k<nExpr );
689 assert( aExpr[k].p!=0 );
690 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
drhd99f7062002-06-08 23:25:08 +0000691 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
drh8aff1012001-12-22 14:49:24 +0000692 if( aExpr[k].idxLeft==idx ){
drhd99f7062002-06-08 23:25:08 +0000693 Expr *pX = aExpr[k].p;
694 if( pX->op!=TK_IN ){
695 sqliteExprCode(pParse, aExpr[k].p->pRight);
696 }else if( pX->pList ){
697 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
698 pLevel->inOp = OP_SetNext;
699 pLevel->inP1 = pX->iTable;
700 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
701 }else{
702 assert( pX->pSelect );
703 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
704 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
705 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
706 pLevel->inOp = OP_Next;
707 pLevel->inP1 = pX->iTable;
708 }
drh8aff1012001-12-22 14:49:24 +0000709 }else{
710 sqliteExprCode(pParse, aExpr[k].p->pLeft);
drhc4a3c772001-04-04 11:48:57 +0000711 }
drh8aff1012001-12-22 14:49:24 +0000712 aExpr[k].p = 0;
drhd99f7062002-06-08 23:25:08 +0000713 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
drhf1351b62002-07-31 19:50:26 +0000714 sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
drhd99f7062002-06-08 23:25:08 +0000715 haveKey = 0;
drh6b125452002-01-28 15:53:03 +0000716 sqliteVdbeAddOp(v, OP_NotExists, base+idx, brk);
drh6b563442001-11-07 16:48:26 +0000717 pLevel->op = OP_Noop;
drhe3184742002-06-19 14:27:05 +0000718 }else if( pIdx!=0 && pLevel->score>0 && pLevel->score%4==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000719 /* Case 2: There is an index and all terms of the WHERE clause that
720 ** refer to the index use the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +0000721 */
drh6b563442001-11-07 16:48:26 +0000722 int start;
drh487ab3c2001-11-08 00:45:21 +0000723 int testOp;
drhc045ec52002-12-04 20:01:06 +0000724 int nColumn = (pLevel->score+4)/8;
drhd99f7062002-06-08 23:25:08 +0000725 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
drh487ab3c2001-11-08 00:45:21 +0000726 for(j=0; j<nColumn; j++){
drh75897232000-05-29 14:26:00 +0000727 for(k=0; k<nExpr; k++){
drhd99f7062002-06-08 23:25:08 +0000728 Expr *pX = aExpr[k].p;
729 if( pX==0 ) continue;
drh75897232000-05-29 14:26:00 +0000730 if( aExpr[k].idxLeft==idx
731 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
drhd99f7062002-06-08 23:25:08 +0000732 && pX->pLeft->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +0000733 ){
drhd99f7062002-06-08 23:25:08 +0000734 if( pX->op==TK_EQ ){
735 sqliteExprCode(pParse, pX->pRight);
736 aExpr[k].p = 0;
737 break;
738 }
739 if( pX->op==TK_IN && nColumn==1 ){
740 if( pX->pList ){
741 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
742 pLevel->inOp = OP_SetNext;
743 pLevel->inP1 = pX->iTable;
744 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
745 }else{
746 assert( pX->pSelect );
747 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
748 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
749 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
750 pLevel->inOp = OP_Next;
751 pLevel->inP1 = pX->iTable;
752 }
753 aExpr[k].p = 0;
754 break;
755 }
drh75897232000-05-29 14:26:00 +0000756 }
757 if( aExpr[k].idxRight==idx
drh487ab3c2001-11-08 00:45:21 +0000758 && aExpr[k].p->op==TK_EQ
drh75897232000-05-29 14:26:00 +0000759 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
drh967e8b72000-06-21 13:59:10 +0000760 && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
drh75897232000-05-29 14:26:00 +0000761 ){
762 sqliteExprCode(pParse, aExpr[k].p->pLeft);
763 aExpr[k].p = 0;
764 break;
765 }
766 }
767 }
drh6b563442001-11-07 16:48:26 +0000768 pLevel->iMem = pParse->nMem++;
drh6b563442001-11-07 16:48:26 +0000769 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
drh487ab3c2001-11-08 00:45:21 +0000770 sqliteVdbeAddOp(v, OP_MakeKey, nColumn, 0);
drha9e99ae2002-08-13 23:02:57 +0000771 sqliteAddIdxKeyType(v, pIdx);
drhc045ec52002-12-04 20:01:06 +0000772 if( nColumn==pIdx->nColumn || pLevel->bRev ){
drh487ab3c2001-11-08 00:45:21 +0000773 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
774 testOp = OP_IdxGT;
775 }else{
776 sqliteVdbeAddOp(v, OP_Dup, 0, 0);
777 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
778 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
779 testOp = OP_IdxGE;
780 }
drhc045ec52002-12-04 20:01:06 +0000781 if( pLevel->bRev ){
782 /* Scan in reverse order */
783 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
784 sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
785 start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
786 sqliteVdbeAddOp(v, OP_IdxLT, pLevel->iCur, brk);
787 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
788 pLevel->op = OP_Prev;
789 }else{
790 /* Scan in the forward order */
791 sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
792 start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
793 sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
794 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
795 pLevel->op = OP_Next;
796 }
drhad3cab52002-05-24 02:04:32 +0000797 if( i==pTabList->nSrc-1 && pushKey ){
drh75897232000-05-29 14:26:00 +0000798 haveKey = 1;
799 }else{
drh99fcd712001-10-13 01:06:47 +0000800 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
drh75897232000-05-29 14:26:00 +0000801 haveKey = 0;
802 }
drh6b563442001-11-07 16:48:26 +0000803 pLevel->p1 = pLevel->iCur;
804 pLevel->p2 = start;
drh8aff1012001-12-22 14:49:24 +0000805 }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
806 /* Case 3: We have an inequality comparison against the ROWID field.
807 */
808 int testOp = OP_Noop;
809 int start;
810
811 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
812 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
813 if( iDirectGt[i]>=0 ){
814 k = iDirectGt[i];
815 assert( k<nExpr );
816 assert( aExpr[k].p!=0 );
817 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
818 if( aExpr[k].idxLeft==idx ){
819 sqliteExprCode(pParse, aExpr[k].p->pRight);
820 }else{
821 sqliteExprCode(pParse, aExpr[k].p->pLeft);
822 }
drhf1351b62002-07-31 19:50:26 +0000823 sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
drh8aff1012001-12-22 14:49:24 +0000824 if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
825 sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
826 }
827 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, brk);
828 aExpr[k].p = 0;
829 }else{
830 sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
831 }
832 if( iDirectLt[i]>=0 ){
833 k = iDirectLt[i];
834 assert( k<nExpr );
835 assert( aExpr[k].p!=0 );
836 assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
837 if( aExpr[k].idxLeft==idx ){
838 sqliteExprCode(pParse, aExpr[k].p->pRight);
839 }else{
840 sqliteExprCode(pParse, aExpr[k].p->pLeft);
841 }
drhf1351b62002-07-31 19:50:26 +0000842 sqliteVdbeAddOp(v, OP_MustBeInt, 1, sqliteVdbeCurrentAddr(v)+1);
drh8aff1012001-12-22 14:49:24 +0000843 pLevel->iMem = pParse->nMem++;
844 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
845 if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
846 testOp = OP_Ge;
847 }else{
848 testOp = OP_Gt;
849 }
850 aExpr[k].p = 0;
851 }
852 start = sqliteVdbeCurrentAddr(v);
853 pLevel->op = OP_Next;
854 pLevel->p1 = base+idx;
855 pLevel->p2 = start;
856 if( testOp!=OP_Noop ){
857 sqliteVdbeAddOp(v, OP_Recno, base+idx, 0);
858 sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
859 sqliteVdbeAddOp(v, testOp, 0, brk);
860 }
861 haveKey = 0;
862 }else if( pIdx==0 ){
drhc27a1ce2002-06-14 20:58:45 +0000863 /* Case 4: There is no usable index. We must do a complete
drh8aff1012001-12-22 14:49:24 +0000864 ** scan of the entire database table.
865 */
866 int start;
867
868 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
869 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
870 sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
871 start = sqliteVdbeCurrentAddr(v);
872 pLevel->op = OP_Next;
873 pLevel->p1 = base+idx;
874 pLevel->p2 = start;
875 haveKey = 0;
drh487ab3c2001-11-08 00:45:21 +0000876 }else{
drhc27a1ce2002-06-14 20:58:45 +0000877 /* Case 5: The WHERE clause term that refers to the right-most
878 ** column of the index is an inequality. For example, if
879 ** the index is on (x,y,z) and the WHERE clause is of the
880 ** form "x=5 AND y<10" then this case is used. Only the
881 ** right-most column can be an inequality - the rest must
882 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +0000883 **
884 ** This case is also used when there are no WHERE clause
885 ** constraints but an index is selected anyway, in order
886 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +0000887 */
888 int score = pLevel->score;
drhc045ec52002-12-04 20:01:06 +0000889 int nEqColumn = score/8;
drh487ab3c2001-11-08 00:45:21 +0000890 int start;
891 int leFlag, geFlag;
892 int testOp;
893
894 /* Evaluate the equality constraints
895 */
896 for(j=0; j<nEqColumn; j++){
897 for(k=0; k<nExpr; k++){
898 if( aExpr[k].p==0 ) continue;
899 if( aExpr[k].idxLeft==idx
900 && aExpr[k].p->op==TK_EQ
901 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
902 && aExpr[k].p->pLeft->iColumn==pIdx->aiColumn[j]
903 ){
904 sqliteExprCode(pParse, aExpr[k].p->pRight);
905 aExpr[k].p = 0;
906 break;
907 }
908 if( aExpr[k].idxRight==idx
909 && aExpr[k].p->op==TK_EQ
910 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
911 && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
912 ){
913 sqliteExprCode(pParse, aExpr[k].p->pLeft);
914 aExpr[k].p = 0;
915 break;
916 }
917 }
918 }
919
drhc27a1ce2002-06-14 20:58:45 +0000920 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +0000921 ** used twice: once to make the termination key and once to make the
922 ** start key.
923 */
924 for(j=0; j<nEqColumn; j++){
925 sqliteVdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
926 }
927
drhc045ec52002-12-04 20:01:06 +0000928 /* Labels for the beginning and end of the loop
929 */
930 cont = pLevel->cont = sqliteVdbeMakeLabel(v);
931 brk = pLevel->brk = sqliteVdbeMakeLabel(v);
932
drh487ab3c2001-11-08 00:45:21 +0000933 /* Generate the termination key. This is the key value that
934 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +0000935 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +0000936 **
937 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
938 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +0000939 */
940 if( (score & 1)!=0 ){
941 for(k=0; k<nExpr; k++){
942 Expr *pExpr = aExpr[k].p;
943 if( pExpr==0 ) continue;
944 if( aExpr[k].idxLeft==idx
945 && (pExpr->op==TK_LT || pExpr->op==TK_LE)
946 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
947 && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
948 ){
949 sqliteExprCode(pParse, pExpr->pRight);
950 leFlag = pExpr->op==TK_LE;
951 aExpr[k].p = 0;
952 break;
953 }
954 if( aExpr[k].idxRight==idx
955 && (pExpr->op==TK_GT || pExpr->op==TK_GE)
956 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
957 && pExpr->pRight->iColumn==pIdx->aiColumn[j]
958 ){
959 sqliteExprCode(pParse, pExpr->pLeft);
960 leFlag = pExpr->op==TK_GE;
961 aExpr[k].p = 0;
962 break;
963 }
964 }
965 testOp = OP_IdxGE;
966 }else{
967 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
968 leFlag = 1;
969 }
970 if( testOp!=OP_Noop ){
971 pLevel->iMem = pParse->nMem++;
972 sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + (score & 1), 0);
drha9e99ae2002-08-13 23:02:57 +0000973 sqliteAddIdxKeyType(v, pIdx);
drh487ab3c2001-11-08 00:45:21 +0000974 if( leFlag ){
975 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
976 }
drhc045ec52002-12-04 20:01:06 +0000977 if( pLevel->bRev ){
978 sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
979 }else{
980 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
981 }
982 }else if( pLevel->bRev ){
983 sqliteVdbeAddOp(v, OP_Last, pLevel->iCur, brk);
drh487ab3c2001-11-08 00:45:21 +0000984 }
985
986 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +0000987 ** bound on the search. There is no start key if there are no
988 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +0000989 ** that case, generate a "Rewind" instruction in place of the
990 ** start key search.
drhc045ec52002-12-04 20:01:06 +0000991 **
992 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
993 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +0000994 */
995 if( (score & 2)!=0 ){
996 for(k=0; k<nExpr; k++){
997 Expr *pExpr = aExpr[k].p;
998 if( pExpr==0 ) continue;
999 if( aExpr[k].idxLeft==idx
1000 && (pExpr->op==TK_GT || pExpr->op==TK_GE)
1001 && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
1002 && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
1003 ){
1004 sqliteExprCode(pParse, pExpr->pRight);
1005 geFlag = pExpr->op==TK_GE;
1006 aExpr[k].p = 0;
1007 break;
1008 }
1009 if( aExpr[k].idxRight==idx
1010 && (pExpr->op==TK_LT || pExpr->op==TK_LE)
1011 && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
1012 && pExpr->pRight->iColumn==pIdx->aiColumn[j]
1013 ){
1014 sqliteExprCode(pParse, pExpr->pLeft);
1015 geFlag = pExpr->op==TK_LE;
1016 aExpr[k].p = 0;
1017 break;
1018 }
1019 }
drh7900ead2001-11-12 13:51:43 +00001020 }else{
1021 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001022 }
drh487ab3c2001-11-08 00:45:21 +00001023 if( nEqColumn>0 || (score&2)!=0 ){
1024 sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + ((score&2)!=0), 0);
drha9e99ae2002-08-13 23:02:57 +00001025 sqliteAddIdxKeyType(v, pIdx);
drh487ab3c2001-11-08 00:45:21 +00001026 if( !geFlag ){
1027 sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
1028 }
drhc045ec52002-12-04 20:01:06 +00001029 if( pLevel->bRev ){
1030 pLevel->iMem = pParse->nMem++;
1031 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
1032 testOp = OP_IdxLT;
1033 }else{
1034 sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
1035 }
1036 }else if( pLevel->bRev ){
1037 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001038 }else{
1039 sqliteVdbeAddOp(v, OP_Rewind, pLevel->iCur, brk);
1040 }
1041
1042 /* Generate the the top of the loop. If there is a termination
1043 ** key we have to test for that key and abort at the top of the
1044 ** loop.
1045 */
1046 start = sqliteVdbeCurrentAddr(v);
1047 if( testOp!=OP_Noop ){
1048 sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1049 sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
1050 }
1051 sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
drhad3cab52002-05-24 02:04:32 +00001052 if( i==pTabList->nSrc-1 && pushKey ){
drh487ab3c2001-11-08 00:45:21 +00001053 haveKey = 1;
1054 }else{
1055 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
1056 haveKey = 0;
1057 }
1058
1059 /* Record the instruction used to terminate the loop.
1060 */
drhc045ec52002-12-04 20:01:06 +00001061 pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
drh487ab3c2001-11-08 00:45:21 +00001062 pLevel->p1 = pLevel->iCur;
1063 pLevel->p2 = start;
drh75897232000-05-29 14:26:00 +00001064 }
1065 loopMask |= 1<<idx;
1066
1067 /* Insert code to test every subexpression that can be completely
1068 ** computed using the current set of tables.
1069 */
1070 for(j=0; j<nExpr; j++){
1071 if( aExpr[j].p==0 ) continue;
drh3f6b5482002-04-02 13:26:10 +00001072 if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
drh1f162302002-10-27 19:35:33 +00001073 if( pLevel->iLeftJoin && !ExprHasProperty(aExpr[j].p,EP_FromJoin) ){
1074 continue;
1075 }
drh75897232000-05-29 14:26:00 +00001076 if( haveKey ){
drh573bd272001-02-19 23:23:38 +00001077 haveKey = 0;
drh99fcd712001-10-13 01:06:47 +00001078 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
drh75897232000-05-29 14:26:00 +00001079 }
drhf5905aa2002-05-26 20:54:33 +00001080 sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
drh75897232000-05-29 14:26:00 +00001081 aExpr[j].p = 0;
1082 }
1083 brk = cont;
drhad2d8302002-05-24 20:31:36 +00001084
1085 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1086 ** at least one row of the right table has matched the left table.
1087 */
1088 if( pLevel->iLeftJoin ){
1089 pLevel->top = sqliteVdbeCurrentAddr(v);
1090 sqliteVdbeAddOp(v, OP_Integer, 1, 0);
1091 sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drh1cc093c2002-06-24 22:01:57 +00001092 for(j=0; j<nExpr; j++){
1093 if( aExpr[j].p==0 ) continue;
1094 if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
1095 if( haveKey ){
drh3b167c72002-06-28 12:18:47 +00001096 /* Cannot happen. "haveKey" can only be true if pushKey is true
1097 ** an pushKey can only be true for DELETE and UPDATE and there are
1098 ** no outer joins with DELETE and UPDATE.
1099 */
drh1cc093c2002-06-24 22:01:57 +00001100 haveKey = 0;
1101 sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
1102 }
1103 sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
1104 aExpr[j].p = 0;
1105 }
drhad2d8302002-05-24 20:31:36 +00001106 }
drh75897232000-05-29 14:26:00 +00001107 }
1108 pWInfo->iContinue = cont;
1109 if( pushKey && !haveKey ){
drh99fcd712001-10-13 01:06:47 +00001110 sqliteVdbeAddOp(v, OP_Recno, base, 0);
drh75897232000-05-29 14:26:00 +00001111 }
1112 sqliteFree(aOrder);
1113 return pWInfo;
1114}
1115
1116/*
drhc27a1ce2002-06-14 20:58:45 +00001117** Generate the end of the WHERE loop. See comments on
1118** sqliteWhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001119*/
1120void sqliteWhereEnd(WhereInfo *pWInfo){
1121 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001122 int i;
drh19a775c2000-06-05 18:54:46 +00001123 int base = pWInfo->base;
drh6b563442001-11-07 16:48:26 +00001124 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001125 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001126
drhad3cab52002-05-24 02:04:32 +00001127 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001128 pLevel = &pWInfo->a[i];
1129 sqliteVdbeResolveLabel(v, pLevel->cont);
1130 if( pLevel->op!=OP_Noop ){
1131 sqliteVdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001132 }
drh6b563442001-11-07 16:48:26 +00001133 sqliteVdbeResolveLabel(v, pLevel->brk);
drhd99f7062002-06-08 23:25:08 +00001134 if( pLevel->inOp!=OP_Noop ){
1135 sqliteVdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
1136 }
drhad2d8302002-05-24 20:31:36 +00001137 if( pLevel->iLeftJoin ){
1138 int addr;
1139 addr = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh7f09b3e2002-08-13 13:15:49 +00001140 sqliteVdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iCur>=0));
drhad2d8302002-05-24 20:31:36 +00001141 sqliteVdbeAddOp(v, OP_NullRow, base+i, 0);
drh7f09b3e2002-08-13 13:15:49 +00001142 if( pLevel->iCur>=0 ){
1143 sqliteVdbeAddOp(v, OP_NullRow, pLevel->iCur, 0);
1144 }
drhad2d8302002-05-24 20:31:36 +00001145 sqliteVdbeAddOp(v, OP_Goto, 0, pLevel->top);
1146 }
drh19a775c2000-06-05 18:54:46 +00001147 }
drh6b563442001-11-07 16:48:26 +00001148 sqliteVdbeResolveLabel(v, pWInfo->iBreak);
drhad3cab52002-05-24 02:04:32 +00001149 for(i=0; i<pTabList->nSrc; i++){
drh22f70c32002-02-18 01:17:00 +00001150 if( pTabList->a[i].pTab->isTransient ) continue;
drh6b563442001-11-07 16:48:26 +00001151 pLevel = &pWInfo->a[i];
1152 sqliteVdbeAddOp(v, OP_Close, base+i, 0);
1153 if( pLevel->pIdx!=0 ){
1154 sqliteVdbeAddOp(v, OP_Close, pLevel->iCur, 0);
1155 }
drh19a775c2000-06-05 18:54:46 +00001156 }
drh142e30d2002-08-28 03:00:58 +00001157#if 0 /* Never reuse a cursor */
drh832508b2002-03-02 17:04:07 +00001158 if( pWInfo->pParse->nTab==pWInfo->peakNTab ){
1159 pWInfo->pParse->nTab = pWInfo->savedNTab;
1160 }
drh142e30d2002-08-28 03:00:58 +00001161#endif
drh75897232000-05-29 14:26:00 +00001162 sqliteFree(pWInfo);
1163 return;
1164}