xref: /titanic_44/usr/src/lib/libsqlite/src/where.c (revision c5c4113dfcabb1eed3d4bdf7609de5170027a794)
1*c5c4113dSnw141292 
2*c5c4113dSnw141292 #pragma ident	"%Z%%M%	%I%	%E% SMI"
3*c5c4113dSnw141292 
4*c5c4113dSnw141292 /*
5*c5c4113dSnw141292 ** 2001 September 15
6*c5c4113dSnw141292 **
7*c5c4113dSnw141292 ** The author disclaims copyright to this source code.  In place of
8*c5c4113dSnw141292 ** a legal notice, here is a blessing:
9*c5c4113dSnw141292 **
10*c5c4113dSnw141292 **    May you do good and not evil.
11*c5c4113dSnw141292 **    May you find forgiveness for yourself and forgive others.
12*c5c4113dSnw141292 **    May you share freely, never taking more than you give.
13*c5c4113dSnw141292 **
14*c5c4113dSnw141292 *************************************************************************
15*c5c4113dSnw141292 ** This module contains C code that generates VDBE code used to process
16*c5c4113dSnw141292 ** the WHERE clause of SQL statements.
17*c5c4113dSnw141292 **
18*c5c4113dSnw141292 ** $Id: where.c,v 1.89.2.2 2004/07/19 19:30:50 drh Exp $
19*c5c4113dSnw141292 */
20*c5c4113dSnw141292 #include "sqliteInt.h"
21*c5c4113dSnw141292 
22*c5c4113dSnw141292 /*
23*c5c4113dSnw141292 ** The query generator uses an array of instances of this structure to
24*c5c4113dSnw141292 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
25*c5c4113dSnw141292 ** clause subexpression is separated from the others by an AND operator.
26*c5c4113dSnw141292 */
27*c5c4113dSnw141292 typedef struct ExprInfo ExprInfo;
28*c5c4113dSnw141292 struct ExprInfo {
29*c5c4113dSnw141292   Expr *p;                /* Pointer to the subexpression */
30*c5c4113dSnw141292   u8 indexable;           /* True if this subexprssion is usable by an index */
31*c5c4113dSnw141292   short int idxLeft;      /* p->pLeft is a column in this table number. -1 if
32*c5c4113dSnw141292                           ** p->pLeft is not the column of any table */
33*c5c4113dSnw141292   short int idxRight;     /* p->pRight is a column in this table number. -1 if
34*c5c4113dSnw141292                           ** p->pRight is not the column of any table */
35*c5c4113dSnw141292   unsigned prereqLeft;    /* Bitmask of tables referenced by p->pLeft */
36*c5c4113dSnw141292   unsigned prereqRight;   /* Bitmask of tables referenced by p->pRight */
37*c5c4113dSnw141292   unsigned prereqAll;     /* Bitmask of tables referenced by p */
38*c5c4113dSnw141292 };
39*c5c4113dSnw141292 
40*c5c4113dSnw141292 /*
41*c5c4113dSnw141292 ** An instance of the following structure keeps track of a mapping
42*c5c4113dSnw141292 ** between VDBE cursor numbers and bitmasks.  The VDBE cursor numbers
43*c5c4113dSnw141292 ** are small integers contained in SrcList_item.iCursor and Expr.iTable
44*c5c4113dSnw141292 ** fields.  For any given WHERE clause, we want to track which cursors
45*c5c4113dSnw141292 ** are being used, so we assign a single bit in a 32-bit word to track
46*c5c4113dSnw141292 ** that cursor.  Then a 32-bit integer is able to show the set of all
47*c5c4113dSnw141292 ** cursors being used.
48*c5c4113dSnw141292 */
49*c5c4113dSnw141292 typedef struct ExprMaskSet ExprMaskSet;
50*c5c4113dSnw141292 struct ExprMaskSet {
51*c5c4113dSnw141292   int n;          /* Number of assigned cursor values */
52*c5c4113dSnw141292   int ix[31];     /* Cursor assigned to each bit */
53*c5c4113dSnw141292 };
54*c5c4113dSnw141292 
55*c5c4113dSnw141292 /*
56*c5c4113dSnw141292 ** Determine the number of elements in an array.
57*c5c4113dSnw141292 */
58*c5c4113dSnw141292 #define ARRAYSIZE(X)  (sizeof(X)/sizeof(X[0]))
59*c5c4113dSnw141292 
60*c5c4113dSnw141292 /*
61*c5c4113dSnw141292 ** This routine is used to divide the WHERE expression into subexpressions
62*c5c4113dSnw141292 ** separated by the AND operator.
63*c5c4113dSnw141292 **
64*c5c4113dSnw141292 ** aSlot[] is an array of subexpressions structures.
65*c5c4113dSnw141292 ** There are nSlot spaces left in this array.  This routine attempts to
66*c5c4113dSnw141292 ** split pExpr into subexpressions and fills aSlot[] with those subexpressions.
67*c5c4113dSnw141292 ** The return value is the number of slots filled.
68*c5c4113dSnw141292 */
exprSplit(int nSlot,ExprInfo * aSlot,Expr * pExpr)69*c5c4113dSnw141292 static int exprSplit(int nSlot, ExprInfo *aSlot, Expr *pExpr){
70*c5c4113dSnw141292   int cnt = 0;
71*c5c4113dSnw141292   if( pExpr==0 || nSlot<1 ) return 0;
72*c5c4113dSnw141292   if( nSlot==1 || pExpr->op!=TK_AND ){
73*c5c4113dSnw141292     aSlot[0].p = pExpr;
74*c5c4113dSnw141292     return 1;
75*c5c4113dSnw141292   }
76*c5c4113dSnw141292   if( pExpr->pLeft->op!=TK_AND ){
77*c5c4113dSnw141292     aSlot[0].p = pExpr->pLeft;
78*c5c4113dSnw141292     cnt = 1 + exprSplit(nSlot-1, &aSlot[1], pExpr->pRight);
79*c5c4113dSnw141292   }else{
80*c5c4113dSnw141292     cnt = exprSplit(nSlot, aSlot, pExpr->pLeft);
81*c5c4113dSnw141292     cnt += exprSplit(nSlot-cnt, &aSlot[cnt], pExpr->pRight);
82*c5c4113dSnw141292   }
83*c5c4113dSnw141292   return cnt;
84*c5c4113dSnw141292 }
85*c5c4113dSnw141292 
86*c5c4113dSnw141292 /*
87*c5c4113dSnw141292 ** Initialize an expression mask set
88*c5c4113dSnw141292 */
89*c5c4113dSnw141292 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
90*c5c4113dSnw141292 
91*c5c4113dSnw141292 /*
92*c5c4113dSnw141292 ** Return the bitmask for the given cursor.  Assign a new bitmask
93*c5c4113dSnw141292 ** if this is the first time the cursor has been seen.
94*c5c4113dSnw141292 */
getMask(ExprMaskSet * pMaskSet,int iCursor)95*c5c4113dSnw141292 static int getMask(ExprMaskSet *pMaskSet, int iCursor){
96*c5c4113dSnw141292   int i;
97*c5c4113dSnw141292   for(i=0; i<pMaskSet->n; i++){
98*c5c4113dSnw141292     if( pMaskSet->ix[i]==iCursor ) return 1<<i;
99*c5c4113dSnw141292   }
100*c5c4113dSnw141292   if( i==pMaskSet->n && i<ARRAYSIZE(pMaskSet->ix) ){
101*c5c4113dSnw141292     pMaskSet->n++;
102*c5c4113dSnw141292     pMaskSet->ix[i] = iCursor;
103*c5c4113dSnw141292     return 1<<i;
104*c5c4113dSnw141292   }
105*c5c4113dSnw141292   return 0;
106*c5c4113dSnw141292 }
107*c5c4113dSnw141292 
108*c5c4113dSnw141292 /*
109*c5c4113dSnw141292 ** Destroy an expression mask set
110*c5c4113dSnw141292 */
111*c5c4113dSnw141292 #define freeMaskSet(P)   /* NO-OP */
112*c5c4113dSnw141292 
113*c5c4113dSnw141292 /*
114*c5c4113dSnw141292 ** This routine walks (recursively) an expression tree and generates
115*c5c4113dSnw141292 ** a bitmask indicating which tables are used in that expression
116*c5c4113dSnw141292 ** tree.
117*c5c4113dSnw141292 **
118*c5c4113dSnw141292 ** In order for this routine to work, the calling function must have
119*c5c4113dSnw141292 ** previously invoked sqliteExprResolveIds() on the expression.  See
120*c5c4113dSnw141292 ** the header comment on that routine for additional information.
121*c5c4113dSnw141292 ** The sqliteExprResolveIds() routines looks for column names and
122*c5c4113dSnw141292 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
123*c5c4113dSnw141292 ** the VDBE cursor number of the table.
124*c5c4113dSnw141292 */
exprTableUsage(ExprMaskSet * pMaskSet,Expr * p)125*c5c4113dSnw141292 static int exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
126*c5c4113dSnw141292   unsigned int mask = 0;
127*c5c4113dSnw141292   if( p==0 ) return 0;
128*c5c4113dSnw141292   if( p->op==TK_COLUMN ){
129*c5c4113dSnw141292     mask = getMask(pMaskSet, p->iTable);
130*c5c4113dSnw141292     if( mask==0 ) mask = -1;
131*c5c4113dSnw141292     return mask;
132*c5c4113dSnw141292   }
133*c5c4113dSnw141292   if( p->pRight ){
134*c5c4113dSnw141292     mask = exprTableUsage(pMaskSet, p->pRight);
135*c5c4113dSnw141292   }
136*c5c4113dSnw141292   if( p->pLeft ){
137*c5c4113dSnw141292     mask |= exprTableUsage(pMaskSet, p->pLeft);
138*c5c4113dSnw141292   }
139*c5c4113dSnw141292   if( p->pList ){
140*c5c4113dSnw141292     int i;
141*c5c4113dSnw141292     for(i=0; i<p->pList->nExpr; i++){
142*c5c4113dSnw141292       mask |= exprTableUsage(pMaskSet, p->pList->a[i].pExpr);
143*c5c4113dSnw141292     }
144*c5c4113dSnw141292   }
145*c5c4113dSnw141292   return mask;
146*c5c4113dSnw141292 }
147*c5c4113dSnw141292 
148*c5c4113dSnw141292 /*
149*c5c4113dSnw141292 ** Return TRUE if the given operator is one of the operators that is
150*c5c4113dSnw141292 ** allowed for an indexable WHERE clause.  The allowed operators are
151*c5c4113dSnw141292 ** "=", "<", ">", "<=", ">=", and "IN".
152*c5c4113dSnw141292 */
allowedOp(int op)153*c5c4113dSnw141292 static int allowedOp(int op){
154*c5c4113dSnw141292   switch( op ){
155*c5c4113dSnw141292     case TK_LT:
156*c5c4113dSnw141292     case TK_LE:
157*c5c4113dSnw141292     case TK_GT:
158*c5c4113dSnw141292     case TK_GE:
159*c5c4113dSnw141292     case TK_EQ:
160*c5c4113dSnw141292     case TK_IN:
161*c5c4113dSnw141292       return 1;
162*c5c4113dSnw141292     default:
163*c5c4113dSnw141292       return 0;
164*c5c4113dSnw141292   }
165*c5c4113dSnw141292 }
166*c5c4113dSnw141292 
167*c5c4113dSnw141292 /*
168*c5c4113dSnw141292 ** The input to this routine is an ExprInfo structure with only the
169*c5c4113dSnw141292 ** "p" field filled in.  The job of this routine is to analyze the
170*c5c4113dSnw141292 ** subexpression and populate all the other fields of the ExprInfo
171*c5c4113dSnw141292 ** structure.
172*c5c4113dSnw141292 */
exprAnalyze(ExprMaskSet * pMaskSet,ExprInfo * pInfo)173*c5c4113dSnw141292 static void exprAnalyze(ExprMaskSet *pMaskSet, ExprInfo *pInfo){
174*c5c4113dSnw141292   Expr *pExpr = pInfo->p;
175*c5c4113dSnw141292   pInfo->prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
176*c5c4113dSnw141292   pInfo->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
177*c5c4113dSnw141292   pInfo->prereqAll = exprTableUsage(pMaskSet, pExpr);
178*c5c4113dSnw141292   pInfo->indexable = 0;
179*c5c4113dSnw141292   pInfo->idxLeft = -1;
180*c5c4113dSnw141292   pInfo->idxRight = -1;
181*c5c4113dSnw141292   if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
182*c5c4113dSnw141292     if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
183*c5c4113dSnw141292       pInfo->idxRight = pExpr->pRight->iTable;
184*c5c4113dSnw141292       pInfo->indexable = 1;
185*c5c4113dSnw141292     }
186*c5c4113dSnw141292     if( pExpr->pLeft->op==TK_COLUMN ){
187*c5c4113dSnw141292       pInfo->idxLeft = pExpr->pLeft->iTable;
188*c5c4113dSnw141292       pInfo->indexable = 1;
189*c5c4113dSnw141292     }
190*c5c4113dSnw141292   }
191*c5c4113dSnw141292 }
192*c5c4113dSnw141292 
193*c5c4113dSnw141292 /*
194*c5c4113dSnw141292 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
195*c5c4113dSnw141292 ** left-most table in the FROM clause of that same SELECT statement and
196*c5c4113dSnw141292 ** the table has a cursor number of "base".
197*c5c4113dSnw141292 **
198*c5c4113dSnw141292 ** This routine attempts to find an index for pTab that generates the
199*c5c4113dSnw141292 ** correct record sequence for the given ORDER BY clause.  The return value
200*c5c4113dSnw141292 ** is a pointer to an index that does the job.  NULL is returned if the
201*c5c4113dSnw141292 ** table has no index that will generate the correct sort order.
202*c5c4113dSnw141292 **
203*c5c4113dSnw141292 ** If there are two or more indices that generate the correct sort order
204*c5c4113dSnw141292 ** and pPreferredIdx is one of those indices, then return pPreferredIdx.
205*c5c4113dSnw141292 **
206*c5c4113dSnw141292 ** nEqCol is the number of columns of pPreferredIdx that are used as
207*c5c4113dSnw141292 ** equality constraints.  Any index returned must have exactly this same
208*c5c4113dSnw141292 ** set of columns.  The ORDER BY clause only matches index columns beyond the
209*c5c4113dSnw141292 ** the first nEqCol columns.
210*c5c4113dSnw141292 **
211*c5c4113dSnw141292 ** All terms of the ORDER BY clause must be either ASC or DESC.  The
212*c5c4113dSnw141292 ** *pbRev value is set to 1 if the ORDER BY clause is all DESC and it is
213*c5c4113dSnw141292 ** set to 0 if the ORDER BY clause is all ASC.
214*c5c4113dSnw141292 */
findSortingIndex(Table * pTab,int base,ExprList * pOrderBy,Index * pPreferredIdx,int nEqCol,int * pbRev)215*c5c4113dSnw141292 static Index *findSortingIndex(
216*c5c4113dSnw141292   Table *pTab,            /* The table to be sorted */
217*c5c4113dSnw141292   int base,               /* Cursor number for pTab */
218*c5c4113dSnw141292   ExprList *pOrderBy,     /* The ORDER BY clause */
219*c5c4113dSnw141292   Index *pPreferredIdx,   /* Use this index, if possible and not NULL */
220*c5c4113dSnw141292   int nEqCol,             /* Number of index columns used with == constraints */
221*c5c4113dSnw141292   int *pbRev              /* Set to 1 if ORDER BY is DESC */
222*c5c4113dSnw141292 ){
223*c5c4113dSnw141292   int i, j;
224*c5c4113dSnw141292   Index *pMatch;
225*c5c4113dSnw141292   Index *pIdx;
226*c5c4113dSnw141292   int sortOrder;
227*c5c4113dSnw141292 
228*c5c4113dSnw141292   assert( pOrderBy!=0 );
229*c5c4113dSnw141292   assert( pOrderBy->nExpr>0 );
230*c5c4113dSnw141292   sortOrder = pOrderBy->a[0].sortOrder & SQLITE_SO_DIRMASK;
231*c5c4113dSnw141292   for(i=0; i<pOrderBy->nExpr; i++){
232*c5c4113dSnw141292     Expr *p;
233*c5c4113dSnw141292     if( (pOrderBy->a[i].sortOrder & SQLITE_SO_DIRMASK)!=sortOrder ){
234*c5c4113dSnw141292       /* Indices can only be used if all ORDER BY terms are either
235*c5c4113dSnw141292       ** DESC or ASC.  Indices cannot be used on a mixture. */
236*c5c4113dSnw141292       return 0;
237*c5c4113dSnw141292     }
238*c5c4113dSnw141292     if( (pOrderBy->a[i].sortOrder & SQLITE_SO_TYPEMASK)!=SQLITE_SO_UNK ){
239*c5c4113dSnw141292       /* Do not sort by index if there is a COLLATE clause */
240*c5c4113dSnw141292       return 0;
241*c5c4113dSnw141292     }
242*c5c4113dSnw141292     p = pOrderBy->a[i].pExpr;
243*c5c4113dSnw141292     if( p->op!=TK_COLUMN || p->iTable!=base ){
244*c5c4113dSnw141292       /* Can not use an index sort on anything that is not a column in the
245*c5c4113dSnw141292       ** left-most table of the FROM clause */
246*c5c4113dSnw141292       return 0;
247*c5c4113dSnw141292     }
248*c5c4113dSnw141292   }
249*c5c4113dSnw141292 
250*c5c4113dSnw141292   /* If we get this far, it means the ORDER BY clause consists only of
251*c5c4113dSnw141292   ** ascending columns in the left-most table of the FROM clause.  Now
252*c5c4113dSnw141292   ** check for a matching index.
253*c5c4113dSnw141292   */
254*c5c4113dSnw141292   pMatch = 0;
255*c5c4113dSnw141292   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
256*c5c4113dSnw141292     int nExpr = pOrderBy->nExpr;
257*c5c4113dSnw141292     if( pIdx->nColumn < nEqCol || pIdx->nColumn < nExpr ) continue;
258*c5c4113dSnw141292     for(i=j=0; i<nEqCol; i++){
259*c5c4113dSnw141292       if( pPreferredIdx->aiColumn[i]!=pIdx->aiColumn[i] ) break;
260*c5c4113dSnw141292       if( j<nExpr && pOrderBy->a[j].pExpr->iColumn==pIdx->aiColumn[i] ){ j++; }
261*c5c4113dSnw141292     }
262*c5c4113dSnw141292     if( i<nEqCol ) continue;
263*c5c4113dSnw141292     for(i=0; i+j<nExpr; i++){
264*c5c4113dSnw141292       if( pOrderBy->a[i+j].pExpr->iColumn!=pIdx->aiColumn[i+nEqCol] ) break;
265*c5c4113dSnw141292     }
266*c5c4113dSnw141292     if( i+j>=nExpr ){
267*c5c4113dSnw141292       pMatch = pIdx;
268*c5c4113dSnw141292       if( pIdx==pPreferredIdx ) break;
269*c5c4113dSnw141292     }
270*c5c4113dSnw141292   }
271*c5c4113dSnw141292   if( pMatch && pbRev ){
272*c5c4113dSnw141292     *pbRev = sortOrder==SQLITE_SO_DESC;
273*c5c4113dSnw141292   }
274*c5c4113dSnw141292   return pMatch;
275*c5c4113dSnw141292 }
276*c5c4113dSnw141292 
277*c5c4113dSnw141292 /*
278*c5c4113dSnw141292 ** Disable a term in the WHERE clause.  Except, do not disable the term
279*c5c4113dSnw141292 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
280*c5c4113dSnw141292 ** or USING clause of that join.
281*c5c4113dSnw141292 **
282*c5c4113dSnw141292 ** Consider the term t2.z='ok' in the following queries:
283*c5c4113dSnw141292 **
284*c5c4113dSnw141292 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
285*c5c4113dSnw141292 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
286*c5c4113dSnw141292 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
287*c5c4113dSnw141292 **
288*c5c4113dSnw141292 ** The t2.z='ok' is disabled in the in (2) because it did not originate
289*c5c4113dSnw141292 ** in the ON clause.  The term is disabled in (3) because it is not part
290*c5c4113dSnw141292 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
291*c5c4113dSnw141292 **
292*c5c4113dSnw141292 ** Disabling a term causes that term to not be tested in the inner loop
293*c5c4113dSnw141292 ** of the join.  Disabling is an optimization.  We would get the correct
294*c5c4113dSnw141292 ** results if nothing were ever disabled, but joins might run a little
295*c5c4113dSnw141292 ** slower.  The trick is to disable as much as we can without disabling
296*c5c4113dSnw141292 ** too much.  If we disabled in (1), we'd get the wrong answer.
297*c5c4113dSnw141292 ** See ticket #813.
298*c5c4113dSnw141292 */
disableTerm(WhereLevel * pLevel,Expr ** ppExpr)299*c5c4113dSnw141292 static void disableTerm(WhereLevel *pLevel, Expr **ppExpr){
300*c5c4113dSnw141292   Expr *pExpr = *ppExpr;
301*c5c4113dSnw141292   if( pLevel->iLeftJoin==0 || ExprHasProperty(pExpr, EP_FromJoin) ){
302*c5c4113dSnw141292     *ppExpr = 0;
303*c5c4113dSnw141292   }
304*c5c4113dSnw141292 }
305*c5c4113dSnw141292 
306*c5c4113dSnw141292 /*
307*c5c4113dSnw141292 ** Generate the beginning of the loop used for WHERE clause processing.
308*c5c4113dSnw141292 ** The return value is a pointer to an (opaque) structure that contains
309*c5c4113dSnw141292 ** information needed to terminate the loop.  Later, the calling routine
310*c5c4113dSnw141292 ** should invoke sqliteWhereEnd() with the return value of this function
311*c5c4113dSnw141292 ** in order to complete the WHERE clause processing.
312*c5c4113dSnw141292 **
313*c5c4113dSnw141292 ** If an error occurs, this routine returns NULL.
314*c5c4113dSnw141292 **
315*c5c4113dSnw141292 ** The basic idea is to do a nested loop, one loop for each table in
316*c5c4113dSnw141292 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
317*c5c4113dSnw141292 ** same as a SELECT with only a single table in the FROM clause.)  For
318*c5c4113dSnw141292 ** example, if the SQL is this:
319*c5c4113dSnw141292 **
320*c5c4113dSnw141292 **       SELECT * FROM t1, t2, t3 WHERE ...;
321*c5c4113dSnw141292 **
322*c5c4113dSnw141292 ** Then the code generated is conceptually like the following:
323*c5c4113dSnw141292 **
324*c5c4113dSnw141292 **      foreach row1 in t1 do       \    Code generated
325*c5c4113dSnw141292 **        foreach row2 in t2 do      |-- by sqliteWhereBegin()
326*c5c4113dSnw141292 **          foreach row3 in t3 do   /
327*c5c4113dSnw141292 **            ...
328*c5c4113dSnw141292 **          end                     \    Code generated
329*c5c4113dSnw141292 **        end                        |-- by sqliteWhereEnd()
330*c5c4113dSnw141292 **      end                         /
331*c5c4113dSnw141292 **
332*c5c4113dSnw141292 ** There are Btree cursors associated with each table.  t1 uses cursor
333*c5c4113dSnw141292 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
334*c5c4113dSnw141292 ** And so forth.  This routine generates code to open those VDBE cursors
335*c5c4113dSnw141292 ** and sqliteWhereEnd() generates the code to close them.
336*c5c4113dSnw141292 **
337*c5c4113dSnw141292 ** If the WHERE clause is empty, the foreach loops must each scan their
338*c5c4113dSnw141292 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
339*c5c4113dSnw141292 ** the tables have indices and there are terms in the WHERE clause that
340*c5c4113dSnw141292 ** refer to those indices, a complete table scan can be avoided and the
341*c5c4113dSnw141292 ** code will run much faster.  Most of the work of this routine is checking
342*c5c4113dSnw141292 ** to see if there are indices that can be used to speed up the loop.
343*c5c4113dSnw141292 **
344*c5c4113dSnw141292 ** Terms of the WHERE clause are also used to limit which rows actually
345*c5c4113dSnw141292 ** make it to the "..." in the middle of the loop.  After each "foreach",
346*c5c4113dSnw141292 ** terms of the WHERE clause that use only terms in that loop and outer
347*c5c4113dSnw141292 ** loops are evaluated and if false a jump is made around all subsequent
348*c5c4113dSnw141292 ** inner loops (or around the "..." if the test occurs within the inner-
349*c5c4113dSnw141292 ** most loop)
350*c5c4113dSnw141292 **
351*c5c4113dSnw141292 ** OUTER JOINS
352*c5c4113dSnw141292 **
353*c5c4113dSnw141292 ** An outer join of tables t1 and t2 is conceptally coded as follows:
354*c5c4113dSnw141292 **
355*c5c4113dSnw141292 **    foreach row1 in t1 do
356*c5c4113dSnw141292 **      flag = 0
357*c5c4113dSnw141292 **      foreach row2 in t2 do
358*c5c4113dSnw141292 **        start:
359*c5c4113dSnw141292 **          ...
360*c5c4113dSnw141292 **          flag = 1
361*c5c4113dSnw141292 **      end
362*c5c4113dSnw141292 **      if flag==0 then
363*c5c4113dSnw141292 **        move the row2 cursor to a null row
364*c5c4113dSnw141292 **        goto start
365*c5c4113dSnw141292 **      fi
366*c5c4113dSnw141292 **    end
367*c5c4113dSnw141292 **
368*c5c4113dSnw141292 ** ORDER BY CLAUSE PROCESSING
369*c5c4113dSnw141292 **
370*c5c4113dSnw141292 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
371*c5c4113dSnw141292 ** if there is one.  If there is no ORDER BY clause or if this routine
372*c5c4113dSnw141292 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
373*c5c4113dSnw141292 **
374*c5c4113dSnw141292 ** If an index can be used so that the natural output order of the table
375*c5c4113dSnw141292 ** scan is correct for the ORDER BY clause, then that index is used and
376*c5c4113dSnw141292 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
377*c5c4113dSnw141292 ** unnecessary sort of the result set if an index appropriate for the
378*c5c4113dSnw141292 ** ORDER BY clause already exists.
379*c5c4113dSnw141292 **
380*c5c4113dSnw141292 ** If the where clause loops cannot be arranged to provide the correct
381*c5c4113dSnw141292 ** output order, then the *ppOrderBy is unchanged.
382*c5c4113dSnw141292 */
sqliteWhereBegin(Parse * pParse,SrcList * pTabList,Expr * pWhere,int pushKey,ExprList ** ppOrderBy)383*c5c4113dSnw141292 WhereInfo *sqliteWhereBegin(
384*c5c4113dSnw141292   Parse *pParse,       /* The parser context */
385*c5c4113dSnw141292   SrcList *pTabList,   /* A list of all tables to be scanned */
386*c5c4113dSnw141292   Expr *pWhere,        /* The WHERE clause */
387*c5c4113dSnw141292   int pushKey,         /* If TRUE, leave the table key on the stack */
388*c5c4113dSnw141292   ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
389*c5c4113dSnw141292 ){
390*c5c4113dSnw141292   int i;                     /* Loop counter */
391*c5c4113dSnw141292   WhereInfo *pWInfo;         /* Will become the return value of this function */
392*c5c4113dSnw141292   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
393*c5c4113dSnw141292   int brk, cont = 0;         /* Addresses used during code generation */
394*c5c4113dSnw141292   int nExpr;           /* Number of subexpressions in the WHERE clause */
395*c5c4113dSnw141292   int loopMask;        /* One bit set for each outer loop */
396*c5c4113dSnw141292   int haveKey;         /* True if KEY is on the stack */
397*c5c4113dSnw141292   ExprMaskSet maskSet; /* The expression mask set */
398*c5c4113dSnw141292   int iDirectEq[32];   /* Term of the form ROWID==X for the N-th table */
399*c5c4113dSnw141292   int iDirectLt[32];   /* Term of the form ROWID<X or ROWID<=X */
400*c5c4113dSnw141292   int iDirectGt[32];   /* Term of the form ROWID>X or ROWID>=X */
401*c5c4113dSnw141292   ExprInfo aExpr[101]; /* The WHERE clause is divided into these expressions */
402*c5c4113dSnw141292 
403*c5c4113dSnw141292   /* pushKey is only allowed if there is a single table (as in an INSERT or
404*c5c4113dSnw141292   ** UPDATE statement)
405*c5c4113dSnw141292   */
406*c5c4113dSnw141292   assert( pushKey==0 || pTabList->nSrc==1 );
407*c5c4113dSnw141292 
408*c5c4113dSnw141292   /* Split the WHERE clause into separate subexpressions where each
409*c5c4113dSnw141292   ** subexpression is separated by an AND operator.  If the aExpr[]
410*c5c4113dSnw141292   ** array fills up, the last entry might point to an expression which
411*c5c4113dSnw141292   ** contains additional unfactored AND operators.
412*c5c4113dSnw141292   */
413*c5c4113dSnw141292   initMaskSet(&maskSet);
414*c5c4113dSnw141292   memset(aExpr, 0, sizeof(aExpr));
415*c5c4113dSnw141292   nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
416*c5c4113dSnw141292   if( nExpr==ARRAYSIZE(aExpr) ){
417*c5c4113dSnw141292     sqliteErrorMsg(pParse, "WHERE clause too complex - no more "
418*c5c4113dSnw141292        "than %d terms allowed", (int)ARRAYSIZE(aExpr)-1);
419*c5c4113dSnw141292     return 0;
420*c5c4113dSnw141292   }
421*c5c4113dSnw141292 
422*c5c4113dSnw141292   /* Allocate and initialize the WhereInfo structure that will become the
423*c5c4113dSnw141292   ** return value.
424*c5c4113dSnw141292   */
425*c5c4113dSnw141292   pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
426*c5c4113dSnw141292   if( sqlite_malloc_failed ){
427*c5c4113dSnw141292     sqliteFree(pWInfo);
428*c5c4113dSnw141292     return 0;
429*c5c4113dSnw141292   }
430*c5c4113dSnw141292   pWInfo->pParse = pParse;
431*c5c4113dSnw141292   pWInfo->pTabList = pTabList;
432*c5c4113dSnw141292   pWInfo->peakNTab = pWInfo->savedNTab = pParse->nTab;
433*c5c4113dSnw141292   pWInfo->iBreak = sqliteVdbeMakeLabel(v);
434*c5c4113dSnw141292 
435*c5c4113dSnw141292   /* Special case: a WHERE clause that is constant.  Evaluate the
436*c5c4113dSnw141292   ** expression and either jump over all of the code or fall thru.
437*c5c4113dSnw141292   */
438*c5c4113dSnw141292   if( pWhere && (pTabList->nSrc==0 || sqliteExprIsConstant(pWhere)) ){
439*c5c4113dSnw141292     sqliteExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
440*c5c4113dSnw141292     pWhere = 0;
441*c5c4113dSnw141292   }
442*c5c4113dSnw141292 
443*c5c4113dSnw141292   /* Analyze all of the subexpressions.
444*c5c4113dSnw141292   */
445*c5c4113dSnw141292   for(i=0; i<nExpr; i++){
446*c5c4113dSnw141292     exprAnalyze(&maskSet, &aExpr[i]);
447*c5c4113dSnw141292 
448*c5c4113dSnw141292     /* If we are executing a trigger body, remove all references to
449*c5c4113dSnw141292     ** new.* and old.* tables from the prerequisite masks.
450*c5c4113dSnw141292     */
451*c5c4113dSnw141292     if( pParse->trigStack ){
452*c5c4113dSnw141292       int x;
453*c5c4113dSnw141292       if( (x = pParse->trigStack->newIdx) >= 0 ){
454*c5c4113dSnw141292         int mask = ~getMask(&maskSet, x);
455*c5c4113dSnw141292         aExpr[i].prereqRight &= mask;
456*c5c4113dSnw141292         aExpr[i].prereqLeft &= mask;
457*c5c4113dSnw141292         aExpr[i].prereqAll &= mask;
458*c5c4113dSnw141292       }
459*c5c4113dSnw141292       if( (x = pParse->trigStack->oldIdx) >= 0 ){
460*c5c4113dSnw141292         int mask = ~getMask(&maskSet, x);
461*c5c4113dSnw141292         aExpr[i].prereqRight &= mask;
462*c5c4113dSnw141292         aExpr[i].prereqLeft &= mask;
463*c5c4113dSnw141292         aExpr[i].prereqAll &= mask;
464*c5c4113dSnw141292       }
465*c5c4113dSnw141292     }
466*c5c4113dSnw141292   }
467*c5c4113dSnw141292 
468*c5c4113dSnw141292   /* Figure out what index to use (if any) for each nested loop.
469*c5c4113dSnw141292   ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
470*c5c4113dSnw141292   ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
471*c5c4113dSnw141292   ** loop.
472*c5c4113dSnw141292   **
473*c5c4113dSnw141292   ** If terms exist that use the ROWID of any table, then set the
474*c5c4113dSnw141292   ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
475*c5c4113dSnw141292   ** to the index of the term containing the ROWID.  We always prefer
476*c5c4113dSnw141292   ** to use a ROWID which can directly access a table rather than an
477*c5c4113dSnw141292   ** index which requires reading an index first to get the rowid then
478*c5c4113dSnw141292   ** doing a second read of the actual database table.
479*c5c4113dSnw141292   **
480*c5c4113dSnw141292   ** Actually, if there are more than 32 tables in the join, only the
481*c5c4113dSnw141292   ** first 32 tables are candidates for indices.  This is (again) due
482*c5c4113dSnw141292   ** to the limit of 32 bits in an integer bitmask.
483*c5c4113dSnw141292   */
484*c5c4113dSnw141292   loopMask = 0;
485*c5c4113dSnw141292   for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++){
486*c5c4113dSnw141292     int j;
487*c5c4113dSnw141292     int iCur = pTabList->a[i].iCursor;    /* The cursor for this table */
488*c5c4113dSnw141292     int mask = getMask(&maskSet, iCur);   /* Cursor mask for this table */
489*c5c4113dSnw141292     Table *pTab = pTabList->a[i].pTab;
490*c5c4113dSnw141292     Index *pIdx;
491*c5c4113dSnw141292     Index *pBestIdx = 0;
492*c5c4113dSnw141292     int bestScore = 0;
493*c5c4113dSnw141292 
494*c5c4113dSnw141292     /* Check to see if there is an expression that uses only the
495*c5c4113dSnw141292     ** ROWID field of this table.  For terms of the form ROWID==expr
496*c5c4113dSnw141292     ** set iDirectEq[i] to the index of the term.  For terms of the
497*c5c4113dSnw141292     ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
498*c5c4113dSnw141292     ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
499*c5c4113dSnw141292     **
500*c5c4113dSnw141292     ** (Added:) Treat ROWID IN expr like ROWID=expr.
501*c5c4113dSnw141292     */
502*c5c4113dSnw141292     pWInfo->a[i].iCur = -1;
503*c5c4113dSnw141292     iDirectEq[i] = -1;
504*c5c4113dSnw141292     iDirectLt[i] = -1;
505*c5c4113dSnw141292     iDirectGt[i] = -1;
506*c5c4113dSnw141292     for(j=0; j<nExpr; j++){
507*c5c4113dSnw141292       if( aExpr[j].idxLeft==iCur && aExpr[j].p->pLeft->iColumn<0
508*c5c4113dSnw141292             && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
509*c5c4113dSnw141292         switch( aExpr[j].p->op ){
510*c5c4113dSnw141292           case TK_IN:
511*c5c4113dSnw141292           case TK_EQ: iDirectEq[i] = j; break;
512*c5c4113dSnw141292           case TK_LE:
513*c5c4113dSnw141292           case TK_LT: iDirectLt[i] = j; break;
514*c5c4113dSnw141292           case TK_GE:
515*c5c4113dSnw141292           case TK_GT: iDirectGt[i] = j;  break;
516*c5c4113dSnw141292         }
517*c5c4113dSnw141292       }
518*c5c4113dSnw141292       if( aExpr[j].idxRight==iCur && aExpr[j].p->pRight->iColumn<0
519*c5c4113dSnw141292             && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
520*c5c4113dSnw141292         switch( aExpr[j].p->op ){
521*c5c4113dSnw141292           case TK_EQ: iDirectEq[i] = j;  break;
522*c5c4113dSnw141292           case TK_LE:
523*c5c4113dSnw141292           case TK_LT: iDirectGt[i] = j;  break;
524*c5c4113dSnw141292           case TK_GE:
525*c5c4113dSnw141292           case TK_GT: iDirectLt[i] = j;  break;
526*c5c4113dSnw141292         }
527*c5c4113dSnw141292       }
528*c5c4113dSnw141292     }
529*c5c4113dSnw141292     if( iDirectEq[i]>=0 ){
530*c5c4113dSnw141292       loopMask |= mask;
531*c5c4113dSnw141292       pWInfo->a[i].pIdx = 0;
532*c5c4113dSnw141292       continue;
533*c5c4113dSnw141292     }
534*c5c4113dSnw141292 
535*c5c4113dSnw141292     /* Do a search for usable indices.  Leave pBestIdx pointing to
536*c5c4113dSnw141292     ** the "best" index.  pBestIdx is left set to NULL if no indices
537*c5c4113dSnw141292     ** are usable.
538*c5c4113dSnw141292     **
539*c5c4113dSnw141292     ** The best index is determined as follows.  For each of the
540*c5c4113dSnw141292     ** left-most terms that is fixed by an equality operator, add
541*c5c4113dSnw141292     ** 8 to the score.  The right-most term of the index may be
542*c5c4113dSnw141292     ** constrained by an inequality.  Add 1 if for an "x<..." constraint
543*c5c4113dSnw141292     ** and add 2 for an "x>..." constraint.  Chose the index that
544*c5c4113dSnw141292     ** gives the best score.
545*c5c4113dSnw141292     **
546*c5c4113dSnw141292     ** This scoring system is designed so that the score can later be
547*c5c4113dSnw141292     ** used to determine how the index is used.  If the score&7 is 0
548*c5c4113dSnw141292     ** then all constraints are equalities.  If score&1 is not 0 then
549*c5c4113dSnw141292     ** there is an inequality used as a termination key.  (ex: "x<...")
550*c5c4113dSnw141292     ** If score&2 is not 0 then there is an inequality used as the
551*c5c4113dSnw141292     ** start key.  (ex: "x>...").  A score or 4 is the special case
552*c5c4113dSnw141292     ** of an IN operator constraint.  (ex:  "x IN ...").
553*c5c4113dSnw141292     **
554*c5c4113dSnw141292     ** The IN operator (as in "<expr> IN (...)") is treated the same as
555*c5c4113dSnw141292     ** an equality comparison except that it can only be used on the
556*c5c4113dSnw141292     ** left-most column of an index and other terms of the WHERE clause
557*c5c4113dSnw141292     ** cannot be used in conjunction with the IN operator to help satisfy
558*c5c4113dSnw141292     ** other columns of the index.
559*c5c4113dSnw141292     */
560*c5c4113dSnw141292     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
561*c5c4113dSnw141292       int eqMask = 0;  /* Index columns covered by an x=... term */
562*c5c4113dSnw141292       int ltMask = 0;  /* Index columns covered by an x<... term */
563*c5c4113dSnw141292       int gtMask = 0;  /* Index columns covered by an x>... term */
564*c5c4113dSnw141292       int inMask = 0;  /* Index columns covered by an x IN .. term */
565*c5c4113dSnw141292       int nEq, m, score;
566*c5c4113dSnw141292 
567*c5c4113dSnw141292       if( pIdx->nColumn>32 ) continue;  /* Ignore indices too many columns */
568*c5c4113dSnw141292       for(j=0; j<nExpr; j++){
569*c5c4113dSnw141292         if( aExpr[j].idxLeft==iCur
570*c5c4113dSnw141292              && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
571*c5c4113dSnw141292           int iColumn = aExpr[j].p->pLeft->iColumn;
572*c5c4113dSnw141292           int k;
573*c5c4113dSnw141292           for(k=0; k<pIdx->nColumn; k++){
574*c5c4113dSnw141292             if( pIdx->aiColumn[k]==iColumn ){
575*c5c4113dSnw141292               switch( aExpr[j].p->op ){
576*c5c4113dSnw141292                 case TK_IN: {
577*c5c4113dSnw141292                   if( k==0 ) inMask |= 1;
578*c5c4113dSnw141292                   break;
579*c5c4113dSnw141292                 }
580*c5c4113dSnw141292                 case TK_EQ: {
581*c5c4113dSnw141292                   eqMask |= 1<<k;
582*c5c4113dSnw141292                   break;
583*c5c4113dSnw141292                 }
584*c5c4113dSnw141292                 case TK_LE:
585*c5c4113dSnw141292                 case TK_LT: {
586*c5c4113dSnw141292                   ltMask |= 1<<k;
587*c5c4113dSnw141292                   break;
588*c5c4113dSnw141292                 }
589*c5c4113dSnw141292                 case TK_GE:
590*c5c4113dSnw141292                 case TK_GT: {
591*c5c4113dSnw141292                   gtMask |= 1<<k;
592*c5c4113dSnw141292                   break;
593*c5c4113dSnw141292                 }
594*c5c4113dSnw141292                 default: {
595*c5c4113dSnw141292                   /* CANT_HAPPEN */
596*c5c4113dSnw141292                   assert( 0 );
597*c5c4113dSnw141292                   break;
598*c5c4113dSnw141292                 }
599*c5c4113dSnw141292               }
600*c5c4113dSnw141292               break;
601*c5c4113dSnw141292             }
602*c5c4113dSnw141292           }
603*c5c4113dSnw141292         }
604*c5c4113dSnw141292         if( aExpr[j].idxRight==iCur
605*c5c4113dSnw141292              && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
606*c5c4113dSnw141292           int iColumn = aExpr[j].p->pRight->iColumn;
607*c5c4113dSnw141292           int k;
608*c5c4113dSnw141292           for(k=0; k<pIdx->nColumn; k++){
609*c5c4113dSnw141292             if( pIdx->aiColumn[k]==iColumn ){
610*c5c4113dSnw141292               switch( aExpr[j].p->op ){
611*c5c4113dSnw141292                 case TK_EQ: {
612*c5c4113dSnw141292                   eqMask |= 1<<k;
613*c5c4113dSnw141292                   break;
614*c5c4113dSnw141292                 }
615*c5c4113dSnw141292                 case TK_LE:
616*c5c4113dSnw141292                 case TK_LT: {
617*c5c4113dSnw141292                   gtMask |= 1<<k;
618*c5c4113dSnw141292                   break;
619*c5c4113dSnw141292                 }
620*c5c4113dSnw141292                 case TK_GE:
621*c5c4113dSnw141292                 case TK_GT: {
622*c5c4113dSnw141292                   ltMask |= 1<<k;
623*c5c4113dSnw141292                   break;
624*c5c4113dSnw141292                 }
625*c5c4113dSnw141292                 default: {
626*c5c4113dSnw141292                   /* CANT_HAPPEN */
627*c5c4113dSnw141292                   assert( 0 );
628*c5c4113dSnw141292                   break;
629*c5c4113dSnw141292                 }
630*c5c4113dSnw141292               }
631*c5c4113dSnw141292               break;
632*c5c4113dSnw141292             }
633*c5c4113dSnw141292           }
634*c5c4113dSnw141292         }
635*c5c4113dSnw141292       }
636*c5c4113dSnw141292 
637*c5c4113dSnw141292       /* The following loop ends with nEq set to the number of columns
638*c5c4113dSnw141292       ** on the left of the index with == constraints.
639*c5c4113dSnw141292       */
640*c5c4113dSnw141292       for(nEq=0; nEq<pIdx->nColumn; nEq++){
641*c5c4113dSnw141292         m = (1<<(nEq+1))-1;
642*c5c4113dSnw141292         if( (m & eqMask)!=m ) break;
643*c5c4113dSnw141292       }
644*c5c4113dSnw141292       score = nEq*8;   /* Base score is 8 times number of == constraints */
645*c5c4113dSnw141292       m = 1<<nEq;
646*c5c4113dSnw141292       if( m & ltMask ) score++;    /* Increase score for a < constraint */
647*c5c4113dSnw141292       if( m & gtMask ) score+=2;   /* Increase score for a > constraint */
648*c5c4113dSnw141292       if( score==0 && inMask ) score = 4;  /* Default score for IN constraint */
649*c5c4113dSnw141292       if( score>bestScore ){
650*c5c4113dSnw141292         pBestIdx = pIdx;
651*c5c4113dSnw141292         bestScore = score;
652*c5c4113dSnw141292       }
653*c5c4113dSnw141292     }
654*c5c4113dSnw141292     pWInfo->a[i].pIdx = pBestIdx;
655*c5c4113dSnw141292     pWInfo->a[i].score = bestScore;
656*c5c4113dSnw141292     pWInfo->a[i].bRev = 0;
657*c5c4113dSnw141292     loopMask |= mask;
658*c5c4113dSnw141292     if( pBestIdx ){
659*c5c4113dSnw141292       pWInfo->a[i].iCur = pParse->nTab++;
660*c5c4113dSnw141292       pWInfo->peakNTab = pParse->nTab;
661*c5c4113dSnw141292     }
662*c5c4113dSnw141292   }
663*c5c4113dSnw141292 
664*c5c4113dSnw141292   /* Check to see if the ORDER BY clause is or can be satisfied by the
665*c5c4113dSnw141292   ** use of an index on the first table.
666*c5c4113dSnw141292   */
667*c5c4113dSnw141292   if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
668*c5c4113dSnw141292      Index *pSortIdx;
669*c5c4113dSnw141292      Index *pIdx;
670*c5c4113dSnw141292      Table *pTab;
671*c5c4113dSnw141292      int bRev = 0;
672*c5c4113dSnw141292 
673*c5c4113dSnw141292      pTab = pTabList->a[0].pTab;
674*c5c4113dSnw141292      pIdx = pWInfo->a[0].pIdx;
675*c5c4113dSnw141292      if( pIdx && pWInfo->a[0].score==4 ){
676*c5c4113dSnw141292        /* If there is already an IN index on the left-most table,
677*c5c4113dSnw141292        ** it will not give the correct sort order.
678*c5c4113dSnw141292        ** So, pretend that no suitable index is found.
679*c5c4113dSnw141292        */
680*c5c4113dSnw141292        pSortIdx = 0;
681*c5c4113dSnw141292      }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
682*c5c4113dSnw141292        /* If the left-most column is accessed using its ROWID, then do
683*c5c4113dSnw141292        ** not try to sort by index.
684*c5c4113dSnw141292        */
685*c5c4113dSnw141292        pSortIdx = 0;
686*c5c4113dSnw141292      }else{
687*c5c4113dSnw141292        int nEqCol = (pWInfo->a[0].score+4)/8;
688*c5c4113dSnw141292        pSortIdx = findSortingIndex(pTab, pTabList->a[0].iCursor,
689*c5c4113dSnw141292                                    *ppOrderBy, pIdx, nEqCol, &bRev);
690*c5c4113dSnw141292      }
691*c5c4113dSnw141292      if( pSortIdx && (pIdx==0 || pIdx==pSortIdx) ){
692*c5c4113dSnw141292        if( pIdx==0 ){
693*c5c4113dSnw141292          pWInfo->a[0].pIdx = pSortIdx;
694*c5c4113dSnw141292          pWInfo->a[0].iCur = pParse->nTab++;
695*c5c4113dSnw141292          pWInfo->peakNTab = pParse->nTab;
696*c5c4113dSnw141292        }
697*c5c4113dSnw141292        pWInfo->a[0].bRev = bRev;
698*c5c4113dSnw141292        *ppOrderBy = 0;
699*c5c4113dSnw141292      }
700*c5c4113dSnw141292   }
701*c5c4113dSnw141292 
702*c5c4113dSnw141292   /* Open all tables in the pTabList and all indices used by those tables.
703*c5c4113dSnw141292   */
704*c5c4113dSnw141292   for(i=0; i<pTabList->nSrc; i++){
705*c5c4113dSnw141292     Table *pTab;
706*c5c4113dSnw141292     Index *pIx;
707*c5c4113dSnw141292 
708*c5c4113dSnw141292     pTab = pTabList->a[i].pTab;
709*c5c4113dSnw141292     if( pTab->isTransient || pTab->pSelect ) continue;
710*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
711*c5c4113dSnw141292     sqliteVdbeOp3(v, OP_OpenRead, pTabList->a[i].iCursor, pTab->tnum,
712*c5c4113dSnw141292                      pTab->zName, P3_STATIC);
713*c5c4113dSnw141292     sqliteCodeVerifySchema(pParse, pTab->iDb);
714*c5c4113dSnw141292     if( (pIx = pWInfo->a[i].pIdx)!=0 ){
715*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Integer, pIx->iDb, 0);
716*c5c4113dSnw141292       sqliteVdbeOp3(v, OP_OpenRead, pWInfo->a[i].iCur, pIx->tnum, pIx->zName,0);
717*c5c4113dSnw141292     }
718*c5c4113dSnw141292   }
719*c5c4113dSnw141292 
720*c5c4113dSnw141292   /* Generate the code to do the search
721*c5c4113dSnw141292   */
722*c5c4113dSnw141292   loopMask = 0;
723*c5c4113dSnw141292   for(i=0; i<pTabList->nSrc; i++){
724*c5c4113dSnw141292     int j, k;
725*c5c4113dSnw141292     int iCur = pTabList->a[i].iCursor;
726*c5c4113dSnw141292     Index *pIdx;
727*c5c4113dSnw141292     WhereLevel *pLevel = &pWInfo->a[i];
728*c5c4113dSnw141292 
729*c5c4113dSnw141292     /* If this is the right table of a LEFT OUTER JOIN, allocate and
730*c5c4113dSnw141292     ** initialize a memory cell that records if this table matches any
731*c5c4113dSnw141292     ** row of the left table of the join.
732*c5c4113dSnw141292     */
733*c5c4113dSnw141292     if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
734*c5c4113dSnw141292       if( !pParse->nMem ) pParse->nMem++;
735*c5c4113dSnw141292       pLevel->iLeftJoin = pParse->nMem++;
736*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_String, 0, 0);
737*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
738*c5c4113dSnw141292     }
739*c5c4113dSnw141292 
740*c5c4113dSnw141292     pIdx = pLevel->pIdx;
741*c5c4113dSnw141292     pLevel->inOp = OP_Noop;
742*c5c4113dSnw141292     if( i<ARRAYSIZE(iDirectEq) && iDirectEq[i]>=0 ){
743*c5c4113dSnw141292       /* Case 1:  We can directly reference a single row using an
744*c5c4113dSnw141292       **          equality comparison against the ROWID field.  Or
745*c5c4113dSnw141292       **          we reference multiple rows using a "rowid IN (...)"
746*c5c4113dSnw141292       **          construct.
747*c5c4113dSnw141292       */
748*c5c4113dSnw141292       k = iDirectEq[i];
749*c5c4113dSnw141292       assert( k<nExpr );
750*c5c4113dSnw141292       assert( aExpr[k].p!=0 );
751*c5c4113dSnw141292       assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
752*c5c4113dSnw141292       brk = pLevel->brk = sqliteVdbeMakeLabel(v);
753*c5c4113dSnw141292       if( aExpr[k].idxLeft==iCur ){
754*c5c4113dSnw141292         Expr *pX = aExpr[k].p;
755*c5c4113dSnw141292         if( pX->op!=TK_IN ){
756*c5c4113dSnw141292           sqliteExprCode(pParse, aExpr[k].p->pRight);
757*c5c4113dSnw141292         }else if( pX->pList ){
758*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
759*c5c4113dSnw141292           pLevel->inOp = OP_SetNext;
760*c5c4113dSnw141292           pLevel->inP1 = pX->iTable;
761*c5c4113dSnw141292           pLevel->inP2 = sqliteVdbeCurrentAddr(v);
762*c5c4113dSnw141292         }else{
763*c5c4113dSnw141292           assert( pX->pSelect );
764*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
765*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
766*c5c4113dSnw141292           pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
767*c5c4113dSnw141292           pLevel->inOp = OP_Next;
768*c5c4113dSnw141292           pLevel->inP1 = pX->iTable;
769*c5c4113dSnw141292         }
770*c5c4113dSnw141292       }else{
771*c5c4113dSnw141292         sqliteExprCode(pParse, aExpr[k].p->pLeft);
772*c5c4113dSnw141292       }
773*c5c4113dSnw141292       disableTerm(pLevel, &aExpr[k].p);
774*c5c4113dSnw141292       cont = pLevel->cont = sqliteVdbeMakeLabel(v);
775*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
776*c5c4113dSnw141292       haveKey = 0;
777*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_NotExists, iCur, brk);
778*c5c4113dSnw141292       pLevel->op = OP_Noop;
779*c5c4113dSnw141292     }else if( pIdx!=0 && pLevel->score>0 && pLevel->score%4==0 ){
780*c5c4113dSnw141292       /* Case 2:  There is an index and all terms of the WHERE clause that
781*c5c4113dSnw141292       **          refer to the index use the "==" or "IN" operators.
782*c5c4113dSnw141292       */
783*c5c4113dSnw141292       int start;
784*c5c4113dSnw141292       int testOp;
785*c5c4113dSnw141292       int nColumn = (pLevel->score+4)/8;
786*c5c4113dSnw141292       brk = pLevel->brk = sqliteVdbeMakeLabel(v);
787*c5c4113dSnw141292       for(j=0; j<nColumn; j++){
788*c5c4113dSnw141292         for(k=0; k<nExpr; k++){
789*c5c4113dSnw141292           Expr *pX = aExpr[k].p;
790*c5c4113dSnw141292           if( pX==0 ) continue;
791*c5c4113dSnw141292           if( aExpr[k].idxLeft==iCur
792*c5c4113dSnw141292              && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
793*c5c4113dSnw141292              && pX->pLeft->iColumn==pIdx->aiColumn[j]
794*c5c4113dSnw141292           ){
795*c5c4113dSnw141292             if( pX->op==TK_EQ ){
796*c5c4113dSnw141292               sqliteExprCode(pParse, pX->pRight);
797*c5c4113dSnw141292               disableTerm(pLevel, &aExpr[k].p);
798*c5c4113dSnw141292               break;
799*c5c4113dSnw141292             }
800*c5c4113dSnw141292             if( pX->op==TK_IN && nColumn==1 ){
801*c5c4113dSnw141292               if( pX->pList ){
802*c5c4113dSnw141292                 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
803*c5c4113dSnw141292                 pLevel->inOp = OP_SetNext;
804*c5c4113dSnw141292                 pLevel->inP1 = pX->iTable;
805*c5c4113dSnw141292                 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
806*c5c4113dSnw141292               }else{
807*c5c4113dSnw141292                 assert( pX->pSelect );
808*c5c4113dSnw141292                 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
809*c5c4113dSnw141292                 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
810*c5c4113dSnw141292                 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
811*c5c4113dSnw141292                 pLevel->inOp = OP_Next;
812*c5c4113dSnw141292                 pLevel->inP1 = pX->iTable;
813*c5c4113dSnw141292               }
814*c5c4113dSnw141292               disableTerm(pLevel, &aExpr[k].p);
815*c5c4113dSnw141292               break;
816*c5c4113dSnw141292             }
817*c5c4113dSnw141292           }
818*c5c4113dSnw141292           if( aExpr[k].idxRight==iCur
819*c5c4113dSnw141292              && aExpr[k].p->op==TK_EQ
820*c5c4113dSnw141292              && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
821*c5c4113dSnw141292              && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
822*c5c4113dSnw141292           ){
823*c5c4113dSnw141292             sqliteExprCode(pParse, aExpr[k].p->pLeft);
824*c5c4113dSnw141292             disableTerm(pLevel, &aExpr[k].p);
825*c5c4113dSnw141292             break;
826*c5c4113dSnw141292           }
827*c5c4113dSnw141292         }
828*c5c4113dSnw141292       }
829*c5c4113dSnw141292       pLevel->iMem = pParse->nMem++;
830*c5c4113dSnw141292       cont = pLevel->cont = sqliteVdbeMakeLabel(v);
831*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_NotNull, -nColumn, sqliteVdbeCurrentAddr(v)+3);
832*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
833*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Goto, 0, brk);
834*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_MakeKey, nColumn, 0);
835*c5c4113dSnw141292       sqliteAddIdxKeyType(v, pIdx);
836*c5c4113dSnw141292       if( nColumn==pIdx->nColumn || pLevel->bRev ){
837*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
838*c5c4113dSnw141292         testOp = OP_IdxGT;
839*c5c4113dSnw141292       }else{
840*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Dup, 0, 0);
841*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
842*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
843*c5c4113dSnw141292         testOp = OP_IdxGE;
844*c5c4113dSnw141292       }
845*c5c4113dSnw141292       if( pLevel->bRev ){
846*c5c4113dSnw141292         /* Scan in reverse order */
847*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
848*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
849*c5c4113dSnw141292         start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
850*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_IdxLT, pLevel->iCur, brk);
851*c5c4113dSnw141292         pLevel->op = OP_Prev;
852*c5c4113dSnw141292       }else{
853*c5c4113dSnw141292         /* Scan in the forward order */
854*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
855*c5c4113dSnw141292         start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
856*c5c4113dSnw141292         sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
857*c5c4113dSnw141292         pLevel->op = OP_Next;
858*c5c4113dSnw141292       }
859*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_RowKey, pLevel->iCur, 0);
860*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
861*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
862*c5c4113dSnw141292       if( i==pTabList->nSrc-1 && pushKey ){
863*c5c4113dSnw141292         haveKey = 1;
864*c5c4113dSnw141292       }else{
865*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
866*c5c4113dSnw141292         haveKey = 0;
867*c5c4113dSnw141292       }
868*c5c4113dSnw141292       pLevel->p1 = pLevel->iCur;
869*c5c4113dSnw141292       pLevel->p2 = start;
870*c5c4113dSnw141292     }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
871*c5c4113dSnw141292       /* Case 3:  We have an inequality comparison against the ROWID field.
872*c5c4113dSnw141292       */
873*c5c4113dSnw141292       int testOp = OP_Noop;
874*c5c4113dSnw141292       int start;
875*c5c4113dSnw141292 
876*c5c4113dSnw141292       brk = pLevel->brk = sqliteVdbeMakeLabel(v);
877*c5c4113dSnw141292       cont = pLevel->cont = sqliteVdbeMakeLabel(v);
878*c5c4113dSnw141292       if( iDirectGt[i]>=0 ){
879*c5c4113dSnw141292         k = iDirectGt[i];
880*c5c4113dSnw141292         assert( k<nExpr );
881*c5c4113dSnw141292         assert( aExpr[k].p!=0 );
882*c5c4113dSnw141292         assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
883*c5c4113dSnw141292         if( aExpr[k].idxLeft==iCur ){
884*c5c4113dSnw141292           sqliteExprCode(pParse, aExpr[k].p->pRight);
885*c5c4113dSnw141292         }else{
886*c5c4113dSnw141292           sqliteExprCode(pParse, aExpr[k].p->pLeft);
887*c5c4113dSnw141292         }
888*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_ForceInt,
889*c5c4113dSnw141292           aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT, brk);
890*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MoveTo, iCur, brk);
891*c5c4113dSnw141292         disableTerm(pLevel, &aExpr[k].p);
892*c5c4113dSnw141292       }else{
893*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Rewind, iCur, brk);
894*c5c4113dSnw141292       }
895*c5c4113dSnw141292       if( iDirectLt[i]>=0 ){
896*c5c4113dSnw141292         k = iDirectLt[i];
897*c5c4113dSnw141292         assert( k<nExpr );
898*c5c4113dSnw141292         assert( aExpr[k].p!=0 );
899*c5c4113dSnw141292         assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
900*c5c4113dSnw141292         if( aExpr[k].idxLeft==iCur ){
901*c5c4113dSnw141292           sqliteExprCode(pParse, aExpr[k].p->pRight);
902*c5c4113dSnw141292         }else{
903*c5c4113dSnw141292           sqliteExprCode(pParse, aExpr[k].p->pLeft);
904*c5c4113dSnw141292         }
905*c5c4113dSnw141292         /* sqliteVdbeAddOp(v, OP_MustBeInt, 0, sqliteVdbeCurrentAddr(v)+1); */
906*c5c4113dSnw141292         pLevel->iMem = pParse->nMem++;
907*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
908*c5c4113dSnw141292         if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
909*c5c4113dSnw141292           testOp = OP_Ge;
910*c5c4113dSnw141292         }else{
911*c5c4113dSnw141292           testOp = OP_Gt;
912*c5c4113dSnw141292         }
913*c5c4113dSnw141292         disableTerm(pLevel, &aExpr[k].p);
914*c5c4113dSnw141292       }
915*c5c4113dSnw141292       start = sqliteVdbeCurrentAddr(v);
916*c5c4113dSnw141292       pLevel->op = OP_Next;
917*c5c4113dSnw141292       pLevel->p1 = iCur;
918*c5c4113dSnw141292       pLevel->p2 = start;
919*c5c4113dSnw141292       if( testOp!=OP_Noop ){
920*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
921*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
922*c5c4113dSnw141292         sqliteVdbeAddOp(v, testOp, 0, brk);
923*c5c4113dSnw141292       }
924*c5c4113dSnw141292       haveKey = 0;
925*c5c4113dSnw141292     }else if( pIdx==0 ){
926*c5c4113dSnw141292       /* Case 4:  There is no usable index.  We must do a complete
927*c5c4113dSnw141292       **          scan of the entire database table.
928*c5c4113dSnw141292       */
929*c5c4113dSnw141292       int start;
930*c5c4113dSnw141292 
931*c5c4113dSnw141292       brk = pLevel->brk = sqliteVdbeMakeLabel(v);
932*c5c4113dSnw141292       cont = pLevel->cont = sqliteVdbeMakeLabel(v);
933*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Rewind, iCur, brk);
934*c5c4113dSnw141292       start = sqliteVdbeCurrentAddr(v);
935*c5c4113dSnw141292       pLevel->op = OP_Next;
936*c5c4113dSnw141292       pLevel->p1 = iCur;
937*c5c4113dSnw141292       pLevel->p2 = start;
938*c5c4113dSnw141292       haveKey = 0;
939*c5c4113dSnw141292     }else{
940*c5c4113dSnw141292       /* Case 5: The WHERE clause term that refers to the right-most
941*c5c4113dSnw141292       **         column of the index is an inequality.  For example, if
942*c5c4113dSnw141292       **         the index is on (x,y,z) and the WHERE clause is of the
943*c5c4113dSnw141292       **         form "x=5 AND y<10" then this case is used.  Only the
944*c5c4113dSnw141292       **         right-most column can be an inequality - the rest must
945*c5c4113dSnw141292       **         use the "==" operator.
946*c5c4113dSnw141292       **
947*c5c4113dSnw141292       **         This case is also used when there are no WHERE clause
948*c5c4113dSnw141292       **         constraints but an index is selected anyway, in order
949*c5c4113dSnw141292       **         to force the output order to conform to an ORDER BY.
950*c5c4113dSnw141292       */
951*c5c4113dSnw141292       int score = pLevel->score;
952*c5c4113dSnw141292       int nEqColumn = score/8;
953*c5c4113dSnw141292       int start;
954*c5c4113dSnw141292       int leFlag, geFlag;
955*c5c4113dSnw141292       int testOp;
956*c5c4113dSnw141292 
957*c5c4113dSnw141292       /* Evaluate the equality constraints
958*c5c4113dSnw141292       */
959*c5c4113dSnw141292       for(j=0; j<nEqColumn; j++){
960*c5c4113dSnw141292         for(k=0; k<nExpr; k++){
961*c5c4113dSnw141292           if( aExpr[k].p==0 ) continue;
962*c5c4113dSnw141292           if( aExpr[k].idxLeft==iCur
963*c5c4113dSnw141292              && aExpr[k].p->op==TK_EQ
964*c5c4113dSnw141292              && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
965*c5c4113dSnw141292              && aExpr[k].p->pLeft->iColumn==pIdx->aiColumn[j]
966*c5c4113dSnw141292           ){
967*c5c4113dSnw141292             sqliteExprCode(pParse, aExpr[k].p->pRight);
968*c5c4113dSnw141292             disableTerm(pLevel, &aExpr[k].p);
969*c5c4113dSnw141292             break;
970*c5c4113dSnw141292           }
971*c5c4113dSnw141292           if( aExpr[k].idxRight==iCur
972*c5c4113dSnw141292              && aExpr[k].p->op==TK_EQ
973*c5c4113dSnw141292              && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
974*c5c4113dSnw141292              && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
975*c5c4113dSnw141292           ){
976*c5c4113dSnw141292             sqliteExprCode(pParse, aExpr[k].p->pLeft);
977*c5c4113dSnw141292             disableTerm(pLevel, &aExpr[k].p);
978*c5c4113dSnw141292             break;
979*c5c4113dSnw141292           }
980*c5c4113dSnw141292         }
981*c5c4113dSnw141292       }
982*c5c4113dSnw141292 
983*c5c4113dSnw141292       /* Duplicate the equality term values because they will all be
984*c5c4113dSnw141292       ** used twice: once to make the termination key and once to make the
985*c5c4113dSnw141292       ** start key.
986*c5c4113dSnw141292       */
987*c5c4113dSnw141292       for(j=0; j<nEqColumn; j++){
988*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
989*c5c4113dSnw141292       }
990*c5c4113dSnw141292 
991*c5c4113dSnw141292       /* Labels for the beginning and end of the loop
992*c5c4113dSnw141292       */
993*c5c4113dSnw141292       cont = pLevel->cont = sqliteVdbeMakeLabel(v);
994*c5c4113dSnw141292       brk = pLevel->brk = sqliteVdbeMakeLabel(v);
995*c5c4113dSnw141292 
996*c5c4113dSnw141292       /* Generate the termination key.  This is the key value that
997*c5c4113dSnw141292       ** will end the search.  There is no termination key if there
998*c5c4113dSnw141292       ** are no equality terms and no "X<..." term.
999*c5c4113dSnw141292       **
1000*c5c4113dSnw141292       ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
1001*c5c4113dSnw141292       ** key computed here really ends up being the start key.
1002*c5c4113dSnw141292       */
1003*c5c4113dSnw141292       if( (score & 1)!=0 ){
1004*c5c4113dSnw141292         for(k=0; k<nExpr; k++){
1005*c5c4113dSnw141292           Expr *pExpr = aExpr[k].p;
1006*c5c4113dSnw141292           if( pExpr==0 ) continue;
1007*c5c4113dSnw141292           if( aExpr[k].idxLeft==iCur
1008*c5c4113dSnw141292              && (pExpr->op==TK_LT || pExpr->op==TK_LE)
1009*c5c4113dSnw141292              && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
1010*c5c4113dSnw141292              && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
1011*c5c4113dSnw141292           ){
1012*c5c4113dSnw141292             sqliteExprCode(pParse, pExpr->pRight);
1013*c5c4113dSnw141292             leFlag = pExpr->op==TK_LE;
1014*c5c4113dSnw141292             disableTerm(pLevel, &aExpr[k].p);
1015*c5c4113dSnw141292             break;
1016*c5c4113dSnw141292           }
1017*c5c4113dSnw141292           if( aExpr[k].idxRight==iCur
1018*c5c4113dSnw141292              && (pExpr->op==TK_GT || pExpr->op==TK_GE)
1019*c5c4113dSnw141292              && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
1020*c5c4113dSnw141292              && pExpr->pRight->iColumn==pIdx->aiColumn[j]
1021*c5c4113dSnw141292           ){
1022*c5c4113dSnw141292             sqliteExprCode(pParse, pExpr->pLeft);
1023*c5c4113dSnw141292             leFlag = pExpr->op==TK_GE;
1024*c5c4113dSnw141292             disableTerm(pLevel, &aExpr[k].p);
1025*c5c4113dSnw141292             break;
1026*c5c4113dSnw141292           }
1027*c5c4113dSnw141292         }
1028*c5c4113dSnw141292         testOp = OP_IdxGE;
1029*c5c4113dSnw141292       }else{
1030*c5c4113dSnw141292         testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
1031*c5c4113dSnw141292         leFlag = 1;
1032*c5c4113dSnw141292       }
1033*c5c4113dSnw141292       if( testOp!=OP_Noop ){
1034*c5c4113dSnw141292         int nCol = nEqColumn + (score & 1);
1035*c5c4113dSnw141292         pLevel->iMem = pParse->nMem++;
1036*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_NotNull, -nCol, sqliteVdbeCurrentAddr(v)+3);
1037*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Pop, nCol, 0);
1038*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Goto, 0, brk);
1039*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MakeKey, nCol, 0);
1040*c5c4113dSnw141292         sqliteAddIdxKeyType(v, pIdx);
1041*c5c4113dSnw141292         if( leFlag ){
1042*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
1043*c5c4113dSnw141292         }
1044*c5c4113dSnw141292         if( pLevel->bRev ){
1045*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
1046*c5c4113dSnw141292         }else{
1047*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
1048*c5c4113dSnw141292         }
1049*c5c4113dSnw141292       }else if( pLevel->bRev ){
1050*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Last, pLevel->iCur, brk);
1051*c5c4113dSnw141292       }
1052*c5c4113dSnw141292 
1053*c5c4113dSnw141292       /* Generate the start key.  This is the key that defines the lower
1054*c5c4113dSnw141292       ** bound on the search.  There is no start key if there are no
1055*c5c4113dSnw141292       ** equality terms and if there is no "X>..." term.  In
1056*c5c4113dSnw141292       ** that case, generate a "Rewind" instruction in place of the
1057*c5c4113dSnw141292       ** start key search.
1058*c5c4113dSnw141292       **
1059*c5c4113dSnw141292       ** 2002-Dec-04: In the case of a reverse-order search, the so-called
1060*c5c4113dSnw141292       ** "start" key really ends up being used as the termination key.
1061*c5c4113dSnw141292       */
1062*c5c4113dSnw141292       if( (score & 2)!=0 ){
1063*c5c4113dSnw141292         for(k=0; k<nExpr; k++){
1064*c5c4113dSnw141292           Expr *pExpr = aExpr[k].p;
1065*c5c4113dSnw141292           if( pExpr==0 ) continue;
1066*c5c4113dSnw141292           if( aExpr[k].idxLeft==iCur
1067*c5c4113dSnw141292              && (pExpr->op==TK_GT || pExpr->op==TK_GE)
1068*c5c4113dSnw141292              && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
1069*c5c4113dSnw141292              && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
1070*c5c4113dSnw141292           ){
1071*c5c4113dSnw141292             sqliteExprCode(pParse, pExpr->pRight);
1072*c5c4113dSnw141292             geFlag = pExpr->op==TK_GE;
1073*c5c4113dSnw141292             disableTerm(pLevel, &aExpr[k].p);
1074*c5c4113dSnw141292             break;
1075*c5c4113dSnw141292           }
1076*c5c4113dSnw141292           if( aExpr[k].idxRight==iCur
1077*c5c4113dSnw141292              && (pExpr->op==TK_LT || pExpr->op==TK_LE)
1078*c5c4113dSnw141292              && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
1079*c5c4113dSnw141292              && pExpr->pRight->iColumn==pIdx->aiColumn[j]
1080*c5c4113dSnw141292           ){
1081*c5c4113dSnw141292             sqliteExprCode(pParse, pExpr->pLeft);
1082*c5c4113dSnw141292             geFlag = pExpr->op==TK_LE;
1083*c5c4113dSnw141292             disableTerm(pLevel, &aExpr[k].p);
1084*c5c4113dSnw141292             break;
1085*c5c4113dSnw141292           }
1086*c5c4113dSnw141292         }
1087*c5c4113dSnw141292       }else{
1088*c5c4113dSnw141292         geFlag = 1;
1089*c5c4113dSnw141292       }
1090*c5c4113dSnw141292       if( nEqColumn>0 || (score&2)!=0 ){
1091*c5c4113dSnw141292         int nCol = nEqColumn + ((score&2)!=0);
1092*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_NotNull, -nCol, sqliteVdbeCurrentAddr(v)+3);
1093*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Pop, nCol, 0);
1094*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Goto, 0, brk);
1095*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MakeKey, nCol, 0);
1096*c5c4113dSnw141292         sqliteAddIdxKeyType(v, pIdx);
1097*c5c4113dSnw141292         if( !geFlag ){
1098*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
1099*c5c4113dSnw141292         }
1100*c5c4113dSnw141292         if( pLevel->bRev ){
1101*c5c4113dSnw141292           pLevel->iMem = pParse->nMem++;
1102*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
1103*c5c4113dSnw141292           testOp = OP_IdxLT;
1104*c5c4113dSnw141292         }else{
1105*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
1106*c5c4113dSnw141292         }
1107*c5c4113dSnw141292       }else if( pLevel->bRev ){
1108*c5c4113dSnw141292         testOp = OP_Noop;
1109*c5c4113dSnw141292       }else{
1110*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Rewind, pLevel->iCur, brk);
1111*c5c4113dSnw141292       }
1112*c5c4113dSnw141292 
1113*c5c4113dSnw141292       /* Generate the the top of the loop.  If there is a termination
1114*c5c4113dSnw141292       ** key we have to test for that key and abort at the top of the
1115*c5c4113dSnw141292       ** loop.
1116*c5c4113dSnw141292       */
1117*c5c4113dSnw141292       start = sqliteVdbeCurrentAddr(v);
1118*c5c4113dSnw141292       if( testOp!=OP_Noop ){
1119*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
1120*c5c4113dSnw141292         sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
1121*c5c4113dSnw141292       }
1122*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_RowKey, pLevel->iCur, 0);
1123*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_IdxIsNull, nEqColumn + (score & 1), cont);
1124*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
1125*c5c4113dSnw141292       if( i==pTabList->nSrc-1 && pushKey ){
1126*c5c4113dSnw141292         haveKey = 1;
1127*c5c4113dSnw141292       }else{
1128*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
1129*c5c4113dSnw141292         haveKey = 0;
1130*c5c4113dSnw141292       }
1131*c5c4113dSnw141292 
1132*c5c4113dSnw141292       /* Record the instruction used to terminate the loop.
1133*c5c4113dSnw141292       */
1134*c5c4113dSnw141292       pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
1135*c5c4113dSnw141292       pLevel->p1 = pLevel->iCur;
1136*c5c4113dSnw141292       pLevel->p2 = start;
1137*c5c4113dSnw141292     }
1138*c5c4113dSnw141292     loopMask |= getMask(&maskSet, iCur);
1139*c5c4113dSnw141292 
1140*c5c4113dSnw141292     /* Insert code to test every subexpression that can be completely
1141*c5c4113dSnw141292     ** computed using the current set of tables.
1142*c5c4113dSnw141292     */
1143*c5c4113dSnw141292     for(j=0; j<nExpr; j++){
1144*c5c4113dSnw141292       if( aExpr[j].p==0 ) continue;
1145*c5c4113dSnw141292       if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
1146*c5c4113dSnw141292       if( pLevel->iLeftJoin && !ExprHasProperty(aExpr[j].p,EP_FromJoin) ){
1147*c5c4113dSnw141292         continue;
1148*c5c4113dSnw141292       }
1149*c5c4113dSnw141292       if( haveKey ){
1150*c5c4113dSnw141292         haveKey = 0;
1151*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
1152*c5c4113dSnw141292       }
1153*c5c4113dSnw141292       sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
1154*c5c4113dSnw141292       aExpr[j].p = 0;
1155*c5c4113dSnw141292     }
1156*c5c4113dSnw141292     brk = cont;
1157*c5c4113dSnw141292 
1158*c5c4113dSnw141292     /* For a LEFT OUTER JOIN, generate code that will record the fact that
1159*c5c4113dSnw141292     ** at least one row of the right table has matched the left table.
1160*c5c4113dSnw141292     */
1161*c5c4113dSnw141292     if( pLevel->iLeftJoin ){
1162*c5c4113dSnw141292       pLevel->top = sqliteVdbeCurrentAddr(v);
1163*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Integer, 1, 0);
1164*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
1165*c5c4113dSnw141292       for(j=0; j<nExpr; j++){
1166*c5c4113dSnw141292         if( aExpr[j].p==0 ) continue;
1167*c5c4113dSnw141292         if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
1168*c5c4113dSnw141292         if( haveKey ){
1169*c5c4113dSnw141292           /* Cannot happen.  "haveKey" can only be true if pushKey is true
1170*c5c4113dSnw141292           ** an pushKey can only be true for DELETE and UPDATE and there are
1171*c5c4113dSnw141292           ** no outer joins with DELETE and UPDATE.
1172*c5c4113dSnw141292           */
1173*c5c4113dSnw141292           haveKey = 0;
1174*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
1175*c5c4113dSnw141292         }
1176*c5c4113dSnw141292         sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
1177*c5c4113dSnw141292         aExpr[j].p = 0;
1178*c5c4113dSnw141292       }
1179*c5c4113dSnw141292     }
1180*c5c4113dSnw141292   }
1181*c5c4113dSnw141292   pWInfo->iContinue = cont;
1182*c5c4113dSnw141292   if( pushKey && !haveKey ){
1183*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Recno, pTabList->a[0].iCursor, 0);
1184*c5c4113dSnw141292   }
1185*c5c4113dSnw141292   freeMaskSet(&maskSet);
1186*c5c4113dSnw141292   return pWInfo;
1187*c5c4113dSnw141292 }
1188*c5c4113dSnw141292 
1189*c5c4113dSnw141292 /*
1190*c5c4113dSnw141292 ** Generate the end of the WHERE loop.  See comments on
1191*c5c4113dSnw141292 ** sqliteWhereBegin() for additional information.
1192*c5c4113dSnw141292 */
sqliteWhereEnd(WhereInfo * pWInfo)1193*c5c4113dSnw141292 void sqliteWhereEnd(WhereInfo *pWInfo){
1194*c5c4113dSnw141292   Vdbe *v = pWInfo->pParse->pVdbe;
1195*c5c4113dSnw141292   int i;
1196*c5c4113dSnw141292   WhereLevel *pLevel;
1197*c5c4113dSnw141292   SrcList *pTabList = pWInfo->pTabList;
1198*c5c4113dSnw141292 
1199*c5c4113dSnw141292   for(i=pTabList->nSrc-1; i>=0; i--){
1200*c5c4113dSnw141292     pLevel = &pWInfo->a[i];
1201*c5c4113dSnw141292     sqliteVdbeResolveLabel(v, pLevel->cont);
1202*c5c4113dSnw141292     if( pLevel->op!=OP_Noop ){
1203*c5c4113dSnw141292       sqliteVdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
1204*c5c4113dSnw141292     }
1205*c5c4113dSnw141292     sqliteVdbeResolveLabel(v, pLevel->brk);
1206*c5c4113dSnw141292     if( pLevel->inOp!=OP_Noop ){
1207*c5c4113dSnw141292       sqliteVdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
1208*c5c4113dSnw141292     }
1209*c5c4113dSnw141292     if( pLevel->iLeftJoin ){
1210*c5c4113dSnw141292       int addr;
1211*c5c4113dSnw141292       addr = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
1212*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iCur>=0));
1213*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
1214*c5c4113dSnw141292       if( pLevel->iCur>=0 ){
1215*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_NullRow, pLevel->iCur, 0);
1216*c5c4113dSnw141292       }
1217*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Goto, 0, pLevel->top);
1218*c5c4113dSnw141292     }
1219*c5c4113dSnw141292   }
1220*c5c4113dSnw141292   sqliteVdbeResolveLabel(v, pWInfo->iBreak);
1221*c5c4113dSnw141292   for(i=0; i<pTabList->nSrc; i++){
1222*c5c4113dSnw141292     Table *pTab = pTabList->a[i].pTab;
1223*c5c4113dSnw141292     assert( pTab!=0 );
1224*c5c4113dSnw141292     if( pTab->isTransient || pTab->pSelect ) continue;
1225*c5c4113dSnw141292     pLevel = &pWInfo->a[i];
1226*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Close, pTabList->a[i].iCursor, 0);
1227*c5c4113dSnw141292     if( pLevel->pIdx!=0 ){
1228*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Close, pLevel->iCur, 0);
1229*c5c4113dSnw141292     }
1230*c5c4113dSnw141292   }
1231*c5c4113dSnw141292 #if 0  /* Never reuse a cursor */
1232*c5c4113dSnw141292   if( pWInfo->pParse->nTab==pWInfo->peakNTab ){
1233*c5c4113dSnw141292     pWInfo->pParse->nTab = pWInfo->savedNTab;
1234*c5c4113dSnw141292   }
1235*c5c4113dSnw141292 #endif
1236*c5c4113dSnw141292   sqliteFree(pWInfo);
1237*c5c4113dSnw141292   return;
1238*c5c4113dSnw141292 }
1239