blob: e376543ca59c64409d0b4b5504e4578e2c36412c [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**
drhfe05af82005-07-21 03:14:59 +000019** $Id: where.c,v 1.148 2005/07/21 03:15:00 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*/
26#define BMS (sizeof(Bitmask)*8-1)
27
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/*
drhfe05af82005-07-21 03:14:59 +000038** An instance of the following structure holds information about how well
39** a particular index helps in a search. A list of such structures is
40** attached to each SrcList_item of a SrcList.
41*/
42struct WhereIdx {
43 Index *pIdx; /* The index under consideration */
44 Bitmask prereq; /* Prerequesite FROM clause elements for using this index */
45 int nEqTerm; /* Number of Idx column constrainted by == or IN */
46 int nTerm; /* Total number of Index Columns used */
47 int flags; /* Flags. See below */
48 double rRowEst; /* Estimated number of rows selected */
49 double rScore; /* Score of this index */
50 WhereIdx *pNext; /* Next WhereIdx on the same FROM clause element */
51};
52
53/*
drh75897232000-05-29 14:26:00 +000054** The query generator uses an array of instances of this structure to
55** help it analyze the subexpressions of the WHERE clause. Each WHERE
56** clause subexpression is separated from the others by an AND operator.
drh51669862004-12-18 18:40:26 +000057**
drh0fcef5e2005-07-19 17:38:22 +000058** All WhereTerms are collected into a single WhereClause structure.
59** The following identity holds:
drh51669862004-12-18 18:40:26 +000060**
drh0fcef5e2005-07-19 17:38:22 +000061** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
drh51669862004-12-18 18:40:26 +000062**
drh0fcef5e2005-07-19 17:38:22 +000063** When a term is of the form:
64**
65** X <op> <expr>
66**
67** where X is a column name and <op> is one of certain operators,
68** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
69** cursor number and column number for X.
70**
71** prereqRight and prereqAll record sets of cursor numbers,
drh51669862004-12-18 18:40:26 +000072** but they do so indirectly. A single ExprMaskSet structure translates
73** cursor number into bits and the translated bit is stored in the prereq
74** fields. The translation is used in order to maximize the number of
75** bits that will fit in a Bitmask. The VDBE cursor numbers might be
76** spread out over the non-negative integers. For example, the cursor
77** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The ExprMaskSet
78** translates these sparse cursor numbers into consecutive integers
79** beginning with 0 in order to make the best possible use of the available
80** bits in the Bitmask. So, in the example above, the cursor numbers
81** would be mapped into integers 0 through 7.
drh75897232000-05-29 14:26:00 +000082*/
drh0aa74ed2005-07-16 13:33:20 +000083typedef struct WhereTerm WhereTerm;
84struct WhereTerm {
drh0fcef5e2005-07-19 17:38:22 +000085 Expr *pExpr; /* Pointer to the subexpression */
86 u16 idx; /* Index of this term in pWC->a[] */
87 i16 iPartner; /* Disable pWC->a[iPartner] when this term disabled */
drh0aa74ed2005-07-16 13:33:20 +000088 u16 flags; /* Bit flags. See below */
drh0fcef5e2005-07-19 17:38:22 +000089 i16 leftCursor; /* Cursor number of X in "X <op> <expr>" */
90 i16 leftColumn; /* Column number of X in "X <op> <expr>" */
drhfe05af82005-07-21 03:14:59 +000091 u8 operator; /* A WO_xx value describing <op> */
drh0fcef5e2005-07-19 17:38:22 +000092 WhereClause *pWC; /* The clause this term is part of */
93 Bitmask prereqRight; /* Bitmask of tables used by pRight */
drh51669862004-12-18 18:40:26 +000094 Bitmask prereqAll; /* Bitmask of tables referenced by p */
drh75897232000-05-29 14:26:00 +000095};
96
97/*
drh0aa74ed2005-07-16 13:33:20 +000098** Allowed values of WhereTerm.flags
99*/
100#define TERM_DYNAMIC 0x0001 /* Need to call sqlite3ExprDelete(p) */
101#define TERM_VIRTUAL 0x0002 /* Added by the optimizer. Do not code */
drh0fcef5e2005-07-19 17:38:22 +0000102#define TERM_CODED 0x0004 /* This term is already coded */
drh0aa74ed2005-07-16 13:33:20 +0000103
104/*
105** An instance of the following structure holds all information about a
106** WHERE clause. Mostly this is a container for one or more WhereTerms.
107*/
drh0aa74ed2005-07-16 13:33:20 +0000108struct WhereClause {
drhfe05af82005-07-21 03:14:59 +0000109 Parse *pParse; /* The parser context */
drh0aa74ed2005-07-16 13:33:20 +0000110 int nTerm; /* Number of terms */
111 int nSlot; /* Number of entries in a[] */
112 WhereTerm *a; /* Pointer to an array of terms */
113 WhereTerm aStatic[10]; /* Initial static space for the terms */
114};
115
116/*
drh6a3ea0e2003-05-02 14:32:12 +0000117** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000118** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000119**
120** The VDBE cursor numbers are small integers contained in
121** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
122** clause, the cursor numbers might not begin with 0 and they might
123** contain gaps in the numbering sequence. But we want to make maximum
124** use of the bits in our bitmasks. This structure provides a mapping
125** from the sparse cursor numbers into consecutive integers beginning
126** with 0.
127**
128** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
129** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
130**
131** For example, if the WHERE clause expression used these VDBE
132** cursors: 4, 5, 8, 29, 57, 73. Then the ExprMaskSet structure
133** would map those cursor numbers into bits 0 through 5.
134**
135** Note that the mapping is not necessarily ordered. In the example
136** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
137** 57->5, 73->4. Or one of 719 other combinations might be used. It
138** does not really matter. What is important is that sparse cursor
139** numbers all get mapped into bit numbers that begin with 0 and contain
140** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000141*/
142typedef struct ExprMaskSet ExprMaskSet;
143struct ExprMaskSet {
drh1398ad32005-01-19 23:24:50 +0000144 int n; /* Number of assigned cursor values */
145 int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000146};
147
drh0aa74ed2005-07-16 13:33:20 +0000148
drh6a3ea0e2003-05-02 14:32:12 +0000149/*
drh0aa74ed2005-07-16 13:33:20 +0000150** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000151*/
drhfe05af82005-07-21 03:14:59 +0000152static void whereClauseInit(WhereClause *pWC, Parse *pParse){
153 pWC->pParse = pParse;
drh0aa74ed2005-07-16 13:33:20 +0000154 pWC->nTerm = 0;
155 pWC->nSlot = ARRAYSIZE(pWC->aStatic);
156 pWC->a = pWC->aStatic;
157}
158
159/*
160** Deallocate a WhereClause structure. The WhereClause structure
161** itself is not freed. This routine is the inverse of whereClauseInit().
162*/
163static void whereClauseClear(WhereClause *pWC){
164 int i;
165 WhereTerm *a;
166 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
167 if( a->flags & TERM_DYNAMIC ){
drh0fcef5e2005-07-19 17:38:22 +0000168 sqlite3ExprDelete(a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000169 }
170 }
171 if( pWC->a!=pWC->aStatic ){
172 sqliteFree(pWC->a);
173 }
174}
175
176/*
177** Add a new entries to the WhereClause structure. Increase the allocated
178** space as necessary.
179*/
drh0fcef5e2005-07-19 17:38:22 +0000180static WhereTerm *whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
drh0aa74ed2005-07-16 13:33:20 +0000181 WhereTerm *pTerm;
182 if( pWC->nTerm>=pWC->nSlot ){
183 WhereTerm *pOld = pWC->a;
184 pWC->a = sqliteMalloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
drh0fcef5e2005-07-19 17:38:22 +0000185 if( pWC->a==0 ) return 0;
drh0aa74ed2005-07-16 13:33:20 +0000186 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
187 if( pOld!=pWC->aStatic ){
188 sqliteFree(pOld);
189 }
190 pWC->nSlot *= 2;
191 }
drh0fcef5e2005-07-19 17:38:22 +0000192 pTerm = &pWC->a[pWC->nTerm];
193 pTerm->idx = pWC->nTerm;
194 pWC->nTerm++;
195 pTerm->pExpr = p;
drh0aa74ed2005-07-16 13:33:20 +0000196 pTerm->flags = flags;
drh0fcef5e2005-07-19 17:38:22 +0000197 pTerm->pWC = pWC;
198 pTerm->iPartner = -1;
199 return pTerm;
drh0aa74ed2005-07-16 13:33:20 +0000200}
drh75897232000-05-29 14:26:00 +0000201
202/*
drh51669862004-12-18 18:40:26 +0000203** This routine identifies subexpressions in the WHERE clause where
204** each subexpression is separate by the AND operator. aSlot is
205** filled with pointers to the subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000206**
drh51669862004-12-18 18:40:26 +0000207** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
208** \________/ \_______________/ \________________/
209** slot[0] slot[1] slot[2]
210**
211** The original WHERE clause in pExpr is unaltered. All this routine
212** does is make aSlot[] entries point to substructure within pExpr.
213**
214** aSlot[] is an array of subexpressions structures. There are nSlot
215** spaces left in this array. This routine finds as many AND-separated
216** subexpressions as it can and puts pointers to those subexpressions
217** into aSlot[] entries. The return value is the number of slots filled.
drh75897232000-05-29 14:26:00 +0000218*/
drh0aa74ed2005-07-16 13:33:20 +0000219static void whereSplit(WhereClause *pWC, Expr *pExpr){
220 if( pExpr==0 ) return;
221 if( pExpr->op!=TK_AND ){
222 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000223 }else{
drh0aa74ed2005-07-16 13:33:20 +0000224 whereSplit(pWC, pExpr->pLeft);
225 whereSplit(pWC, pExpr->pRight);
drh75897232000-05-29 14:26:00 +0000226 }
drh75897232000-05-29 14:26:00 +0000227}
228
229/*
drh6a3ea0e2003-05-02 14:32:12 +0000230** Initialize an expression mask set
231*/
232#define initMaskSet(P) memset(P, 0, sizeof(*P))
233
234/*
drh1398ad32005-01-19 23:24:50 +0000235** Return the bitmask for the given cursor number. Return 0 if
236** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000237*/
drh51669862004-12-18 18:40:26 +0000238static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000239 int i;
240 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000241 if( pMaskSet->ix[i]==iCursor ){
242 return ((Bitmask)1)<<i;
243 }
drh6a3ea0e2003-05-02 14:32:12 +0000244 }
drh6a3ea0e2003-05-02 14:32:12 +0000245 return 0;
246}
247
248/*
drh1398ad32005-01-19 23:24:50 +0000249** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000250**
251** There is one cursor per table in the FROM clause. The number of
252** tables in the FROM clause is limited by a test early in the
253** sqlite3WhereBegin() routien. So we know that the pMaskSet->ix[]
254** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000255*/
256static void createMask(ExprMaskSet *pMaskSet, int iCursor){
drh0fcef5e2005-07-19 17:38:22 +0000257 assert( pMaskSet->n < ARRAYSIZE(pMaskSet->ix) );
258 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000259}
260
261/*
drh6a3ea0e2003-05-02 14:32:12 +0000262** Destroy an expression mask set
263*/
264#define freeMaskSet(P) /* NO-OP */
265
266/*
drh75897232000-05-29 14:26:00 +0000267** This routine walks (recursively) an expression tree and generates
268** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000269** tree.
drh75897232000-05-29 14:26:00 +0000270**
271** In order for this routine to work, the calling function must have
drh626a8792005-01-17 22:08:19 +0000272** previously invoked sqlite3ExprResolveNames() on the expression. See
drh75897232000-05-29 14:26:00 +0000273** the header comment on that routine for additional information.
drh626a8792005-01-17 22:08:19 +0000274** The sqlite3ExprResolveNames() routines looks for column names and
drh6a3ea0e2003-05-02 14:32:12 +0000275** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
276** the VDBE cursor number of the table.
drh75897232000-05-29 14:26:00 +0000277*/
danielk1977b3bce662005-01-29 08:32:43 +0000278static Bitmask exprListTableUsage(ExprMaskSet *, ExprList *);
drh51669862004-12-18 18:40:26 +0000279static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
280 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000281 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000282 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000283 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000284 return mask;
drh75897232000-05-29 14:26:00 +0000285 }
danielk1977b3bce662005-01-29 08:32:43 +0000286 mask = exprTableUsage(pMaskSet, p->pRight);
287 mask |= exprTableUsage(pMaskSet, p->pLeft);
288 mask |= exprListTableUsage(pMaskSet, p->pList);
289 if( p->pSelect ){
290 Select *pS = p->pSelect;
291 mask |= exprListTableUsage(pMaskSet, pS->pEList);
292 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
293 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
294 mask |= exprTableUsage(pMaskSet, pS->pWhere);
295 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drh75897232000-05-29 14:26:00 +0000296 }
danielk1977b3bce662005-01-29 08:32:43 +0000297 return mask;
298}
299static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
300 int i;
301 Bitmask mask = 0;
302 if( pList ){
303 for(i=0; i<pList->nExpr; i++){
304 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000305 }
306 }
drh75897232000-05-29 14:26:00 +0000307 return mask;
308}
309
310/*
drh487ab3c2001-11-08 00:45:21 +0000311** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000312** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000313** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000314*/
315static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000316 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
317 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
318 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
319 assert( TK_GE==TK_EQ+4 );
drh9a432672004-10-04 13:38:09 +0000320 return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
drh487ab3c2001-11-08 00:45:21 +0000321}
322
323/*
drh51669862004-12-18 18:40:26 +0000324** Swap two objects of type T.
drh193bd772004-07-20 18:23:14 +0000325*/
326#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
327
328/*
drh0fcef5e2005-07-19 17:38:22 +0000329** Commute a comparision operator. Expressions of the form "X op Y"
330** are converted into "Y op X".
drh193bd772004-07-20 18:23:14 +0000331*/
drh0fcef5e2005-07-19 17:38:22 +0000332static void exprCommute(Expr *pExpr){
drhfe05af82005-07-21 03:14:59 +0000333 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drh0fcef5e2005-07-19 17:38:22 +0000334 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
335 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
336 if( pExpr->op>=TK_GT ){
337 assert( TK_LT==TK_GT+2 );
338 assert( TK_GE==TK_LE+2 );
339 assert( TK_GT>TK_EQ );
340 assert( TK_GT<TK_LE );
341 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
342 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000343 }
drh193bd772004-07-20 18:23:14 +0000344}
345
346/*
drhfe05af82005-07-21 03:14:59 +0000347** Bitmasks for the operators that indices are able to exploit. An
348** OR-ed combination of these values can be used when searching for
349** terms in the where clause.
350*/
351#define WO_IN 1
352#define WO_EQ 2
353#define WO_LT (2<<(TK_LT-TK_EQ))
354#define WO_LE (2<<(TK_LE-TK_EQ))
355#define WO_GT (2<<(TK_GT-TK_EQ))
356#define WO_GE (2<<(TK_GE-TK_EQ))
357
358/*
359** Translate from TK_xx operator to WO_xx bitmask.
360*/
361static int operatorMask(int op){
362 assert( allowedOp(op) );
363 if( op==TK_IN ){
364 return WO_IN;
365 }else{
366 return 1<<(op+1-TK_EQ);
367 }
368}
369
370/*
371** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
372** where X is a reference to the iColumn of table iCur and <op> is one of
373** the WO_xx operator codes specified by the op parameter.
374** Return a pointer to the term. Return 0 if not found.
375*/
376static WhereTerm *findTerm(
377 WhereClause *pWC, /* The WHERE clause to be searched */
378 int iCur, /* Cursor number of LHS */
379 int iColumn, /* Column number of LHS */
380 Bitmask notReady, /* RHS must not overlap with this mask */
381 u8 op, /* Mask of WO_xx values describing operator */
382 Index *pIdx /* Must be compatible with this index, if not NULL */
383){
384 WhereTerm *pTerm;
385 int k;
386 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
387 if( pTerm->leftCursor==iCur
388 && (pTerm->prereqRight & notReady)==0
389 && pTerm->leftColumn==iColumn
390 && (pTerm->operator & op)!=0
391 ){
392 if( iCur>=0 && pIdx ){
393 Expr *pX = pTerm->pExpr;
394 CollSeq *pColl;
395 char idxaff;
396 int k;
397 Parse *pParse = pWC->pParse;
398
399 idxaff = pIdx->pTable->aCol[iColumn].affinity;
400 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
401 pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
402 if( !pColl ){
403 if( pX->pRight ){
404 pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
405 }
406 if( !pColl ){
407 pColl = pParse->db->pDfltColl;
408 }
409 }
410 for(k=0; k<pIdx->nColumn && pIdx->aiColumn[k]!=iColumn; k++){}
411 assert( k<pIdx->nColumn );
412 if( pColl!=pIdx->keyInfo.aColl[k] ) continue;
413 }
414 return pTerm;
415 }
416 }
417 return 0;
418}
419
420/*
drh0aa74ed2005-07-16 13:33:20 +0000421** The input to this routine is an WhereTerm structure with only the
drh75897232000-05-29 14:26:00 +0000422** "p" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +0000423** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +0000424** structure.
425*/
drh0fcef5e2005-07-19 17:38:22 +0000426static void exprAnalyze(
427 SrcList *pSrc, /* the FROM clause */
428 ExprMaskSet *pMaskSet, /* table masks */
429 WhereTerm *pTerm /* the WHERE clause term to be analyzed */
430){
431 Expr *pExpr = pTerm->pExpr;
432 Bitmask prereqLeft;
433 Bitmask prereqAll;
434 int idxRight;
435
436 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
437 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
438 pTerm->prereqAll = prereqAll = exprTableUsage(pMaskSet, pExpr);
439 pTerm->leftCursor = -1;
440 pTerm->iPartner = -1;
drhfe05af82005-07-21 03:14:59 +0000441 pTerm->operator = 0;
drh0fcef5e2005-07-19 17:38:22 +0000442 idxRight = -1;
443 if( allowedOp(pExpr->op) && (pTerm->prereqRight & prereqLeft)==0 ){
444 Expr *pLeft = pExpr->pLeft;
445 Expr *pRight = pExpr->pRight;
446 if( pLeft->op==TK_COLUMN ){
447 pTerm->leftCursor = pLeft->iTable;
448 pTerm->leftColumn = pLeft->iColumn;
drhfe05af82005-07-21 03:14:59 +0000449 pTerm->operator = operatorMask(pExpr->op);
drh75897232000-05-29 14:26:00 +0000450 }
drh0fcef5e2005-07-19 17:38:22 +0000451 if( pRight && pRight->op==TK_COLUMN ){
452 WhereTerm *pNew;
453 Expr *pDup;
454 if( pTerm->leftCursor>=0 ){
455 pDup = sqlite3ExprDup(pExpr);
456 pNew = whereClauseInsert(pTerm->pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
457 if( pNew==0 ) return;
458 pNew->iPartner = pTerm->idx;
459 }else{
460 pDup = pExpr;
461 pNew = pTerm;
462 }
463 exprCommute(pDup);
464 pLeft = pDup->pLeft;
465 pNew->leftCursor = pLeft->iTable;
466 pNew->leftColumn = pLeft->iColumn;
467 pNew->prereqRight = prereqLeft;
468 pNew->prereqAll = prereqAll;
drhfe05af82005-07-21 03:14:59 +0000469 pNew->operator = operatorMask(pDup->op);
drh75897232000-05-29 14:26:00 +0000470 }
471 }
472}
473
drh0fcef5e2005-07-19 17:38:22 +0000474
drh75897232000-05-29 14:26:00 +0000475/*
drh51669862004-12-18 18:40:26 +0000476** This routine decides if pIdx can be used to satisfy the ORDER BY
477** clause. If it can, it returns 1. If pIdx cannot satisfy the
478** ORDER BY clause, this routine returns 0.
479**
480** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
481** left-most table in the FROM clause of that same SELECT statement and
482** the table has a cursor number of "base". pIdx is an index on pTab.
483**
484** nEqCol is the number of columns of pIdx that are used as equality
485** constraints. Any of these columns may be missing from the ORDER BY
486** clause and the match can still be a success.
487**
488** If the index is UNIQUE, then the ORDER BY clause is allowed to have
489** additional terms past the end of the index and the match will still
490** be a success.
491**
492** All terms of the ORDER BY that match against the index must be either
493** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
494** index do not need to satisfy this constraint.) The *pbRev value is
495** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
496** the ORDER BY clause is all ASC.
497*/
498static int isSortingIndex(
499 Parse *pParse, /* Parsing context */
500 Index *pIdx, /* The index we are testing */
501 Table *pTab, /* The table to be sorted */
502 int base, /* Cursor number for pTab */
503 ExprList *pOrderBy, /* The ORDER BY clause */
504 int nEqCol, /* Number of index columns with == constraints */
505 int *pbRev /* Set to 1 if ORDER BY is DESC */
506){
507 int i, j; /* Loop counters */
508 int sortOrder; /* Which direction we are sorting */
509 int nTerm; /* Number of ORDER BY terms */
510 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
511 sqlite3 *db = pParse->db;
512
513 assert( pOrderBy!=0 );
514 nTerm = pOrderBy->nExpr;
515 assert( nTerm>0 );
516
517 /* Match terms of the ORDER BY clause against columns of
518 ** the index.
519 */
520 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
521 Expr *pExpr; /* The expression of the ORDER BY pTerm */
522 CollSeq *pColl; /* The collating sequence of pExpr */
523
524 pExpr = pTerm->pExpr;
525 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
526 /* Can not use an index sort on anything that is not a column in the
527 ** left-most table of the FROM clause */
528 return 0;
529 }
530 pColl = sqlite3ExprCollSeq(pParse, pExpr);
531 if( !pColl ) pColl = db->pDfltColl;
drh9012bcb2004-12-19 00:11:35 +0000532 if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
533 /* Term j of the ORDER BY clause does not match column i of the index */
534 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +0000535 /* If an index column that is constrained by == fails to match an
536 ** ORDER BY term, that is OK. Just ignore that column of the index
537 */
538 continue;
539 }else{
540 /* If an index column fails to match and is not constrained by ==
541 ** then the index cannot satisfy the ORDER BY constraint.
542 */
543 return 0;
544 }
545 }
546 if( i>nEqCol ){
547 if( pTerm->sortOrder!=sortOrder ){
548 /* Indices can only be used if all ORDER BY terms past the
549 ** equality constraints are all either DESC or ASC. */
550 return 0;
551 }
552 }else{
553 sortOrder = pTerm->sortOrder;
554 }
555 j++;
556 pTerm++;
557 }
558
559 /* The index can be used for sorting if all terms of the ORDER BY clause
560 ** or covered or if we ran out of index columns and the it is a UNIQUE
561 ** index.
562 */
563 if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
564 *pbRev = sortOrder==SQLITE_SO_DESC;
565 return 1;
566 }
567 return 0;
568}
569
570/*
drhb6c29892004-11-22 19:12:19 +0000571** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
572** by sorting in order of ROWID. Return true if so and set *pbRev to be
573** true for reverse ROWID and false for forward ROWID order.
574*/
575static int sortableByRowid(
576 int base, /* Cursor number for table to be sorted */
577 ExprList *pOrderBy, /* The ORDER BY clause */
578 int *pbRev /* Set to 1 if ORDER BY is DESC */
579){
580 Expr *p;
581
582 assert( pOrderBy!=0 );
583 assert( pOrderBy->nExpr>0 );
584 p = pOrderBy->a[0].pExpr;
585 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
586 *pbRev = pOrderBy->a[0].sortOrder;
587 return 1;
588 }
589 return 0;
590}
591
drhfe05af82005-07-21 03:14:59 +0000592/*
593** Value for flags returned by bestIndex()
594*/
595#define WHERE_ROWID_EQ 0x001 /* rowid=EXPR or rowid IN (...) */
596#define WHERE_ROWID_RANGE 0x002 /* rowid<EXPR and/or rowid>EXPR */
597#define WHERE_COLUMN_EQ 0x004 /* x=EXPR or x IN (...) */
598#define WHERE_COLUMN_RANGE 0x008 /* x<EXPR and/or x>EXPR */
599#define WHERE_SCAN 0x010 /* Do a full table scan */
600#define WHERE_REVERSE 0x020 /* Scan in reverse order */
601#define WHERE_ORDERBY 0x040 /* Output will appear in correct order */
602#define WHERE_IDX_ONLY 0x080 /* Use index only - omit table */
603#define WHERE_TOP_LIMIT 0x100 /* x<EXPR or x<=EXPR constraint */
604#define WHERE_BTM_LIMIT 0x200 /* x>EXPR or x>=EXPR constraint */
605
606/*
607** Find the best index for accessing a particular table. Return the index,
608** flags that describe how the index should be used, and the "score" for
609** this index.
610*/
611static double bestIndex(
612 Parse *pParse, /* The parsing context */
613 WhereClause *pWC, /* The WHERE clause */
614 struct SrcList_item *pSrc, /* The FROM clause term to search */
615 Bitmask notReady, /* Mask of cursors that are not available */
616 ExprList *pOrderBy, /* The order by clause */
617 Index **ppIndex, /* Make *ppIndex point to the best index */
618 int *pFlags /* Put flags describing this choice in *pFlags */
619){
620 WhereTerm *pTerm;
621 Index *pProbe;
622 Index *bestIdx = 0;
623 double bestScore = 0.0;
624 int bestFlags = 0;
625 int iCur = pSrc->iCursor;
626 int rev;
627
628 /* Check for a rowid=EXPR or rowid IN (...) constraint
629 */
630 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
631 if( pTerm ){
632 *ppIndex = 0;
633 if( pTerm->operator & WO_EQ ){
634 *pFlags = WHERE_ROWID_EQ;
635 if( pOrderBy ) *pFlags |= WHERE_ORDERBY;
636 return 1.0e10;
637 }else{
638 *pFlags = WHERE_ROWID_EQ;
639 return 1.0e9;
640 }
641 }
642
643 /* Check for constraints on a range of rowids
644 */
645 pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
646 if( pTerm ){
647 int flags;
648 *ppIndex = 0;
649 if( pTerm->operator & (WO_LT|WO_LE) ){
650 flags = WHERE_ROWID_RANGE | WHERE_TOP_LIMIT;
651 if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
652 flags |= WHERE_BTM_LIMIT;
653 }
654 }else{
655 flags = WHERE_ROWID_RANGE | WHERE_BTM_LIMIT;
656 if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
657 flags |= WHERE_TOP_LIMIT;
658 }
659 }
660 if( pOrderBy && sortableByRowid(iCur, pOrderBy, &rev) ){
661 flags |= WHERE_ORDERBY;
662 if( rev ) flags |= WHERE_REVERSE;
663 }
664 bestScore = 99.0;
665 bestFlags = flags;
666 }
667
668 /* Look at each index.
669 */
670 for(pProbe=pSrc->pTab->pIndex; pProbe; pProbe=pProbe->pNext){
671 int i;
672 int nEq;
673 int usesIN = 0;
674 int flags;
675 double score = 0.0;
676
677 /* Count the number of columns in the index that are satisfied
678 ** by x=EXPR constraints or x IN (...) constraints.
679 */
680 for(i=0; i<pProbe->nColumn; i++){
681 int j = pProbe->aiColumn[i];
682 pTerm = findTerm(pWC, iCur, j, notReady, WO_EQ|WO_IN, pProbe);
683 if( pTerm==0 ) break;
684 if( pTerm->operator==WO_IN ){
685 if( i==0 ) usesIN = 1;
686 break;
687 }
688 }
689 nEq = i + usesIN;
690 score = i*100.0 + usesIN*50.0;
691
692 /* The optimization type is RANGE if there are no == or IN constraints
693 */
694 if( usesIN || nEq ){
695 flags = WHERE_COLUMN_EQ;
696 }else{
697 flags = WHERE_COLUMN_RANGE;
698 }
699
700 /* Look for range constraints
701 */
702 if( !usesIN && nEq<pProbe->nColumn ){
703 int j = pProbe->aiColumn[nEq];
704 pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
705 if( pTerm ){
706 score += 20.0;
707 flags = WHERE_COLUMN_RANGE;
708 if( pTerm->operator & (WO_LT|WO_LE) ){
709 flags |= WHERE_TOP_LIMIT;
710 if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
711 flags |= WHERE_BTM_LIMIT;
712 score += 20.0;
713 }
714 }else{
715 flags |= WHERE_BTM_LIMIT;
716 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
717 flags |= WHERE_TOP_LIMIT;
718 score += 20;
719 }
720 }
721 }
722 }
723
724 /* Add extra points if this index can be used to satisfy the ORDER BY
725 ** clause
726 */
727 if( pOrderBy && !usesIN &&
728 isSortingIndex(pParse, pProbe, pSrc->pTab, iCur, pOrderBy, nEq, &rev) ){
729 flags |= WHERE_ORDERBY;
730 score += 10.0;
731 if( rev ) flags |= WHERE_REVERSE;
732 }
733
734 /* Check to see if we can get away with using just the index without
735 ** ever reading the table. If that is the case, then add one bonus
736 ** point to the score.
737 */
738 if( score>0.0 && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
739 Bitmask m = pSrc->colUsed;
740 int j;
741 for(j=0; j<pProbe->nColumn; j++){
742 int x = pProbe->aiColumn[j];
743 if( x<BMS-1 ){
744 m &= ~(((Bitmask)1)<<x);
745 }
746 }
747 if( m==0 ){
748 flags |= WHERE_IDX_ONLY;
749 score += 5;
750 }
751 }
752
753 /* If this index has achieved the best score so far, then use it.
754 */
755 if( score>bestScore ){
756 bestIdx = pProbe;
757 bestScore = score;
758 bestFlags = flags;
759 }
760 }
761
762 /* Disable sorting if we are coming out in rowid order
763 */
764 if( bestIdx==0 && pOrderBy && sortableByRowid(iCur, pOrderBy, &rev) ){
765 bestFlags |= WHERE_ORDERBY;
766 if( rev ) bestFlags |= WHERE_REVERSE;
767 }
768
769
770 /* Report the best result
771 */
772 *ppIndex = bestIdx;
773 *pFlags = bestFlags;
774 return bestScore;
775}
776
drhb6c29892004-11-22 19:12:19 +0000777
778/*
drh2ffb1182004-07-19 19:14:01 +0000779** Disable a term in the WHERE clause. Except, do not disable the term
780** if it controls a LEFT OUTER JOIN and it did not originate in the ON
781** or USING clause of that join.
782**
783** Consider the term t2.z='ok' in the following queries:
784**
785** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
786** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
787** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
788**
drh23bf66d2004-12-14 03:34:34 +0000789** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +0000790** in the ON clause. The term is disabled in (3) because it is not part
791** of a LEFT OUTER JOIN. In (1), the term is not disabled.
792**
793** Disabling a term causes that term to not be tested in the inner loop
794** of the join. Disabling is an optimization. We would get the correct
795** results if nothing were ever disabled, but joins might run a little
796** slower. The trick is to disable as much as we can without disabling
797** too much. If we disabled in (1), we'd get the wrong answer.
798** See ticket #813.
799*/
drh0fcef5e2005-07-19 17:38:22 +0000800static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
801 if( pTerm
802 && (pTerm->flags & TERM_CODED)==0
803 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
804 ){
805 pTerm->flags |= TERM_CODED;
806 if( pTerm->iPartner>=0 ){
807 disableTerm(pLevel, &pTerm->pWC->a[pTerm->iPartner]);
808 }
drh2ffb1182004-07-19 19:14:01 +0000809 }
810}
811
812/*
drh94a11212004-09-25 13:12:14 +0000813** Generate code that builds a probe for an index. Details:
814**
815** * Check the top nColumn entries on the stack. If any
816** of those entries are NULL, jump immediately to brk,
817** which is the loop exit, since no index entry will match
818** if any part of the key is NULL.
819**
820** * Construct a probe entry from the top nColumn entries in
821** the stack with affinities appropriate for index pIdx.
822*/
823static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
824 sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
825 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
826 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
827 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
828 sqlite3IndexAffinityStr(v, pIdx);
829}
830
drhe8b97272005-07-19 22:22:12 +0000831
832/*
drh94a11212004-09-25 13:12:14 +0000833** Generate code for an equality term of the WHERE clause. An equality
834** term can be either X=expr or X IN (...). pTerm is the X.
835*/
836static void codeEqualityTerm(
837 Parse *pParse, /* The parsing context */
drh0aa74ed2005-07-16 13:33:20 +0000838 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh94a11212004-09-25 13:12:14 +0000839 int brk, /* Jump here to abandon the loop */
840 WhereLevel *pLevel /* When level of the FROM clause we are working on */
841){
drh0fcef5e2005-07-19 17:38:22 +0000842 Expr *pX = pTerm->pExpr;
drh94a11212004-09-25 13:12:14 +0000843 if( pX->op!=TK_IN ){
844 assert( pX->op==TK_EQ );
845 sqlite3ExprCode(pParse, pX->pRight);
danielk1977b3bce662005-01-29 08:32:43 +0000846#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +0000847 }else{
danielk1977b3bce662005-01-29 08:32:43 +0000848 int iTab;
drh94a11212004-09-25 13:12:14 +0000849 Vdbe *v = pParse->pVdbe;
danielk1977b3bce662005-01-29 08:32:43 +0000850
851 sqlite3CodeSubselect(pParse, pX);
852 iTab = pX->iTable;
drh94a11212004-09-25 13:12:14 +0000853 sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
danielk1977b3bce662005-01-29 08:32:43 +0000854 VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
drh9012bcb2004-12-19 00:11:35 +0000855 pLevel->inP2 = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
drh94a11212004-09-25 13:12:14 +0000856 pLevel->inOp = OP_Next;
857 pLevel->inP1 = iTab;
danielk1977b3bce662005-01-29 08:32:43 +0000858#endif
drh94a11212004-09-25 13:12:14 +0000859 }
drh0fcef5e2005-07-19 17:38:22 +0000860 disableTerm(pLevel, pTerm);
drh94a11212004-09-25 13:12:14 +0000861}
862
drh84bfda42005-07-15 13:05:21 +0000863#ifdef SQLITE_TEST
864/*
865** The following variable holds a text description of query plan generated
866** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
867** overwrites the previous. This information is used for testing and
868** analysis only.
869*/
870char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
871static int nQPlan = 0; /* Next free slow in _query_plan[] */
872
873#endif /* SQLITE_TEST */
874
875
drh94a11212004-09-25 13:12:14 +0000876
877/*
drhe3184742002-06-19 14:27:05 +0000878** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +0000879** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +0000880** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +0000881** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +0000882** in order to complete the WHERE clause processing.
883**
884** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +0000885**
886** The basic idea is to do a nested loop, one loop for each table in
887** the FROM clause of a select. (INSERT and UPDATE statements are the
888** same as a SELECT with only a single table in the FROM clause.) For
889** example, if the SQL is this:
890**
891** SELECT * FROM t1, t2, t3 WHERE ...;
892**
893** Then the code generated is conceptually like the following:
894**
895** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000896** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +0000897** foreach row3 in t3 do /
898** ...
899** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000900** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +0000901** end /
902**
903** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +0000904** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
905** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +0000906** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +0000907**
drhe6f85e72004-12-25 01:03:13 +0000908** The code that sqlite3WhereBegin() generates leaves the cursors named
909** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +0000910** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +0000911** data from the various tables of the loop.
912**
drhc27a1ce2002-06-14 20:58:45 +0000913** If the WHERE clause is empty, the foreach loops must each scan their
914** entire tables. Thus a three-way join is an O(N^3) operation. But if
915** the tables have indices and there are terms in the WHERE clause that
916** refer to those indices, a complete table scan can be avoided and the
917** code will run much faster. Most of the work of this routine is checking
918** to see if there are indices that can be used to speed up the loop.
919**
920** Terms of the WHERE clause are also used to limit which rows actually
921** make it to the "..." in the middle of the loop. After each "foreach",
922** terms of the WHERE clause that use only terms in that loop and outer
923** loops are evaluated and if false a jump is made around all subsequent
924** inner loops (or around the "..." if the test occurs within the inner-
925** most loop)
926**
927** OUTER JOINS
928**
929** An outer join of tables t1 and t2 is conceptally coded as follows:
930**
931** foreach row1 in t1 do
932** flag = 0
933** foreach row2 in t2 do
934** start:
935** ...
936** flag = 1
937** end
drhe3184742002-06-19 14:27:05 +0000938** if flag==0 then
939** move the row2 cursor to a null row
940** goto start
941** fi
drhc27a1ce2002-06-14 20:58:45 +0000942** end
943**
drhe3184742002-06-19 14:27:05 +0000944** ORDER BY CLAUSE PROCESSING
945**
946** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
947** if there is one. If there is no ORDER BY clause or if this routine
948** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
949**
950** If an index can be used so that the natural output order of the table
951** scan is correct for the ORDER BY clause, then that index is used and
952** *ppOrderBy is set to NULL. This is an optimization that prevents an
953** unnecessary sort of the result set if an index appropriate for the
954** ORDER BY clause already exists.
955**
956** If the where clause loops cannot be arranged to provide the correct
957** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +0000958*/
danielk19774adee202004-05-08 08:23:19 +0000959WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +0000960 Parse *pParse, /* The parser context */
961 SrcList *pTabList, /* A list of all tables to be scanned */
962 Expr *pWhere, /* The WHERE clause */
drhf8db1bc2005-04-22 02:38:37 +0000963 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +0000964){
965 int i; /* Loop counter */
966 WhereInfo *pWInfo; /* Will become the return value of this function */
967 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhd4f5ee22003-07-16 00:54:31 +0000968 int brk, cont = 0; /* Addresses used during code generation */
drhfe05af82005-07-21 03:14:59 +0000969 Bitmask notReady; /* Cursors that are not yet positioned */
drh0aa74ed2005-07-16 13:33:20 +0000970 WhereTerm *pTerm; /* A single term in the WHERE clause */
971 ExprMaskSet maskSet; /* The expression mask set */
drh0aa74ed2005-07-16 13:33:20 +0000972 WhereClause wc; /* The WHERE clause is divided into these terms */
drh9012bcb2004-12-19 00:11:35 +0000973 struct SrcList_item *pTabItem; /* A single entry from pTabList */
974 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh75897232000-05-29 14:26:00 +0000975
drh1398ad32005-01-19 23:24:50 +0000976 /* The number of terms in the FROM clause is limited by the number of
977 ** bits in a Bitmask
978 */
979 if( pTabList->nSrc>sizeof(Bitmask)*8 ){
980 sqlite3ErrorMsg(pParse, "at most %d tables in a join",
981 sizeof(Bitmask)*8);
982 return 0;
983 }
984
drh83dcb1a2002-06-28 01:02:38 +0000985 /* Split the WHERE clause into separate subexpressions where each
drh0aa74ed2005-07-16 13:33:20 +0000986 ** subexpression is separated by an AND operator. If the wc.a[]
drh83dcb1a2002-06-28 01:02:38 +0000987 ** array fills up, the last entry might point to an expression which
988 ** contains additional unfactored AND operators.
989 */
drh6a3ea0e2003-05-02 14:32:12 +0000990 initMaskSet(&maskSet);
drhfe05af82005-07-21 03:14:59 +0000991 whereClauseInit(&wc, pParse);
drh0aa74ed2005-07-16 13:33:20 +0000992 whereSplit(&wc, pWhere);
drh1398ad32005-01-19 23:24:50 +0000993
drh75897232000-05-29 14:26:00 +0000994 /* Allocate and initialize the WhereInfo structure that will become the
995 ** return value.
996 */
drhad3cab52002-05-24 02:04:32 +0000997 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
danielk1977132872b2004-05-10 10:37:18 +0000998 if( sqlite3_malloc_failed ){
danielk1977d5d56522005-03-16 12:15:20 +0000999 sqliteFree(pWInfo); /* Avoid leaking memory when malloc fails */
drh0aa74ed2005-07-16 13:33:20 +00001000 whereClauseClear(&wc);
drh75897232000-05-29 14:26:00 +00001001 return 0;
1002 }
1003 pWInfo->pParse = pParse;
1004 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +00001005 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh08192d52002-04-30 19:20:28 +00001006
1007 /* Special case: a WHERE clause that is constant. Evaluate the
1008 ** expression and either jump over all of the code or fall thru.
1009 */
danielk19774adee202004-05-08 08:23:19 +00001010 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
1011 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +00001012 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00001013 }
drh75897232000-05-29 14:26:00 +00001014
drh75897232000-05-29 14:26:00 +00001015 /* Analyze all of the subexpressions.
1016 */
drh1398ad32005-01-19 23:24:50 +00001017 for(i=0; i<pTabList->nSrc; i++){
1018 createMask(&maskSet, pTabList->a[i].iCursor);
1019 }
drh0fcef5e2005-07-19 17:38:22 +00001020 for(i=wc.nTerm-1; i>=0; i--){
1021 exprAnalyze(pTabList, &maskSet, &wc.a[i]);
drh75897232000-05-29 14:26:00 +00001022 }
1023
drhfe05af82005-07-21 03:14:59 +00001024 /* Chose the best index to use for each table in the FROM clause
drh75897232000-05-29 14:26:00 +00001025 */
drhfe05af82005-07-21 03:14:59 +00001026 notReady = ~(Bitmask)0;
drh9012bcb2004-12-19 00:11:35 +00001027 pTabItem = pTabList->a;
1028 pLevel = pWInfo->a;
drhfe05af82005-07-21 03:14:59 +00001029 for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
1030 Index *pBest;
1031 int flags;
1032 bestIndex(pParse, &wc, pTabItem, notReady,
1033 (i==0 && ppOrderBy) ? *ppOrderBy : 0,
1034 &pBest, &flags);
1035 if( flags & WHERE_ORDERBY ){
1036 *ppOrderBy = 0;
drhc4a3c772001-04-04 11:48:57 +00001037 }
drhfe05af82005-07-21 03:14:59 +00001038 pLevel->flags = flags;
1039 pLevel->pIdx = pBest;
1040 if( pBest ){
drh9012bcb2004-12-19 00:11:35 +00001041 pLevel->iIdxCur = pParse->nTab++;
drhfe05af82005-07-21 03:14:59 +00001042 }else{
1043 pLevel->iIdxCur = -1;
drh6b563442001-11-07 16:48:26 +00001044 }
drhfe05af82005-07-21 03:14:59 +00001045 notReady &= ~getMask(&maskSet, pTabItem->iCursor);
drh75897232000-05-29 14:26:00 +00001046 }
1047
drh9012bcb2004-12-19 00:11:35 +00001048 /* Open all tables in the pTabList and any indices selected for
1049 ** searching those tables.
1050 */
1051 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
1052 pLevel = pWInfo->a;
1053 for(i=0, pTabItem=pTabList->a; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
1054 Table *pTab;
1055 Index *pIx;
1056 int iIdxCur = pLevel->iIdxCur;
1057
1058 pTab = pTabItem->pTab;
1059 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001060 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001061 sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
1062 }
1063 pLevel->iTabCur = pTabItem->iCursor;
1064 if( (pIx = pLevel->pIdx)!=0 ){
1065 sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
1066 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
1067 (char*)&pIx->keyInfo, P3_KEYINFO);
1068 }
drhfe05af82005-07-21 03:14:59 +00001069 if( (pLevel->flags & WHERE_IDX_ONLY)!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001070 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
1071 }
1072 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh84bfda42005-07-15 13:05:21 +00001073
1074#ifdef SQLITE_TEST
1075 /* Record in the query plan information about the current table
1076 ** and the index used to access it (if any). If the table itself
drh9042f392005-07-15 23:24:23 +00001077 ** is not used, its name is just '{}'. If no index is used
drh84bfda42005-07-15 13:05:21 +00001078 ** the index is listed as "{}"
1079 */
1080 {
drh9042f392005-07-15 23:24:23 +00001081 char *z = pTabItem->zAlias;
1082 int n;
1083 if( z==0 ) z = pTab->zName;
1084 n = strlen(z);
drh84bfda42005-07-15 13:05:21 +00001085 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
drhfe05af82005-07-21 03:14:59 +00001086 if( pLevel->flags & WHERE_IDX_ONLY ){
drh9042f392005-07-15 23:24:23 +00001087 strcpy(&sqlite3_query_plan[nQPlan], "{}");
1088 nQPlan += 2;
1089 }else{
1090 strcpy(&sqlite3_query_plan[nQPlan], z);
1091 nQPlan += n;
drh84bfda42005-07-15 13:05:21 +00001092 }
1093 sqlite3_query_plan[nQPlan++] = ' ';
1094 }
1095 if( pIx==0 ){
1096 strcpy(&sqlite3_query_plan[nQPlan], " {}");
1097 nQPlan += 3;
1098 }else{
1099 n = strlen(pIx->zName);
1100 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
1101 strcpy(&sqlite3_query_plan[nQPlan], pIx->zName);
1102 nQPlan += n;
1103 sqlite3_query_plan[nQPlan++] = ' ';
1104 }
1105 }
1106 }
1107#endif
drh9012bcb2004-12-19 00:11:35 +00001108 }
1109 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
1110
drh84bfda42005-07-15 13:05:21 +00001111#ifdef SQLITE_TEST
1112 /* Terminate the query plan description
1113 */
1114 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
1115 sqlite3_query_plan[--nQPlan] = 0;
1116 }
1117 sqlite3_query_plan[nQPlan] = 0;
1118 nQPlan = 0;
1119#endif
1120
drh75897232000-05-29 14:26:00 +00001121 /* Generate the code to do the search
1122 */
drhfe05af82005-07-21 03:14:59 +00001123 notReady = ~(Bitmask)0;
drh9012bcb2004-12-19 00:11:35 +00001124 pLevel = pWInfo->a;
1125 pTabItem = pTabList->a;
1126 for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
drhfe05af82005-07-21 03:14:59 +00001127 int j;
drh9012bcb2004-12-19 00:11:35 +00001128 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
1129 Index *pIdx; /* The index we will be using */
1130 int iIdxCur; /* The VDBE cursor for the index */
1131 int omitTable; /* True if we use the index only */
1132
1133 pIdx = pLevel->pIdx;
1134 iIdxCur = pLevel->iIdxCur;
1135 pLevel->inOp = OP_Noop;
1136
1137 /* Check to see if it is appropriate to omit the use of the table
1138 ** here and use its index instead.
1139 */
drhfe05af82005-07-21 03:14:59 +00001140 omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
drh75897232000-05-29 14:26:00 +00001141
drhad2d8302002-05-24 20:31:36 +00001142 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +00001143 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +00001144 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +00001145 */
1146 if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
1147 if( !pParse->nMem ) pParse->nMem++;
1148 pLevel->iLeftJoin = pParse->nMem++;
drhf0863fe2005-06-12 21:35:51 +00001149 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001150 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001151 VdbeComment((v, "# init LEFT JOIN no-match flag"));
drhad2d8302002-05-24 20:31:36 +00001152 }
1153
drhfe05af82005-07-21 03:14:59 +00001154 if( pLevel->flags & WHERE_ROWID_EQ ){
drh8aff1012001-12-22 14:49:24 +00001155 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +00001156 ** equality comparison against the ROWID field. Or
1157 ** we reference multiple rows using a "rowid IN (...)"
1158 ** construct.
drhc4a3c772001-04-04 11:48:57 +00001159 */
drhfe05af82005-07-21 03:14:59 +00001160 pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1161 assert( pTerm!=0 );
drh0fcef5e2005-07-19 17:38:22 +00001162 assert( pTerm->pExpr!=0 );
1163 assert( pTerm->leftCursor==iCur );
drh9012bcb2004-12-19 00:11:35 +00001164 assert( omitTable==0 );
drh94a11212004-09-25 13:12:14 +00001165 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1166 codeEqualityTerm(pParse, pTerm, brk, pLevel);
danielk19774adee202004-05-08 08:23:19 +00001167 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1168 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
danielk19774adee202004-05-08 08:23:19 +00001169 sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001170 VdbeComment((v, "pk"));
drh6b563442001-11-07 16:48:26 +00001171 pLevel->op = OP_Noop;
drhfe05af82005-07-21 03:14:59 +00001172 }else if( pLevel->flags & WHERE_COLUMN_EQ ){
drhc27a1ce2002-06-14 20:58:45 +00001173 /* Case 2: There is an index and all terms of the WHERE clause that
drhb6c29892004-11-22 19:12:19 +00001174 ** refer to the index using the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +00001175 */
drh6b563442001-11-07 16:48:26 +00001176 int start;
drhfe05af82005-07-21 03:14:59 +00001177 int nColumn;
danielk19774adee202004-05-08 08:23:19 +00001178 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
drh772ae622004-05-19 13:13:08 +00001179
1180 /* For each column of the index, find the term of the WHERE clause that
1181 ** constraints that column. If the WHERE clause term is X=expr, then
drh0aa74ed2005-07-16 13:33:20 +00001182 ** generate code to evaluate expr and leave the result on the stack */
drhfe05af82005-07-21 03:14:59 +00001183 for(j=0; 1; j++){
1184 int k = pIdx->aiColumn[j];
1185 pTerm = findTerm(&wc, iCur, k, notReady, WO_EQ|WO_IN, pIdx);
1186 if( pTerm==0 ) break;
1187 if( pTerm->operator==WO_IN && j>0 ) break;
drhe8b97272005-07-19 22:22:12 +00001188 assert( (pTerm->flags & TERM_CODED)==0 );
1189 codeEqualityTerm(pParse, pTerm, brk, pLevel);
drhfe05af82005-07-21 03:14:59 +00001190 if( pTerm->operator==WO_IN ){
1191 j++;
1192 break;
1193 }
drh75897232000-05-29 14:26:00 +00001194 }
drhfe05af82005-07-21 03:14:59 +00001195 nColumn = j;
drh6b563442001-11-07 16:48:26 +00001196 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001197 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drh94a11212004-09-25 13:12:14 +00001198 buildIndexProbe(v, nColumn, brk, pIdx);
danielk19773d1bfea2004-05-14 11:00:53 +00001199 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
drh772ae622004-05-19 13:13:08 +00001200
drh772ae622004-05-19 13:13:08 +00001201 /* Generate code (1) to move to the first matching element of the table.
1202 ** Then generate code (2) that jumps to "brk" after the cursor is past
1203 ** the last matching element of the table. The code (1) is executed
1204 ** once to initialize the search, the code (2) is executed before each
1205 ** iteration of the scan to see if the scan has finished. */
drhfe05af82005-07-21 03:14:59 +00001206 if( pLevel->flags & WHERE_REVERSE ){
drhc045ec52002-12-04 20:01:06 +00001207 /* Scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001208 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001209 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001210 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001211 pLevel->op = OP_Prev;
1212 }else{
1213 /* Scan in the forward order */
drh9012bcb2004-12-19 00:11:35 +00001214 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001215 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001216 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
drhc045ec52002-12-04 20:01:06 +00001217 pLevel->op = OP_Next;
1218 }
drh9012bcb2004-12-19 00:11:35 +00001219 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001220 sqlite3VdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
drhe6f85e72004-12-25 01:03:13 +00001221 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001222 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001223 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh75897232000-05-29 14:26:00 +00001224 }
drh9012bcb2004-12-19 00:11:35 +00001225 pLevel->p1 = iIdxCur;
drh6b563442001-11-07 16:48:26 +00001226 pLevel->p2 = start;
drhfe05af82005-07-21 03:14:59 +00001227 }else if( pLevel->flags & WHERE_ROWID_RANGE ){
drh8aff1012001-12-22 14:49:24 +00001228 /* Case 3: We have an inequality comparison against the ROWID field.
1229 */
1230 int testOp = OP_Noop;
1231 int start;
drhfe05af82005-07-21 03:14:59 +00001232 WhereTerm *pStart, *pEnd;
1233 int bRev = (pLevel->flags & WHERE_REVERSE)!=0;
drh8aff1012001-12-22 14:49:24 +00001234
drh9012bcb2004-12-19 00:11:35 +00001235 assert( omitTable==0 );
danielk19774adee202004-05-08 08:23:19 +00001236 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1237 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
drhfe05af82005-07-21 03:14:59 +00001238 if( pLevel->flags & WHERE_BTM_LIMIT ){
1239 pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
1240 assert( pStart!=0 );
1241 }else{
1242 pStart = 0;
drhb6c29892004-11-22 19:12:19 +00001243 }
drhfe05af82005-07-21 03:14:59 +00001244 if( pLevel->flags & WHERE_TOP_LIMIT ){
1245 pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
1246 assert( pEnd!=0 );
1247 }else{
1248 pEnd = 0;
1249 }
1250 assert( pStart!=0 || pEnd!=0 );
1251 if( bRev ){
1252 pTerm = pStart;
1253 pStart = pEnd;
1254 pEnd = pTerm;
1255 }
1256 if( pStart ){
drh94a11212004-09-25 13:12:14 +00001257 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001258 pX = pStart->pExpr;
drh94a11212004-09-25 13:12:14 +00001259 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001260 assert( pStart->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001261 sqlite3ExprCode(pParse, pX->pRight);
danielk1977d0a69322005-02-02 01:10:44 +00001262 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
drhb6c29892004-11-22 19:12:19 +00001263 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001264 VdbeComment((v, "pk"));
drhfe05af82005-07-21 03:14:59 +00001265 disableTerm(pLevel, pStart);
drh8aff1012001-12-22 14:49:24 +00001266 }else{
drhb6c29892004-11-22 19:12:19 +00001267 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
drh8aff1012001-12-22 14:49:24 +00001268 }
drhfe05af82005-07-21 03:14:59 +00001269 if( pEnd ){
drh94a11212004-09-25 13:12:14 +00001270 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001271 pX = pEnd->pExpr;
drh94a11212004-09-25 13:12:14 +00001272 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001273 assert( pEnd->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001274 sqlite3ExprCode(pParse, pX->pRight);
drh8aff1012001-12-22 14:49:24 +00001275 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001276 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drh94a11212004-09-25 13:12:14 +00001277 if( pX->op==TK_LT || pX->op==TK_GT ){
drhb6c29892004-11-22 19:12:19 +00001278 testOp = bRev ? OP_Le : OP_Ge;
drh8aff1012001-12-22 14:49:24 +00001279 }else{
drhb6c29892004-11-22 19:12:19 +00001280 testOp = bRev ? OP_Lt : OP_Gt;
drh8aff1012001-12-22 14:49:24 +00001281 }
drhfe05af82005-07-21 03:14:59 +00001282 disableTerm(pLevel, pEnd);
drh8aff1012001-12-22 14:49:24 +00001283 }
danielk19774adee202004-05-08 08:23:19 +00001284 start = sqlite3VdbeCurrentAddr(v);
drhb6c29892004-11-22 19:12:19 +00001285 pLevel->op = bRev ? OP_Prev : OP_Next;
drh6a3ea0e2003-05-02 14:32:12 +00001286 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001287 pLevel->p2 = start;
1288 if( testOp!=OP_Noop ){
drhf0863fe2005-06-12 21:35:51 +00001289 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001290 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drhf0863fe2005-06-12 21:35:51 +00001291 sqlite3VdbeAddOp(v, testOp, 'n', brk);
drh8aff1012001-12-22 14:49:24 +00001292 }
drhfe05af82005-07-21 03:14:59 +00001293 }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
1294 /* Case 4: The WHERE clause term that refers to the right-most
drhc27a1ce2002-06-14 20:58:45 +00001295 ** column of the index is an inequality. For example, if
1296 ** the index is on (x,y,z) and the WHERE clause is of the
1297 ** form "x=5 AND y<10" then this case is used. Only the
1298 ** right-most column can be an inequality - the rest must
1299 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +00001300 **
1301 ** This case is also used when there are no WHERE clause
1302 ** constraints but an index is selected anyway, in order
1303 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +00001304 */
drhfe05af82005-07-21 03:14:59 +00001305 int nEqColumn;
drh487ab3c2001-11-08 00:45:21 +00001306 int start;
danielk1977f7df9cc2004-06-16 12:02:47 +00001307 int leFlag=0, geFlag=0;
drh487ab3c2001-11-08 00:45:21 +00001308 int testOp;
drhfe05af82005-07-21 03:14:59 +00001309 int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
1310 int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
1311 int bRev = (pLevel->flags & WHERE_REVERSE)!=0;
drh487ab3c2001-11-08 00:45:21 +00001312
1313 /* Evaluate the equality constraints
1314 */
drhfe05af82005-07-21 03:14:59 +00001315 for(j=0; 1; j++){
1316 int k = pIdx->aiColumn[j];
1317 pTerm = findTerm(&wc, iCur, k, notReady, WO_EQ, pIdx);
1318 if( pTerm==0 ) break;
drhe8b97272005-07-19 22:22:12 +00001319 assert( (pTerm->flags & TERM_CODED)==0 );
1320 sqlite3ExprCode(pParse, pTerm->pExpr->pRight);
1321 disableTerm(pLevel, pTerm);
drh487ab3c2001-11-08 00:45:21 +00001322 }
drhfe05af82005-07-21 03:14:59 +00001323 nEqColumn = j;
drh487ab3c2001-11-08 00:45:21 +00001324
drhc27a1ce2002-06-14 20:58:45 +00001325 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +00001326 ** used twice: once to make the termination key and once to make the
1327 ** start key.
1328 */
1329 for(j=0; j<nEqColumn; j++){
danielk19774adee202004-05-08 08:23:19 +00001330 sqlite3VdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
drh487ab3c2001-11-08 00:45:21 +00001331 }
1332
drhc045ec52002-12-04 20:01:06 +00001333 /* Labels for the beginning and end of the loop
1334 */
danielk19774adee202004-05-08 08:23:19 +00001335 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1336 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
drhc045ec52002-12-04 20:01:06 +00001337
drh487ab3c2001-11-08 00:45:21 +00001338 /* Generate the termination key. This is the key value that
1339 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +00001340 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +00001341 **
1342 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1343 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +00001344 */
drhfe05af82005-07-21 03:14:59 +00001345 if( topLimit ){
drhe8b97272005-07-19 22:22:12 +00001346 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001347 int k = pIdx->aiColumn[j];
1348 pTerm = findTerm(&wc, iCur, k, notReady, WO_LT|WO_LE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001349 assert( pTerm!=0 );
1350 pX = pTerm->pExpr;
1351 assert( (pTerm->flags & TERM_CODED)==0 );
1352 sqlite3ExprCode(pParse, pX->pRight);
1353 leFlag = pX->op==TK_LE;
1354 disableTerm(pLevel, pTerm);
drh487ab3c2001-11-08 00:45:21 +00001355 testOp = OP_IdxGE;
1356 }else{
1357 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
1358 leFlag = 1;
1359 }
1360 if( testOp!=OP_Noop ){
drhfe05af82005-07-21 03:14:59 +00001361 int nCol = nEqColumn + topLimit;
drh487ab3c2001-11-08 00:45:21 +00001362 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001363 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001364 if( bRev ){
drh7cf6e4d2004-05-19 14:56:55 +00001365 int op = leFlag ? OP_MoveLe : OP_MoveLt;
drh9012bcb2004-12-19 00:11:35 +00001366 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001367 }else{
danielk19774adee202004-05-08 08:23:19 +00001368 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001369 }
drhfe05af82005-07-21 03:14:59 +00001370 }else if( bRev ){
drh9012bcb2004-12-19 00:11:35 +00001371 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001372 }
1373
1374 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001375 ** bound on the search. There is no start key if there are no
1376 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001377 ** that case, generate a "Rewind" instruction in place of the
1378 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001379 **
1380 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1381 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001382 */
drhfe05af82005-07-21 03:14:59 +00001383 if( btmLimit ){
drhe8b97272005-07-19 22:22:12 +00001384 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001385 int k = pIdx->aiColumn[j];
1386 pTerm = findTerm(&wc, iCur, k, notReady, WO_GT|WO_GE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001387 assert( pTerm!=0 );
1388 pX = pTerm->pExpr;
1389 assert( (pTerm->flags & TERM_CODED)==0 );
1390 sqlite3ExprCode(pParse, pX->pRight);
1391 geFlag = pX->op==TK_GE;
1392 disableTerm(pLevel, pTerm);
drh7900ead2001-11-12 13:51:43 +00001393 }else{
1394 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001395 }
drhfe05af82005-07-21 03:14:59 +00001396 if( nEqColumn>0 || btmLimit ){
1397 int nCol = nEqColumn + btmLimit;
drh94a11212004-09-25 13:12:14 +00001398 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001399 if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001400 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001401 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001402 testOp = OP_IdxLT;
1403 }else{
drh7cf6e4d2004-05-19 14:56:55 +00001404 int op = geFlag ? OP_MoveGe : OP_MoveGt;
drh9012bcb2004-12-19 00:11:35 +00001405 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001406 }
drhfe05af82005-07-21 03:14:59 +00001407 }else if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001408 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001409 }else{
drh9012bcb2004-12-19 00:11:35 +00001410 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001411 }
1412
1413 /* Generate the the top of the loop. If there is a termination
1414 ** key we have to test for that key and abort at the top of the
1415 ** loop.
1416 */
danielk19774adee202004-05-08 08:23:19 +00001417 start = sqlite3VdbeCurrentAddr(v);
drh487ab3c2001-11-08 00:45:21 +00001418 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001419 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001420 sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
drhfe05af82005-07-21 03:14:59 +00001421 if( (leFlag && !bRev) || (!geFlag && bRev) ){
danielk19773d1bfea2004-05-14 11:00:53 +00001422 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
1423 }
drh487ab3c2001-11-08 00:45:21 +00001424 }
drh9012bcb2004-12-19 00:11:35 +00001425 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
drhfe05af82005-07-21 03:14:59 +00001426 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEqColumn + topLimit, cont);
drhe6f85e72004-12-25 01:03:13 +00001427 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001428 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001429 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh487ab3c2001-11-08 00:45:21 +00001430 }
1431
1432 /* Record the instruction used to terminate the loop.
1433 */
drhfe05af82005-07-21 03:14:59 +00001434 pLevel->op = bRev ? OP_Prev : OP_Next;
drh9012bcb2004-12-19 00:11:35 +00001435 pLevel->p1 = iIdxCur;
drh487ab3c2001-11-08 00:45:21 +00001436 pLevel->p2 = start;
drhfe05af82005-07-21 03:14:59 +00001437 }else{
1438 /* Case 5: There is no usable index. We must do a complete
1439 ** scan of the entire table.
1440 */
1441 int start;
1442 int opRewind;
1443
1444 assert( omitTable==0 );
1445 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1446 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1447 if( pLevel->flags & WHERE_REVERSE ){
1448 opRewind = OP_Last;
1449 pLevel->op = OP_Prev;
1450 }else{
1451 opRewind = OP_Rewind;
1452 pLevel->op = OP_Next;
1453 }
1454 sqlite3VdbeAddOp(v, opRewind, iCur, brk);
1455 start = sqlite3VdbeCurrentAddr(v);
1456 pLevel->p1 = iCur;
1457 pLevel->p2 = start;
drh75897232000-05-29 14:26:00 +00001458 }
drhfe05af82005-07-21 03:14:59 +00001459 notReady &= ~getMask(&maskSet, iCur);
drh75897232000-05-29 14:26:00 +00001460
1461 /* Insert code to test every subexpression that can be completely
1462 ** computed using the current set of tables.
1463 */
drh0fcef5e2005-07-19 17:38:22 +00001464 for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
1465 Expr *pE;
1466 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001467 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001468 pE = pTerm->pExpr;
1469 assert( pE!=0 );
drh392e5972005-07-08 14:14:22 +00001470 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
drh1f162302002-10-27 19:35:33 +00001471 continue;
1472 }
drh392e5972005-07-08 14:14:22 +00001473 sqlite3ExprIfFalse(pParse, pE, cont, 1);
drh0fcef5e2005-07-19 17:38:22 +00001474 pTerm->flags |= TERM_CODED;
drh75897232000-05-29 14:26:00 +00001475 }
1476 brk = cont;
drhad2d8302002-05-24 20:31:36 +00001477
1478 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1479 ** at least one row of the right table has matched the left table.
1480 */
1481 if( pLevel->iLeftJoin ){
danielk19774adee202004-05-08 08:23:19 +00001482 pLevel->top = sqlite3VdbeCurrentAddr(v);
1483 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1484 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001485 VdbeComment((v, "# record LEFT JOIN hit"));
drh0aa74ed2005-07-16 13:33:20 +00001486 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
drh0fcef5e2005-07-19 17:38:22 +00001487 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001488 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001489 assert( pTerm->pExpr );
1490 sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
1491 pTerm->flags |= TERM_CODED;
drh1cc093c2002-06-24 22:01:57 +00001492 }
drhad2d8302002-05-24 20:31:36 +00001493 }
drh75897232000-05-29 14:26:00 +00001494 }
1495 pWInfo->iContinue = cont;
drh6a3ea0e2003-05-02 14:32:12 +00001496 freeMaskSet(&maskSet);
drh0aa74ed2005-07-16 13:33:20 +00001497 whereClauseClear(&wc);
drh75897232000-05-29 14:26:00 +00001498 return pWInfo;
1499}
1500
1501/*
drhc27a1ce2002-06-14 20:58:45 +00001502** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00001503** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001504*/
danielk19774adee202004-05-08 08:23:19 +00001505void sqlite3WhereEnd(WhereInfo *pWInfo){
drh75897232000-05-29 14:26:00 +00001506 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001507 int i;
drh6b563442001-11-07 16:48:26 +00001508 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001509 SrcList *pTabList = pWInfo->pTabList;
drh9012bcb2004-12-19 00:11:35 +00001510 struct SrcList_item *pTabItem;
drh19a775c2000-06-05 18:54:46 +00001511
drh9012bcb2004-12-19 00:11:35 +00001512 /* Generate loop termination code.
1513 */
drhad3cab52002-05-24 02:04:32 +00001514 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001515 pLevel = &pWInfo->a[i];
danielk19774adee202004-05-08 08:23:19 +00001516 sqlite3VdbeResolveLabel(v, pLevel->cont);
drh6b563442001-11-07 16:48:26 +00001517 if( pLevel->op!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001518 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001519 }
danielk19774adee202004-05-08 08:23:19 +00001520 sqlite3VdbeResolveLabel(v, pLevel->brk);
drhd99f7062002-06-08 23:25:08 +00001521 if( pLevel->inOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001522 sqlite3VdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
drhd99f7062002-06-08 23:25:08 +00001523 }
drhad2d8302002-05-24 20:31:36 +00001524 if( pLevel->iLeftJoin ){
1525 int addr;
danielk19774adee202004-05-08 08:23:19 +00001526 addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh9012bcb2004-12-19 00:11:35 +00001527 sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
danielk19774adee202004-05-08 08:23:19 +00001528 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
drh9012bcb2004-12-19 00:11:35 +00001529 if( pLevel->iIdxCur>=0 ){
1530 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
drh7f09b3e2002-08-13 13:15:49 +00001531 }
danielk19774adee202004-05-08 08:23:19 +00001532 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
drhad2d8302002-05-24 20:31:36 +00001533 }
drh19a775c2000-06-05 18:54:46 +00001534 }
drh9012bcb2004-12-19 00:11:35 +00001535
1536 /* The "break" point is here, just past the end of the outer loop.
1537 ** Set it.
1538 */
danielk19774adee202004-05-08 08:23:19 +00001539 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00001540
drhacf3b982005-01-03 01:27:18 +00001541 /* Close all of the cursors that were opend by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00001542 */
1543 pLevel = pWInfo->a;
1544 pTabItem = pTabList->a;
1545 for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
1546 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00001547 assert( pTab!=0 );
1548 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001549 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001550 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
1551 }
drh6b563442001-11-07 16:48:26 +00001552 if( pLevel->pIdx!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001553 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
1554 }
1555
drhacf3b982005-01-03 01:27:18 +00001556 /* Make cursor substitutions for cases where we want to use
drh9012bcb2004-12-19 00:11:35 +00001557 ** just the index and never reference the table.
1558 **
1559 ** Calls to the code generator in between sqlite3WhereBegin and
1560 ** sqlite3WhereEnd will have created code that references the table
1561 ** directly. This loop scans all that code looking for opcodes
1562 ** that reference the table and converts them into opcodes that
1563 ** reference the index.
1564 */
drhfe05af82005-07-21 03:14:59 +00001565 if( pLevel->flags & WHERE_IDX_ONLY ){
drh9012bcb2004-12-19 00:11:35 +00001566 int i, j, last;
1567 VdbeOp *pOp;
1568 Index *pIdx = pLevel->pIdx;
1569
1570 assert( pIdx!=0 );
1571 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1572 last = sqlite3VdbeCurrentAddr(v);
1573 for(i=pWInfo->iTop; i<last; i++, pOp++){
1574 if( pOp->p1!=pLevel->iTabCur ) continue;
1575 if( pOp->opcode==OP_Column ){
1576 pOp->p1 = pLevel->iIdxCur;
1577 for(j=0; j<pIdx->nColumn; j++){
1578 if( pOp->p2==pIdx->aiColumn[j] ){
1579 pOp->p2 = j;
1580 break;
1581 }
1582 }
drhf0863fe2005-06-12 21:35:51 +00001583 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00001584 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00001585 pOp->opcode = OP_IdxRowid;
danielk19776c18b6e2005-01-30 09:17:58 +00001586 }else if( pOp->opcode==OP_NullRow ){
1587 pOp->opcode = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001588 }
1589 }
drh6b563442001-11-07 16:48:26 +00001590 }
drh19a775c2000-06-05 18:54:46 +00001591 }
drh9012bcb2004-12-19 00:11:35 +00001592
1593 /* Final cleanup
1594 */
drh75897232000-05-29 14:26:00 +00001595 sqliteFree(pWInfo);
1596 return;
1597}
drhfe05af82005-07-21 03:14:59 +00001598
1599
1600/*
1601** Delete a list of WhereIdx structures.
1602*/
1603void sqlite3WhereIdxListDelete(WhereIdx *p){
1604 WhereIdx *pNext;
1605 while( p ){
1606 pNext = p->pNext;
1607 sqliteFree(p);
1608 p = pNext;
1609 }
1610}