4
** The author disclaims copyright to this source code. In place of
5
** a legal notice, here is a blessing:
7
** 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.
11
*************************************************************************
12
** This module contains C code that generates VDBE code used to process
13
** the WHERE clause of SQL statements.
15
** $Id: where.c 326789 2004-07-07 21:25:56Z pahlibar $
17
#include "sqliteInt.h"
20
** The query generator uses an array of instances of this structure to
21
** help it analyze the subexpressions of the WHERE clause. Each WHERE
22
** clause subexpression is separated from the others by an AND operator.
24
typedef struct ExprInfo ExprInfo;
26
Expr *p; /* Pointer to the subexpression */
27
u8 indexable; /* True if this subexprssion is usable by an index */
28
short int idxLeft; /* p->pLeft is a column in this table number. -1 if
29
** p->pLeft is not the column of any table */
30
short int idxRight; /* p->pRight is a column in this table number. -1 if
31
** p->pRight is not the column of any table */
32
unsigned prereqLeft; /* Bitmask of tables referenced by p->pLeft */
33
unsigned prereqRight; /* Bitmask of tables referenced by p->pRight */
34
unsigned prereqAll; /* Bitmask of tables referenced by p */
38
** An instance of the following structure keeps track of a mapping
39
** between VDBE cursor numbers and bitmasks. The VDBE cursor numbers
40
** are small integers contained in SrcList_item.iCursor and Expr.iTable
41
** fields. For any given WHERE clause, we want to track which cursors
42
** are being used, so we assign a single bit in a 32-bit word to track
43
** that cursor. Then a 32-bit integer is able to show the set of all
44
** cursors being used.
46
typedef struct ExprMaskSet ExprMaskSet;
48
int n; /* Number of assigned cursor values */
49
int ix[32]; /* Cursor assigned to each bit */
53
** Determine the number of elements in an array.
55
#define ARRAYSIZE(X) (sizeof(X)/sizeof(X[0]))
58
** This routine is used to divide the WHERE expression into subexpressions
59
** separated by the AND operator.
61
** aSlot[] is an array of subexpressions structures.
62
** There are nSlot spaces left in this array. This routine attempts to
63
** split pExpr into subexpressions and fills aSlot[] with those subexpressions.
64
** The return value is the number of slots filled.
66
static int exprSplit(int nSlot, ExprInfo *aSlot, Expr *pExpr){
68
if( pExpr==0 || nSlot<1 ) return 0;
69
if( nSlot==1 || pExpr->op!=TK_AND ){
73
if( pExpr->pLeft->op!=TK_AND ){
74
aSlot[0].p = pExpr->pLeft;
75
cnt = 1 + exprSplit(nSlot-1, &aSlot[1], pExpr->pRight);
77
cnt = exprSplit(nSlot, aSlot, pExpr->pLeft);
78
cnt += exprSplit(nSlot-cnt, &aSlot[cnt], pExpr->pRight);
84
** Initialize an expression mask set
86
#define initMaskSet(P) memset(P, 0, sizeof(*P))
89
** Return the bitmask for the given cursor. Assign a new bitmask
90
** if this is the first time the cursor has been seen.
92
static int getMask(ExprMaskSet *pMaskSet, int iCursor){
94
for(i=0; i<pMaskSet->n; i++){
95
if( pMaskSet->ix[i]==iCursor ) return 1<<i;
97
if( i==pMaskSet->n && i<ARRAYSIZE(pMaskSet->ix) ){
99
pMaskSet->ix[i] = iCursor;
106
** Destroy an expression mask set
108
#define freeMaskSet(P) /* NO-OP */
111
** This routine walks (recursively) an expression tree and generates
112
** a bitmask indicating which tables are used in that expression
115
** In order for this routine to work, the calling function must have
116
** previously invoked sqliteExprResolveIds() on the expression. See
117
** the header comment on that routine for additional information.
118
** The sqliteExprResolveIds() routines looks for column names and
119
** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
120
** the VDBE cursor number of the table.
122
static int exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
123
unsigned int mask = 0;
125
if( p->op==TK_COLUMN ){
126
return getMask(pMaskSet, p->iTable);
129
mask = exprTableUsage(pMaskSet, p->pRight);
132
mask |= exprTableUsage(pMaskSet, p->pLeft);
136
for(i=0; i<p->pList->nExpr; i++){
137
mask |= exprTableUsage(pMaskSet, p->pList->a[i].pExpr);
144
** Return TRUE if the given operator is one of the operators that is
145
** allowed for an indexable WHERE clause. The allowed operators are
146
** "=", "<", ">", "<=", ">=", and "IN".
148
static int allowedOp(int op){
163
** The input to this routine is an ExprInfo structure with only the
164
** "p" field filled in. The job of this routine is to analyze the
165
** subexpression and populate all the other fields of the ExprInfo
168
static void exprAnalyze(ExprMaskSet *pMaskSet, ExprInfo *pInfo){
169
Expr *pExpr = pInfo->p;
170
pInfo->prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
171
pInfo->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
172
pInfo->prereqAll = exprTableUsage(pMaskSet, pExpr);
173
pInfo->indexable = 0;
175
pInfo->idxRight = -1;
176
if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
177
if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
178
pInfo->idxRight = pExpr->pRight->iTable;
179
pInfo->indexable = 1;
181
if( pExpr->pLeft->op==TK_COLUMN ){
182
pInfo->idxLeft = pExpr->pLeft->iTable;
183
pInfo->indexable = 1;
189
** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
190
** left-most table in the FROM clause of that same SELECT statement and
191
** the table has a cursor number of "base".
193
** This routine attempts to find an index for pTab that generates the
194
** correct record sequence for the given ORDER BY clause. The return value
195
** is a pointer to an index that does the job. NULL is returned if the
196
** table has no index that will generate the correct sort order.
198
** If there are two or more indices that generate the correct sort order
199
** and pPreferredIdx is one of those indices, then return pPreferredIdx.
201
** nEqCol is the number of columns of pPreferredIdx that are used as
202
** equality constraints. Any index returned must have exactly this same
203
** set of columns. The ORDER BY clause only matches index columns beyond the
204
** the first nEqCol columns.
206
** All terms of the ORDER BY clause must be either ASC or DESC. The
207
** *pbRev value is set to 1 if the ORDER BY clause is all DESC and it is
208
** set to 0 if the ORDER BY clause is all ASC.
210
static Index *findSortingIndex(
211
Table *pTab, /* The table to be sorted */
212
int base, /* Cursor number for pTab */
213
ExprList *pOrderBy, /* The ORDER BY clause */
214
Index *pPreferredIdx, /* Use this index, if possible and not NULL */
215
int nEqCol, /* Number of index columns used with == constraints */
216
int *pbRev /* Set to 1 if ORDER BY is DESC */
223
assert( pOrderBy!=0 );
224
assert( pOrderBy->nExpr>0 );
225
sortOrder = pOrderBy->a[0].sortOrder & SQLITE_SO_DIRMASK;
226
for(i=0; i<pOrderBy->nExpr; i++){
228
if( (pOrderBy->a[i].sortOrder & SQLITE_SO_DIRMASK)!=sortOrder ){
229
/* Indices can only be used if all ORDER BY terms are either
230
** DESC or ASC. Indices cannot be used on a mixture. */
233
if( (pOrderBy->a[i].sortOrder & SQLITE_SO_TYPEMASK)!=SQLITE_SO_UNK ){
234
/* Do not sort by index if there is a COLLATE clause */
237
p = pOrderBy->a[i].pExpr;
238
if( p->op!=TK_COLUMN || p->iTable!=base ){
239
/* Can not use an index sort on anything that is not a column in the
240
** left-most table of the FROM clause */
245
/* If we get this far, it means the ORDER BY clause consists only of
246
** ascending columns in the left-most table of the FROM clause. Now
247
** check for a matching index.
250
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
251
int nExpr = pOrderBy->nExpr;
252
if( pIdx->nColumn < nEqCol || pIdx->nColumn < nExpr ) continue;
253
for(i=j=0; i<nEqCol; i++){
254
if( pPreferredIdx->aiColumn[i]!=pIdx->aiColumn[i] ) break;
255
if( j<nExpr && pOrderBy->a[j].pExpr->iColumn==pIdx->aiColumn[i] ){ j++; }
257
if( i<nEqCol ) continue;
258
for(i=0; i+j<nExpr; i++){
259
if( pOrderBy->a[i+j].pExpr->iColumn!=pIdx->aiColumn[i+nEqCol] ) break;
263
if( pIdx==pPreferredIdx ) break;
266
if( pMatch && pbRev ){
267
*pbRev = sortOrder==SQLITE_SO_DESC;
273
** Generate the beginning of the loop used for WHERE clause processing.
274
** The return value is a pointer to an (opaque) structure that contains
275
** information needed to terminate the loop. Later, the calling routine
276
** should invoke sqliteWhereEnd() with the return value of this function
277
** in order to complete the WHERE clause processing.
279
** If an error occurs, this routine returns NULL.
281
** The basic idea is to do a nested loop, one loop for each table in
282
** the FROM clause of a select. (INSERT and UPDATE statements are the
283
** same as a SELECT with only a single table in the FROM clause.) For
284
** example, if the SQL is this:
286
** SELECT * FROM t1, t2, t3 WHERE ...;
288
** Then the code generated is conceptually like the following:
290
** foreach row1 in t1 do \ Code generated
291
** foreach row2 in t2 do |-- by sqliteWhereBegin()
292
** foreach row3 in t3 do /
294
** end \ Code generated
295
** end |-- by sqliteWhereEnd()
298
** There are Btree cursors associated with each table. t1 uses cursor
299
** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
300
** And so forth. This routine generates code to open those VDBE cursors
301
** and sqliteWhereEnd() generates the code to close them.
303
** If the WHERE clause is empty, the foreach loops must each scan their
304
** entire tables. Thus a three-way join is an O(N^3) operation. But if
305
** the tables have indices and there are terms in the WHERE clause that
306
** refer to those indices, a complete table scan can be avoided and the
307
** code will run much faster. Most of the work of this routine is checking
308
** to see if there are indices that can be used to speed up the loop.
310
** Terms of the WHERE clause are also used to limit which rows actually
311
** make it to the "..." in the middle of the loop. After each "foreach",
312
** terms of the WHERE clause that use only terms in that loop and outer
313
** loops are evaluated and if false a jump is made around all subsequent
314
** inner loops (or around the "..." if the test occurs within the inner-
319
** An outer join of tables t1 and t2 is conceptally coded as follows:
321
** foreach row1 in t1 do
323
** foreach row2 in t2 do
329
** move the row2 cursor to a null row
334
** ORDER BY CLAUSE PROCESSING
336
** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
337
** if there is one. If there is no ORDER BY clause or if this routine
338
** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
340
** If an index can be used so that the natural output order of the table
341
** scan is correct for the ORDER BY clause, then that index is used and
342
** *ppOrderBy is set to NULL. This is an optimization that prevents an
343
** unnecessary sort of the result set if an index appropriate for the
344
** ORDER BY clause already exists.
346
** If the where clause loops cannot be arranged to provide the correct
347
** output order, then the *ppOrderBy is unchanged.
349
WhereInfo *sqliteWhereBegin(
350
Parse *pParse, /* The parser context */
351
SrcList *pTabList, /* A list of all tables to be scanned */
352
Expr *pWhere, /* The WHERE clause */
353
int pushKey, /* If TRUE, leave the table key on the stack */
354
ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
356
int i; /* Loop counter */
357
WhereInfo *pWInfo; /* Will become the return value of this function */
358
Vdbe *v = pParse->pVdbe; /* The virtual database engine */
359
int brk, cont = 0; /* Addresses used during code generation */
360
int nExpr; /* Number of subexpressions in the WHERE clause */
361
int loopMask; /* One bit set for each outer loop */
362
int haveKey; /* True if KEY is on the stack */
363
ExprMaskSet maskSet; /* The expression mask set */
364
int iDirectEq[32]; /* Term of the form ROWID==X for the N-th table */
365
int iDirectLt[32]; /* Term of the form ROWID<X or ROWID<=X */
366
int iDirectGt[32]; /* Term of the form ROWID>X or ROWID>=X */
367
ExprInfo aExpr[101]; /* The WHERE clause is divided into these expressions */
369
/* pushKey is only allowed if there is a single table (as in an INSERT or
372
assert( pushKey==0 || pTabList->nSrc==1 );
374
/* Split the WHERE clause into separate subexpressions where each
375
** subexpression is separated by an AND operator. If the aExpr[]
376
** array fills up, the last entry might point to an expression which
377
** contains additional unfactored AND operators.
379
initMaskSet(&maskSet);
380
memset(aExpr, 0, sizeof(aExpr));
381
nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
382
if( nExpr==ARRAYSIZE(aExpr) ){
383
sqliteErrorMsg(pParse, "WHERE clause too complex - no more "
384
"than %d terms allowed", (int)ARRAYSIZE(aExpr)-1);
388
/* Allocate and initialize the WhereInfo structure that will become the
391
pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
392
if( sqlite_malloc_failed ){
396
pWInfo->pParse = pParse;
397
pWInfo->pTabList = pTabList;
398
pWInfo->peakNTab = pWInfo->savedNTab = pParse->nTab;
399
pWInfo->iBreak = sqliteVdbeMakeLabel(v);
401
/* Special case: a WHERE clause that is constant. Evaluate the
402
** expression and either jump over all of the code or fall thru.
404
if( pWhere && (pTabList->nSrc==0 || sqliteExprIsConstant(pWhere)) ){
405
sqliteExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
409
/* Analyze all of the subexpressions.
411
for(i=0; i<nExpr; i++){
412
exprAnalyze(&maskSet, &aExpr[i]);
414
/* If we are executing a trigger body, remove all references to
415
** new.* and old.* tables from the prerequisite masks.
417
if( pParse->trigStack ){
419
if( (x = pParse->trigStack->newIdx) >= 0 ){
420
int mask = ~getMask(&maskSet, x);
421
aExpr[i].prereqRight &= mask;
422
aExpr[i].prereqLeft &= mask;
423
aExpr[i].prereqAll &= mask;
425
if( (x = pParse->trigStack->oldIdx) >= 0 ){
426
int mask = ~getMask(&maskSet, x);
427
aExpr[i].prereqRight &= mask;
428
aExpr[i].prereqLeft &= mask;
429
aExpr[i].prereqAll &= mask;
434
/* Figure out what index to use (if any) for each nested loop.
435
** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
436
** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
439
** If terms exist that use the ROWID of any table, then set the
440
** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
441
** to the index of the term containing the ROWID. We always prefer
442
** to use a ROWID which can directly access a table rather than an
443
** index which requires reading an index first to get the rowid then
444
** doing a second read of the actual database table.
446
** Actually, if there are more than 32 tables in the join, only the
447
** first 32 tables are candidates for indices. This is (again) due
448
** to the limit of 32 bits in an integer bitmask.
451
for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++){
453
int iCur = pTabList->a[i].iCursor; /* The cursor for this table */
454
int mask = getMask(&maskSet, iCur); /* Cursor mask for this table */
455
Table *pTab = pTabList->a[i].pTab;
460
/* Check to see if there is an expression that uses only the
461
** ROWID field of this table. For terms of the form ROWID==expr
462
** set iDirectEq[i] to the index of the term. For terms of the
463
** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
464
** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
466
** (Added:) Treat ROWID IN expr like ROWID=expr.
468
pWInfo->a[i].iCur = -1;
472
for(j=0; j<nExpr; j++){
473
if( aExpr[j].idxLeft==iCur && aExpr[j].p->pLeft->iColumn<0
474
&& (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
475
switch( aExpr[j].p->op ){
477
case TK_EQ: iDirectEq[i] = j; break;
479
case TK_LT: iDirectLt[i] = j; break;
481
case TK_GT: iDirectGt[i] = j; break;
484
if( aExpr[j].idxRight==iCur && aExpr[j].p->pRight->iColumn<0
485
&& (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
486
switch( aExpr[j].p->op ){
487
case TK_EQ: iDirectEq[i] = j; break;
489
case TK_LT: iDirectGt[i] = j; break;
491
case TK_GT: iDirectLt[i] = j; break;
495
if( iDirectEq[i]>=0 ){
497
pWInfo->a[i].pIdx = 0;
501
/* Do a search for usable indices. Leave pBestIdx pointing to
502
** the "best" index. pBestIdx is left set to NULL if no indices
505
** The best index is determined as follows. For each of the
506
** left-most terms that is fixed by an equality operator, add
507
** 8 to the score. The right-most term of the index may be
508
** constrained by an inequality. Add 1 if for an "x<..." constraint
509
** and add 2 for an "x>..." constraint. Chose the index that
510
** gives the best score.
512
** This scoring system is designed so that the score can later be
513
** used to determine how the index is used. If the score&7 is 0
514
** then all constraints are equalities. If score&1 is not 0 then
515
** there is an inequality used as a termination key. (ex: "x<...")
516
** If score&2 is not 0 then there is an inequality used as the
517
** start key. (ex: "x>..."). A score or 4 is the special case
518
** of an IN operator constraint. (ex: "x IN ...").
520
** The IN operator (as in "<expr> IN (...)") is treated the same as
521
** an equality comparison except that it can only be used on the
522
** left-most column of an index and other terms of the WHERE clause
523
** cannot be used in conjunction with the IN operator to help satisfy
524
** other columns of the index.
526
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
527
int eqMask = 0; /* Index columns covered by an x=... term */
528
int ltMask = 0; /* Index columns covered by an x<... term */
529
int gtMask = 0; /* Index columns covered by an x>... term */
530
int inMask = 0; /* Index columns covered by an x IN .. term */
533
if( pIdx->nColumn>32 ) continue; /* Ignore indices too many columns */
534
for(j=0; j<nExpr; j++){
535
if( aExpr[j].idxLeft==iCur
536
&& (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
537
int iColumn = aExpr[j].p->pLeft->iColumn;
539
for(k=0; k<pIdx->nColumn; k++){
540
if( pIdx->aiColumn[k]==iColumn ){
541
switch( aExpr[j].p->op ){
543
if( k==0 ) inMask |= 1;
570
if( aExpr[j].idxRight==iCur
571
&& (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
572
int iColumn = aExpr[j].p->pRight->iColumn;
574
for(k=0; k<pIdx->nColumn; k++){
575
if( pIdx->aiColumn[k]==iColumn ){
576
switch( aExpr[j].p->op ){
603
/* The following loop ends with nEq set to the number of columns
604
** on the left of the index with == constraints.
606
for(nEq=0; nEq<pIdx->nColumn; nEq++){
608
if( (m & eqMask)!=m ) break;
610
score = nEq*8; /* Base score is 8 times number of == constraints */
612
if( m & ltMask ) score++; /* Increase score for a < constraint */
613
if( m & gtMask ) score+=2; /* Increase score for a > constraint */
614
if( score==0 && inMask ) score = 4; /* Default score for IN constraint */
615
if( score>bestScore ){
620
pWInfo->a[i].pIdx = pBestIdx;
621
pWInfo->a[i].score = bestScore;
622
pWInfo->a[i].bRev = 0;
625
pWInfo->a[i].iCur = pParse->nTab++;
626
pWInfo->peakNTab = pParse->nTab;
630
/* Check to see if the ORDER BY clause is or can be satisfied by the
631
** use of an index on the first table.
633
if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
639
pTab = pTabList->a[0].pTab;
640
pIdx = pWInfo->a[0].pIdx;
641
if( pIdx && pWInfo->a[0].score==4 ){
642
/* If there is already an IN index on the left-most table,
643
** it will not give the correct sort order.
644
** So, pretend that no suitable index is found.
647
}else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
648
/* If the left-most column is accessed using its ROWID, then do
649
** not try to sort by index.
653
int nEqCol = (pWInfo->a[0].score+4)/8;
654
pSortIdx = findSortingIndex(pTab, pTabList->a[0].iCursor,
655
*ppOrderBy, pIdx, nEqCol, &bRev);
657
if( pSortIdx && (pIdx==0 || pIdx==pSortIdx) ){
659
pWInfo->a[0].pIdx = pSortIdx;
660
pWInfo->a[0].iCur = pParse->nTab++;
661
pWInfo->peakNTab = pParse->nTab;
663
pWInfo->a[0].bRev = bRev;
668
/* Open all tables in the pTabList and all indices used by those tables.
670
for(i=0; i<pTabList->nSrc; i++){
674
pTab = pTabList->a[i].pTab;
675
if( pTab->isTransient || pTab->pSelect ) continue;
676
sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
677
sqliteVdbeOp3(v, OP_OpenRead, pTabList->a[i].iCursor, pTab->tnum,
678
pTab->zName, P3_STATIC);
679
sqliteCodeVerifySchema(pParse, pTab->iDb);
680
if( (pIx = pWInfo->a[i].pIdx)!=0 ){
681
sqliteVdbeAddOp(v, OP_Integer, pIx->iDb, 0);
682
sqliteVdbeOp3(v, OP_OpenRead, pWInfo->a[i].iCur, pIx->tnum, pIx->zName,0);
686
/* Generate the code to do the search
689
for(i=0; i<pTabList->nSrc; i++){
691
int iCur = pTabList->a[i].iCursor;
693
WhereLevel *pLevel = &pWInfo->a[i];
695
/* If this is the right table of a LEFT OUTER JOIN, allocate and
696
** initialize a memory cell that records if this table matches any
697
** row of the left table of the join.
699
if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
700
if( !pParse->nMem ) pParse->nMem++;
701
pLevel->iLeftJoin = pParse->nMem++;
702
sqliteVdbeAddOp(v, OP_String, 0, 0);
703
sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
707
pLevel->inOp = OP_Noop;
708
if( i<ARRAYSIZE(iDirectEq) && iDirectEq[i]>=0 ){
709
/* Case 1: We can directly reference a single row using an
710
** equality comparison against the ROWID field. Or
711
** we reference multiple rows using a "rowid IN (...)"
716
assert( aExpr[k].p!=0 );
717
assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
718
brk = pLevel->brk = sqliteVdbeMakeLabel(v);
719
if( aExpr[k].idxLeft==iCur ){
720
Expr *pX = aExpr[k].p;
722
sqliteExprCode(pParse, aExpr[k].p->pRight);
723
}else if( pX->pList ){
724
sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
725
pLevel->inOp = OP_SetNext;
726
pLevel->inP1 = pX->iTable;
727
pLevel->inP2 = sqliteVdbeCurrentAddr(v);
729
assert( pX->pSelect );
730
sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
731
sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
732
pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
733
pLevel->inOp = OP_Next;
734
pLevel->inP1 = pX->iTable;
737
sqliteExprCode(pParse, aExpr[k].p->pLeft);
740
cont = pLevel->cont = sqliteVdbeMakeLabel(v);
741
sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
743
sqliteVdbeAddOp(v, OP_NotExists, iCur, brk);
744
pLevel->op = OP_Noop;
745
}else if( pIdx!=0 && pLevel->score>0 && pLevel->score%4==0 ){
746
/* Case 2: There is an index and all terms of the WHERE clause that
747
** refer to the index use the "==" or "IN" operators.
751
int nColumn = (pLevel->score+4)/8;
752
brk = pLevel->brk = sqliteVdbeMakeLabel(v);
753
for(j=0; j<nColumn; j++){
754
for(k=0; k<nExpr; k++){
755
Expr *pX = aExpr[k].p;
756
if( pX==0 ) continue;
757
if( aExpr[k].idxLeft==iCur
758
&& (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
759
&& pX->pLeft->iColumn==pIdx->aiColumn[j]
762
sqliteExprCode(pParse, pX->pRight);
766
if( pX->op==TK_IN && nColumn==1 ){
768
sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
769
pLevel->inOp = OP_SetNext;
770
pLevel->inP1 = pX->iTable;
771
pLevel->inP2 = sqliteVdbeCurrentAddr(v);
773
assert( pX->pSelect );
774
sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
775
sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
776
pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
777
pLevel->inOp = OP_Next;
778
pLevel->inP1 = pX->iTable;
784
if( aExpr[k].idxRight==iCur
785
&& aExpr[k].p->op==TK_EQ
786
&& (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
787
&& aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
789
sqliteExprCode(pParse, aExpr[k].p->pLeft);
795
pLevel->iMem = pParse->nMem++;
796
cont = pLevel->cont = sqliteVdbeMakeLabel(v);
797
sqliteVdbeAddOp(v, OP_NotNull, -nColumn, sqliteVdbeCurrentAddr(v)+3);
798
sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
799
sqliteVdbeAddOp(v, OP_Goto, 0, brk);
800
sqliteVdbeAddOp(v, OP_MakeKey, nColumn, 0);
801
sqliteAddIdxKeyType(v, pIdx);
802
if( nColumn==pIdx->nColumn || pLevel->bRev ){
803
sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
806
sqliteVdbeAddOp(v, OP_Dup, 0, 0);
807
sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
808
sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
812
/* Scan in reverse order */
813
sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
814
sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
815
start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
816
sqliteVdbeAddOp(v, OP_IdxLT, pLevel->iCur, brk);
817
pLevel->op = OP_Prev;
819
/* Scan in the forward order */
820
sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
821
start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
822
sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
823
pLevel->op = OP_Next;
825
sqliteVdbeAddOp(v, OP_RowKey, pLevel->iCur, 0);
826
sqliteVdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
827
sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
828
if( i==pTabList->nSrc-1 && pushKey ){
831
sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
834
pLevel->p1 = pLevel->iCur;
836
}else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
837
/* Case 3: We have an inequality comparison against the ROWID field.
839
int testOp = OP_Noop;
842
brk = pLevel->brk = sqliteVdbeMakeLabel(v);
843
cont = pLevel->cont = sqliteVdbeMakeLabel(v);
844
if( iDirectGt[i]>=0 ){
847
assert( aExpr[k].p!=0 );
848
assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
849
if( aExpr[k].idxLeft==iCur ){
850
sqliteExprCode(pParse, aExpr[k].p->pRight);
852
sqliteExprCode(pParse, aExpr[k].p->pLeft);
854
sqliteVdbeAddOp(v, OP_ForceInt,
855
aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT, brk);
856
sqliteVdbeAddOp(v, OP_MoveTo, iCur, brk);
859
sqliteVdbeAddOp(v, OP_Rewind, iCur, brk);
861
if( iDirectLt[i]>=0 ){
864
assert( aExpr[k].p!=0 );
865
assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
866
if( aExpr[k].idxLeft==iCur ){
867
sqliteExprCode(pParse, aExpr[k].p->pRight);
869
sqliteExprCode(pParse, aExpr[k].p->pLeft);
871
/* sqliteVdbeAddOp(v, OP_MustBeInt, 0, sqliteVdbeCurrentAddr(v)+1); */
872
pLevel->iMem = pParse->nMem++;
873
sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
874
if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
881
start = sqliteVdbeCurrentAddr(v);
882
pLevel->op = OP_Next;
885
if( testOp!=OP_Noop ){
886
sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
887
sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
888
sqliteVdbeAddOp(v, testOp, 0, brk);
892
/* Case 4: There is no usable index. We must do a complete
893
** scan of the entire database table.
897
brk = pLevel->brk = sqliteVdbeMakeLabel(v);
898
cont = pLevel->cont = sqliteVdbeMakeLabel(v);
899
sqliteVdbeAddOp(v, OP_Rewind, iCur, brk);
900
start = sqliteVdbeCurrentAddr(v);
901
pLevel->op = OP_Next;
906
/* Case 5: The WHERE clause term that refers to the right-most
907
** column of the index is an inequality. For example, if
908
** the index is on (x,y,z) and the WHERE clause is of the
909
** form "x=5 AND y<10" then this case is used. Only the
910
** right-most column can be an inequality - the rest must
911
** use the "==" operator.
913
** This case is also used when there are no WHERE clause
914
** constraints but an index is selected anyway, in order
915
** to force the output order to conform to an ORDER BY.
917
int score = pLevel->score;
918
int nEqColumn = score/8;
923
/* Evaluate the equality constraints
925
for(j=0; j<nEqColumn; j++){
926
for(k=0; k<nExpr; k++){
927
if( aExpr[k].p==0 ) continue;
928
if( aExpr[k].idxLeft==iCur
929
&& aExpr[k].p->op==TK_EQ
930
&& (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
931
&& aExpr[k].p->pLeft->iColumn==pIdx->aiColumn[j]
933
sqliteExprCode(pParse, aExpr[k].p->pRight);
937
if( aExpr[k].idxRight==iCur
938
&& aExpr[k].p->op==TK_EQ
939
&& (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
940
&& aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
942
sqliteExprCode(pParse, aExpr[k].p->pLeft);
949
/* Duplicate the equality term values because they will all be
950
** used twice: once to make the termination key and once to make the
953
for(j=0; j<nEqColumn; j++){
954
sqliteVdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
957
/* Labels for the beginning and end of the loop
959
cont = pLevel->cont = sqliteVdbeMakeLabel(v);
960
brk = pLevel->brk = sqliteVdbeMakeLabel(v);
962
/* Generate the termination key. This is the key value that
963
** will end the search. There is no termination key if there
964
** are no equality terms and no "X<..." term.
966
** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
967
** key computed here really ends up being the start key.
969
if( (score & 1)!=0 ){
970
for(k=0; k<nExpr; k++){
971
Expr *pExpr = aExpr[k].p;
972
if( pExpr==0 ) continue;
973
if( aExpr[k].idxLeft==iCur
974
&& (pExpr->op==TK_LT || pExpr->op==TK_LE)
975
&& (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
976
&& pExpr->pLeft->iColumn==pIdx->aiColumn[j]
978
sqliteExprCode(pParse, pExpr->pRight);
979
leFlag = pExpr->op==TK_LE;
983
if( aExpr[k].idxRight==iCur
984
&& (pExpr->op==TK_GT || pExpr->op==TK_GE)
985
&& (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
986
&& pExpr->pRight->iColumn==pIdx->aiColumn[j]
988
sqliteExprCode(pParse, pExpr->pLeft);
989
leFlag = pExpr->op==TK_GE;
996
testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
999
if( testOp!=OP_Noop ){
1000
int nCol = nEqColumn + (score & 1);
1001
pLevel->iMem = pParse->nMem++;
1002
sqliteVdbeAddOp(v, OP_NotNull, -nCol, sqliteVdbeCurrentAddr(v)+3);
1003
sqliteVdbeAddOp(v, OP_Pop, nCol, 0);
1004
sqliteVdbeAddOp(v, OP_Goto, 0, brk);
1005
sqliteVdbeAddOp(v, OP_MakeKey, nCol, 0);
1006
sqliteAddIdxKeyType(v, pIdx);
1008
sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
1011
sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
1013
sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
1015
}else if( pLevel->bRev ){
1016
sqliteVdbeAddOp(v, OP_Last, pLevel->iCur, brk);
1019
/* Generate the start key. This is the key that defines the lower
1020
** bound on the search. There is no start key if there are no
1021
** equality terms and if there is no "X>..." term. In
1022
** that case, generate a "Rewind" instruction in place of the
1023
** start key search.
1025
** 2002-Dec-04: In the case of a reverse-order search, the so-called
1026
** "start" key really ends up being used as the termination key.
1028
if( (score & 2)!=0 ){
1029
for(k=0; k<nExpr; k++){
1030
Expr *pExpr = aExpr[k].p;
1031
if( pExpr==0 ) continue;
1032
if( aExpr[k].idxLeft==iCur
1033
&& (pExpr->op==TK_GT || pExpr->op==TK_GE)
1034
&& (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
1035
&& pExpr->pLeft->iColumn==pIdx->aiColumn[j]
1037
sqliteExprCode(pParse, pExpr->pRight);
1038
geFlag = pExpr->op==TK_GE;
1042
if( aExpr[k].idxRight==iCur
1043
&& (pExpr->op==TK_LT || pExpr->op==TK_LE)
1044
&& (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
1045
&& pExpr->pRight->iColumn==pIdx->aiColumn[j]
1047
sqliteExprCode(pParse, pExpr->pLeft);
1048
geFlag = pExpr->op==TK_LE;
1056
if( nEqColumn>0 || (score&2)!=0 ){
1057
int nCol = nEqColumn + ((score&2)!=0);
1058
sqliteVdbeAddOp(v, OP_NotNull, -nCol, sqliteVdbeCurrentAddr(v)+3);
1059
sqliteVdbeAddOp(v, OP_Pop, nCol, 0);
1060
sqliteVdbeAddOp(v, OP_Goto, 0, brk);
1061
sqliteVdbeAddOp(v, OP_MakeKey, nCol, 0);
1062
sqliteAddIdxKeyType(v, pIdx);
1064
sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
1067
pLevel->iMem = pParse->nMem++;
1068
sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
1071
sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
1073
}else if( pLevel->bRev ){
1076
sqliteVdbeAddOp(v, OP_Rewind, pLevel->iCur, brk);
1079
/* Generate the the top of the loop. If there is a termination
1080
** key we have to test for that key and abort at the top of the
1083
start = sqliteVdbeCurrentAddr(v);
1084
if( testOp!=OP_Noop ){
1085
sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1086
sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
1088
sqliteVdbeAddOp(v, OP_RowKey, pLevel->iCur, 0);
1089
sqliteVdbeAddOp(v, OP_IdxIsNull, nEqColumn + (score & 1), cont);
1090
sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
1091
if( i==pTabList->nSrc-1 && pushKey ){
1094
sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
1098
/* Record the instruction used to terminate the loop.
1100
pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
1101
pLevel->p1 = pLevel->iCur;
1104
loopMask |= getMask(&maskSet, iCur);
1106
/* Insert code to test every subexpression that can be completely
1107
** computed using the current set of tables.
1109
for(j=0; j<nExpr; j++){
1110
if( aExpr[j].p==0 ) continue;
1111
if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
1112
if( pLevel->iLeftJoin && !ExprHasProperty(aExpr[j].p,EP_FromJoin) ){
1117
sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
1119
sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
1124
/* For a LEFT OUTER JOIN, generate code that will record the fact that
1125
** at least one row of the right table has matched the left table.
1127
if( pLevel->iLeftJoin ){
1128
pLevel->top = sqliteVdbeCurrentAddr(v);
1129
sqliteVdbeAddOp(v, OP_Integer, 1, 0);
1130
sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
1131
for(j=0; j<nExpr; j++){
1132
if( aExpr[j].p==0 ) continue;
1133
if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
1135
/* Cannot happen. "haveKey" can only be true if pushKey is true
1136
** an pushKey can only be true for DELETE and UPDATE and there are
1137
** no outer joins with DELETE and UPDATE.
1140
sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
1142
sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
1147
pWInfo->iContinue = cont;
1148
if( pushKey && !haveKey ){
1149
sqliteVdbeAddOp(v, OP_Recno, pTabList->a[0].iCursor, 0);
1151
freeMaskSet(&maskSet);
1156
** Generate the end of the WHERE loop. See comments on
1157
** sqliteWhereBegin() for additional information.
1159
void sqliteWhereEnd(WhereInfo *pWInfo){
1160
Vdbe *v = pWInfo->pParse->pVdbe;
1163
SrcList *pTabList = pWInfo->pTabList;
1165
for(i=pTabList->nSrc-1; i>=0; i--){
1166
pLevel = &pWInfo->a[i];
1167
sqliteVdbeResolveLabel(v, pLevel->cont);
1168
if( pLevel->op!=OP_Noop ){
1169
sqliteVdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
1171
sqliteVdbeResolveLabel(v, pLevel->brk);
1172
if( pLevel->inOp!=OP_Noop ){
1173
sqliteVdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
1175
if( pLevel->iLeftJoin ){
1177
addr = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
1178
sqliteVdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iCur>=0));
1179
sqliteVdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
1180
if( pLevel->iCur>=0 ){
1181
sqliteVdbeAddOp(v, OP_NullRow, pLevel->iCur, 0);
1183
sqliteVdbeAddOp(v, OP_Goto, 0, pLevel->top);
1186
sqliteVdbeResolveLabel(v, pWInfo->iBreak);
1187
for(i=0; i<pTabList->nSrc; i++){
1188
Table *pTab = pTabList->a[i].pTab;
1190
if( pTab->isTransient || pTab->pSelect ) continue;
1191
pLevel = &pWInfo->a[i];
1192
sqliteVdbeAddOp(v, OP_Close, pTabList->a[i].iCursor, 0);
1193
if( pLevel->pIdx!=0 ){
1194
sqliteVdbeAddOp(v, OP_Close, pLevel->iCur, 0);
1197
#if 0 /* Never reuse a cursor */
1198
if( pWInfo->pParse->nTab==pWInfo->peakNTab ){
1199
pWInfo->pParse->nTab = pWInfo->savedNTab;