blob: 5082cdd24a5720fd2e1ef88efad2840b6e684cb4 [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
drh51669862004-12-18 18:40:26 +000013** the WHERE clause of SQL statements. This module is reponsible for
14** generating the code that loops through a table looking for applicable
15** rows. Indices are selected and used to speed the search when doing
16** so is applicable. Because this module is responsible for selecting
17** indices, you might also think of this module as the "query optimizer".
drh75897232000-05-29 14:26:00 +000018**
drhe23399f2005-07-22 00:31:39 +000019** $Id: where.c,v 1.151 2005/07/22 00:31:40 drh Exp $
drh75897232000-05-29 14:26:00 +000020*/
21#include "sqliteInt.h"
22
23/*
drh0aa74ed2005-07-16 13:33:20 +000024** The number of bits in a Bitmask. "BMS" means "BitMask Size".
25*/
drh29dda4a2005-07-21 18:23:20 +000026#define BMS (sizeof(Bitmask)*8)
drh0aa74ed2005-07-16 13:33:20 +000027
28/*
29** Determine the number of elements in an array.
30*/
31#define ARRAYSIZE(X) (sizeof(X)/sizeof(X[0]))
32
drh0fcef5e2005-07-19 17:38:22 +000033/* Forward reference
34*/
35typedef struct WhereClause WhereClause;
drh0aa74ed2005-07-16 13:33:20 +000036
37/*
drh75897232000-05-29 14:26:00 +000038** The query generator uses an array of instances of this structure to
39** help it analyze the subexpressions of the WHERE clause. Each WHERE
40** clause subexpression is separated from the others by an AND operator.
drh51669862004-12-18 18:40:26 +000041**
drh0fcef5e2005-07-19 17:38:22 +000042** All WhereTerms are collected into a single WhereClause structure.
43** The following identity holds:
drh51669862004-12-18 18:40:26 +000044**
drh0fcef5e2005-07-19 17:38:22 +000045** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
drh51669862004-12-18 18:40:26 +000046**
drh0fcef5e2005-07-19 17:38:22 +000047** When a term is of the form:
48**
49** X <op> <expr>
50**
51** where X is a column name and <op> is one of certain operators,
52** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
53** cursor number and column number for X.
54**
55** prereqRight and prereqAll record sets of cursor numbers,
drh51669862004-12-18 18:40:26 +000056** but they do so indirectly. A single ExprMaskSet structure translates
57** cursor number into bits and the translated bit is stored in the prereq
58** fields. The translation is used in order to maximize the number of
59** bits that will fit in a Bitmask. The VDBE cursor numbers might be
60** spread out over the non-negative integers. For example, the cursor
61** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The ExprMaskSet
62** translates these sparse cursor numbers into consecutive integers
63** beginning with 0 in order to make the best possible use of the available
64** bits in the Bitmask. So, in the example above, the cursor numbers
65** would be mapped into integers 0 through 7.
drh75897232000-05-29 14:26:00 +000066*/
drh0aa74ed2005-07-16 13:33:20 +000067typedef struct WhereTerm WhereTerm;
68struct WhereTerm {
drh0fcef5e2005-07-19 17:38:22 +000069 Expr *pExpr; /* Pointer to the subexpression */
70 u16 idx; /* Index of this term in pWC->a[] */
71 i16 iPartner; /* Disable pWC->a[iPartner] when this term disabled */
drh0aa74ed2005-07-16 13:33:20 +000072 u16 flags; /* Bit flags. See below */
drh0fcef5e2005-07-19 17:38:22 +000073 i16 leftCursor; /* Cursor number of X in "X <op> <expr>" */
74 i16 leftColumn; /* Column number of X in "X <op> <expr>" */
drhfe05af82005-07-21 03:14:59 +000075 u8 operator; /* A WO_xx value describing <op> */
drh0fcef5e2005-07-19 17:38:22 +000076 WhereClause *pWC; /* The clause this term is part of */
77 Bitmask prereqRight; /* Bitmask of tables used by pRight */
drh51669862004-12-18 18:40:26 +000078 Bitmask prereqAll; /* Bitmask of tables referenced by p */
drh75897232000-05-29 14:26:00 +000079};
80
81/*
drh0aa74ed2005-07-16 13:33:20 +000082** Allowed values of WhereTerm.flags
83*/
84#define TERM_DYNAMIC 0x0001 /* Need to call sqlite3ExprDelete(p) */
85#define TERM_VIRTUAL 0x0002 /* Added by the optimizer. Do not code */
drh0fcef5e2005-07-19 17:38:22 +000086#define TERM_CODED 0x0004 /* This term is already coded */
drh0aa74ed2005-07-16 13:33:20 +000087
88/*
89** An instance of the following structure holds all information about a
90** WHERE clause. Mostly this is a container for one or more WhereTerms.
91*/
drh0aa74ed2005-07-16 13:33:20 +000092struct WhereClause {
drhfe05af82005-07-21 03:14:59 +000093 Parse *pParse; /* The parser context */
drh0aa74ed2005-07-16 13:33:20 +000094 int nTerm; /* Number of terms */
95 int nSlot; /* Number of entries in a[] */
96 WhereTerm *a; /* Pointer to an array of terms */
97 WhereTerm aStatic[10]; /* Initial static space for the terms */
98};
99
100/*
drhe23399f2005-07-22 00:31:39 +0000101** When WhereTerms are used to select elements from an index, we
102** call those terms "constraints". For example, consider the following
103** SQL:
104**
105** CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, d);
106** CREATE INDEX t1i1 ON t1(b,c);
107**
108** SELECT * FROM t1 WHERE d=5 AND b=7 AND c>11;
109**
110** In the SELECT statement, the "b=7" and "c>11" terms are constraints
111** because they can be used to choose rows out of the t1i1 index. But
112** the "d=5" term is not a constraint because it is not indexed.
113**
114** When generating code to access an index, we have to keep track of
115** all of the constraints associated with that index. This is done
116** using an array of instanaces of the following structure. There is
117** one instance of this structure for each constraint on the index.
118**
119** Actually, we allocate the array of this structure based on the total
120** number of terms in the entire WHERE clause (because the number of
121** constraints can never be more than that) and reuse it when coding
122** each index.
123*/
124typedef struct WhereConstraint WhereConstraint;
125struct WhereConstraint {
126 int iMem; /* Mem cell used to hold <expr> part of constraint */
127};
128
129/*
drh6a3ea0e2003-05-02 14:32:12 +0000130** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000131** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000132**
133** The VDBE cursor numbers are small integers contained in
134** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
135** clause, the cursor numbers might not begin with 0 and they might
136** contain gaps in the numbering sequence. But we want to make maximum
137** use of the bits in our bitmasks. This structure provides a mapping
138** from the sparse cursor numbers into consecutive integers beginning
139** with 0.
140**
141** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
142** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
143**
144** For example, if the WHERE clause expression used these VDBE
145** cursors: 4, 5, 8, 29, 57, 73. Then the ExprMaskSet structure
146** would map those cursor numbers into bits 0 through 5.
147**
148** Note that the mapping is not necessarily ordered. In the example
149** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
150** 57->5, 73->4. Or one of 719 other combinations might be used. It
151** does not really matter. What is important is that sparse cursor
152** numbers all get mapped into bit numbers that begin with 0 and contain
153** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000154*/
155typedef struct ExprMaskSet ExprMaskSet;
156struct ExprMaskSet {
drh1398ad32005-01-19 23:24:50 +0000157 int n; /* Number of assigned cursor values */
158 int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000159};
160
drh0aa74ed2005-07-16 13:33:20 +0000161
drh6a3ea0e2003-05-02 14:32:12 +0000162/*
drh0aa74ed2005-07-16 13:33:20 +0000163** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000164*/
drhfe05af82005-07-21 03:14:59 +0000165static void whereClauseInit(WhereClause *pWC, Parse *pParse){
166 pWC->pParse = pParse;
drh0aa74ed2005-07-16 13:33:20 +0000167 pWC->nTerm = 0;
168 pWC->nSlot = ARRAYSIZE(pWC->aStatic);
169 pWC->a = pWC->aStatic;
170}
171
172/*
173** Deallocate a WhereClause structure. The WhereClause structure
174** itself is not freed. This routine is the inverse of whereClauseInit().
175*/
176static void whereClauseClear(WhereClause *pWC){
177 int i;
178 WhereTerm *a;
179 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
180 if( a->flags & TERM_DYNAMIC ){
drh0fcef5e2005-07-19 17:38:22 +0000181 sqlite3ExprDelete(a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000182 }
183 }
184 if( pWC->a!=pWC->aStatic ){
185 sqliteFree(pWC->a);
186 }
187}
188
189/*
190** Add a new entries to the WhereClause structure. Increase the allocated
191** space as necessary.
192*/
drh0fcef5e2005-07-19 17:38:22 +0000193static WhereTerm *whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
drh0aa74ed2005-07-16 13:33:20 +0000194 WhereTerm *pTerm;
195 if( pWC->nTerm>=pWC->nSlot ){
196 WhereTerm *pOld = pWC->a;
197 pWC->a = sqliteMalloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
drh0fcef5e2005-07-19 17:38:22 +0000198 if( pWC->a==0 ) return 0;
drh0aa74ed2005-07-16 13:33:20 +0000199 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
200 if( pOld!=pWC->aStatic ){
201 sqliteFree(pOld);
202 }
203 pWC->nSlot *= 2;
204 }
drh0fcef5e2005-07-19 17:38:22 +0000205 pTerm = &pWC->a[pWC->nTerm];
206 pTerm->idx = pWC->nTerm;
207 pWC->nTerm++;
208 pTerm->pExpr = p;
drh0aa74ed2005-07-16 13:33:20 +0000209 pTerm->flags = flags;
drh0fcef5e2005-07-19 17:38:22 +0000210 pTerm->pWC = pWC;
211 pTerm->iPartner = -1;
212 return pTerm;
drh0aa74ed2005-07-16 13:33:20 +0000213}
drh75897232000-05-29 14:26:00 +0000214
215/*
drh51669862004-12-18 18:40:26 +0000216** This routine identifies subexpressions in the WHERE clause where
217** each subexpression is separate by the AND operator. aSlot is
218** filled with pointers to the subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000219**
drh51669862004-12-18 18:40:26 +0000220** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
221** \________/ \_______________/ \________________/
222** slot[0] slot[1] slot[2]
223**
224** The original WHERE clause in pExpr is unaltered. All this routine
225** does is make aSlot[] entries point to substructure within pExpr.
226**
227** aSlot[] is an array of subexpressions structures. There are nSlot
228** spaces left in this array. This routine finds as many AND-separated
229** subexpressions as it can and puts pointers to those subexpressions
230** into aSlot[] entries. The return value is the number of slots filled.
drh75897232000-05-29 14:26:00 +0000231*/
drh0aa74ed2005-07-16 13:33:20 +0000232static void whereSplit(WhereClause *pWC, Expr *pExpr){
233 if( pExpr==0 ) return;
234 if( pExpr->op!=TK_AND ){
235 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000236 }else{
drh0aa74ed2005-07-16 13:33:20 +0000237 whereSplit(pWC, pExpr->pLeft);
238 whereSplit(pWC, pExpr->pRight);
drh75897232000-05-29 14:26:00 +0000239 }
drh75897232000-05-29 14:26:00 +0000240}
241
242/*
drh6a3ea0e2003-05-02 14:32:12 +0000243** Initialize an expression mask set
244*/
245#define initMaskSet(P) memset(P, 0, sizeof(*P))
246
247/*
drh1398ad32005-01-19 23:24:50 +0000248** Return the bitmask for the given cursor number. Return 0 if
249** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000250*/
drh51669862004-12-18 18:40:26 +0000251static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000252 int i;
253 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000254 if( pMaskSet->ix[i]==iCursor ){
255 return ((Bitmask)1)<<i;
256 }
drh6a3ea0e2003-05-02 14:32:12 +0000257 }
drh6a3ea0e2003-05-02 14:32:12 +0000258 return 0;
259}
260
261/*
drh1398ad32005-01-19 23:24:50 +0000262** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000263**
264** There is one cursor per table in the FROM clause. The number of
265** tables in the FROM clause is limited by a test early in the
266** sqlite3WhereBegin() routien. So we know that the pMaskSet->ix[]
267** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000268*/
269static void createMask(ExprMaskSet *pMaskSet, int iCursor){
drh0fcef5e2005-07-19 17:38:22 +0000270 assert( pMaskSet->n < ARRAYSIZE(pMaskSet->ix) );
271 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000272}
273
274/*
drh75897232000-05-29 14:26:00 +0000275** This routine walks (recursively) an expression tree and generates
276** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000277** tree.
drh75897232000-05-29 14:26:00 +0000278**
279** In order for this routine to work, the calling function must have
drh626a8792005-01-17 22:08:19 +0000280** previously invoked sqlite3ExprResolveNames() on the expression. See
drh75897232000-05-29 14:26:00 +0000281** the header comment on that routine for additional information.
drh626a8792005-01-17 22:08:19 +0000282** The sqlite3ExprResolveNames() routines looks for column names and
drh6a3ea0e2003-05-02 14:32:12 +0000283** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
284** the VDBE cursor number of the table.
drh75897232000-05-29 14:26:00 +0000285*/
danielk1977b3bce662005-01-29 08:32:43 +0000286static Bitmask exprListTableUsage(ExprMaskSet *, ExprList *);
drh51669862004-12-18 18:40:26 +0000287static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
288 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000289 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000290 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000291 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000292 return mask;
drh75897232000-05-29 14:26:00 +0000293 }
danielk1977b3bce662005-01-29 08:32:43 +0000294 mask = exprTableUsage(pMaskSet, p->pRight);
295 mask |= exprTableUsage(pMaskSet, p->pLeft);
296 mask |= exprListTableUsage(pMaskSet, p->pList);
297 if( p->pSelect ){
298 Select *pS = p->pSelect;
299 mask |= exprListTableUsage(pMaskSet, pS->pEList);
300 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
301 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
302 mask |= exprTableUsage(pMaskSet, pS->pWhere);
303 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drh75897232000-05-29 14:26:00 +0000304 }
danielk1977b3bce662005-01-29 08:32:43 +0000305 return mask;
306}
307static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
308 int i;
309 Bitmask mask = 0;
310 if( pList ){
311 for(i=0; i<pList->nExpr; i++){
312 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000313 }
314 }
drh75897232000-05-29 14:26:00 +0000315 return mask;
316}
317
318/*
drh487ab3c2001-11-08 00:45:21 +0000319** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000320** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000321** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000322*/
323static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000324 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
325 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
326 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
327 assert( TK_GE==TK_EQ+4 );
drh9a432672004-10-04 13:38:09 +0000328 return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
drh487ab3c2001-11-08 00:45:21 +0000329}
330
331/*
drh51669862004-12-18 18:40:26 +0000332** Swap two objects of type T.
drh193bd772004-07-20 18:23:14 +0000333*/
334#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
335
336/*
drh0fcef5e2005-07-19 17:38:22 +0000337** Commute a comparision operator. Expressions of the form "X op Y"
338** are converted into "Y op X".
drh193bd772004-07-20 18:23:14 +0000339*/
drh0fcef5e2005-07-19 17:38:22 +0000340static void exprCommute(Expr *pExpr){
drhfe05af82005-07-21 03:14:59 +0000341 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drh0fcef5e2005-07-19 17:38:22 +0000342 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
343 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
344 if( pExpr->op>=TK_GT ){
345 assert( TK_LT==TK_GT+2 );
346 assert( TK_GE==TK_LE+2 );
347 assert( TK_GT>TK_EQ );
348 assert( TK_GT<TK_LE );
349 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
350 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000351 }
drh193bd772004-07-20 18:23:14 +0000352}
353
354/*
drhfe05af82005-07-21 03:14:59 +0000355** Bitmasks for the operators that indices are able to exploit. An
356** OR-ed combination of these values can be used when searching for
357** terms in the where clause.
358*/
359#define WO_IN 1
360#define WO_EQ 2
361#define WO_LT (2<<(TK_LT-TK_EQ))
362#define WO_LE (2<<(TK_LE-TK_EQ))
363#define WO_GT (2<<(TK_GT-TK_EQ))
364#define WO_GE (2<<(TK_GE-TK_EQ))
365
366/*
367** Translate from TK_xx operator to WO_xx bitmask.
368*/
369static int operatorMask(int op){
370 assert( allowedOp(op) );
371 if( op==TK_IN ){
372 return WO_IN;
373 }else{
374 return 1<<(op+1-TK_EQ);
375 }
376}
377
378/*
379** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
380** where X is a reference to the iColumn of table iCur and <op> is one of
381** the WO_xx operator codes specified by the op parameter.
382** Return a pointer to the term. Return 0 if not found.
383*/
384static WhereTerm *findTerm(
385 WhereClause *pWC, /* The WHERE clause to be searched */
386 int iCur, /* Cursor number of LHS */
387 int iColumn, /* Column number of LHS */
388 Bitmask notReady, /* RHS must not overlap with this mask */
389 u8 op, /* Mask of WO_xx values describing operator */
390 Index *pIdx /* Must be compatible with this index, if not NULL */
391){
392 WhereTerm *pTerm;
393 int k;
394 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
395 if( pTerm->leftCursor==iCur
396 && (pTerm->prereqRight & notReady)==0
397 && pTerm->leftColumn==iColumn
398 && (pTerm->operator & op)!=0
399 ){
400 if( iCur>=0 && pIdx ){
401 Expr *pX = pTerm->pExpr;
402 CollSeq *pColl;
403 char idxaff;
404 int k;
405 Parse *pParse = pWC->pParse;
406
407 idxaff = pIdx->pTable->aCol[iColumn].affinity;
408 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
409 pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
410 if( !pColl ){
411 if( pX->pRight ){
412 pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
413 }
414 if( !pColl ){
415 pColl = pParse->db->pDfltColl;
416 }
417 }
418 for(k=0; k<pIdx->nColumn && pIdx->aiColumn[k]!=iColumn; k++){}
419 assert( k<pIdx->nColumn );
420 if( pColl!=pIdx->keyInfo.aColl[k] ) continue;
421 }
422 return pTerm;
423 }
424 }
425 return 0;
426}
427
428/*
drh0aa74ed2005-07-16 13:33:20 +0000429** The input to this routine is an WhereTerm structure with only the
drh75897232000-05-29 14:26:00 +0000430** "p" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +0000431** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +0000432** structure.
433*/
drh0fcef5e2005-07-19 17:38:22 +0000434static void exprAnalyze(
435 SrcList *pSrc, /* the FROM clause */
436 ExprMaskSet *pMaskSet, /* table masks */
437 WhereTerm *pTerm /* the WHERE clause term to be analyzed */
438){
439 Expr *pExpr = pTerm->pExpr;
440 Bitmask prereqLeft;
441 Bitmask prereqAll;
442 int idxRight;
443
444 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
445 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
446 pTerm->prereqAll = prereqAll = exprTableUsage(pMaskSet, pExpr);
447 pTerm->leftCursor = -1;
448 pTerm->iPartner = -1;
drhfe05af82005-07-21 03:14:59 +0000449 pTerm->operator = 0;
drh0fcef5e2005-07-19 17:38:22 +0000450 idxRight = -1;
451 if( allowedOp(pExpr->op) && (pTerm->prereqRight & prereqLeft)==0 ){
452 Expr *pLeft = pExpr->pLeft;
453 Expr *pRight = pExpr->pRight;
454 if( pLeft->op==TK_COLUMN ){
455 pTerm->leftCursor = pLeft->iTable;
456 pTerm->leftColumn = pLeft->iColumn;
drhfe05af82005-07-21 03:14:59 +0000457 pTerm->operator = operatorMask(pExpr->op);
drh75897232000-05-29 14:26:00 +0000458 }
drh0fcef5e2005-07-19 17:38:22 +0000459 if( pRight && pRight->op==TK_COLUMN ){
460 WhereTerm *pNew;
461 Expr *pDup;
462 if( pTerm->leftCursor>=0 ){
463 pDup = sqlite3ExprDup(pExpr);
464 pNew = whereClauseInsert(pTerm->pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
465 if( pNew==0 ) return;
466 pNew->iPartner = pTerm->idx;
467 }else{
468 pDup = pExpr;
469 pNew = pTerm;
470 }
471 exprCommute(pDup);
472 pLeft = pDup->pLeft;
473 pNew->leftCursor = pLeft->iTable;
474 pNew->leftColumn = pLeft->iColumn;
475 pNew->prereqRight = prereqLeft;
476 pNew->prereqAll = prereqAll;
drhfe05af82005-07-21 03:14:59 +0000477 pNew->operator = operatorMask(pDup->op);
drh75897232000-05-29 14:26:00 +0000478 }
479 }
480}
481
drh0fcef5e2005-07-19 17:38:22 +0000482
drh75897232000-05-29 14:26:00 +0000483/*
drh51669862004-12-18 18:40:26 +0000484** This routine decides if pIdx can be used to satisfy the ORDER BY
485** clause. If it can, it returns 1. If pIdx cannot satisfy the
486** ORDER BY clause, this routine returns 0.
487**
488** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
489** left-most table in the FROM clause of that same SELECT statement and
490** the table has a cursor number of "base". pIdx is an index on pTab.
491**
492** nEqCol is the number of columns of pIdx that are used as equality
493** constraints. Any of these columns may be missing from the ORDER BY
494** clause and the match can still be a success.
495**
496** If the index is UNIQUE, then the ORDER BY clause is allowed to have
497** additional terms past the end of the index and the match will still
498** be a success.
499**
500** All terms of the ORDER BY that match against the index must be either
501** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
502** index do not need to satisfy this constraint.) The *pbRev value is
503** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
504** the ORDER BY clause is all ASC.
505*/
506static int isSortingIndex(
507 Parse *pParse, /* Parsing context */
508 Index *pIdx, /* The index we are testing */
509 Table *pTab, /* The table to be sorted */
510 int base, /* Cursor number for pTab */
511 ExprList *pOrderBy, /* The ORDER BY clause */
512 int nEqCol, /* Number of index columns with == constraints */
513 int *pbRev /* Set to 1 if ORDER BY is DESC */
514){
515 int i, j; /* Loop counters */
516 int sortOrder; /* Which direction we are sorting */
517 int nTerm; /* Number of ORDER BY terms */
518 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
519 sqlite3 *db = pParse->db;
520
521 assert( pOrderBy!=0 );
522 nTerm = pOrderBy->nExpr;
523 assert( nTerm>0 );
524
525 /* Match terms of the ORDER BY clause against columns of
526 ** the index.
527 */
528 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
529 Expr *pExpr; /* The expression of the ORDER BY pTerm */
530 CollSeq *pColl; /* The collating sequence of pExpr */
531
532 pExpr = pTerm->pExpr;
533 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
534 /* Can not use an index sort on anything that is not a column in the
535 ** left-most table of the FROM clause */
536 return 0;
537 }
538 pColl = sqlite3ExprCollSeq(pParse, pExpr);
539 if( !pColl ) pColl = db->pDfltColl;
drh9012bcb2004-12-19 00:11:35 +0000540 if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
541 /* Term j of the ORDER BY clause does not match column i of the index */
542 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +0000543 /* If an index column that is constrained by == fails to match an
544 ** ORDER BY term, that is OK. Just ignore that column of the index
545 */
546 continue;
547 }else{
548 /* If an index column fails to match and is not constrained by ==
549 ** then the index cannot satisfy the ORDER BY constraint.
550 */
551 return 0;
552 }
553 }
554 if( i>nEqCol ){
555 if( pTerm->sortOrder!=sortOrder ){
556 /* Indices can only be used if all ORDER BY terms past the
557 ** equality constraints are all either DESC or ASC. */
558 return 0;
559 }
560 }else{
561 sortOrder = pTerm->sortOrder;
562 }
563 j++;
564 pTerm++;
565 }
566
567 /* The index can be used for sorting if all terms of the ORDER BY clause
568 ** or covered or if we ran out of index columns and the it is a UNIQUE
569 ** index.
570 */
571 if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
572 *pbRev = sortOrder==SQLITE_SO_DESC;
573 return 1;
574 }
575 return 0;
576}
577
578/*
drhb6c29892004-11-22 19:12:19 +0000579** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
580** by sorting in order of ROWID. Return true if so and set *pbRev to be
581** true for reverse ROWID and false for forward ROWID order.
582*/
583static int sortableByRowid(
584 int base, /* Cursor number for table to be sorted */
585 ExprList *pOrderBy, /* The ORDER BY clause */
586 int *pbRev /* Set to 1 if ORDER BY is DESC */
587){
588 Expr *p;
589
590 assert( pOrderBy!=0 );
591 assert( pOrderBy->nExpr>0 );
592 p = pOrderBy->a[0].pExpr;
593 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
594 *pbRev = pOrderBy->a[0].sortOrder;
595 return 1;
596 }
597 return 0;
598}
599
drhfe05af82005-07-21 03:14:59 +0000600/*
601** Value for flags returned by bestIndex()
602*/
drhe23399f2005-07-22 00:31:39 +0000603#define WHERE_ROWID_EQ 0x0001 /* rowid=EXPR or rowid IN (...) */
604#define WHERE_ROWID_RANGE 0x0002 /* rowid<EXPR and/or rowid>EXPR */
605#define WHERE_COLUMN_EQ 0x0004 /* x=EXPR or x IN (...) */
606#define WHERE_COLUMN_RANGE 0x0008 /* x<EXPR and/or x>EXPR */
607#define WHERE_SCAN 0x0010 /* Do a full table scan */
608#define WHERE_REVERSE 0x0020 /* Scan in reverse order */
609#define WHERE_ORDERBY 0x0040 /* Output will appear in correct order */
610#define WHERE_IDX_ONLY 0x0080 /* Use index only - omit table */
611#define WHERE_TOP_LIMIT 0x0100 /* x<EXPR or x<=EXPR constraint */
612#define WHERE_BTM_LIMIT 0x0200 /* x>EXPR or x>=EXPR constraint */
613#define WHERE_USES_IN 0x0400 /* True if the IN operator is used */
614#define WHERE_UNIQUE 0x0800 /* True if fully specifies a unique idx */
drhfe05af82005-07-21 03:14:59 +0000615
616/*
617** Find the best index for accessing a particular table. Return the index,
618** flags that describe how the index should be used, and the "score" for
619** this index.
620*/
621static double bestIndex(
622 Parse *pParse, /* The parsing context */
623 WhereClause *pWC, /* The WHERE clause */
624 struct SrcList_item *pSrc, /* The FROM clause term to search */
625 Bitmask notReady, /* Mask of cursors that are not available */
626 ExprList *pOrderBy, /* The order by clause */
627 Index **ppIndex, /* Make *ppIndex point to the best index */
628 int *pFlags /* Put flags describing this choice in *pFlags */
629){
630 WhereTerm *pTerm;
631 Index *pProbe;
632 Index *bestIdx = 0;
633 double bestScore = 0.0;
634 int bestFlags = 0;
635 int iCur = pSrc->iCursor;
636 int rev;
637
638 /* Check for a rowid=EXPR or rowid IN (...) constraint
639 */
640 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
641 if( pTerm ){
642 *ppIndex = 0;
643 if( pTerm->operator & WO_EQ ){
644 *pFlags = WHERE_ROWID_EQ;
645 if( pOrderBy ) *pFlags |= WHERE_ORDERBY;
646 return 1.0e10;
647 }else{
drhe23399f2005-07-22 00:31:39 +0000648 *pFlags = WHERE_ROWID_EQ | WHERE_USES_IN;
drhfe05af82005-07-21 03:14:59 +0000649 return 1.0e9;
650 }
651 }
652
653 /* Check for constraints on a range of rowids
654 */
655 pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
656 if( pTerm ){
657 int flags;
658 *ppIndex = 0;
659 if( pTerm->operator & (WO_LT|WO_LE) ){
660 flags = WHERE_ROWID_RANGE | WHERE_TOP_LIMIT;
661 if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
662 flags |= WHERE_BTM_LIMIT;
663 }
664 }else{
665 flags = WHERE_ROWID_RANGE | WHERE_BTM_LIMIT;
666 if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
667 flags |= WHERE_TOP_LIMIT;
668 }
669 }
670 if( pOrderBy && sortableByRowid(iCur, pOrderBy, &rev) ){
671 flags |= WHERE_ORDERBY;
672 if( rev ) flags |= WHERE_REVERSE;
673 }
674 bestScore = 99.0;
675 bestFlags = flags;
676 }
677
678 /* Look at each index.
679 */
680 for(pProbe=pSrc->pTab->pIndex; pProbe; pProbe=pProbe->pNext){
681 int i;
682 int nEq;
683 int usesIN = 0;
684 int flags;
685 double score = 0.0;
686
687 /* Count the number of columns in the index that are satisfied
688 ** by x=EXPR constraints or x IN (...) constraints.
689 */
690 for(i=0; i<pProbe->nColumn; i++){
691 int j = pProbe->aiColumn[i];
692 pTerm = findTerm(pWC, iCur, j, notReady, WO_EQ|WO_IN, pProbe);
693 if( pTerm==0 ) break;
694 if( pTerm->operator==WO_IN ){
695 if( i==0 ) usesIN = 1;
696 break;
697 }
698 }
699 nEq = i + usesIN;
700 score = i*100.0 + usesIN*50.0;
701
702 /* The optimization type is RANGE if there are no == or IN constraints
703 */
drhe23399f2005-07-22 00:31:39 +0000704 if( usesIN ){
705 flags = WHERE_COLUMN_EQ | WHERE_USES_IN;
706 }else if( nEq ){
drhfe05af82005-07-21 03:14:59 +0000707 flags = WHERE_COLUMN_EQ;
708 }else{
709 flags = WHERE_COLUMN_RANGE;
710 }
711
drhe23399f2005-07-22 00:31:39 +0000712 /* Check for a uniquely specified row
713 */
714#if 0
715 if( nEq==pProbe->nColumn && pProbe->isUnique ){
716 flags |= WHERE_UNIQUE;
717 }
718#endif
719
drhfe05af82005-07-21 03:14:59 +0000720 /* Look for range constraints
721 */
722 if( !usesIN && nEq<pProbe->nColumn ){
723 int j = pProbe->aiColumn[nEq];
724 pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
725 if( pTerm ){
726 score += 20.0;
727 flags = WHERE_COLUMN_RANGE;
728 if( pTerm->operator & (WO_LT|WO_LE) ){
729 flags |= WHERE_TOP_LIMIT;
730 if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
731 flags |= WHERE_BTM_LIMIT;
732 score += 20.0;
733 }
734 }else{
735 flags |= WHERE_BTM_LIMIT;
736 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
737 flags |= WHERE_TOP_LIMIT;
738 score += 20;
739 }
740 }
741 }
742 }
743
744 /* Add extra points if this index can be used to satisfy the ORDER BY
745 ** clause
746 */
747 if( pOrderBy && !usesIN &&
748 isSortingIndex(pParse, pProbe, pSrc->pTab, iCur, pOrderBy, nEq, &rev) ){
749 flags |= WHERE_ORDERBY;
750 score += 10.0;
751 if( rev ) flags |= WHERE_REVERSE;
752 }
753
754 /* Check to see if we can get away with using just the index without
755 ** ever reading the table. If that is the case, then add one bonus
756 ** point to the score.
757 */
758 if( score>0.0 && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
759 Bitmask m = pSrc->colUsed;
760 int j;
761 for(j=0; j<pProbe->nColumn; j++){
762 int x = pProbe->aiColumn[j];
763 if( x<BMS-1 ){
764 m &= ~(((Bitmask)1)<<x);
765 }
766 }
767 if( m==0 ){
768 flags |= WHERE_IDX_ONLY;
769 score += 5;
770 }
771 }
772
773 /* If this index has achieved the best score so far, then use it.
774 */
775 if( score>bestScore ){
776 bestIdx = pProbe;
777 bestScore = score;
778 bestFlags = flags;
779 }
780 }
781
782 /* Disable sorting if we are coming out in rowid order
783 */
784 if( bestIdx==0 && pOrderBy && sortableByRowid(iCur, pOrderBy, &rev) ){
785 bestFlags |= WHERE_ORDERBY;
786 if( rev ) bestFlags |= WHERE_REVERSE;
787 }
788
789
790 /* Report the best result
791 */
792 *ppIndex = bestIdx;
793 *pFlags = bestFlags;
794 return bestScore;
795}
796
drhb6c29892004-11-22 19:12:19 +0000797
798/*
drh2ffb1182004-07-19 19:14:01 +0000799** Disable a term in the WHERE clause. Except, do not disable the term
800** if it controls a LEFT OUTER JOIN and it did not originate in the ON
801** or USING clause of that join.
802**
803** Consider the term t2.z='ok' in the following queries:
804**
805** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
806** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
807** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
808**
drh23bf66d2004-12-14 03:34:34 +0000809** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +0000810** in the ON clause. The term is disabled in (3) because it is not part
811** of a LEFT OUTER JOIN. In (1), the term is not disabled.
812**
813** Disabling a term causes that term to not be tested in the inner loop
814** of the join. Disabling is an optimization. We would get the correct
815** results if nothing were ever disabled, but joins might run a little
816** slower. The trick is to disable as much as we can without disabling
817** too much. If we disabled in (1), we'd get the wrong answer.
818** See ticket #813.
819*/
drh0fcef5e2005-07-19 17:38:22 +0000820static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
821 if( pTerm
822 && (pTerm->flags & TERM_CODED)==0
823 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
824 ){
825 pTerm->flags |= TERM_CODED;
826 if( pTerm->iPartner>=0 ){
827 disableTerm(pLevel, &pTerm->pWC->a[pTerm->iPartner]);
828 }
drh2ffb1182004-07-19 19:14:01 +0000829 }
830}
831
832/*
drh94a11212004-09-25 13:12:14 +0000833** Generate code that builds a probe for an index. Details:
834**
835** * Check the top nColumn entries on the stack. If any
836** of those entries are NULL, jump immediately to brk,
837** which is the loop exit, since no index entry will match
838** if any part of the key is NULL.
839**
840** * Construct a probe entry from the top nColumn entries in
841** the stack with affinities appropriate for index pIdx.
842*/
843static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
844 sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
845 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
846 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
847 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
848 sqlite3IndexAffinityStr(v, pIdx);
849}
850
drhe8b97272005-07-19 22:22:12 +0000851
852/*
drh94a11212004-09-25 13:12:14 +0000853** Generate code for an equality term of the WHERE clause. An equality
854** term can be either X=expr or X IN (...). pTerm is the X.
855*/
856static void codeEqualityTerm(
857 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +0000858 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh94a11212004-09-25 13:12:14 +0000859 int brk, /* Jump here to abandon the loop */
860 WhereLevel *pLevel /* When level of the FROM clause we are working on */
861){
drh0fcef5e2005-07-19 17:38:22 +0000862 Expr *pX = pTerm->pExpr;
drh94a11212004-09-25 13:12:14 +0000863 if( pX->op!=TK_IN ){
864 assert( pX->op==TK_EQ );
865 sqlite3ExprCode(pParse, pX->pRight);
danielk1977b3bce662005-01-29 08:32:43 +0000866#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +0000867 }else{
danielk1977b3bce662005-01-29 08:32:43 +0000868 int iTab;
drhe23399f2005-07-22 00:31:39 +0000869 int *aIn;
drh94a11212004-09-25 13:12:14 +0000870 Vdbe *v = pParse->pVdbe;
danielk1977b3bce662005-01-29 08:32:43 +0000871
872 sqlite3CodeSubselect(pParse, pX);
873 iTab = pX->iTable;
drh94a11212004-09-25 13:12:14 +0000874 sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
danielk1977b3bce662005-01-29 08:32:43 +0000875 VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
drhe23399f2005-07-22 00:31:39 +0000876 pLevel->nIn++;
877 pLevel->aInLoop = aIn = sqliteRealloc(pLevel->aInLoop,
878 sizeof(pLevel->aInLoop[0])*3*pLevel->nIn);
879 if( aIn ){
880 aIn += pLevel->nIn*3 - 3;
881 aIn[0] = OP_Next;
882 aIn[1] = iTab;
883 aIn[2] = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
884 }
danielk1977b3bce662005-01-29 08:32:43 +0000885#endif
drh94a11212004-09-25 13:12:14 +0000886 }
drh0fcef5e2005-07-19 17:38:22 +0000887 disableTerm(pLevel, pTerm);
drh94a11212004-09-25 13:12:14 +0000888}
889
drh84bfda42005-07-15 13:05:21 +0000890#ifdef SQLITE_TEST
891/*
892** The following variable holds a text description of query plan generated
893** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
894** overwrites the previous. This information is used for testing and
895** analysis only.
896*/
897char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
898static int nQPlan = 0; /* Next free slow in _query_plan[] */
899
900#endif /* SQLITE_TEST */
901
902
drh94a11212004-09-25 13:12:14 +0000903
904/*
drhe3184742002-06-19 14:27:05 +0000905** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +0000906** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +0000907** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +0000908** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +0000909** in order to complete the WHERE clause processing.
910**
911** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +0000912**
913** The basic idea is to do a nested loop, one loop for each table in
914** the FROM clause of a select. (INSERT and UPDATE statements are the
915** same as a SELECT with only a single table in the FROM clause.) For
916** example, if the SQL is this:
917**
918** SELECT * FROM t1, t2, t3 WHERE ...;
919**
920** Then the code generated is conceptually like the following:
921**
922** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000923** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +0000924** foreach row3 in t3 do /
925** ...
926** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000927** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +0000928** end /
929**
drh29dda4a2005-07-21 18:23:20 +0000930** Note that the loops might not be nested in the order in which they
931** appear in the FROM clause if a different order is better able to make
932** use of indices.
933**
drhc27a1ce2002-06-14 20:58:45 +0000934** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +0000935** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
936** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +0000937** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +0000938**
drhe6f85e72004-12-25 01:03:13 +0000939** The code that sqlite3WhereBegin() generates leaves the cursors named
940** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +0000941** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +0000942** data from the various tables of the loop.
943**
drhc27a1ce2002-06-14 20:58:45 +0000944** If the WHERE clause is empty, the foreach loops must each scan their
945** entire tables. Thus a three-way join is an O(N^3) operation. But if
946** the tables have indices and there are terms in the WHERE clause that
947** refer to those indices, a complete table scan can be avoided and the
948** code will run much faster. Most of the work of this routine is checking
949** to see if there are indices that can be used to speed up the loop.
950**
951** Terms of the WHERE clause are also used to limit which rows actually
952** make it to the "..." in the middle of the loop. After each "foreach",
953** terms of the WHERE clause that use only terms in that loop and outer
954** loops are evaluated and if false a jump is made around all subsequent
955** inner loops (or around the "..." if the test occurs within the inner-
956** most loop)
957**
958** OUTER JOINS
959**
960** An outer join of tables t1 and t2 is conceptally coded as follows:
961**
962** foreach row1 in t1 do
963** flag = 0
964** foreach row2 in t2 do
965** start:
966** ...
967** flag = 1
968** end
drhe3184742002-06-19 14:27:05 +0000969** if flag==0 then
970** move the row2 cursor to a null row
971** goto start
972** fi
drhc27a1ce2002-06-14 20:58:45 +0000973** end
974**
drhe3184742002-06-19 14:27:05 +0000975** ORDER BY CLAUSE PROCESSING
976**
977** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
978** if there is one. If there is no ORDER BY clause or if this routine
979** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
980**
981** If an index can be used so that the natural output order of the table
982** scan is correct for the ORDER BY clause, then that index is used and
983** *ppOrderBy is set to NULL. This is an optimization that prevents an
984** unnecessary sort of the result set if an index appropriate for the
985** ORDER BY clause already exists.
986**
987** If the where clause loops cannot be arranged to provide the correct
988** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +0000989*/
danielk19774adee202004-05-08 08:23:19 +0000990WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +0000991 Parse *pParse, /* The parser context */
992 SrcList *pTabList, /* A list of all tables to be scanned */
993 Expr *pWhere, /* The WHERE clause */
drhf8db1bc2005-04-22 02:38:37 +0000994 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +0000995){
996 int i; /* Loop counter */
997 WhereInfo *pWInfo; /* Will become the return value of this function */
998 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhd4f5ee22003-07-16 00:54:31 +0000999 int brk, cont = 0; /* Addresses used during code generation */
drhfe05af82005-07-21 03:14:59 +00001000 Bitmask notReady; /* Cursors that are not yet positioned */
drh0aa74ed2005-07-16 13:33:20 +00001001 WhereTerm *pTerm; /* A single term in the WHERE clause */
1002 ExprMaskSet maskSet; /* The expression mask set */
drh0aa74ed2005-07-16 13:33:20 +00001003 WhereClause wc; /* The WHERE clause is divided into these terms */
drh9012bcb2004-12-19 00:11:35 +00001004 struct SrcList_item *pTabItem; /* A single entry from pTabList */
1005 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh29dda4a2005-07-21 18:23:20 +00001006 int iFrom; /* First unused FROM clause element */
drhe23399f2005-07-22 00:31:39 +00001007 WhereConstraint *aConstraint; /* Information on constraints */
drh75897232000-05-29 14:26:00 +00001008
drh29dda4a2005-07-21 18:23:20 +00001009 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00001010 ** bits in a Bitmask
1011 */
drh29dda4a2005-07-21 18:23:20 +00001012 if( pTabList->nSrc>BMS ){
1013 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00001014 return 0;
1015 }
1016
drh83dcb1a2002-06-28 01:02:38 +00001017 /* Split the WHERE clause into separate subexpressions where each
drh29dda4a2005-07-21 18:23:20 +00001018 ** subexpression is separated by an AND operator.
drh83dcb1a2002-06-28 01:02:38 +00001019 */
drh6a3ea0e2003-05-02 14:32:12 +00001020 initMaskSet(&maskSet);
drhfe05af82005-07-21 03:14:59 +00001021 whereClauseInit(&wc, pParse);
drh0aa74ed2005-07-16 13:33:20 +00001022 whereSplit(&wc, pWhere);
drh1398ad32005-01-19 23:24:50 +00001023
drh75897232000-05-29 14:26:00 +00001024 /* Allocate and initialize the WhereInfo structure that will become the
1025 ** return value.
1026 */
drhad3cab52002-05-24 02:04:32 +00001027 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
danielk1977132872b2004-05-10 10:37:18 +00001028 if( sqlite3_malloc_failed ){
drhe23399f2005-07-22 00:31:39 +00001029 goto whereBeginNoMem;
drh75897232000-05-29 14:26:00 +00001030 }
1031 pWInfo->pParse = pParse;
1032 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +00001033 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh08192d52002-04-30 19:20:28 +00001034
1035 /* Special case: a WHERE clause that is constant. Evaluate the
1036 ** expression and either jump over all of the code or fall thru.
1037 */
danielk19774adee202004-05-08 08:23:19 +00001038 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
1039 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +00001040 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00001041 }
drh75897232000-05-29 14:26:00 +00001042
drh29dda4a2005-07-21 18:23:20 +00001043 /* Analyze all of the subexpressions. Note that exprAnalyze() might
1044 ** add new virtual terms onto the end of the WHERE clause. We do not
1045 ** want to analyze these virtual terms, so start analyzing at the end
1046 ** and work forward so that they added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00001047 */
drh1398ad32005-01-19 23:24:50 +00001048 for(i=0; i<pTabList->nSrc; i++){
1049 createMask(&maskSet, pTabList->a[i].iCursor);
1050 }
drh0fcef5e2005-07-19 17:38:22 +00001051 for(i=wc.nTerm-1; i>=0; i--){
1052 exprAnalyze(pTabList, &maskSet, &wc.a[i]);
drh75897232000-05-29 14:26:00 +00001053 }
drhe23399f2005-07-22 00:31:39 +00001054 aConstraint = sqliteMalloc( wc.nTerm*sizeof(aConstraint[0]) );
1055 if( aConstraint==0 && wc.nTerm>0 ){
1056 goto whereBeginNoMem;
1057 }
drh75897232000-05-29 14:26:00 +00001058
drh29dda4a2005-07-21 18:23:20 +00001059 /* Chose the best index to use for each table in the FROM clause.
1060 **
1061 ** This loop fills in the pWInfo->a[].pIdx and pWInfo->a[].flags fields
1062 ** with information
1063 ** Reorder tables if necessary in order to choose a good ordering.
1064 ** However, LEFT JOIN tables cannot be reordered.
drh75897232000-05-29 14:26:00 +00001065 */
drhfe05af82005-07-21 03:14:59 +00001066 notReady = ~(Bitmask)0;
drh9012bcb2004-12-19 00:11:35 +00001067 pTabItem = pTabList->a;
1068 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001069 for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1070 Index *pIdx; /* Index for FROM table at pTabItem */
1071 int flags; /* Flags asssociated with pIdx */
1072 double score; /* The score for pIdx */
1073 int j; /* For looping over FROM tables */
1074 Index *pBest = 0; /* The best index seen so far */
1075 int bestFlags = 0; /* Flags associated with pBest */
1076 double bestScore = -1.0; /* The score of pBest */
1077 int bestJ; /* The value of j */
1078 Bitmask m; /* Bitmask value for j or bestJ */
1079
1080 for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
1081 m = getMask(&maskSet, pTabItem->iCursor);
1082 if( (m & notReady)==0 ){
1083 if( j==iFrom ) iFrom++;
1084 continue;
1085 }
1086 score = bestIndex(pParse, &wc, pTabItem, notReady,
1087 (j==0 && ppOrderBy) ? *ppOrderBy : 0,
1088 &pIdx, &flags);
1089 if( score>bestScore ){
1090 bestScore = score;
1091 pBest = pIdx;
1092 bestFlags = flags;
1093 bestJ = j;
1094 }
1095 if( (pTabItem->jointype & JT_LEFT)!=0
1096 || (j>0 && (pTabItem[-1].jointype & JT_LEFT)!=0)
1097 ){
1098 break;
1099 }
1100 }
1101 if( bestFlags & WHERE_ORDERBY ){
drhfe05af82005-07-21 03:14:59 +00001102 *ppOrderBy = 0;
drhc4a3c772001-04-04 11:48:57 +00001103 }
drh29dda4a2005-07-21 18:23:20 +00001104 pLevel->flags = bestFlags;
drhfe05af82005-07-21 03:14:59 +00001105 pLevel->pIdx = pBest;
drhe23399f2005-07-22 00:31:39 +00001106 pLevel->aInLoop = 0;
1107 pLevel->nIn = 0;
drhfe05af82005-07-21 03:14:59 +00001108 if( pBest ){
drh9012bcb2004-12-19 00:11:35 +00001109 pLevel->iIdxCur = pParse->nTab++;
drhfe05af82005-07-21 03:14:59 +00001110 }else{
1111 pLevel->iIdxCur = -1;
drh6b563442001-11-07 16:48:26 +00001112 }
drh29dda4a2005-07-21 18:23:20 +00001113 notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
1114 pLevel->iFrom = bestJ;
drh75897232000-05-29 14:26:00 +00001115 }
1116
drh9012bcb2004-12-19 00:11:35 +00001117 /* Open all tables in the pTabList and any indices selected for
1118 ** searching those tables.
1119 */
1120 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
1121 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001122 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drh9012bcb2004-12-19 00:11:35 +00001123 Table *pTab;
1124 Index *pIx;
1125 int iIdxCur = pLevel->iIdxCur;
1126
drh29dda4a2005-07-21 18:23:20 +00001127 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001128 pTab = pTabItem->pTab;
1129 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001130 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001131 sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
1132 }
1133 pLevel->iTabCur = pTabItem->iCursor;
1134 if( (pIx = pLevel->pIdx)!=0 ){
1135 sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
drh29dda4a2005-07-21 18:23:20 +00001136 VdbeComment((v, "# %s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00001137 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
1138 (char*)&pIx->keyInfo, P3_KEYINFO);
1139 }
drhfe05af82005-07-21 03:14:59 +00001140 if( (pLevel->flags & WHERE_IDX_ONLY)!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001141 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
1142 }
1143 sqlite3CodeVerifySchema(pParse, pTab->iDb);
1144 }
1145 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
1146
drh29dda4a2005-07-21 18:23:20 +00001147 /* Generate the code to do the search. Each iteration of the for
1148 ** loop below generates code for a single nested loop of the VM
1149 ** program.
drh75897232000-05-29 14:26:00 +00001150 */
drhfe05af82005-07-21 03:14:59 +00001151 notReady = ~(Bitmask)0;
drh29dda4a2005-07-21 18:23:20 +00001152 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drhfe05af82005-07-21 03:14:59 +00001153 int j;
drh9012bcb2004-12-19 00:11:35 +00001154 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
1155 Index *pIdx; /* The index we will be using */
1156 int iIdxCur; /* The VDBE cursor for the index */
1157 int omitTable; /* True if we use the index only */
drh29dda4a2005-07-21 18:23:20 +00001158 int bRev; /* True if we need to scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001159
drh29dda4a2005-07-21 18:23:20 +00001160 pTabItem = &pTabList->a[pLevel->iFrom];
1161 iCur = pTabItem->iCursor;
drh9012bcb2004-12-19 00:11:35 +00001162 pIdx = pLevel->pIdx;
1163 iIdxCur = pLevel->iIdxCur;
drh29dda4a2005-07-21 18:23:20 +00001164 bRev = (pLevel->flags & WHERE_REVERSE)!=0;
drhfe05af82005-07-21 03:14:59 +00001165 omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
drh75897232000-05-29 14:26:00 +00001166
drh29dda4a2005-07-21 18:23:20 +00001167 /* Create labels for the "break" and "continue" instructions
1168 ** for the current loop. Jump to brk to break out of a loop.
1169 ** Jump to cont to go immediately to the next iteration of the
1170 ** loop.
1171 */
1172 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1173 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1174
drhad2d8302002-05-24 20:31:36 +00001175 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +00001176 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +00001177 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +00001178 */
drh29dda4a2005-07-21 18:23:20 +00001179 if( pLevel->iFrom>0 && (pTabItem[-1].jointype & JT_LEFT)!=0 ){
drhad2d8302002-05-24 20:31:36 +00001180 if( !pParse->nMem ) pParse->nMem++;
1181 pLevel->iLeftJoin = pParse->nMem++;
drhf0863fe2005-06-12 21:35:51 +00001182 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001183 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001184 VdbeComment((v, "# init LEFT JOIN no-match flag"));
drhad2d8302002-05-24 20:31:36 +00001185 }
1186
drhfe05af82005-07-21 03:14:59 +00001187 if( pLevel->flags & WHERE_ROWID_EQ ){
drh8aff1012001-12-22 14:49:24 +00001188 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +00001189 ** equality comparison against the ROWID field. Or
1190 ** we reference multiple rows using a "rowid IN (...)"
1191 ** construct.
drhc4a3c772001-04-04 11:48:57 +00001192 */
drhfe05af82005-07-21 03:14:59 +00001193 pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1194 assert( pTerm!=0 );
drh0fcef5e2005-07-19 17:38:22 +00001195 assert( pTerm->pExpr!=0 );
1196 assert( pTerm->leftCursor==iCur );
drh9012bcb2004-12-19 00:11:35 +00001197 assert( omitTable==0 );
drh94a11212004-09-25 13:12:14 +00001198 codeEqualityTerm(pParse, pTerm, brk, pLevel);
danielk19774adee202004-05-08 08:23:19 +00001199 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
danielk19774adee202004-05-08 08:23:19 +00001200 sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001201 VdbeComment((v, "pk"));
drh6b563442001-11-07 16:48:26 +00001202 pLevel->op = OP_Noop;
drhfe05af82005-07-21 03:14:59 +00001203 }else if( pLevel->flags & WHERE_COLUMN_EQ ){
drhc27a1ce2002-06-14 20:58:45 +00001204 /* Case 2: There is an index and all terms of the WHERE clause that
drhb6c29892004-11-22 19:12:19 +00001205 ** refer to the index using the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +00001206 */
drh6b563442001-11-07 16:48:26 +00001207 int start;
drhfe05af82005-07-21 03:14:59 +00001208 int nColumn;
drh772ae622004-05-19 13:13:08 +00001209
1210 /* For each column of the index, find the term of the WHERE clause that
1211 ** constraints that column. If the WHERE clause term is X=expr, then
drh0aa74ed2005-07-16 13:33:20 +00001212 ** generate code to evaluate expr and leave the result on the stack */
drhfe05af82005-07-21 03:14:59 +00001213 for(j=0; 1; j++){
1214 int k = pIdx->aiColumn[j];
1215 pTerm = findTerm(&wc, iCur, k, notReady, WO_EQ|WO_IN, pIdx);
1216 if( pTerm==0 ) break;
1217 if( pTerm->operator==WO_IN && j>0 ) break;
drhe8b97272005-07-19 22:22:12 +00001218 assert( (pTerm->flags & TERM_CODED)==0 );
1219 codeEqualityTerm(pParse, pTerm, brk, pLevel);
drhfe05af82005-07-21 03:14:59 +00001220 if( pTerm->operator==WO_IN ){
1221 j++;
1222 break;
1223 }
drh75897232000-05-29 14:26:00 +00001224 }
drhfe05af82005-07-21 03:14:59 +00001225 nColumn = j;
drh6b563442001-11-07 16:48:26 +00001226 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001227 buildIndexProbe(v, nColumn, brk, pIdx);
danielk19773d1bfea2004-05-14 11:00:53 +00001228 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
drh772ae622004-05-19 13:13:08 +00001229
drh772ae622004-05-19 13:13:08 +00001230 /* Generate code (1) to move to the first matching element of the table.
1231 ** Then generate code (2) that jumps to "brk" after the cursor is past
1232 ** the last matching element of the table. The code (1) is executed
1233 ** once to initialize the search, the code (2) is executed before each
1234 ** iteration of the scan to see if the scan has finished. */
drh29dda4a2005-07-21 18:23:20 +00001235 if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001236 /* Scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001237 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001238 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001239 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001240 pLevel->op = OP_Prev;
1241 }else{
1242 /* Scan in the forward order */
drh9012bcb2004-12-19 00:11:35 +00001243 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001244 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001245 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
drhc045ec52002-12-04 20:01:06 +00001246 pLevel->op = OP_Next;
1247 }
drh9012bcb2004-12-19 00:11:35 +00001248 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001249 sqlite3VdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
drhe6f85e72004-12-25 01:03:13 +00001250 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001251 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001252 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh75897232000-05-29 14:26:00 +00001253 }
drh9012bcb2004-12-19 00:11:35 +00001254 pLevel->p1 = iIdxCur;
drh6b563442001-11-07 16:48:26 +00001255 pLevel->p2 = start;
drhfe05af82005-07-21 03:14:59 +00001256 }else if( pLevel->flags & WHERE_ROWID_RANGE ){
drh8aff1012001-12-22 14:49:24 +00001257 /* Case 3: We have an inequality comparison against the ROWID field.
1258 */
1259 int testOp = OP_Noop;
1260 int start;
drhfe05af82005-07-21 03:14:59 +00001261 WhereTerm *pStart, *pEnd;
drh8aff1012001-12-22 14:49:24 +00001262
drh9012bcb2004-12-19 00:11:35 +00001263 assert( omitTable==0 );
drhfe05af82005-07-21 03:14:59 +00001264 if( pLevel->flags & WHERE_BTM_LIMIT ){
1265 pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
1266 assert( pStart!=0 );
1267 }else{
1268 pStart = 0;
drhb6c29892004-11-22 19:12:19 +00001269 }
drhfe05af82005-07-21 03:14:59 +00001270 if( pLevel->flags & WHERE_TOP_LIMIT ){
1271 pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
1272 assert( pEnd!=0 );
1273 }else{
1274 pEnd = 0;
1275 }
1276 assert( pStart!=0 || pEnd!=0 );
1277 if( bRev ){
1278 pTerm = pStart;
1279 pStart = pEnd;
1280 pEnd = pTerm;
1281 }
1282 if( pStart ){
drh94a11212004-09-25 13:12:14 +00001283 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001284 pX = pStart->pExpr;
drh94a11212004-09-25 13:12:14 +00001285 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001286 assert( pStart->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001287 sqlite3ExprCode(pParse, pX->pRight);
danielk1977d0a69322005-02-02 01:10:44 +00001288 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
drhb6c29892004-11-22 19:12:19 +00001289 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001290 VdbeComment((v, "pk"));
drhfe05af82005-07-21 03:14:59 +00001291 disableTerm(pLevel, pStart);
drh8aff1012001-12-22 14:49:24 +00001292 }else{
drhb6c29892004-11-22 19:12:19 +00001293 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
drh8aff1012001-12-22 14:49:24 +00001294 }
drhfe05af82005-07-21 03:14:59 +00001295 if( pEnd ){
drh94a11212004-09-25 13:12:14 +00001296 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001297 pX = pEnd->pExpr;
drh94a11212004-09-25 13:12:14 +00001298 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001299 assert( pEnd->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001300 sqlite3ExprCode(pParse, pX->pRight);
drh8aff1012001-12-22 14:49:24 +00001301 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001302 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drh94a11212004-09-25 13:12:14 +00001303 if( pX->op==TK_LT || pX->op==TK_GT ){
drhb6c29892004-11-22 19:12:19 +00001304 testOp = bRev ? OP_Le : OP_Ge;
drh8aff1012001-12-22 14:49:24 +00001305 }else{
drhb6c29892004-11-22 19:12:19 +00001306 testOp = bRev ? OP_Lt : OP_Gt;
drh8aff1012001-12-22 14:49:24 +00001307 }
drhfe05af82005-07-21 03:14:59 +00001308 disableTerm(pLevel, pEnd);
drh8aff1012001-12-22 14:49:24 +00001309 }
danielk19774adee202004-05-08 08:23:19 +00001310 start = sqlite3VdbeCurrentAddr(v);
drhb6c29892004-11-22 19:12:19 +00001311 pLevel->op = bRev ? OP_Prev : OP_Next;
drh6a3ea0e2003-05-02 14:32:12 +00001312 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001313 pLevel->p2 = start;
1314 if( testOp!=OP_Noop ){
drhf0863fe2005-06-12 21:35:51 +00001315 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001316 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drhf0863fe2005-06-12 21:35:51 +00001317 sqlite3VdbeAddOp(v, testOp, 'n', brk);
drh8aff1012001-12-22 14:49:24 +00001318 }
drhfe05af82005-07-21 03:14:59 +00001319 }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
1320 /* Case 4: The WHERE clause term that refers to the right-most
drhc27a1ce2002-06-14 20:58:45 +00001321 ** column of the index is an inequality. For example, if
1322 ** the index is on (x,y,z) and the WHERE clause is of the
1323 ** form "x=5 AND y<10" then this case is used. Only the
1324 ** right-most column can be an inequality - the rest must
1325 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +00001326 **
1327 ** This case is also used when there are no WHERE clause
1328 ** constraints but an index is selected anyway, in order
1329 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +00001330 */
drhfe05af82005-07-21 03:14:59 +00001331 int nEqColumn;
drh487ab3c2001-11-08 00:45:21 +00001332 int start;
danielk1977f7df9cc2004-06-16 12:02:47 +00001333 int leFlag=0, geFlag=0;
drh487ab3c2001-11-08 00:45:21 +00001334 int testOp;
drhfe05af82005-07-21 03:14:59 +00001335 int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
1336 int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
drh487ab3c2001-11-08 00:45:21 +00001337
1338 /* Evaluate the equality constraints
1339 */
drhfe05af82005-07-21 03:14:59 +00001340 for(j=0; 1; j++){
1341 int k = pIdx->aiColumn[j];
1342 pTerm = findTerm(&wc, iCur, k, notReady, WO_EQ, pIdx);
1343 if( pTerm==0 ) break;
drhe8b97272005-07-19 22:22:12 +00001344 assert( (pTerm->flags & TERM_CODED)==0 );
1345 sqlite3ExprCode(pParse, pTerm->pExpr->pRight);
1346 disableTerm(pLevel, pTerm);
drh487ab3c2001-11-08 00:45:21 +00001347 }
drhfe05af82005-07-21 03:14:59 +00001348 nEqColumn = j;
drh487ab3c2001-11-08 00:45:21 +00001349
drhc27a1ce2002-06-14 20:58:45 +00001350 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +00001351 ** used twice: once to make the termination key and once to make the
1352 ** start key.
1353 */
1354 for(j=0; j<nEqColumn; j++){
danielk19774adee202004-05-08 08:23:19 +00001355 sqlite3VdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
drh487ab3c2001-11-08 00:45:21 +00001356 }
1357
1358 /* Generate the termination key. This is the key value that
1359 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +00001360 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +00001361 **
1362 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1363 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +00001364 */
drhfe05af82005-07-21 03:14:59 +00001365 if( topLimit ){
drhe8b97272005-07-19 22:22:12 +00001366 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001367 int k = pIdx->aiColumn[j];
1368 pTerm = findTerm(&wc, iCur, k, notReady, WO_LT|WO_LE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001369 assert( pTerm!=0 );
1370 pX = pTerm->pExpr;
1371 assert( (pTerm->flags & TERM_CODED)==0 );
1372 sqlite3ExprCode(pParse, pX->pRight);
1373 leFlag = pX->op==TK_LE;
1374 disableTerm(pLevel, pTerm);
drh487ab3c2001-11-08 00:45:21 +00001375 testOp = OP_IdxGE;
1376 }else{
1377 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
1378 leFlag = 1;
1379 }
1380 if( testOp!=OP_Noop ){
drhfe05af82005-07-21 03:14:59 +00001381 int nCol = nEqColumn + topLimit;
drh487ab3c2001-11-08 00:45:21 +00001382 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001383 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001384 if( bRev ){
drh7cf6e4d2004-05-19 14:56:55 +00001385 int op = leFlag ? OP_MoveLe : OP_MoveLt;
drh9012bcb2004-12-19 00:11:35 +00001386 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001387 }else{
danielk19774adee202004-05-08 08:23:19 +00001388 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001389 }
drhfe05af82005-07-21 03:14:59 +00001390 }else if( bRev ){
drh9012bcb2004-12-19 00:11:35 +00001391 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001392 }
1393
1394 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001395 ** bound on the search. There is no start key if there are no
1396 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001397 ** that case, generate a "Rewind" instruction in place of the
1398 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001399 **
1400 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1401 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001402 */
drhfe05af82005-07-21 03:14:59 +00001403 if( btmLimit ){
drhe8b97272005-07-19 22:22:12 +00001404 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001405 int k = pIdx->aiColumn[j];
1406 pTerm = findTerm(&wc, iCur, k, notReady, WO_GT|WO_GE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001407 assert( pTerm!=0 );
1408 pX = pTerm->pExpr;
1409 assert( (pTerm->flags & TERM_CODED)==0 );
1410 sqlite3ExprCode(pParse, pX->pRight);
1411 geFlag = pX->op==TK_GE;
1412 disableTerm(pLevel, pTerm);
drh7900ead2001-11-12 13:51:43 +00001413 }else{
1414 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001415 }
drhfe05af82005-07-21 03:14:59 +00001416 if( nEqColumn>0 || btmLimit ){
1417 int nCol = nEqColumn + btmLimit;
drh94a11212004-09-25 13:12:14 +00001418 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001419 if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001420 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001421 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001422 testOp = OP_IdxLT;
1423 }else{
drh7cf6e4d2004-05-19 14:56:55 +00001424 int op = geFlag ? OP_MoveGe : OP_MoveGt;
drh9012bcb2004-12-19 00:11:35 +00001425 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001426 }
drhfe05af82005-07-21 03:14:59 +00001427 }else if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001428 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001429 }else{
drh9012bcb2004-12-19 00:11:35 +00001430 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001431 }
1432
1433 /* Generate the the top of the loop. If there is a termination
1434 ** key we have to test for that key and abort at the top of the
1435 ** loop.
1436 */
danielk19774adee202004-05-08 08:23:19 +00001437 start = sqlite3VdbeCurrentAddr(v);
drh487ab3c2001-11-08 00:45:21 +00001438 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001439 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001440 sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
drhfe05af82005-07-21 03:14:59 +00001441 if( (leFlag && !bRev) || (!geFlag && bRev) ){
danielk19773d1bfea2004-05-14 11:00:53 +00001442 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
1443 }
drh487ab3c2001-11-08 00:45:21 +00001444 }
drh9012bcb2004-12-19 00:11:35 +00001445 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
drhfe05af82005-07-21 03:14:59 +00001446 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEqColumn + topLimit, cont);
drhe6f85e72004-12-25 01:03:13 +00001447 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001448 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001449 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh487ab3c2001-11-08 00:45:21 +00001450 }
1451
1452 /* Record the instruction used to terminate the loop.
1453 */
drhfe05af82005-07-21 03:14:59 +00001454 pLevel->op = bRev ? OP_Prev : OP_Next;
drh9012bcb2004-12-19 00:11:35 +00001455 pLevel->p1 = iIdxCur;
drh487ab3c2001-11-08 00:45:21 +00001456 pLevel->p2 = start;
drhfe05af82005-07-21 03:14:59 +00001457 }else{
1458 /* Case 5: There is no usable index. We must do a complete
1459 ** scan of the entire table.
1460 */
drhfe05af82005-07-21 03:14:59 +00001461 int opRewind;
1462
1463 assert( omitTable==0 );
drh29dda4a2005-07-21 18:23:20 +00001464 if( bRev ){
drhfe05af82005-07-21 03:14:59 +00001465 opRewind = OP_Last;
1466 pLevel->op = OP_Prev;
1467 }else{
1468 opRewind = OP_Rewind;
1469 pLevel->op = OP_Next;
1470 }
drhfe05af82005-07-21 03:14:59 +00001471 pLevel->p1 = iCur;
drh29dda4a2005-07-21 18:23:20 +00001472 pLevel->p2 = 1 + sqlite3VdbeAddOp(v, opRewind, iCur, brk);
drh75897232000-05-29 14:26:00 +00001473 }
drhfe05af82005-07-21 03:14:59 +00001474 notReady &= ~getMask(&maskSet, iCur);
drh75897232000-05-29 14:26:00 +00001475
1476 /* Insert code to test every subexpression that can be completely
1477 ** computed using the current set of tables.
1478 */
drh0fcef5e2005-07-19 17:38:22 +00001479 for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
1480 Expr *pE;
1481 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001482 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001483 pE = pTerm->pExpr;
1484 assert( pE!=0 );
drh392e5972005-07-08 14:14:22 +00001485 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
drh1f162302002-10-27 19:35:33 +00001486 continue;
1487 }
drh392e5972005-07-08 14:14:22 +00001488 sqlite3ExprIfFalse(pParse, pE, cont, 1);
drh0fcef5e2005-07-19 17:38:22 +00001489 pTerm->flags |= TERM_CODED;
drh75897232000-05-29 14:26:00 +00001490 }
drhad2d8302002-05-24 20:31:36 +00001491
1492 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1493 ** at least one row of the right table has matched the left table.
1494 */
1495 if( pLevel->iLeftJoin ){
danielk19774adee202004-05-08 08:23:19 +00001496 pLevel->top = sqlite3VdbeCurrentAddr(v);
1497 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1498 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001499 VdbeComment((v, "# record LEFT JOIN hit"));
drh0aa74ed2005-07-16 13:33:20 +00001500 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
drh0fcef5e2005-07-19 17:38:22 +00001501 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001502 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001503 assert( pTerm->pExpr );
1504 sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
1505 pTerm->flags |= TERM_CODED;
drh1cc093c2002-06-24 22:01:57 +00001506 }
drhad2d8302002-05-24 20:31:36 +00001507 }
drh75897232000-05-29 14:26:00 +00001508 }
drh7ec764a2005-07-21 03:48:20 +00001509
1510#ifdef SQLITE_TEST /* For testing and debugging use only */
1511 /* Record in the query plan information about the current table
1512 ** and the index used to access it (if any). If the table itself
1513 ** is not used, its name is just '{}'. If no index is used
1514 ** the index is listed as "{}". If the primary key is used the
1515 ** index name is '*'.
1516 */
1517 for(i=0; i<pTabList->nSrc; i++){
1518 char *z;
1519 int n;
drh7ec764a2005-07-21 03:48:20 +00001520 pLevel = &pWInfo->a[i];
drh29dda4a2005-07-21 18:23:20 +00001521 pTabItem = &pTabList->a[pLevel->iFrom];
drh7ec764a2005-07-21 03:48:20 +00001522 z = pTabItem->zAlias;
1523 if( z==0 ) z = pTabItem->pTab->zName;
1524 n = strlen(z);
1525 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
1526 if( pLevel->flags & WHERE_IDX_ONLY ){
1527 strcpy(&sqlite3_query_plan[nQPlan], "{}");
1528 nQPlan += 2;
1529 }else{
1530 strcpy(&sqlite3_query_plan[nQPlan], z);
1531 nQPlan += n;
1532 }
1533 sqlite3_query_plan[nQPlan++] = ' ';
1534 }
1535 if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
1536 strcpy(&sqlite3_query_plan[nQPlan], "* ");
1537 nQPlan += 2;
1538 }else if( pLevel->pIdx==0 ){
1539 strcpy(&sqlite3_query_plan[nQPlan], "{} ");
1540 nQPlan += 3;
1541 }else{
1542 n = strlen(pLevel->pIdx->zName);
1543 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
1544 strcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName);
1545 nQPlan += n;
1546 sqlite3_query_plan[nQPlan++] = ' ';
1547 }
1548 }
1549 }
1550 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
1551 sqlite3_query_plan[--nQPlan] = 0;
1552 }
1553 sqlite3_query_plan[nQPlan] = 0;
1554 nQPlan = 0;
1555#endif /* SQLITE_TEST // Testing and debugging use only */
1556
drh29dda4a2005-07-21 18:23:20 +00001557 /* Record the continuation address in the WhereInfo structure. Then
1558 ** clean up and return.
1559 */
drh75897232000-05-29 14:26:00 +00001560 pWInfo->iContinue = cont;
drh0aa74ed2005-07-16 13:33:20 +00001561 whereClauseClear(&wc);
drhe23399f2005-07-22 00:31:39 +00001562 sqliteFree(aConstraint);
drh75897232000-05-29 14:26:00 +00001563 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00001564
1565 /* Jump here if malloc fails */
1566whereBeginNoMem:
1567 whereClauseClear(&wc);
1568 sqliteFree(pWInfo);
1569 return 0;
drh75897232000-05-29 14:26:00 +00001570}
1571
1572/*
drhc27a1ce2002-06-14 20:58:45 +00001573** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00001574** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001575*/
danielk19774adee202004-05-08 08:23:19 +00001576void sqlite3WhereEnd(WhereInfo *pWInfo){
drh75897232000-05-29 14:26:00 +00001577 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001578 int i;
drh6b563442001-11-07 16:48:26 +00001579 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001580 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001581
drh9012bcb2004-12-19 00:11:35 +00001582 /* Generate loop termination code.
1583 */
drhad3cab52002-05-24 02:04:32 +00001584 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001585 pLevel = &pWInfo->a[i];
danielk19774adee202004-05-08 08:23:19 +00001586 sqlite3VdbeResolveLabel(v, pLevel->cont);
drh6b563442001-11-07 16:48:26 +00001587 if( pLevel->op!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001588 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001589 }
danielk19774adee202004-05-08 08:23:19 +00001590 sqlite3VdbeResolveLabel(v, pLevel->brk);
drhe23399f2005-07-22 00:31:39 +00001591 if( pLevel->nIn ){
1592 int *a;
1593 int j;
1594 for(j=pLevel->nIn, a=&pLevel->aInLoop[j*3-3]; j>0; j--, a-=3){
1595 sqlite3VdbeAddOp(v, a[0], a[1], a[2]);
1596 }
1597 sqliteFree(pLevel->aInLoop);
drhd99f7062002-06-08 23:25:08 +00001598 }
drhad2d8302002-05-24 20:31:36 +00001599 if( pLevel->iLeftJoin ){
1600 int addr;
danielk19774adee202004-05-08 08:23:19 +00001601 addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh9012bcb2004-12-19 00:11:35 +00001602 sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
danielk19774adee202004-05-08 08:23:19 +00001603 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
drh9012bcb2004-12-19 00:11:35 +00001604 if( pLevel->iIdxCur>=0 ){
1605 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
drh7f09b3e2002-08-13 13:15:49 +00001606 }
danielk19774adee202004-05-08 08:23:19 +00001607 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
drhad2d8302002-05-24 20:31:36 +00001608 }
drh19a775c2000-06-05 18:54:46 +00001609 }
drh9012bcb2004-12-19 00:11:35 +00001610
1611 /* The "break" point is here, just past the end of the outer loop.
1612 ** Set it.
1613 */
danielk19774adee202004-05-08 08:23:19 +00001614 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00001615
drh29dda4a2005-07-21 18:23:20 +00001616 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00001617 */
drh29dda4a2005-07-21 18:23:20 +00001618 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1619 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001620 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00001621 assert( pTab!=0 );
1622 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001623 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001624 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
1625 }
drh6b563442001-11-07 16:48:26 +00001626 if( pLevel->pIdx!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001627 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
1628 }
1629
drhacf3b982005-01-03 01:27:18 +00001630 /* Make cursor substitutions for cases where we want to use
drh9012bcb2004-12-19 00:11:35 +00001631 ** just the index and never reference the table.
1632 **
1633 ** Calls to the code generator in between sqlite3WhereBegin and
1634 ** sqlite3WhereEnd will have created code that references the table
1635 ** directly. This loop scans all that code looking for opcodes
1636 ** that reference the table and converts them into opcodes that
1637 ** reference the index.
1638 */
drhfe05af82005-07-21 03:14:59 +00001639 if( pLevel->flags & WHERE_IDX_ONLY ){
drh9012bcb2004-12-19 00:11:35 +00001640 int i, j, last;
1641 VdbeOp *pOp;
1642 Index *pIdx = pLevel->pIdx;
1643
1644 assert( pIdx!=0 );
1645 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1646 last = sqlite3VdbeCurrentAddr(v);
1647 for(i=pWInfo->iTop; i<last; i++, pOp++){
1648 if( pOp->p1!=pLevel->iTabCur ) continue;
1649 if( pOp->opcode==OP_Column ){
1650 pOp->p1 = pLevel->iIdxCur;
1651 for(j=0; j<pIdx->nColumn; j++){
1652 if( pOp->p2==pIdx->aiColumn[j] ){
1653 pOp->p2 = j;
1654 break;
1655 }
1656 }
drhf0863fe2005-06-12 21:35:51 +00001657 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00001658 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00001659 pOp->opcode = OP_IdxRowid;
danielk19776c18b6e2005-01-30 09:17:58 +00001660 }else if( pOp->opcode==OP_NullRow ){
1661 pOp->opcode = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001662 }
1663 }
drh6b563442001-11-07 16:48:26 +00001664 }
drh19a775c2000-06-05 18:54:46 +00001665 }
drh9012bcb2004-12-19 00:11:35 +00001666
1667 /* Final cleanup
1668 */
drh75897232000-05-29 14:26:00 +00001669 sqliteFree(pWInfo);
1670 return;
1671}