blob: 7b1e5a7d3fbdbf87a05b6634b06c1cbccc666620 [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**
drh29dda4a2005-07-21 18:23:20 +000019** $Id: where.c,v 1.150 2005/07/21 18:23:20 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/*
drh6a3ea0e2003-05-02 14:32:12 +0000101** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000102** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000103**
104** The VDBE cursor numbers are small integers contained in
105** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
106** clause, the cursor numbers might not begin with 0 and they might
107** contain gaps in the numbering sequence. But we want to make maximum
108** use of the bits in our bitmasks. This structure provides a mapping
109** from the sparse cursor numbers into consecutive integers beginning
110** with 0.
111**
112** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
113** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
114**
115** For example, if the WHERE clause expression used these VDBE
116** cursors: 4, 5, 8, 29, 57, 73. Then the ExprMaskSet structure
117** would map those cursor numbers into bits 0 through 5.
118**
119** Note that the mapping is not necessarily ordered. In the example
120** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
121** 57->5, 73->4. Or one of 719 other combinations might be used. It
122** does not really matter. What is important is that sparse cursor
123** numbers all get mapped into bit numbers that begin with 0 and contain
124** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000125*/
126typedef struct ExprMaskSet ExprMaskSet;
127struct ExprMaskSet {
drh1398ad32005-01-19 23:24:50 +0000128 int n; /* Number of assigned cursor values */
129 int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000130};
131
drh0aa74ed2005-07-16 13:33:20 +0000132
drh6a3ea0e2003-05-02 14:32:12 +0000133/*
drh0aa74ed2005-07-16 13:33:20 +0000134** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000135*/
drhfe05af82005-07-21 03:14:59 +0000136static void whereClauseInit(WhereClause *pWC, Parse *pParse){
137 pWC->pParse = pParse;
drh0aa74ed2005-07-16 13:33:20 +0000138 pWC->nTerm = 0;
139 pWC->nSlot = ARRAYSIZE(pWC->aStatic);
140 pWC->a = pWC->aStatic;
141}
142
143/*
144** Deallocate a WhereClause structure. The WhereClause structure
145** itself is not freed. This routine is the inverse of whereClauseInit().
146*/
147static void whereClauseClear(WhereClause *pWC){
148 int i;
149 WhereTerm *a;
150 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
151 if( a->flags & TERM_DYNAMIC ){
drh0fcef5e2005-07-19 17:38:22 +0000152 sqlite3ExprDelete(a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000153 }
154 }
155 if( pWC->a!=pWC->aStatic ){
156 sqliteFree(pWC->a);
157 }
158}
159
160/*
161** Add a new entries to the WhereClause structure. Increase the allocated
162** space as necessary.
163*/
drh0fcef5e2005-07-19 17:38:22 +0000164static WhereTerm *whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
drh0aa74ed2005-07-16 13:33:20 +0000165 WhereTerm *pTerm;
166 if( pWC->nTerm>=pWC->nSlot ){
167 WhereTerm *pOld = pWC->a;
168 pWC->a = sqliteMalloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
drh0fcef5e2005-07-19 17:38:22 +0000169 if( pWC->a==0 ) return 0;
drh0aa74ed2005-07-16 13:33:20 +0000170 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
171 if( pOld!=pWC->aStatic ){
172 sqliteFree(pOld);
173 }
174 pWC->nSlot *= 2;
175 }
drh0fcef5e2005-07-19 17:38:22 +0000176 pTerm = &pWC->a[pWC->nTerm];
177 pTerm->idx = pWC->nTerm;
178 pWC->nTerm++;
179 pTerm->pExpr = p;
drh0aa74ed2005-07-16 13:33:20 +0000180 pTerm->flags = flags;
drh0fcef5e2005-07-19 17:38:22 +0000181 pTerm->pWC = pWC;
182 pTerm->iPartner = -1;
183 return pTerm;
drh0aa74ed2005-07-16 13:33:20 +0000184}
drh75897232000-05-29 14:26:00 +0000185
186/*
drh51669862004-12-18 18:40:26 +0000187** This routine identifies subexpressions in the WHERE clause where
188** each subexpression is separate by the AND operator. aSlot is
189** filled with pointers to the subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000190**
drh51669862004-12-18 18:40:26 +0000191** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
192** \________/ \_______________/ \________________/
193** slot[0] slot[1] slot[2]
194**
195** The original WHERE clause in pExpr is unaltered. All this routine
196** does is make aSlot[] entries point to substructure within pExpr.
197**
198** aSlot[] is an array of subexpressions structures. There are nSlot
199** spaces left in this array. This routine finds as many AND-separated
200** subexpressions as it can and puts pointers to those subexpressions
201** into aSlot[] entries. The return value is the number of slots filled.
drh75897232000-05-29 14:26:00 +0000202*/
drh0aa74ed2005-07-16 13:33:20 +0000203static void whereSplit(WhereClause *pWC, Expr *pExpr){
204 if( pExpr==0 ) return;
205 if( pExpr->op!=TK_AND ){
206 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000207 }else{
drh0aa74ed2005-07-16 13:33:20 +0000208 whereSplit(pWC, pExpr->pLeft);
209 whereSplit(pWC, pExpr->pRight);
drh75897232000-05-29 14:26:00 +0000210 }
drh75897232000-05-29 14:26:00 +0000211}
212
213/*
drh6a3ea0e2003-05-02 14:32:12 +0000214** Initialize an expression mask set
215*/
216#define initMaskSet(P) memset(P, 0, sizeof(*P))
217
218/*
drh1398ad32005-01-19 23:24:50 +0000219** Return the bitmask for the given cursor number. Return 0 if
220** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000221*/
drh51669862004-12-18 18:40:26 +0000222static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000223 int i;
224 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000225 if( pMaskSet->ix[i]==iCursor ){
226 return ((Bitmask)1)<<i;
227 }
drh6a3ea0e2003-05-02 14:32:12 +0000228 }
drh6a3ea0e2003-05-02 14:32:12 +0000229 return 0;
230}
231
232/*
drh1398ad32005-01-19 23:24:50 +0000233** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000234**
235** There is one cursor per table in the FROM clause. The number of
236** tables in the FROM clause is limited by a test early in the
237** sqlite3WhereBegin() routien. So we know that the pMaskSet->ix[]
238** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000239*/
240static void createMask(ExprMaskSet *pMaskSet, int iCursor){
drh0fcef5e2005-07-19 17:38:22 +0000241 assert( pMaskSet->n < ARRAYSIZE(pMaskSet->ix) );
242 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000243}
244
245/*
drh6a3ea0e2003-05-02 14:32:12 +0000246** Destroy an expression mask set
247*/
248#define freeMaskSet(P) /* NO-OP */
249
250/*
drh75897232000-05-29 14:26:00 +0000251** This routine walks (recursively) an expression tree and generates
252** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000253** tree.
drh75897232000-05-29 14:26:00 +0000254**
255** In order for this routine to work, the calling function must have
drh626a8792005-01-17 22:08:19 +0000256** previously invoked sqlite3ExprResolveNames() on the expression. See
drh75897232000-05-29 14:26:00 +0000257** the header comment on that routine for additional information.
drh626a8792005-01-17 22:08:19 +0000258** The sqlite3ExprResolveNames() routines looks for column names and
drh6a3ea0e2003-05-02 14:32:12 +0000259** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
260** the VDBE cursor number of the table.
drh75897232000-05-29 14:26:00 +0000261*/
danielk1977b3bce662005-01-29 08:32:43 +0000262static Bitmask exprListTableUsage(ExprMaskSet *, ExprList *);
drh51669862004-12-18 18:40:26 +0000263static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
264 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000265 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000266 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000267 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000268 return mask;
drh75897232000-05-29 14:26:00 +0000269 }
danielk1977b3bce662005-01-29 08:32:43 +0000270 mask = exprTableUsage(pMaskSet, p->pRight);
271 mask |= exprTableUsage(pMaskSet, p->pLeft);
272 mask |= exprListTableUsage(pMaskSet, p->pList);
273 if( p->pSelect ){
274 Select *pS = p->pSelect;
275 mask |= exprListTableUsage(pMaskSet, pS->pEList);
276 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
277 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
278 mask |= exprTableUsage(pMaskSet, pS->pWhere);
279 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drh75897232000-05-29 14:26:00 +0000280 }
danielk1977b3bce662005-01-29 08:32:43 +0000281 return mask;
282}
283static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
284 int i;
285 Bitmask mask = 0;
286 if( pList ){
287 for(i=0; i<pList->nExpr; i++){
288 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000289 }
290 }
drh75897232000-05-29 14:26:00 +0000291 return mask;
292}
293
294/*
drh487ab3c2001-11-08 00:45:21 +0000295** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000296** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000297** "=", "<", ">", "<=", ">=", and "IN".
drh487ab3c2001-11-08 00:45:21 +0000298*/
299static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000300 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
301 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
302 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
303 assert( TK_GE==TK_EQ+4 );
drh9a432672004-10-04 13:38:09 +0000304 return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
drh487ab3c2001-11-08 00:45:21 +0000305}
306
307/*
drh51669862004-12-18 18:40:26 +0000308** Swap two objects of type T.
drh193bd772004-07-20 18:23:14 +0000309*/
310#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
311
312/*
drh0fcef5e2005-07-19 17:38:22 +0000313** Commute a comparision operator. Expressions of the form "X op Y"
314** are converted into "Y op X".
drh193bd772004-07-20 18:23:14 +0000315*/
drh0fcef5e2005-07-19 17:38:22 +0000316static void exprCommute(Expr *pExpr){
drhfe05af82005-07-21 03:14:59 +0000317 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drh0fcef5e2005-07-19 17:38:22 +0000318 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
319 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
320 if( pExpr->op>=TK_GT ){
321 assert( TK_LT==TK_GT+2 );
322 assert( TK_GE==TK_LE+2 );
323 assert( TK_GT>TK_EQ );
324 assert( TK_GT<TK_LE );
325 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
326 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000327 }
drh193bd772004-07-20 18:23:14 +0000328}
329
330/*
drhfe05af82005-07-21 03:14:59 +0000331** Bitmasks for the operators that indices are able to exploit. An
332** OR-ed combination of these values can be used when searching for
333** terms in the where clause.
334*/
335#define WO_IN 1
336#define WO_EQ 2
337#define WO_LT (2<<(TK_LT-TK_EQ))
338#define WO_LE (2<<(TK_LE-TK_EQ))
339#define WO_GT (2<<(TK_GT-TK_EQ))
340#define WO_GE (2<<(TK_GE-TK_EQ))
341
342/*
343** Translate from TK_xx operator to WO_xx bitmask.
344*/
345static int operatorMask(int op){
346 assert( allowedOp(op) );
347 if( op==TK_IN ){
348 return WO_IN;
349 }else{
350 return 1<<(op+1-TK_EQ);
351 }
352}
353
354/*
355** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
356** where X is a reference to the iColumn of table iCur and <op> is one of
357** the WO_xx operator codes specified by the op parameter.
358** Return a pointer to the term. Return 0 if not found.
359*/
360static WhereTerm *findTerm(
361 WhereClause *pWC, /* The WHERE clause to be searched */
362 int iCur, /* Cursor number of LHS */
363 int iColumn, /* Column number of LHS */
364 Bitmask notReady, /* RHS must not overlap with this mask */
365 u8 op, /* Mask of WO_xx values describing operator */
366 Index *pIdx /* Must be compatible with this index, if not NULL */
367){
368 WhereTerm *pTerm;
369 int k;
370 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
371 if( pTerm->leftCursor==iCur
372 && (pTerm->prereqRight & notReady)==0
373 && pTerm->leftColumn==iColumn
374 && (pTerm->operator & op)!=0
375 ){
376 if( iCur>=0 && pIdx ){
377 Expr *pX = pTerm->pExpr;
378 CollSeq *pColl;
379 char idxaff;
380 int k;
381 Parse *pParse = pWC->pParse;
382
383 idxaff = pIdx->pTable->aCol[iColumn].affinity;
384 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
385 pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
386 if( !pColl ){
387 if( pX->pRight ){
388 pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
389 }
390 if( !pColl ){
391 pColl = pParse->db->pDfltColl;
392 }
393 }
394 for(k=0; k<pIdx->nColumn && pIdx->aiColumn[k]!=iColumn; k++){}
395 assert( k<pIdx->nColumn );
396 if( pColl!=pIdx->keyInfo.aColl[k] ) continue;
397 }
398 return pTerm;
399 }
400 }
401 return 0;
402}
403
404/*
drh0aa74ed2005-07-16 13:33:20 +0000405** The input to this routine is an WhereTerm structure with only the
drh75897232000-05-29 14:26:00 +0000406** "p" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +0000407** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +0000408** structure.
409*/
drh0fcef5e2005-07-19 17:38:22 +0000410static void exprAnalyze(
411 SrcList *pSrc, /* the FROM clause */
412 ExprMaskSet *pMaskSet, /* table masks */
413 WhereTerm *pTerm /* the WHERE clause term to be analyzed */
414){
415 Expr *pExpr = pTerm->pExpr;
416 Bitmask prereqLeft;
417 Bitmask prereqAll;
418 int idxRight;
419
420 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
421 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
422 pTerm->prereqAll = prereqAll = exprTableUsage(pMaskSet, pExpr);
423 pTerm->leftCursor = -1;
424 pTerm->iPartner = -1;
drhfe05af82005-07-21 03:14:59 +0000425 pTerm->operator = 0;
drh0fcef5e2005-07-19 17:38:22 +0000426 idxRight = -1;
427 if( allowedOp(pExpr->op) && (pTerm->prereqRight & prereqLeft)==0 ){
428 Expr *pLeft = pExpr->pLeft;
429 Expr *pRight = pExpr->pRight;
430 if( pLeft->op==TK_COLUMN ){
431 pTerm->leftCursor = pLeft->iTable;
432 pTerm->leftColumn = pLeft->iColumn;
drhfe05af82005-07-21 03:14:59 +0000433 pTerm->operator = operatorMask(pExpr->op);
drh75897232000-05-29 14:26:00 +0000434 }
drh0fcef5e2005-07-19 17:38:22 +0000435 if( pRight && pRight->op==TK_COLUMN ){
436 WhereTerm *pNew;
437 Expr *pDup;
438 if( pTerm->leftCursor>=0 ){
439 pDup = sqlite3ExprDup(pExpr);
440 pNew = whereClauseInsert(pTerm->pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
441 if( pNew==0 ) return;
442 pNew->iPartner = pTerm->idx;
443 }else{
444 pDup = pExpr;
445 pNew = pTerm;
446 }
447 exprCommute(pDup);
448 pLeft = pDup->pLeft;
449 pNew->leftCursor = pLeft->iTable;
450 pNew->leftColumn = pLeft->iColumn;
451 pNew->prereqRight = prereqLeft;
452 pNew->prereqAll = prereqAll;
drhfe05af82005-07-21 03:14:59 +0000453 pNew->operator = operatorMask(pDup->op);
drh75897232000-05-29 14:26:00 +0000454 }
455 }
456}
457
drh0fcef5e2005-07-19 17:38:22 +0000458
drh75897232000-05-29 14:26:00 +0000459/*
drh51669862004-12-18 18:40:26 +0000460** This routine decides if pIdx can be used to satisfy the ORDER BY
461** clause. If it can, it returns 1. If pIdx cannot satisfy the
462** ORDER BY clause, this routine returns 0.
463**
464** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
465** left-most table in the FROM clause of that same SELECT statement and
466** the table has a cursor number of "base". pIdx is an index on pTab.
467**
468** nEqCol is the number of columns of pIdx that are used as equality
469** constraints. Any of these columns may be missing from the ORDER BY
470** clause and the match can still be a success.
471**
472** If the index is UNIQUE, then the ORDER BY clause is allowed to have
473** additional terms past the end of the index and the match will still
474** be a success.
475**
476** All terms of the ORDER BY that match against the index must be either
477** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
478** index do not need to satisfy this constraint.) The *pbRev value is
479** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
480** the ORDER BY clause is all ASC.
481*/
482static int isSortingIndex(
483 Parse *pParse, /* Parsing context */
484 Index *pIdx, /* The index we are testing */
485 Table *pTab, /* The table to be sorted */
486 int base, /* Cursor number for pTab */
487 ExprList *pOrderBy, /* The ORDER BY clause */
488 int nEqCol, /* Number of index columns with == constraints */
489 int *pbRev /* Set to 1 if ORDER BY is DESC */
490){
491 int i, j; /* Loop counters */
492 int sortOrder; /* Which direction we are sorting */
493 int nTerm; /* Number of ORDER BY terms */
494 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
495 sqlite3 *db = pParse->db;
496
497 assert( pOrderBy!=0 );
498 nTerm = pOrderBy->nExpr;
499 assert( nTerm>0 );
500
501 /* Match terms of the ORDER BY clause against columns of
502 ** the index.
503 */
504 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
505 Expr *pExpr; /* The expression of the ORDER BY pTerm */
506 CollSeq *pColl; /* The collating sequence of pExpr */
507
508 pExpr = pTerm->pExpr;
509 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
510 /* Can not use an index sort on anything that is not a column in the
511 ** left-most table of the FROM clause */
512 return 0;
513 }
514 pColl = sqlite3ExprCollSeq(pParse, pExpr);
515 if( !pColl ) pColl = db->pDfltColl;
drh9012bcb2004-12-19 00:11:35 +0000516 if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
517 /* Term j of the ORDER BY clause does not match column i of the index */
518 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +0000519 /* If an index column that is constrained by == fails to match an
520 ** ORDER BY term, that is OK. Just ignore that column of the index
521 */
522 continue;
523 }else{
524 /* If an index column fails to match and is not constrained by ==
525 ** then the index cannot satisfy the ORDER BY constraint.
526 */
527 return 0;
528 }
529 }
530 if( i>nEqCol ){
531 if( pTerm->sortOrder!=sortOrder ){
532 /* Indices can only be used if all ORDER BY terms past the
533 ** equality constraints are all either DESC or ASC. */
534 return 0;
535 }
536 }else{
537 sortOrder = pTerm->sortOrder;
538 }
539 j++;
540 pTerm++;
541 }
542
543 /* The index can be used for sorting if all terms of the ORDER BY clause
544 ** or covered or if we ran out of index columns and the it is a UNIQUE
545 ** index.
546 */
547 if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
548 *pbRev = sortOrder==SQLITE_SO_DESC;
549 return 1;
550 }
551 return 0;
552}
553
554/*
drhb6c29892004-11-22 19:12:19 +0000555** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
556** by sorting in order of ROWID. Return true if so and set *pbRev to be
557** true for reverse ROWID and false for forward ROWID order.
558*/
559static int sortableByRowid(
560 int base, /* Cursor number for table to be sorted */
561 ExprList *pOrderBy, /* The ORDER BY clause */
562 int *pbRev /* Set to 1 if ORDER BY is DESC */
563){
564 Expr *p;
565
566 assert( pOrderBy!=0 );
567 assert( pOrderBy->nExpr>0 );
568 p = pOrderBy->a[0].pExpr;
569 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
570 *pbRev = pOrderBy->a[0].sortOrder;
571 return 1;
572 }
573 return 0;
574}
575
drhfe05af82005-07-21 03:14:59 +0000576/*
577** Value for flags returned by bestIndex()
578*/
579#define WHERE_ROWID_EQ 0x001 /* rowid=EXPR or rowid IN (...) */
580#define WHERE_ROWID_RANGE 0x002 /* rowid<EXPR and/or rowid>EXPR */
581#define WHERE_COLUMN_EQ 0x004 /* x=EXPR or x IN (...) */
582#define WHERE_COLUMN_RANGE 0x008 /* x<EXPR and/or x>EXPR */
583#define WHERE_SCAN 0x010 /* Do a full table scan */
584#define WHERE_REVERSE 0x020 /* Scan in reverse order */
585#define WHERE_ORDERBY 0x040 /* Output will appear in correct order */
586#define WHERE_IDX_ONLY 0x080 /* Use index only - omit table */
587#define WHERE_TOP_LIMIT 0x100 /* x<EXPR or x<=EXPR constraint */
588#define WHERE_BTM_LIMIT 0x200 /* x>EXPR or x>=EXPR constraint */
589
590/*
591** Find the best index for accessing a particular table. Return the index,
592** flags that describe how the index should be used, and the "score" for
593** this index.
594*/
595static double bestIndex(
596 Parse *pParse, /* The parsing context */
597 WhereClause *pWC, /* The WHERE clause */
598 struct SrcList_item *pSrc, /* The FROM clause term to search */
599 Bitmask notReady, /* Mask of cursors that are not available */
600 ExprList *pOrderBy, /* The order by clause */
601 Index **ppIndex, /* Make *ppIndex point to the best index */
602 int *pFlags /* Put flags describing this choice in *pFlags */
603){
604 WhereTerm *pTerm;
605 Index *pProbe;
606 Index *bestIdx = 0;
607 double bestScore = 0.0;
608 int bestFlags = 0;
609 int iCur = pSrc->iCursor;
610 int rev;
611
612 /* Check for a rowid=EXPR or rowid IN (...) constraint
613 */
614 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
615 if( pTerm ){
616 *ppIndex = 0;
617 if( pTerm->operator & WO_EQ ){
618 *pFlags = WHERE_ROWID_EQ;
619 if( pOrderBy ) *pFlags |= WHERE_ORDERBY;
620 return 1.0e10;
621 }else{
622 *pFlags = WHERE_ROWID_EQ;
623 return 1.0e9;
624 }
625 }
626
627 /* Check for constraints on a range of rowids
628 */
629 pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
630 if( pTerm ){
631 int flags;
632 *ppIndex = 0;
633 if( pTerm->operator & (WO_LT|WO_LE) ){
634 flags = WHERE_ROWID_RANGE | WHERE_TOP_LIMIT;
635 if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
636 flags |= WHERE_BTM_LIMIT;
637 }
638 }else{
639 flags = WHERE_ROWID_RANGE | WHERE_BTM_LIMIT;
640 if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
641 flags |= WHERE_TOP_LIMIT;
642 }
643 }
644 if( pOrderBy && sortableByRowid(iCur, pOrderBy, &rev) ){
645 flags |= WHERE_ORDERBY;
646 if( rev ) flags |= WHERE_REVERSE;
647 }
648 bestScore = 99.0;
649 bestFlags = flags;
650 }
651
652 /* Look at each index.
653 */
654 for(pProbe=pSrc->pTab->pIndex; pProbe; pProbe=pProbe->pNext){
655 int i;
656 int nEq;
657 int usesIN = 0;
658 int flags;
659 double score = 0.0;
660
661 /* Count the number of columns in the index that are satisfied
662 ** by x=EXPR constraints or x IN (...) constraints.
663 */
664 for(i=0; i<pProbe->nColumn; i++){
665 int j = pProbe->aiColumn[i];
666 pTerm = findTerm(pWC, iCur, j, notReady, WO_EQ|WO_IN, pProbe);
667 if( pTerm==0 ) break;
668 if( pTerm->operator==WO_IN ){
669 if( i==0 ) usesIN = 1;
670 break;
671 }
672 }
673 nEq = i + usesIN;
674 score = i*100.0 + usesIN*50.0;
675
676 /* The optimization type is RANGE if there are no == or IN constraints
677 */
678 if( usesIN || nEq ){
679 flags = WHERE_COLUMN_EQ;
680 }else{
681 flags = WHERE_COLUMN_RANGE;
682 }
683
684 /* Look for range constraints
685 */
686 if( !usesIN && nEq<pProbe->nColumn ){
687 int j = pProbe->aiColumn[nEq];
688 pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
689 if( pTerm ){
690 score += 20.0;
691 flags = WHERE_COLUMN_RANGE;
692 if( pTerm->operator & (WO_LT|WO_LE) ){
693 flags |= WHERE_TOP_LIMIT;
694 if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
695 flags |= WHERE_BTM_LIMIT;
696 score += 20.0;
697 }
698 }else{
699 flags |= WHERE_BTM_LIMIT;
700 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
701 flags |= WHERE_TOP_LIMIT;
702 score += 20;
703 }
704 }
705 }
706 }
707
708 /* Add extra points if this index can be used to satisfy the ORDER BY
709 ** clause
710 */
711 if( pOrderBy && !usesIN &&
712 isSortingIndex(pParse, pProbe, pSrc->pTab, iCur, pOrderBy, nEq, &rev) ){
713 flags |= WHERE_ORDERBY;
714 score += 10.0;
715 if( rev ) flags |= WHERE_REVERSE;
716 }
717
718 /* Check to see if we can get away with using just the index without
719 ** ever reading the table. If that is the case, then add one bonus
720 ** point to the score.
721 */
722 if( score>0.0 && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
723 Bitmask m = pSrc->colUsed;
724 int j;
725 for(j=0; j<pProbe->nColumn; j++){
726 int x = pProbe->aiColumn[j];
727 if( x<BMS-1 ){
728 m &= ~(((Bitmask)1)<<x);
729 }
730 }
731 if( m==0 ){
732 flags |= WHERE_IDX_ONLY;
733 score += 5;
734 }
735 }
736
737 /* If this index has achieved the best score so far, then use it.
738 */
739 if( score>bestScore ){
740 bestIdx = pProbe;
741 bestScore = score;
742 bestFlags = flags;
743 }
744 }
745
746 /* Disable sorting if we are coming out in rowid order
747 */
748 if( bestIdx==0 && pOrderBy && sortableByRowid(iCur, pOrderBy, &rev) ){
749 bestFlags |= WHERE_ORDERBY;
750 if( rev ) bestFlags |= WHERE_REVERSE;
751 }
752
753
754 /* Report the best result
755 */
756 *ppIndex = bestIdx;
757 *pFlags = bestFlags;
758 return bestScore;
759}
760
drhb6c29892004-11-22 19:12:19 +0000761
762/*
drh2ffb1182004-07-19 19:14:01 +0000763** Disable a term in the WHERE clause. Except, do not disable the term
764** if it controls a LEFT OUTER JOIN and it did not originate in the ON
765** or USING clause of that join.
766**
767** Consider the term t2.z='ok' in the following queries:
768**
769** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
770** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
771** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
772**
drh23bf66d2004-12-14 03:34:34 +0000773** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +0000774** in the ON clause. The term is disabled in (3) because it is not part
775** of a LEFT OUTER JOIN. In (1), the term is not disabled.
776**
777** Disabling a term causes that term to not be tested in the inner loop
778** of the join. Disabling is an optimization. We would get the correct
779** results if nothing were ever disabled, but joins might run a little
780** slower. The trick is to disable as much as we can without disabling
781** too much. If we disabled in (1), we'd get the wrong answer.
782** See ticket #813.
783*/
drh0fcef5e2005-07-19 17:38:22 +0000784static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
785 if( pTerm
786 && (pTerm->flags & TERM_CODED)==0
787 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
788 ){
789 pTerm->flags |= TERM_CODED;
790 if( pTerm->iPartner>=0 ){
791 disableTerm(pLevel, &pTerm->pWC->a[pTerm->iPartner]);
792 }
drh2ffb1182004-07-19 19:14:01 +0000793 }
794}
795
796/*
drh94a11212004-09-25 13:12:14 +0000797** Generate code that builds a probe for an index. Details:
798**
799** * Check the top nColumn entries on the stack. If any
800** of those entries are NULL, jump immediately to brk,
801** which is the loop exit, since no index entry will match
802** if any part of the key is NULL.
803**
804** * Construct a probe entry from the top nColumn entries in
805** the stack with affinities appropriate for index pIdx.
806*/
807static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
808 sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
809 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
810 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
811 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
812 sqlite3IndexAffinityStr(v, pIdx);
813}
814
drhe8b97272005-07-19 22:22:12 +0000815
816/*
drh94a11212004-09-25 13:12:14 +0000817** Generate code for an equality term of the WHERE clause. An equality
818** term can be either X=expr or X IN (...). pTerm is the X.
819*/
820static void codeEqualityTerm(
821 Parse *pParse, /* The parsing context */
drh0aa74ed2005-07-16 13:33:20 +0000822 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh94a11212004-09-25 13:12:14 +0000823 int brk, /* Jump here to abandon the loop */
824 WhereLevel *pLevel /* When level of the FROM clause we are working on */
825){
drh0fcef5e2005-07-19 17:38:22 +0000826 Expr *pX = pTerm->pExpr;
drh94a11212004-09-25 13:12:14 +0000827 if( pX->op!=TK_IN ){
828 assert( pX->op==TK_EQ );
829 sqlite3ExprCode(pParse, pX->pRight);
danielk1977b3bce662005-01-29 08:32:43 +0000830#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +0000831 }else{
danielk1977b3bce662005-01-29 08:32:43 +0000832 int iTab;
drh94a11212004-09-25 13:12:14 +0000833 Vdbe *v = pParse->pVdbe;
danielk1977b3bce662005-01-29 08:32:43 +0000834
835 sqlite3CodeSubselect(pParse, pX);
836 iTab = pX->iTable;
drh94a11212004-09-25 13:12:14 +0000837 sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
danielk1977b3bce662005-01-29 08:32:43 +0000838 VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
drh9012bcb2004-12-19 00:11:35 +0000839 pLevel->inP2 = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
drh94a11212004-09-25 13:12:14 +0000840 pLevel->inOp = OP_Next;
841 pLevel->inP1 = iTab;
danielk1977b3bce662005-01-29 08:32:43 +0000842#endif
drh94a11212004-09-25 13:12:14 +0000843 }
drh0fcef5e2005-07-19 17:38:22 +0000844 disableTerm(pLevel, pTerm);
drh94a11212004-09-25 13:12:14 +0000845}
846
drh84bfda42005-07-15 13:05:21 +0000847#ifdef SQLITE_TEST
848/*
849** The following variable holds a text description of query plan generated
850** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
851** overwrites the previous. This information is used for testing and
852** analysis only.
853*/
854char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
855static int nQPlan = 0; /* Next free slow in _query_plan[] */
856
857#endif /* SQLITE_TEST */
858
859
drh94a11212004-09-25 13:12:14 +0000860
861/*
drhe3184742002-06-19 14:27:05 +0000862** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +0000863** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +0000864** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +0000865** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +0000866** in order to complete the WHERE clause processing.
867**
868** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +0000869**
870** The basic idea is to do a nested loop, one loop for each table in
871** the FROM clause of a select. (INSERT and UPDATE statements are the
872** same as a SELECT with only a single table in the FROM clause.) For
873** example, if the SQL is this:
874**
875** SELECT * FROM t1, t2, t3 WHERE ...;
876**
877** Then the code generated is conceptually like the following:
878**
879** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000880** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +0000881** foreach row3 in t3 do /
882** ...
883** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +0000884** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +0000885** end /
886**
drh29dda4a2005-07-21 18:23:20 +0000887** Note that the loops might not be nested in the order in which they
888** appear in the FROM clause if a different order is better able to make
889** use of indices.
890**
drhc27a1ce2002-06-14 20:58:45 +0000891** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +0000892** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
893** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +0000894** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +0000895**
drhe6f85e72004-12-25 01:03:13 +0000896** The code that sqlite3WhereBegin() generates leaves the cursors named
897** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +0000898** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +0000899** data from the various tables of the loop.
900**
drhc27a1ce2002-06-14 20:58:45 +0000901** If the WHERE clause is empty, the foreach loops must each scan their
902** entire tables. Thus a three-way join is an O(N^3) operation. But if
903** the tables have indices and there are terms in the WHERE clause that
904** refer to those indices, a complete table scan can be avoided and the
905** code will run much faster. Most of the work of this routine is checking
906** to see if there are indices that can be used to speed up the loop.
907**
908** Terms of the WHERE clause are also used to limit which rows actually
909** make it to the "..." in the middle of the loop. After each "foreach",
910** terms of the WHERE clause that use only terms in that loop and outer
911** loops are evaluated and if false a jump is made around all subsequent
912** inner loops (or around the "..." if the test occurs within the inner-
913** most loop)
914**
915** OUTER JOINS
916**
917** An outer join of tables t1 and t2 is conceptally coded as follows:
918**
919** foreach row1 in t1 do
920** flag = 0
921** foreach row2 in t2 do
922** start:
923** ...
924** flag = 1
925** end
drhe3184742002-06-19 14:27:05 +0000926** if flag==0 then
927** move the row2 cursor to a null row
928** goto start
929** fi
drhc27a1ce2002-06-14 20:58:45 +0000930** end
931**
drhe3184742002-06-19 14:27:05 +0000932** ORDER BY CLAUSE PROCESSING
933**
934** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
935** if there is one. If there is no ORDER BY clause or if this routine
936** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
937**
938** If an index can be used so that the natural output order of the table
939** scan is correct for the ORDER BY clause, then that index is used and
940** *ppOrderBy is set to NULL. This is an optimization that prevents an
941** unnecessary sort of the result set if an index appropriate for the
942** ORDER BY clause already exists.
943**
944** If the where clause loops cannot be arranged to provide the correct
945** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +0000946*/
danielk19774adee202004-05-08 08:23:19 +0000947WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +0000948 Parse *pParse, /* The parser context */
949 SrcList *pTabList, /* A list of all tables to be scanned */
950 Expr *pWhere, /* The WHERE clause */
drhf8db1bc2005-04-22 02:38:37 +0000951 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
drh75897232000-05-29 14:26:00 +0000952){
953 int i; /* Loop counter */
954 WhereInfo *pWInfo; /* Will become the return value of this function */
955 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhd4f5ee22003-07-16 00:54:31 +0000956 int brk, cont = 0; /* Addresses used during code generation */
drhfe05af82005-07-21 03:14:59 +0000957 Bitmask notReady; /* Cursors that are not yet positioned */
drh0aa74ed2005-07-16 13:33:20 +0000958 WhereTerm *pTerm; /* A single term in the WHERE clause */
959 ExprMaskSet maskSet; /* The expression mask set */
drh0aa74ed2005-07-16 13:33:20 +0000960 WhereClause wc; /* The WHERE clause is divided into these terms */
drh9012bcb2004-12-19 00:11:35 +0000961 struct SrcList_item *pTabItem; /* A single entry from pTabList */
962 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh29dda4a2005-07-21 18:23:20 +0000963 int iFrom; /* First unused FROM clause element */
drh75897232000-05-29 14:26:00 +0000964
drh29dda4a2005-07-21 18:23:20 +0000965 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +0000966 ** bits in a Bitmask
967 */
drh29dda4a2005-07-21 18:23:20 +0000968 if( pTabList->nSrc>BMS ){
969 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +0000970 return 0;
971 }
972
drh83dcb1a2002-06-28 01:02:38 +0000973 /* Split the WHERE clause into separate subexpressions where each
drh29dda4a2005-07-21 18:23:20 +0000974 ** subexpression is separated by an AND operator.
drh83dcb1a2002-06-28 01:02:38 +0000975 */
drh6a3ea0e2003-05-02 14:32:12 +0000976 initMaskSet(&maskSet);
drhfe05af82005-07-21 03:14:59 +0000977 whereClauseInit(&wc, pParse);
drh0aa74ed2005-07-16 13:33:20 +0000978 whereSplit(&wc, pWhere);
drh1398ad32005-01-19 23:24:50 +0000979
drh75897232000-05-29 14:26:00 +0000980 /* Allocate and initialize the WhereInfo structure that will become the
981 ** return value.
982 */
drhad3cab52002-05-24 02:04:32 +0000983 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
danielk1977132872b2004-05-10 10:37:18 +0000984 if( sqlite3_malloc_failed ){
danielk1977d5d56522005-03-16 12:15:20 +0000985 sqliteFree(pWInfo); /* Avoid leaking memory when malloc fails */
drh0aa74ed2005-07-16 13:33:20 +0000986 whereClauseClear(&wc);
drh75897232000-05-29 14:26:00 +0000987 return 0;
988 }
989 pWInfo->pParse = pParse;
990 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +0000991 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh08192d52002-04-30 19:20:28 +0000992
993 /* Special case: a WHERE clause that is constant. Evaluate the
994 ** expression and either jump over all of the code or fall thru.
995 */
danielk19774adee202004-05-08 08:23:19 +0000996 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
997 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
drhdf199a22002-06-14 22:38:41 +0000998 pWhere = 0;
drh08192d52002-04-30 19:20:28 +0000999 }
drh75897232000-05-29 14:26:00 +00001000
drh29dda4a2005-07-21 18:23:20 +00001001 /* Analyze all of the subexpressions. Note that exprAnalyze() might
1002 ** add new virtual terms onto the end of the WHERE clause. We do not
1003 ** want to analyze these virtual terms, so start analyzing at the end
1004 ** and work forward so that they added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00001005 */
drh1398ad32005-01-19 23:24:50 +00001006 for(i=0; i<pTabList->nSrc; i++){
1007 createMask(&maskSet, pTabList->a[i].iCursor);
1008 }
drh0fcef5e2005-07-19 17:38:22 +00001009 for(i=wc.nTerm-1; i>=0; i--){
1010 exprAnalyze(pTabList, &maskSet, &wc.a[i]);
drh75897232000-05-29 14:26:00 +00001011 }
1012
drh29dda4a2005-07-21 18:23:20 +00001013 /* Chose the best index to use for each table in the FROM clause.
1014 **
1015 ** This loop fills in the pWInfo->a[].pIdx and pWInfo->a[].flags fields
1016 ** with information
1017 ** Reorder tables if necessary in order to choose a good ordering.
1018 ** However, LEFT JOIN tables cannot be reordered.
drh75897232000-05-29 14:26:00 +00001019 */
drhfe05af82005-07-21 03:14:59 +00001020 notReady = ~(Bitmask)0;
drh9012bcb2004-12-19 00:11:35 +00001021 pTabItem = pTabList->a;
1022 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001023 for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1024 Index *pIdx; /* Index for FROM table at pTabItem */
1025 int flags; /* Flags asssociated with pIdx */
1026 double score; /* The score for pIdx */
1027 int j; /* For looping over FROM tables */
1028 Index *pBest = 0; /* The best index seen so far */
1029 int bestFlags = 0; /* Flags associated with pBest */
1030 double bestScore = -1.0; /* The score of pBest */
1031 int bestJ; /* The value of j */
1032 Bitmask m; /* Bitmask value for j or bestJ */
1033
1034 for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
1035 m = getMask(&maskSet, pTabItem->iCursor);
1036 if( (m & notReady)==0 ){
1037 if( j==iFrom ) iFrom++;
1038 continue;
1039 }
1040 score = bestIndex(pParse, &wc, pTabItem, notReady,
1041 (j==0 && ppOrderBy) ? *ppOrderBy : 0,
1042 &pIdx, &flags);
1043 if( score>bestScore ){
1044 bestScore = score;
1045 pBest = pIdx;
1046 bestFlags = flags;
1047 bestJ = j;
1048 }
1049 if( (pTabItem->jointype & JT_LEFT)!=0
1050 || (j>0 && (pTabItem[-1].jointype & JT_LEFT)!=0)
1051 ){
1052 break;
1053 }
1054 }
1055 if( bestFlags & WHERE_ORDERBY ){
drhfe05af82005-07-21 03:14:59 +00001056 *ppOrderBy = 0;
drhc4a3c772001-04-04 11:48:57 +00001057 }
drh29dda4a2005-07-21 18:23:20 +00001058 pLevel->flags = bestFlags;
drhfe05af82005-07-21 03:14:59 +00001059 pLevel->pIdx = pBest;
1060 if( pBest ){
drh9012bcb2004-12-19 00:11:35 +00001061 pLevel->iIdxCur = pParse->nTab++;
drhfe05af82005-07-21 03:14:59 +00001062 }else{
1063 pLevel->iIdxCur = -1;
drh6b563442001-11-07 16:48:26 +00001064 }
drh29dda4a2005-07-21 18:23:20 +00001065 notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
1066 pLevel->iFrom = bestJ;
drh75897232000-05-29 14:26:00 +00001067 }
1068
drh9012bcb2004-12-19 00:11:35 +00001069 /* Open all tables in the pTabList and any indices selected for
1070 ** searching those tables.
1071 */
1072 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
1073 pLevel = pWInfo->a;
drh29dda4a2005-07-21 18:23:20 +00001074 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drh9012bcb2004-12-19 00:11:35 +00001075 Table *pTab;
1076 Index *pIx;
1077 int iIdxCur = pLevel->iIdxCur;
1078
drh29dda4a2005-07-21 18:23:20 +00001079 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001080 pTab = pTabItem->pTab;
1081 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001082 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001083 sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
1084 }
1085 pLevel->iTabCur = pTabItem->iCursor;
1086 if( (pIx = pLevel->pIdx)!=0 ){
1087 sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
drh29dda4a2005-07-21 18:23:20 +00001088 VdbeComment((v, "# %s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00001089 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
1090 (char*)&pIx->keyInfo, P3_KEYINFO);
1091 }
drhfe05af82005-07-21 03:14:59 +00001092 if( (pLevel->flags & WHERE_IDX_ONLY)!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001093 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
1094 }
1095 sqlite3CodeVerifySchema(pParse, pTab->iDb);
1096 }
1097 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
1098
drh29dda4a2005-07-21 18:23:20 +00001099 /* Generate the code to do the search. Each iteration of the for
1100 ** loop below generates code for a single nested loop of the VM
1101 ** program.
drh75897232000-05-29 14:26:00 +00001102 */
drhfe05af82005-07-21 03:14:59 +00001103 notReady = ~(Bitmask)0;
drh29dda4a2005-07-21 18:23:20 +00001104 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
drhfe05af82005-07-21 03:14:59 +00001105 int j;
drh9012bcb2004-12-19 00:11:35 +00001106 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
1107 Index *pIdx; /* The index we will be using */
1108 int iIdxCur; /* The VDBE cursor for the index */
1109 int omitTable; /* True if we use the index only */
drh29dda4a2005-07-21 18:23:20 +00001110 int bRev; /* True if we need to scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001111
drh29dda4a2005-07-21 18:23:20 +00001112 pTabItem = &pTabList->a[pLevel->iFrom];
1113 iCur = pTabItem->iCursor;
drh9012bcb2004-12-19 00:11:35 +00001114 pIdx = pLevel->pIdx;
1115 iIdxCur = pLevel->iIdxCur;
1116 pLevel->inOp = OP_Noop;
drh29dda4a2005-07-21 18:23:20 +00001117 bRev = (pLevel->flags & WHERE_REVERSE)!=0;
drhfe05af82005-07-21 03:14:59 +00001118 omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
drh75897232000-05-29 14:26:00 +00001119
drh29dda4a2005-07-21 18:23:20 +00001120 /* Create labels for the "break" and "continue" instructions
1121 ** for the current loop. Jump to brk to break out of a loop.
1122 ** Jump to cont to go immediately to the next iteration of the
1123 ** loop.
1124 */
1125 brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
1126 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1127
drhad2d8302002-05-24 20:31:36 +00001128 /* If this is the right table of a LEFT OUTER JOIN, allocate and
drh174b6192002-12-03 02:22:52 +00001129 ** initialize a memory cell that records if this table matches any
drhc27a1ce2002-06-14 20:58:45 +00001130 ** row of the left table of the join.
drhad2d8302002-05-24 20:31:36 +00001131 */
drh29dda4a2005-07-21 18:23:20 +00001132 if( pLevel->iFrom>0 && (pTabItem[-1].jointype & JT_LEFT)!=0 ){
drhad2d8302002-05-24 20:31:36 +00001133 if( !pParse->nMem ) pParse->nMem++;
1134 pLevel->iLeftJoin = pParse->nMem++;
drhf0863fe2005-06-12 21:35:51 +00001135 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001136 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001137 VdbeComment((v, "# init LEFT JOIN no-match flag"));
drhad2d8302002-05-24 20:31:36 +00001138 }
1139
drhfe05af82005-07-21 03:14:59 +00001140 if( pLevel->flags & WHERE_ROWID_EQ ){
drh8aff1012001-12-22 14:49:24 +00001141 /* Case 1: We can directly reference a single row using an
drhc27a1ce2002-06-14 20:58:45 +00001142 ** equality comparison against the ROWID field. Or
1143 ** we reference multiple rows using a "rowid IN (...)"
1144 ** construct.
drhc4a3c772001-04-04 11:48:57 +00001145 */
drhfe05af82005-07-21 03:14:59 +00001146 pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1147 assert( pTerm!=0 );
drh0fcef5e2005-07-19 17:38:22 +00001148 assert( pTerm->pExpr!=0 );
1149 assert( pTerm->leftCursor==iCur );
drh9012bcb2004-12-19 00:11:35 +00001150 assert( omitTable==0 );
drh94a11212004-09-25 13:12:14 +00001151 codeEqualityTerm(pParse, pTerm, brk, pLevel);
danielk19774adee202004-05-08 08:23:19 +00001152 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
danielk19774adee202004-05-08 08:23:19 +00001153 sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001154 VdbeComment((v, "pk"));
drh6b563442001-11-07 16:48:26 +00001155 pLevel->op = OP_Noop;
drhfe05af82005-07-21 03:14:59 +00001156 }else if( pLevel->flags & WHERE_COLUMN_EQ ){
drhc27a1ce2002-06-14 20:58:45 +00001157 /* Case 2: There is an index and all terms of the WHERE clause that
drhb6c29892004-11-22 19:12:19 +00001158 ** refer to the index using the "==" or "IN" operators.
drh75897232000-05-29 14:26:00 +00001159 */
drh6b563442001-11-07 16:48:26 +00001160 int start;
drhfe05af82005-07-21 03:14:59 +00001161 int nColumn;
drh772ae622004-05-19 13:13:08 +00001162
1163 /* For each column of the index, find the term of the WHERE clause that
1164 ** constraints that column. If the WHERE clause term is X=expr, then
drh0aa74ed2005-07-16 13:33:20 +00001165 ** generate code to evaluate expr and leave the result on the stack */
drhfe05af82005-07-21 03:14:59 +00001166 for(j=0; 1; j++){
1167 int k = pIdx->aiColumn[j];
1168 pTerm = findTerm(&wc, iCur, k, notReady, WO_EQ|WO_IN, pIdx);
1169 if( pTerm==0 ) break;
1170 if( pTerm->operator==WO_IN && j>0 ) break;
drhe8b97272005-07-19 22:22:12 +00001171 assert( (pTerm->flags & TERM_CODED)==0 );
1172 codeEqualityTerm(pParse, pTerm, brk, pLevel);
drhfe05af82005-07-21 03:14:59 +00001173 if( pTerm->operator==WO_IN ){
1174 j++;
1175 break;
1176 }
drh75897232000-05-29 14:26:00 +00001177 }
drhfe05af82005-07-21 03:14:59 +00001178 nColumn = j;
drh6b563442001-11-07 16:48:26 +00001179 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001180 buildIndexProbe(v, nColumn, brk, pIdx);
danielk19773d1bfea2004-05-14 11:00:53 +00001181 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
drh772ae622004-05-19 13:13:08 +00001182
drh772ae622004-05-19 13:13:08 +00001183 /* Generate code (1) to move to the first matching element of the table.
1184 ** Then generate code (2) that jumps to "brk" after the cursor is past
1185 ** the last matching element of the table. The code (1) is executed
1186 ** once to initialize the search, the code (2) is executed before each
1187 ** iteration of the scan to see if the scan has finished. */
drh29dda4a2005-07-21 18:23:20 +00001188 if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001189 /* Scan in reverse order */
drh9012bcb2004-12-19 00:11:35 +00001190 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001191 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001192 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001193 pLevel->op = OP_Prev;
1194 }else{
1195 /* Scan in the forward order */
drh9012bcb2004-12-19 00:11:35 +00001196 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
danielk19774adee202004-05-08 08:23:19 +00001197 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001198 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
drhc045ec52002-12-04 20:01:06 +00001199 pLevel->op = OP_Next;
1200 }
drh9012bcb2004-12-19 00:11:35 +00001201 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001202 sqlite3VdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
drhe6f85e72004-12-25 01:03:13 +00001203 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001204 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001205 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh75897232000-05-29 14:26:00 +00001206 }
drh9012bcb2004-12-19 00:11:35 +00001207 pLevel->p1 = iIdxCur;
drh6b563442001-11-07 16:48:26 +00001208 pLevel->p2 = start;
drhfe05af82005-07-21 03:14:59 +00001209 }else if( pLevel->flags & WHERE_ROWID_RANGE ){
drh8aff1012001-12-22 14:49:24 +00001210 /* Case 3: We have an inequality comparison against the ROWID field.
1211 */
1212 int testOp = OP_Noop;
1213 int start;
drhfe05af82005-07-21 03:14:59 +00001214 WhereTerm *pStart, *pEnd;
drh8aff1012001-12-22 14:49:24 +00001215
drh9012bcb2004-12-19 00:11:35 +00001216 assert( omitTable==0 );
drhfe05af82005-07-21 03:14:59 +00001217 if( pLevel->flags & WHERE_BTM_LIMIT ){
1218 pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
1219 assert( pStart!=0 );
1220 }else{
1221 pStart = 0;
drhb6c29892004-11-22 19:12:19 +00001222 }
drhfe05af82005-07-21 03:14:59 +00001223 if( pLevel->flags & WHERE_TOP_LIMIT ){
1224 pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
1225 assert( pEnd!=0 );
1226 }else{
1227 pEnd = 0;
1228 }
1229 assert( pStart!=0 || pEnd!=0 );
1230 if( bRev ){
1231 pTerm = pStart;
1232 pStart = pEnd;
1233 pEnd = pTerm;
1234 }
1235 if( pStart ){
drh94a11212004-09-25 13:12:14 +00001236 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001237 pX = pStart->pExpr;
drh94a11212004-09-25 13:12:14 +00001238 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001239 assert( pStart->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001240 sqlite3ExprCode(pParse, pX->pRight);
danielk1977d0a69322005-02-02 01:10:44 +00001241 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
drhb6c29892004-11-22 19:12:19 +00001242 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
tpoindex7a9b1612005-01-03 18:13:18 +00001243 VdbeComment((v, "pk"));
drhfe05af82005-07-21 03:14:59 +00001244 disableTerm(pLevel, pStart);
drh8aff1012001-12-22 14:49:24 +00001245 }else{
drhb6c29892004-11-22 19:12:19 +00001246 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
drh8aff1012001-12-22 14:49:24 +00001247 }
drhfe05af82005-07-21 03:14:59 +00001248 if( pEnd ){
drh94a11212004-09-25 13:12:14 +00001249 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001250 pX = pEnd->pExpr;
drh94a11212004-09-25 13:12:14 +00001251 assert( pX!=0 );
drhfe05af82005-07-21 03:14:59 +00001252 assert( pEnd->leftCursor==iCur );
drh94a11212004-09-25 13:12:14 +00001253 sqlite3ExprCode(pParse, pX->pRight);
drh8aff1012001-12-22 14:49:24 +00001254 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001255 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drh94a11212004-09-25 13:12:14 +00001256 if( pX->op==TK_LT || pX->op==TK_GT ){
drhb6c29892004-11-22 19:12:19 +00001257 testOp = bRev ? OP_Le : OP_Ge;
drh8aff1012001-12-22 14:49:24 +00001258 }else{
drhb6c29892004-11-22 19:12:19 +00001259 testOp = bRev ? OP_Lt : OP_Gt;
drh8aff1012001-12-22 14:49:24 +00001260 }
drhfe05af82005-07-21 03:14:59 +00001261 disableTerm(pLevel, pEnd);
drh8aff1012001-12-22 14:49:24 +00001262 }
danielk19774adee202004-05-08 08:23:19 +00001263 start = sqlite3VdbeCurrentAddr(v);
drhb6c29892004-11-22 19:12:19 +00001264 pLevel->op = bRev ? OP_Prev : OP_Next;
drh6a3ea0e2003-05-02 14:32:12 +00001265 pLevel->p1 = iCur;
drh8aff1012001-12-22 14:49:24 +00001266 pLevel->p2 = start;
1267 if( testOp!=OP_Noop ){
drhf0863fe2005-06-12 21:35:51 +00001268 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
danielk19774adee202004-05-08 08:23:19 +00001269 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drhf0863fe2005-06-12 21:35:51 +00001270 sqlite3VdbeAddOp(v, testOp, 'n', brk);
drh8aff1012001-12-22 14:49:24 +00001271 }
drhfe05af82005-07-21 03:14:59 +00001272 }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
1273 /* Case 4: The WHERE clause term that refers to the right-most
drhc27a1ce2002-06-14 20:58:45 +00001274 ** column of the index is an inequality. For example, if
1275 ** the index is on (x,y,z) and the WHERE clause is of the
1276 ** form "x=5 AND y<10" then this case is used. Only the
1277 ** right-most column can be an inequality - the rest must
1278 ** use the "==" operator.
drhe3184742002-06-19 14:27:05 +00001279 **
1280 ** This case is also used when there are no WHERE clause
1281 ** constraints but an index is selected anyway, in order
1282 ** to force the output order to conform to an ORDER BY.
drh487ab3c2001-11-08 00:45:21 +00001283 */
drhfe05af82005-07-21 03:14:59 +00001284 int nEqColumn;
drh487ab3c2001-11-08 00:45:21 +00001285 int start;
danielk1977f7df9cc2004-06-16 12:02:47 +00001286 int leFlag=0, geFlag=0;
drh487ab3c2001-11-08 00:45:21 +00001287 int testOp;
drhfe05af82005-07-21 03:14:59 +00001288 int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
1289 int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
drh487ab3c2001-11-08 00:45:21 +00001290
1291 /* Evaluate the equality constraints
1292 */
drhfe05af82005-07-21 03:14:59 +00001293 for(j=0; 1; j++){
1294 int k = pIdx->aiColumn[j];
1295 pTerm = findTerm(&wc, iCur, k, notReady, WO_EQ, pIdx);
1296 if( pTerm==0 ) break;
drhe8b97272005-07-19 22:22:12 +00001297 assert( (pTerm->flags & TERM_CODED)==0 );
1298 sqlite3ExprCode(pParse, pTerm->pExpr->pRight);
1299 disableTerm(pLevel, pTerm);
drh487ab3c2001-11-08 00:45:21 +00001300 }
drhfe05af82005-07-21 03:14:59 +00001301 nEqColumn = j;
drh487ab3c2001-11-08 00:45:21 +00001302
drhc27a1ce2002-06-14 20:58:45 +00001303 /* Duplicate the equality term values because they will all be
drh487ab3c2001-11-08 00:45:21 +00001304 ** used twice: once to make the termination key and once to make the
1305 ** start key.
1306 */
1307 for(j=0; j<nEqColumn; j++){
danielk19774adee202004-05-08 08:23:19 +00001308 sqlite3VdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
drh487ab3c2001-11-08 00:45:21 +00001309 }
1310
1311 /* Generate the termination key. This is the key value that
1312 ** will end the search. There is no termination key if there
drhc27a1ce2002-06-14 20:58:45 +00001313 ** are no equality terms and no "X<..." term.
drhc045ec52002-12-04 20:01:06 +00001314 **
1315 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1316 ** key computed here really ends up being the start key.
drh487ab3c2001-11-08 00:45:21 +00001317 */
drhfe05af82005-07-21 03:14:59 +00001318 if( topLimit ){
drhe8b97272005-07-19 22:22:12 +00001319 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001320 int k = pIdx->aiColumn[j];
1321 pTerm = findTerm(&wc, iCur, k, notReady, WO_LT|WO_LE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001322 assert( pTerm!=0 );
1323 pX = pTerm->pExpr;
1324 assert( (pTerm->flags & TERM_CODED)==0 );
1325 sqlite3ExprCode(pParse, pX->pRight);
1326 leFlag = pX->op==TK_LE;
1327 disableTerm(pLevel, pTerm);
drh487ab3c2001-11-08 00:45:21 +00001328 testOp = OP_IdxGE;
1329 }else{
1330 testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
1331 leFlag = 1;
1332 }
1333 if( testOp!=OP_Noop ){
drhfe05af82005-07-21 03:14:59 +00001334 int nCol = nEqColumn + topLimit;
drh487ab3c2001-11-08 00:45:21 +00001335 pLevel->iMem = pParse->nMem++;
drh94a11212004-09-25 13:12:14 +00001336 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001337 if( bRev ){
drh7cf6e4d2004-05-19 14:56:55 +00001338 int op = leFlag ? OP_MoveLe : OP_MoveLt;
drh9012bcb2004-12-19 00:11:35 +00001339 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001340 }else{
danielk19774adee202004-05-08 08:23:19 +00001341 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001342 }
drhfe05af82005-07-21 03:14:59 +00001343 }else if( bRev ){
drh9012bcb2004-12-19 00:11:35 +00001344 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001345 }
1346
1347 /* Generate the start key. This is the key that defines the lower
drhc27a1ce2002-06-14 20:58:45 +00001348 ** bound on the search. There is no start key if there are no
1349 ** equality terms and if there is no "X>..." term. In
drh487ab3c2001-11-08 00:45:21 +00001350 ** that case, generate a "Rewind" instruction in place of the
1351 ** start key search.
drhc045ec52002-12-04 20:01:06 +00001352 **
1353 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1354 ** "start" key really ends up being used as the termination key.
drh487ab3c2001-11-08 00:45:21 +00001355 */
drhfe05af82005-07-21 03:14:59 +00001356 if( btmLimit ){
drhe8b97272005-07-19 22:22:12 +00001357 Expr *pX;
drhfe05af82005-07-21 03:14:59 +00001358 int k = pIdx->aiColumn[j];
1359 pTerm = findTerm(&wc, iCur, k, notReady, WO_GT|WO_GE, pIdx);
drhe8b97272005-07-19 22:22:12 +00001360 assert( pTerm!=0 );
1361 pX = pTerm->pExpr;
1362 assert( (pTerm->flags & TERM_CODED)==0 );
1363 sqlite3ExprCode(pParse, pX->pRight);
1364 geFlag = pX->op==TK_GE;
1365 disableTerm(pLevel, pTerm);
drh7900ead2001-11-12 13:51:43 +00001366 }else{
1367 geFlag = 1;
drh487ab3c2001-11-08 00:45:21 +00001368 }
drhfe05af82005-07-21 03:14:59 +00001369 if( nEqColumn>0 || btmLimit ){
1370 int nCol = nEqColumn + btmLimit;
drh94a11212004-09-25 13:12:14 +00001371 buildIndexProbe(v, nCol, brk, pIdx);
drhfe05af82005-07-21 03:14:59 +00001372 if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001373 pLevel->iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001374 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
drhc045ec52002-12-04 20:01:06 +00001375 testOp = OP_IdxLT;
1376 }else{
drh7cf6e4d2004-05-19 14:56:55 +00001377 int op = geFlag ? OP_MoveGe : OP_MoveGt;
drh9012bcb2004-12-19 00:11:35 +00001378 sqlite3VdbeAddOp(v, op, iIdxCur, brk);
drhc045ec52002-12-04 20:01:06 +00001379 }
drhfe05af82005-07-21 03:14:59 +00001380 }else if( bRev ){
drhc045ec52002-12-04 20:01:06 +00001381 testOp = OP_Noop;
drh487ab3c2001-11-08 00:45:21 +00001382 }else{
drh9012bcb2004-12-19 00:11:35 +00001383 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
drh487ab3c2001-11-08 00:45:21 +00001384 }
1385
1386 /* Generate the the top of the loop. If there is a termination
1387 ** key we have to test for that key and abort at the top of the
1388 ** loop.
1389 */
danielk19774adee202004-05-08 08:23:19 +00001390 start = sqlite3VdbeCurrentAddr(v);
drh487ab3c2001-11-08 00:45:21 +00001391 if( testOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001392 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
drh9012bcb2004-12-19 00:11:35 +00001393 sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
drhfe05af82005-07-21 03:14:59 +00001394 if( (leFlag && !bRev) || (!geFlag && bRev) ){
danielk19773d1bfea2004-05-14 11:00:53 +00001395 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
1396 }
drh487ab3c2001-11-08 00:45:21 +00001397 }
drh9012bcb2004-12-19 00:11:35 +00001398 sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
drhfe05af82005-07-21 03:14:59 +00001399 sqlite3VdbeAddOp(v, OP_IdxIsNull, nEqColumn + topLimit, cont);
drhe6f85e72004-12-25 01:03:13 +00001400 if( !omitTable ){
drhf0863fe2005-06-12 21:35:51 +00001401 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
drhe6f85e72004-12-25 01:03:13 +00001402 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
drh487ab3c2001-11-08 00:45:21 +00001403 }
1404
1405 /* Record the instruction used to terminate the loop.
1406 */
drhfe05af82005-07-21 03:14:59 +00001407 pLevel->op = bRev ? OP_Prev : OP_Next;
drh9012bcb2004-12-19 00:11:35 +00001408 pLevel->p1 = iIdxCur;
drh487ab3c2001-11-08 00:45:21 +00001409 pLevel->p2 = start;
drhfe05af82005-07-21 03:14:59 +00001410 }else{
1411 /* Case 5: There is no usable index. We must do a complete
1412 ** scan of the entire table.
1413 */
drhfe05af82005-07-21 03:14:59 +00001414 int opRewind;
1415
1416 assert( omitTable==0 );
drh29dda4a2005-07-21 18:23:20 +00001417 if( bRev ){
drhfe05af82005-07-21 03:14:59 +00001418 opRewind = OP_Last;
1419 pLevel->op = OP_Prev;
1420 }else{
1421 opRewind = OP_Rewind;
1422 pLevel->op = OP_Next;
1423 }
drhfe05af82005-07-21 03:14:59 +00001424 pLevel->p1 = iCur;
drh29dda4a2005-07-21 18:23:20 +00001425 pLevel->p2 = 1 + sqlite3VdbeAddOp(v, opRewind, iCur, brk);
drh75897232000-05-29 14:26:00 +00001426 }
drhfe05af82005-07-21 03:14:59 +00001427 notReady &= ~getMask(&maskSet, iCur);
drh75897232000-05-29 14:26:00 +00001428
1429 /* Insert code to test every subexpression that can be completely
1430 ** computed using the current set of tables.
1431 */
drh0fcef5e2005-07-19 17:38:22 +00001432 for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
1433 Expr *pE;
1434 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001435 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001436 pE = pTerm->pExpr;
1437 assert( pE!=0 );
drh392e5972005-07-08 14:14:22 +00001438 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
drh1f162302002-10-27 19:35:33 +00001439 continue;
1440 }
drh392e5972005-07-08 14:14:22 +00001441 sqlite3ExprIfFalse(pParse, pE, cont, 1);
drh0fcef5e2005-07-19 17:38:22 +00001442 pTerm->flags |= TERM_CODED;
drh75897232000-05-29 14:26:00 +00001443 }
drhad2d8302002-05-24 20:31:36 +00001444
1445 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1446 ** at least one row of the right table has matched the left table.
1447 */
1448 if( pLevel->iLeftJoin ){
danielk19774adee202004-05-08 08:23:19 +00001449 pLevel->top = sqlite3VdbeCurrentAddr(v);
1450 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1451 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
drhad6d9462004-09-19 02:15:24 +00001452 VdbeComment((v, "# record LEFT JOIN hit"));
drh0aa74ed2005-07-16 13:33:20 +00001453 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
drh0fcef5e2005-07-19 17:38:22 +00001454 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhfe05af82005-07-21 03:14:59 +00001455 if( (pTerm->prereqAll & notReady)!=0 ) continue;
drh0fcef5e2005-07-19 17:38:22 +00001456 assert( pTerm->pExpr );
1457 sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
1458 pTerm->flags |= TERM_CODED;
drh1cc093c2002-06-24 22:01:57 +00001459 }
drhad2d8302002-05-24 20:31:36 +00001460 }
drh75897232000-05-29 14:26:00 +00001461 }
drh7ec764a2005-07-21 03:48:20 +00001462
1463#ifdef SQLITE_TEST /* For testing and debugging use only */
1464 /* Record in the query plan information about the current table
1465 ** and the index used to access it (if any). If the table itself
1466 ** is not used, its name is just '{}'. If no index is used
1467 ** the index is listed as "{}". If the primary key is used the
1468 ** index name is '*'.
1469 */
1470 for(i=0; i<pTabList->nSrc; i++){
1471 char *z;
1472 int n;
drh7ec764a2005-07-21 03:48:20 +00001473 pLevel = &pWInfo->a[i];
drh29dda4a2005-07-21 18:23:20 +00001474 pTabItem = &pTabList->a[pLevel->iFrom];
drh7ec764a2005-07-21 03:48:20 +00001475 z = pTabItem->zAlias;
1476 if( z==0 ) z = pTabItem->pTab->zName;
1477 n = strlen(z);
1478 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
1479 if( pLevel->flags & WHERE_IDX_ONLY ){
1480 strcpy(&sqlite3_query_plan[nQPlan], "{}");
1481 nQPlan += 2;
1482 }else{
1483 strcpy(&sqlite3_query_plan[nQPlan], z);
1484 nQPlan += n;
1485 }
1486 sqlite3_query_plan[nQPlan++] = ' ';
1487 }
1488 if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
1489 strcpy(&sqlite3_query_plan[nQPlan], "* ");
1490 nQPlan += 2;
1491 }else if( pLevel->pIdx==0 ){
1492 strcpy(&sqlite3_query_plan[nQPlan], "{} ");
1493 nQPlan += 3;
1494 }else{
1495 n = strlen(pLevel->pIdx->zName);
1496 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
1497 strcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName);
1498 nQPlan += n;
1499 sqlite3_query_plan[nQPlan++] = ' ';
1500 }
1501 }
1502 }
1503 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
1504 sqlite3_query_plan[--nQPlan] = 0;
1505 }
1506 sqlite3_query_plan[nQPlan] = 0;
1507 nQPlan = 0;
1508#endif /* SQLITE_TEST // Testing and debugging use only */
1509
drh29dda4a2005-07-21 18:23:20 +00001510 /* Record the continuation address in the WhereInfo structure. Then
1511 ** clean up and return.
1512 */
drh75897232000-05-29 14:26:00 +00001513 pWInfo->iContinue = cont;
drh6a3ea0e2003-05-02 14:32:12 +00001514 freeMaskSet(&maskSet);
drh0aa74ed2005-07-16 13:33:20 +00001515 whereClauseClear(&wc);
drh75897232000-05-29 14:26:00 +00001516 return pWInfo;
1517}
1518
1519/*
drhc27a1ce2002-06-14 20:58:45 +00001520** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00001521** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00001522*/
danielk19774adee202004-05-08 08:23:19 +00001523void sqlite3WhereEnd(WhereInfo *pWInfo){
drh75897232000-05-29 14:26:00 +00001524 Vdbe *v = pWInfo->pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00001525 int i;
drh6b563442001-11-07 16:48:26 +00001526 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00001527 SrcList *pTabList = pWInfo->pTabList;
drh19a775c2000-06-05 18:54:46 +00001528
drh9012bcb2004-12-19 00:11:35 +00001529 /* Generate loop termination code.
1530 */
drhad3cab52002-05-24 02:04:32 +00001531 for(i=pTabList->nSrc-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00001532 pLevel = &pWInfo->a[i];
danielk19774adee202004-05-08 08:23:19 +00001533 sqlite3VdbeResolveLabel(v, pLevel->cont);
drh6b563442001-11-07 16:48:26 +00001534 if( pLevel->op!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001535 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
drh19a775c2000-06-05 18:54:46 +00001536 }
danielk19774adee202004-05-08 08:23:19 +00001537 sqlite3VdbeResolveLabel(v, pLevel->brk);
drhd99f7062002-06-08 23:25:08 +00001538 if( pLevel->inOp!=OP_Noop ){
danielk19774adee202004-05-08 08:23:19 +00001539 sqlite3VdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
drhd99f7062002-06-08 23:25:08 +00001540 }
drhad2d8302002-05-24 20:31:36 +00001541 if( pLevel->iLeftJoin ){
1542 int addr;
danielk19774adee202004-05-08 08:23:19 +00001543 addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
drh9012bcb2004-12-19 00:11:35 +00001544 sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
danielk19774adee202004-05-08 08:23:19 +00001545 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
drh9012bcb2004-12-19 00:11:35 +00001546 if( pLevel->iIdxCur>=0 ){
1547 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
drh7f09b3e2002-08-13 13:15:49 +00001548 }
danielk19774adee202004-05-08 08:23:19 +00001549 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
drhad2d8302002-05-24 20:31:36 +00001550 }
drh19a775c2000-06-05 18:54:46 +00001551 }
drh9012bcb2004-12-19 00:11:35 +00001552
1553 /* The "break" point is here, just past the end of the outer loop.
1554 ** Set it.
1555 */
danielk19774adee202004-05-08 08:23:19 +00001556 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00001557
drh29dda4a2005-07-21 18:23:20 +00001558 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00001559 */
drh29dda4a2005-07-21 18:23:20 +00001560 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1561 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00001562 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00001563 assert( pTab!=0 );
1564 if( pTab->isTransient || pTab->pSelect ) continue;
drhfe05af82005-07-21 03:14:59 +00001565 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
drh9012bcb2004-12-19 00:11:35 +00001566 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
1567 }
drh6b563442001-11-07 16:48:26 +00001568 if( pLevel->pIdx!=0 ){
drh9012bcb2004-12-19 00:11:35 +00001569 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
1570 }
1571
drhacf3b982005-01-03 01:27:18 +00001572 /* Make cursor substitutions for cases where we want to use
drh9012bcb2004-12-19 00:11:35 +00001573 ** just the index and never reference the table.
1574 **
1575 ** Calls to the code generator in between sqlite3WhereBegin and
1576 ** sqlite3WhereEnd will have created code that references the table
1577 ** directly. This loop scans all that code looking for opcodes
1578 ** that reference the table and converts them into opcodes that
1579 ** reference the index.
1580 */
drhfe05af82005-07-21 03:14:59 +00001581 if( pLevel->flags & WHERE_IDX_ONLY ){
drh9012bcb2004-12-19 00:11:35 +00001582 int i, j, last;
1583 VdbeOp *pOp;
1584 Index *pIdx = pLevel->pIdx;
1585
1586 assert( pIdx!=0 );
1587 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1588 last = sqlite3VdbeCurrentAddr(v);
1589 for(i=pWInfo->iTop; i<last; i++, pOp++){
1590 if( pOp->p1!=pLevel->iTabCur ) continue;
1591 if( pOp->opcode==OP_Column ){
1592 pOp->p1 = pLevel->iIdxCur;
1593 for(j=0; j<pIdx->nColumn; j++){
1594 if( pOp->p2==pIdx->aiColumn[j] ){
1595 pOp->p2 = j;
1596 break;
1597 }
1598 }
drhf0863fe2005-06-12 21:35:51 +00001599 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00001600 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00001601 pOp->opcode = OP_IdxRowid;
danielk19776c18b6e2005-01-30 09:17:58 +00001602 }else if( pOp->opcode==OP_NullRow ){
1603 pOp->opcode = OP_Noop;
drh9012bcb2004-12-19 00:11:35 +00001604 }
1605 }
drh6b563442001-11-07 16:48:26 +00001606 }
drh19a775c2000-06-05 18:54:46 +00001607 }
drh9012bcb2004-12-19 00:11:35 +00001608
1609 /* Final cleanup
1610 */
drh75897232000-05-29 14:26:00 +00001611 sqliteFree(pWInfo);
1612 return;
1613}