~oif-team/ubuntu/natty/qt4-x11/xi2.1

« back to all changes in this revision

Viewing changes to src/3rdparty/sqlite/where.c

  • Committer: Bazaar Package Importer
  • Author(s): Adam Conrad
  • Date: 2005-08-24 04:09:09 UTC
  • Revision ID: james.westby@ubuntu.com-20050824040909-xmxe9jfr4a0w5671
Tags: upstream-4.0.0
ImportĀ upstreamĀ versionĀ 4.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
** 2001 September 15
 
3
**
 
4
** The author disclaims copyright to this source code.  In place of
 
5
** a legal notice, here is a blessing:
 
6
**
 
7
**    May you do good and not evil.
 
8
**    May you find forgiveness for yourself and forgive others.
 
9
**    May you share freely, never taking more than you give.
 
10
**
 
11
*************************************************************************
 
12
** This module contains C code that generates VDBE code used to process
 
13
** 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".
 
18
**
 
19
** $Id: where.c,v 1.136 2005/03/16 12:15:21 danielk1977 Exp $
 
20
*/
 
21
#include "sqliteInt.h"
 
22
 
 
23
/*
 
24
** The query generator uses an array of instances of this structure to
 
25
** help it analyze the subexpressions of the WHERE clause.  Each WHERE
 
26
** clause subexpression is separated from the others by an AND operator.
 
27
**
 
28
** The idxLeft and idxRight fields are the VDBE cursor numbers for the
 
29
** table that contains the column that appears on the left-hand and
 
30
** right-hand side of ExprInfo.p.  If either side of ExprInfo.p is
 
31
** something other than a simple column reference, then idxLeft or
 
32
** idxRight are -1.  
 
33
**
 
34
** It is the VDBE cursor number is the value stored in Expr.iTable
 
35
** when Expr.op==TK_COLUMN and the value stored in SrcList.a[].iCursor.
 
36
**
 
37
** prereqLeft, prereqRight, and prereqAll record sets of cursor numbers,
 
38
** but they do so indirectly.  A single ExprMaskSet structure translates
 
39
** cursor number into bits and the translated bit is stored in the prereq
 
40
** fields.  The translation is used in order to maximize the number of
 
41
** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
 
42
** spread out over the non-negative integers.  For example, the cursor
 
43
** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The ExprMaskSet
 
44
** translates these sparse cursor numbers into consecutive integers
 
45
** beginning with 0 in order to make the best possible use of the available
 
46
** bits in the Bitmask.  So, in the example above, the cursor numbers
 
47
** would be mapped into integers 0 through 7.
 
48
**
 
49
** prereqLeft tells us every VDBE cursor that is referenced on the
 
50
** left-hand side of ExprInfo.p.  prereqRight does the same for the
 
51
** right-hand side of the expression.  The following identity always
 
52
** holds:
 
53
**
 
54
**       prereqAll = prereqLeft | prereqRight
 
55
**
 
56
** The ExprInfo.indexable field is true if the ExprInfo.p expression
 
57
** is of a form that might control an index.  Indexable expressions
 
58
** look like this:
 
59
**
 
60
**              <column> <op> <expr>
 
61
**
 
62
** Where <column> is a simple column name and <op> is on of the operators
 
63
** that allowedOp() recognizes.  
 
64
*/
 
65
typedef struct ExprInfo ExprInfo;
 
66
struct ExprInfo {
 
67
  Expr *p;                /* Pointer to the subexpression */
 
68
  u8 indexable;           /* True if this subexprssion is usable by an index */
 
69
  short int idxLeft;      /* p->pLeft is a column in this table number. -1 if
 
70
                          ** p->pLeft is not the column of any table */
 
71
  short int idxRight;     /* p->pRight is a column in this table number. -1 if
 
72
                          ** p->pRight is not the column of any table */
 
73
  Bitmask prereqLeft;     /* Bitmask of tables referenced by p->pLeft */
 
74
  Bitmask prereqRight;    /* Bitmask of tables referenced by p->pRight */
 
75
  Bitmask prereqAll;      /* Bitmask of tables referenced by p */
 
76
};
 
77
 
 
78
/*
 
79
** An instance of the following structure keeps track of a mapping
 
80
** between VDBE cursor numbers and bits of the bitmasks in ExprInfo.
 
81
**
 
82
** The VDBE cursor numbers are small integers contained in 
 
83
** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
 
84
** clause, the cursor numbers might not begin with 0 and they might
 
85
** contain gaps in the numbering sequence.  But we want to make maximum
 
86
** use of the bits in our bitmasks.  This structure provides a mapping
 
87
** from the sparse cursor numbers into consecutive integers beginning
 
88
** with 0.
 
89
**
 
90
** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
 
91
** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
 
92
**
 
93
** For example, if the WHERE clause expression used these VDBE
 
94
** cursors:  4, 5, 8, 29, 57, 73.  Then the  ExprMaskSet structure
 
95
** would map those cursor numbers into bits 0 through 5.
 
96
**
 
97
** Note that the mapping is not necessarily ordered.  In the example
 
98
** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
 
99
** 57->5, 73->4.  Or one of 719 other combinations might be used. It
 
100
** does not really matter.  What is important is that sparse cursor
 
101
** numbers all get mapped into bit numbers that begin with 0 and contain
 
102
** no gaps.
 
103
*/
 
104
typedef struct ExprMaskSet ExprMaskSet;
 
105
struct ExprMaskSet {
 
106
  int n;                        /* Number of assigned cursor values */
 
107
  int ix[sizeof(Bitmask)*8];    /* Cursor assigned to each bit */
 
108
};
 
109
 
 
110
/*
 
111
** Determine the number of elements in an array.
 
112
*/
 
113
#define ARRAYSIZE(X)  (sizeof(X)/sizeof(X[0]))
 
114
 
 
115
/*
 
116
** This routine identifies subexpressions in the WHERE clause where
 
117
** each subexpression is separate by the AND operator.  aSlot is 
 
118
** filled with pointers to the subexpressions.  For example:
 
119
**
 
120
**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
 
121
**           \________/     \_______________/     \________________/
 
122
**            slot[0]            slot[1]               slot[2]
 
123
**
 
124
** The original WHERE clause in pExpr is unaltered.  All this routine
 
125
** does is make aSlot[] entries point to substructure within pExpr.
 
126
**
 
127
** aSlot[] is an array of subexpressions structures.  There are nSlot
 
128
** spaces left in this array.  This routine finds as many AND-separated
 
129
** subexpressions as it can and puts pointers to those subexpressions
 
130
** into aSlot[] entries.  The return value is the number of slots filled.
 
131
*/
 
132
static int exprSplit(int nSlot, ExprInfo *aSlot, Expr *pExpr){
 
133
  int cnt = 0;
 
134
  if( pExpr==0 || nSlot<1 ) return 0;
 
135
  if( nSlot==1 || pExpr->op!=TK_AND ){
 
136
    aSlot[0].p = pExpr;
 
137
    return 1;
 
138
  }
 
139
  if( pExpr->pLeft->op!=TK_AND ){
 
140
    aSlot[0].p = pExpr->pLeft;
 
141
    cnt = 1 + exprSplit(nSlot-1, &aSlot[1], pExpr->pRight);
 
142
  }else{
 
143
    cnt = exprSplit(nSlot, aSlot, pExpr->pLeft);
 
144
    cnt += exprSplit(nSlot-cnt, &aSlot[cnt], pExpr->pRight);
 
145
  }
 
146
  return cnt;
 
147
}
 
148
 
 
149
/*
 
150
** Initialize an expression mask set
 
151
*/
 
152
#define initMaskSet(P)  memset(P, 0, sizeof(*P))
 
153
 
 
154
/*
 
155
** Return the bitmask for the given cursor number.  Return 0 if
 
156
** iCursor is not in the set.
 
157
*/
 
158
static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
 
159
  int i;
 
160
  for(i=0; i<pMaskSet->n; i++){
 
161
    if( pMaskSet->ix[i]==iCursor ){
 
162
      return ((Bitmask)1)<<i;
 
163
    }
 
164
  }
 
165
  return 0;
 
166
}
 
167
 
 
168
/*
 
169
** Create a new mask for cursor iCursor.
 
170
*/
 
171
static void createMask(ExprMaskSet *pMaskSet, int iCursor){
 
172
  if( pMaskSet->n<ARRAYSIZE(pMaskSet->ix) ){
 
173
    pMaskSet->ix[pMaskSet->n++] = iCursor;
 
174
  }
 
175
}
 
176
 
 
177
/*
 
178
** Destroy an expression mask set
 
179
*/
 
180
#define freeMaskSet(P)   /* NO-OP */
 
181
 
 
182
/*
 
183
** This routine walks (recursively) an expression tree and generates
 
184
** a bitmask indicating which tables are used in that expression
 
185
** tree.
 
186
**
 
187
** In order for this routine to work, the calling function must have
 
188
** previously invoked sqlite3ExprResolveNames() on the expression.  See
 
189
** the header comment on that routine for additional information.
 
190
** The sqlite3ExprResolveNames() routines looks for column names and
 
191
** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
 
192
** the VDBE cursor number of the table.
 
193
*/
 
194
static Bitmask exprListTableUsage(ExprMaskSet *, ExprList *);
 
195
static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
 
196
  Bitmask mask = 0;
 
197
  if( p==0 ) return 0;
 
198
  if( p->op==TK_COLUMN ){
 
199
    mask = getMask(pMaskSet, p->iTable);
 
200
    return mask;
 
201
  }
 
202
  mask = exprTableUsage(pMaskSet, p->pRight);
 
203
  mask |= exprTableUsage(pMaskSet, p->pLeft);
 
204
  mask |= exprListTableUsage(pMaskSet, p->pList);
 
205
  if( p->pSelect ){
 
206
    Select *pS = p->pSelect;
 
207
    mask |= exprListTableUsage(pMaskSet, pS->pEList);
 
208
    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
 
209
    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
 
210
    mask |= exprTableUsage(pMaskSet, pS->pWhere);
 
211
    mask |= exprTableUsage(pMaskSet, pS->pHaving);
 
212
  }
 
213
  return mask;
 
214
}
 
215
static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
 
216
  int i;
 
217
  Bitmask mask = 0;
 
218
  if( pList ){
 
219
    for(i=0; i<pList->nExpr; i++){
 
220
      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
 
221
    }
 
222
  }
 
223
  return mask;
 
224
}
 
225
 
 
226
/*
 
227
** Return TRUE if the given operator is one of the operators that is
 
228
** allowed for an indexable WHERE clause term.  The allowed operators are
 
229
** "=", "<", ">", "<=", ">=", and "IN".
 
230
*/
 
231
static int allowedOp(int op){
 
232
  assert( TK_GT==TK_LE-1 && TK_LE==TK_LT-1 && TK_LT==TK_GE-1 && TK_EQ==TK_GT-1);
 
233
  return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
 
234
}
 
235
 
 
236
/*
 
237
** Swap two objects of type T.
 
238
*/
 
239
#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
 
240
 
 
241
/*
 
242
** Return the index in the SrcList that uses cursor iCur.  If iCur is
 
243
** used by the first entry in SrcList return 0.  If iCur is used by
 
244
** the second entry return 1.  And so forth.
 
245
**
 
246
** SrcList is the set of tables in the FROM clause in the order that
 
247
** they will be processed.  The value returned here gives us an index
 
248
** of which tables will be processed first.
 
249
*/
 
250
static int tableOrder(SrcList *pList, int iCur){
 
251
  int i;
 
252
  struct SrcList_item *pItem;
 
253
  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
 
254
    if( pItem->iCursor==iCur ) return i;
 
255
  }
 
256
  return -1;
 
257
}
 
258
 
 
259
/*
 
260
** The input to this routine is an ExprInfo structure with only the
 
261
** "p" field filled in.  The job of this routine is to analyze the
 
262
** subexpression and populate all the other fields of the ExprInfo
 
263
** structure.
 
264
*/
 
265
static void exprAnalyze(SrcList *pSrc, ExprMaskSet *pMaskSet, ExprInfo *pInfo){
 
266
  Expr *pExpr = pInfo->p;
 
267
  pInfo->prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
 
268
  pInfo->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
 
269
  pInfo->prereqAll = exprTableUsage(pMaskSet, pExpr);
 
270
  pInfo->indexable = 0;
 
271
  pInfo->idxLeft = -1;
 
272
  pInfo->idxRight = -1;
 
273
  if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
 
274
    if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
 
275
      pInfo->idxRight = pExpr->pRight->iTable;
 
276
      pInfo->indexable = 1;
 
277
    }
 
278
    if( pExpr->pLeft->op==TK_COLUMN ){
 
279
      pInfo->idxLeft = pExpr->pLeft->iTable;
 
280
      pInfo->indexable = 1;
 
281
    }
 
282
  }
 
283
  if( pInfo->indexable ){
 
284
    assert( pInfo->idxLeft!=pInfo->idxRight );
 
285
 
 
286
    /* We want the expression to be of the form "X = expr", not "expr = X".
 
287
    ** So flip it over if necessary.  If the expression is "X = Y", then
 
288
    ** we want Y to come from an earlier table than X.
 
289
    **
 
290
    ** The collating sequence rule is to always choose the left expression.
 
291
    ** So if we do a flip, we also have to move the collating sequence.
 
292
    */
 
293
    if( tableOrder(pSrc,pInfo->idxLeft)<tableOrder(pSrc,pInfo->idxRight) ){
 
294
      assert( pExpr->op!=TK_IN );
 
295
      SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
 
296
      SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
 
297
      if( pExpr->op>=TK_GT ){
 
298
        assert( TK_LT==TK_GT+2 );
 
299
        assert( TK_GE==TK_LE+2 );
 
300
        assert( TK_GT>TK_EQ );
 
301
        assert( TK_GT<TK_LE );
 
302
        assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
 
303
        pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
 
304
      }
 
305
      SWAP(unsigned, pInfo->prereqLeft, pInfo->prereqRight);
 
306
      SWAP(short int, pInfo->idxLeft, pInfo->idxRight);
 
307
    }
 
308
  }      
 
309
 
 
310
}
 
311
 
 
312
/*
 
313
** This routine decides if pIdx can be used to satisfy the ORDER BY
 
314
** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
 
315
** ORDER BY clause, this routine returns 0.
 
316
**
 
317
** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
 
318
** left-most table in the FROM clause of that same SELECT statement and
 
319
** the table has a cursor number of "base".  pIdx is an index on pTab.
 
320
**
 
321
** nEqCol is the number of columns of pIdx that are used as equality
 
322
** constraints.  Any of these columns may be missing from the ORDER BY
 
323
** clause and the match can still be a success.
 
324
**
 
325
** If the index is UNIQUE, then the ORDER BY clause is allowed to have
 
326
** additional terms past the end of the index and the match will still
 
327
** be a success.
 
328
**
 
329
** All terms of the ORDER BY that match against the index must be either
 
330
** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
 
331
** index do not need to satisfy this constraint.)  The *pbRev value is
 
332
** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
 
333
** the ORDER BY clause is all ASC.
 
334
*/
 
335
static int isSortingIndex(
 
336
  Parse *pParse,          /* Parsing context */
 
337
  Index *pIdx,            /* The index we are testing */
 
338
  Table *pTab,            /* The table to be sorted */
 
339
  int base,               /* Cursor number for pTab */
 
340
  ExprList *pOrderBy,     /* The ORDER BY clause */
 
341
  int nEqCol,             /* Number of index columns with == constraints */
 
342
  int *pbRev              /* Set to 1 if ORDER BY is DESC */
 
343
){
 
344
  int i, j;                    /* Loop counters */
 
345
  int sortOrder;               /* Which direction we are sorting */
 
346
  int nTerm;                   /* Number of ORDER BY terms */
 
347
  struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
 
348
  sqlite3 *db = pParse->db;
 
349
 
 
350
  assert( pOrderBy!=0 );
 
351
  nTerm = pOrderBy->nExpr;
 
352
  assert( nTerm>0 );
 
353
 
 
354
  /* Match terms of the ORDER BY clause against columns of
 
355
  ** the index.
 
356
  */
 
357
  for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
 
358
    Expr *pExpr;       /* The expression of the ORDER BY pTerm */
 
359
    CollSeq *pColl;    /* The collating sequence of pExpr */
 
360
 
 
361
    pExpr = pTerm->pExpr;
 
362
    if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
 
363
      /* Can not use an index sort on anything that is not a column in the
 
364
      ** left-most table of the FROM clause */
 
365
      return 0;
 
366
    }
 
367
    pColl = sqlite3ExprCollSeq(pParse, pExpr);
 
368
    if( !pColl ) pColl = db->pDfltColl;
 
369
    if( pExpr->iColumn!=pIdx->aiColumn[i] || pColl!=pIdx->keyInfo.aColl[i] ){
 
370
      /* Term j of the ORDER BY clause does not match column i of the index */
 
371
      if( i<nEqCol ){
 
372
        /* If an index column that is constrained by == fails to match an
 
373
        ** ORDER BY term, that is OK.  Just ignore that column of the index
 
374
        */
 
375
        continue;
 
376
      }else{
 
377
        /* If an index column fails to match and is not constrained by ==
 
378
        ** then the index cannot satisfy the ORDER BY constraint.
 
379
        */
 
380
        return 0;
 
381
      }
 
382
    }
 
383
    if( i>nEqCol ){
 
384
      if( pTerm->sortOrder!=sortOrder ){
 
385
        /* Indices can only be used if all ORDER BY terms past the
 
386
        ** equality constraints are all either DESC or ASC. */
 
387
        return 0;
 
388
      }
 
389
    }else{
 
390
      sortOrder = pTerm->sortOrder;
 
391
    }
 
392
    j++;
 
393
    pTerm++;
 
394
  }
 
395
 
 
396
  /* The index can be used for sorting if all terms of the ORDER BY clause
 
397
  ** or covered or if we ran out of index columns and the it is a UNIQUE
 
398
  ** index.
 
399
  */
 
400
  if( j>=nTerm || (i>=pIdx->nColumn && pIdx->onError!=OE_None) ){
 
401
    *pbRev = sortOrder==SQLITE_SO_DESC;
 
402
    return 1;
 
403
  }
 
404
  return 0;
 
405
}
 
406
 
 
407
/*
 
408
** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
 
409
** by sorting in order of ROWID.  Return true if so and set *pbRev to be
 
410
** true for reverse ROWID and false for forward ROWID order.
 
411
*/
 
412
static int sortableByRowid(
 
413
  int base,               /* Cursor number for table to be sorted */
 
414
  ExprList *pOrderBy,     /* The ORDER BY clause */
 
415
  int *pbRev              /* Set to 1 if ORDER BY is DESC */
 
416
){
 
417
  Expr *p;
 
418
 
 
419
  assert( pOrderBy!=0 );
 
420
  assert( pOrderBy->nExpr>0 );
 
421
  p = pOrderBy->a[0].pExpr;
 
422
  if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ){
 
423
    *pbRev = pOrderBy->a[0].sortOrder;
 
424
    return 1;
 
425
  }
 
426
  return 0;
 
427
}
 
428
 
 
429
 
 
430
/*
 
431
** Disable a term in the WHERE clause.  Except, do not disable the term
 
432
** if it controls a LEFT OUTER JOIN and it did not originate in the ON
 
433
** or USING clause of that join.
 
434
**
 
435
** Consider the term t2.z='ok' in the following queries:
 
436
**
 
437
**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
 
438
**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
 
439
**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
 
440
**
 
441
** The t2.z='ok' is disabled in the in (2) because it originates
 
442
** in the ON clause.  The term is disabled in (3) because it is not part
 
443
** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
 
444
**
 
445
** Disabling a term causes that term to not be tested in the inner loop
 
446
** of the join.  Disabling is an optimization.  We would get the correct
 
447
** results if nothing were ever disabled, but joins might run a little
 
448
** slower.  The trick is to disable as much as we can without disabling
 
449
** too much.  If we disabled in (1), we'd get the wrong answer.
 
450
** See ticket #813.
 
451
*/
 
452
static void disableTerm(WhereLevel *pLevel, Expr **ppExpr){
 
453
  Expr *pExpr = *ppExpr;
 
454
  if( pLevel->iLeftJoin==0 || ExprHasProperty(pExpr, EP_FromJoin) ){
 
455
    *ppExpr = 0;
 
456
  }
 
457
}
 
458
 
 
459
/*
 
460
** Generate code that builds a probe for an index.  Details:
 
461
**
 
462
**    *  Check the top nColumn entries on the stack.  If any
 
463
**       of those entries are NULL, jump immediately to brk,
 
464
**       which is the loop exit, since no index entry will match
 
465
**       if any part of the key is NULL.
 
466
**
 
467
**    *  Construct a probe entry from the top nColumn entries in
 
468
**       the stack with affinities appropriate for index pIdx.
 
469
*/
 
470
static void buildIndexProbe(Vdbe *v, int nColumn, int brk, Index *pIdx){
 
471
  sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
 
472
  sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
 
473
  sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
 
474
  sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
 
475
  sqlite3IndexAffinityStr(v, pIdx);
 
476
}
 
477
 
 
478
/*
 
479
** Generate code for an equality term of the WHERE clause.  An equality
 
480
** term can be either X=expr  or X IN (...).   pTerm is the X.  
 
481
*/
 
482
static void codeEqualityTerm(
 
483
  Parse *pParse,      /* The parsing context */
 
484
  ExprInfo *pTerm,    /* The term of the WHERE clause to be coded */
 
485
  int brk,            /* Jump here to abandon the loop */
 
486
  WhereLevel *pLevel  /* When level of the FROM clause we are working on */
 
487
){
 
488
  Expr *pX = pTerm->p;
 
489
  if( pX->op!=TK_IN ){
 
490
    assert( pX->op==TK_EQ );
 
491
    sqlite3ExprCode(pParse, pX->pRight);
 
492
#ifndef SQLITE_OMIT_SUBQUERY
 
493
  }else{
 
494
    int iTab;
 
495
    Vdbe *v = pParse->pVdbe;
 
496
 
 
497
    sqlite3CodeSubselect(pParse, pX);
 
498
    iTab = pX->iTable;
 
499
    sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
 
500
    sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
 
501
    VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
 
502
    pLevel->inP2 = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
 
503
    pLevel->inOp = OP_Next;
 
504
    pLevel->inP1 = iTab;
 
505
#endif
 
506
  }
 
507
  disableTerm(pLevel, &pTerm->p);
 
508
}
 
509
 
 
510
/*
 
511
** The number of bits in a Bitmask
 
512
*/
 
513
#define BMS  (sizeof(Bitmask)*8-1)
 
514
 
 
515
 
 
516
/*
 
517
** Generate the beginning of the loop used for WHERE clause processing.
 
518
** The return value is a pointer to an opaque structure that contains
 
519
** information needed to terminate the loop.  Later, the calling routine
 
520
** should invoke sqlite3WhereEnd() with the return value of this function
 
521
** in order to complete the WHERE clause processing.
 
522
**
 
523
** If an error occurs, this routine returns NULL.
 
524
**
 
525
** The basic idea is to do a nested loop, one loop for each table in
 
526
** the FROM clause of a select.  (INSERT and UPDATE statements are the
 
527
** same as a SELECT with only a single table in the FROM clause.)  For
 
528
** example, if the SQL is this:
 
529
**
 
530
**       SELECT * FROM t1, t2, t3 WHERE ...;
 
531
**
 
532
** Then the code generated is conceptually like the following:
 
533
**
 
534
**      foreach row1 in t1 do       \    Code generated
 
535
**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
 
536
**          foreach row3 in t3 do   /
 
537
**            ...
 
538
**          end                     \    Code generated
 
539
**        end                        |-- by sqlite3WhereEnd()
 
540
**      end                         /
 
541
**
 
542
** There are Btree cursors associated with each table.  t1 uses cursor
 
543
** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
 
544
** And so forth.  This routine generates code to open those VDBE cursors
 
545
** and sqlite3WhereEnd() generates the code to close them.
 
546
**
 
547
** The code that sqlite3WhereBegin() generates leaves the cursors named
 
548
** in pTabList pointing at their appropriate entries.  The [...] code
 
549
** can use OP_Column and OP_Recno opcodes on these cursors to extract
 
550
** data from the various tables of the loop.
 
551
**
 
552
** If the WHERE clause is empty, the foreach loops must each scan their
 
553
** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
 
554
** the tables have indices and there are terms in the WHERE clause that
 
555
** refer to those indices, a complete table scan can be avoided and the
 
556
** code will run much faster.  Most of the work of this routine is checking
 
557
** to see if there are indices that can be used to speed up the loop.
 
558
**
 
559
** Terms of the WHERE clause are also used to limit which rows actually
 
560
** make it to the "..." in the middle of the loop.  After each "foreach",
 
561
** terms of the WHERE clause that use only terms in that loop and outer
 
562
** loops are evaluated and if false a jump is made around all subsequent
 
563
** inner loops (or around the "..." if the test occurs within the inner-
 
564
** most loop)
 
565
**
 
566
** OUTER JOINS
 
567
**
 
568
** An outer join of tables t1 and t2 is conceptally coded as follows:
 
569
**
 
570
**    foreach row1 in t1 do
 
571
**      flag = 0
 
572
**      foreach row2 in t2 do
 
573
**        start:
 
574
**          ...
 
575
**          flag = 1
 
576
**      end
 
577
**      if flag==0 then
 
578
**        move the row2 cursor to a null row
 
579
**        goto start
 
580
**      fi
 
581
**    end
 
582
**
 
583
** ORDER BY CLAUSE PROCESSING
 
584
**
 
585
** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
 
586
** if there is one.  If there is no ORDER BY clause or if this routine
 
587
** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
 
588
**
 
589
** If an index can be used so that the natural output order of the table
 
590
** scan is correct for the ORDER BY clause, then that index is used and
 
591
** *ppOrderBy is set to NULL.  This is an optimization that prevents an
 
592
** unnecessary sort of the result set if an index appropriate for the
 
593
** ORDER BY clause already exists.
 
594
**
 
595
** If the where clause loops cannot be arranged to provide the correct
 
596
** output order, then the *ppOrderBy is unchanged.
 
597
*/
 
598
WhereInfo *sqlite3WhereBegin(
 
599
  Parse *pParse,        /* The parser context */
 
600
  SrcList *pTabList,    /* A list of all tables to be scanned */
 
601
  Expr *pWhere,         /* The WHERE clause */
 
602
  ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
 
603
  Fetch *pFetch         /* Initial location of cursors.  NULL otherwise */
 
604
){
 
605
  int i;                     /* Loop counter */
 
606
  WhereInfo *pWInfo;         /* Will become the return value of this function */
 
607
  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
 
608
  int brk, cont = 0;         /* Addresses used during code generation */
 
609
  int nExpr;           /* Number of subexpressions in the WHERE clause */
 
610
  Bitmask loopMask;    /* One bit set for each outer loop */
 
611
  ExprInfo *pTerm;     /* A single term in the WHERE clause; ptr to aExpr[] */
 
612
  ExprMaskSet maskSet; /* The expression mask set */
 
613
  int iDirectEq[BMS];  /* Term of the form ROWID==X for the N-th table */
 
614
  int iDirectLt[BMS];  /* Term of the form ROWID<X or ROWID<=X */
 
615
  int iDirectGt[BMS];  /* Term of the form ROWID>X or ROWID>=X */
 
616
  ExprInfo aExpr[101]; /* The WHERE clause is divided into these terms */
 
617
  struct SrcList_item *pTabItem;  /* A single entry from pTabList */
 
618
  WhereLevel *pLevel;             /* A single level in the pWInfo list */
 
619
 
 
620
  /* The number of terms in the FROM clause is limited by the number of
 
621
  ** bits in a Bitmask 
 
622
  */
 
623
  if( pTabList->nSrc>sizeof(Bitmask)*8 ){
 
624
    sqlite3ErrorMsg(pParse, "at most %d tables in a join",
 
625
       sizeof(Bitmask)*8);
 
626
    return 0;
 
627
  }
 
628
 
 
629
  /* Split the WHERE clause into separate subexpressions where each
 
630
  ** subexpression is separated by an AND operator.  If the aExpr[]
 
631
  ** array fills up, the last entry might point to an expression which
 
632
  ** contains additional unfactored AND operators.
 
633
  */
 
634
  initMaskSet(&maskSet);
 
635
  memset(aExpr, 0, sizeof(aExpr));
 
636
  nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
 
637
  if( nExpr==ARRAYSIZE(aExpr) ){
 
638
    sqlite3ErrorMsg(pParse, "WHERE clause too complex - no more "
 
639
       "than %d terms allowed", (int)ARRAYSIZE(aExpr)-1);
 
640
    return 0;
 
641
  }
 
642
    
 
643
  /* Allocate and initialize the WhereInfo structure that will become the
 
644
  ** return value.
 
645
  */
 
646
  pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
 
647
  if( sqlite3_malloc_failed ){
 
648
    sqliteFree(pWInfo); /* Avoid leaking memory when malloc fails */
 
649
    return 0;
 
650
  }
 
651
  pWInfo->pParse = pParse;
 
652
  pWInfo->pTabList = pTabList;
 
653
  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
 
654
 
 
655
  /* Special case: a WHERE clause that is constant.  Evaluate the
 
656
  ** expression and either jump over all of the code or fall thru.
 
657
  */
 
658
  if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
 
659
    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
 
660
    pWhere = 0;
 
661
  }
 
662
 
 
663
  /* Analyze all of the subexpressions.
 
664
  */
 
665
  for(i=0; i<pTabList->nSrc; i++){
 
666
    createMask(&maskSet, pTabList->a[i].iCursor);
 
667
  }
 
668
  for(pTerm=aExpr, i=0; i<nExpr; i++, pTerm++){
 
669
    exprAnalyze(pTabList, &maskSet, pTerm);
 
670
  }
 
671
 
 
672
  /* Figure out what index to use (if any) for each nested loop.
 
673
  ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
 
674
  ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
 
675
  ** loop. 
 
676
  **
 
677
  ** If terms exist that use the ROWID of any table, then set the
 
678
  ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
 
679
  ** to the index of the term containing the ROWID.  We always prefer
 
680
  ** to use a ROWID which can directly access a table rather than an
 
681
  ** index which requires reading an index first to get the rowid then
 
682
  ** doing a second read of the actual database table.
 
683
  **
 
684
  ** Actually, if there are more than 32 tables in the join, only the
 
685
  ** first 32 tables are candidates for indices.  This is (again) due
 
686
  ** to the limit of 32 bits in an integer bitmask.
 
687
  */
 
688
  loopMask = 0;
 
689
  pTabItem = pTabList->a;
 
690
  pLevel = pWInfo->a;
 
691
  for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++,pTabItem++,pLevel++){
 
692
    int j;
 
693
    int iCur = pTabItem->iCursor;            /* The cursor for this table */
 
694
    Bitmask mask = getMask(&maskSet, iCur);  /* Cursor mask for this table */
 
695
    Table *pTab = pTabItem->pTab;
 
696
    Index *pIdx;
 
697
    Index *pBestIdx = 0;
 
698
    int bestScore = 0;
 
699
    int bestRev = 0;
 
700
 
 
701
    /* Check to see if there is an expression that uses only the
 
702
    ** ROWID field of this table.  For terms of the form ROWID==expr
 
703
    ** set iDirectEq[i] to the index of the term.  For terms of the
 
704
    ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
 
705
    ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
 
706
    **
 
707
    ** (Added:) Treat ROWID IN expr like ROWID=expr.
 
708
    */
 
709
    pLevel->iIdxCur = -1;
 
710
    iDirectEq[i] = -1;
 
711
    iDirectLt[i] = -1;
 
712
    iDirectGt[i] = -1;
 
713
    for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
 
714
      Expr *pX = pTerm->p;
 
715
      if( pTerm->idxLeft==iCur && pX->pLeft->iColumn<0
 
716
            && (pTerm->prereqRight & loopMask)==pTerm->prereqRight ){
 
717
        switch( pX->op ){
 
718
          case TK_IN:
 
719
          case TK_EQ: iDirectEq[i] = j; break;
 
720
          case TK_LE:
 
721
          case TK_LT: iDirectLt[i] = j; break;
 
722
          case TK_GE:
 
723
          case TK_GT: iDirectGt[i] = j;  break;
 
724
        }
 
725
      }
 
726
    }
 
727
 
 
728
    /* If we found a term that tests ROWID with == or IN, that term
 
729
    ** will be used to locate the rows in the database table.  There
 
730
    ** is not need to continue into the code below that looks for
 
731
    ** an index.  We will always use the ROWID over an index.
 
732
    */
 
733
    if( iDirectEq[i]>=0 ){
 
734
      loopMask |= mask;
 
735
      pLevel->pIdx = 0;
 
736
      continue;
 
737
    }
 
738
 
 
739
    /* Do a search for usable indices.  Leave pBestIdx pointing to
 
740
    ** the "best" index.  pBestIdx is left set to NULL if no indices
 
741
    ** are usable.
 
742
    **
 
743
    ** The best index is the one with the highest score.  The score
 
744
    ** for the index is determined as follows.  For each of the
 
745
    ** left-most terms that is fixed by an equality operator, add
 
746
    ** 32 to the score.  The right-most term of the index may be
 
747
    ** constrained by an inequality.  Add 4 if for an "x<..." constraint
 
748
    ** and add 8 for an "x>..." constraint.  If both constraints
 
749
    ** are present, add 12.
 
750
    **
 
751
    ** If the left-most term of the index uses an IN operator
 
752
    ** (ex:  "x IN (...)")  then add 16 to the score.
 
753
    **
 
754
    ** If an index can be used for sorting, add 2 to the score.
 
755
    ** If an index contains all the terms of a table that are ever
 
756
    ** used by any expression in the SQL statement, then add 1 to
 
757
    ** the score.
 
758
    **
 
759
    ** This scoring system is designed so that the score can later be
 
760
    ** used to determine how the index is used.  If the score&0x1c is 0
 
761
    ** then all constraints are equalities.  If score&0x4 is not 0 then
 
762
    ** there is an inequality used as a termination key.  (ex: "x<...")
 
763
    ** If score&0x8 is not 0 then there is an inequality used as the
 
764
    ** start key.  (ex: "x>...").  A score or 0x10 is the special case
 
765
    ** of an IN operator constraint.  (ex:  "x IN ...").
 
766
    **
 
767
    ** The IN operator (as in "<expr> IN (...)") is treated the same as
 
768
    ** an equality comparison except that it can only be used on the
 
769
    ** left-most column of an index and other terms of the WHERE clause
 
770
    ** cannot be used in conjunction with the IN operator to help satisfy
 
771
    ** other columns of the index.
 
772
    */
 
773
    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 
774
      Bitmask eqMask = 0;  /* Index columns covered by an x=... term */
 
775
      Bitmask ltMask = 0;  /* Index columns covered by an x<... term */
 
776
      Bitmask gtMask = 0;  /* Index columns covered by an x>... term */
 
777
      Bitmask inMask = 0;  /* Index columns covered by an x IN .. term */
 
778
      Bitmask m;
 
779
      int nEq, score, bRev = 0;
 
780
 
 
781
      if( pIdx->nColumn>sizeof(eqMask)*8 ){
 
782
        continue;  /* Ignore indices with too many columns to analyze */
 
783
      }
 
784
      for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
 
785
        Expr *pX = pTerm->p;
 
786
        CollSeq *pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
 
787
        if( !pColl && pX->pRight ){
 
788
          pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
 
789
        }
 
790
        if( !pColl ){
 
791
          pColl = pParse->db->pDfltColl;
 
792
        }
 
793
        if( pTerm->idxLeft==iCur 
 
794
             && (pTerm->prereqRight & loopMask)==pTerm->prereqRight ){
 
795
          int iColumn = pX->pLeft->iColumn;
 
796
          int k;
 
797
          char idxaff = pIdx->pTable->aCol[iColumn].affinity; 
 
798
          for(k=0; k<pIdx->nColumn; k++){
 
799
            /* If the collating sequences or affinities don't match, 
 
800
            ** ignore this index.  */
 
801
            if( pColl!=pIdx->keyInfo.aColl[k] ) continue;
 
802
            if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
 
803
            if( pIdx->aiColumn[k]==iColumn ){
 
804
              switch( pX->op ){
 
805
                case TK_IN: {
 
806
                  if( k==0 ) inMask |= 1;
 
807
                  break;
 
808
                }
 
809
                case TK_EQ: {
 
810
                  eqMask |= ((Bitmask)1)<<k;
 
811
                  break;
 
812
                }
 
813
                case TK_LE:
 
814
                case TK_LT: {
 
815
                  ltMask |= ((Bitmask)1)<<k;
 
816
                  break;
 
817
                }
 
818
                case TK_GE:
 
819
                case TK_GT: {
 
820
                  gtMask |= ((Bitmask)1)<<k;
 
821
                  break;
 
822
                }
 
823
                default: {
 
824
                  /* CANT_HAPPEN */
 
825
                  assert( 0 );
 
826
                  break;
 
827
                }
 
828
              }
 
829
              break;
 
830
            }
 
831
          }
 
832
        }
 
833
      }
 
834
 
 
835
      /* The following loop ends with nEq set to the number of columns
 
836
      ** on the left of the index with == constraints.
 
837
      */
 
838
      for(nEq=0; nEq<pIdx->nColumn; nEq++){
 
839
        m = (((Bitmask)1)<<(nEq+1))-1;
 
840
        if( (m & eqMask)!=m ) break;
 
841
      }
 
842
 
 
843
      /* Begin assemblying the score
 
844
      */
 
845
      score = nEq*32;   /* Base score is 32 times number of == constraints */
 
846
      m = ((Bitmask)1)<<nEq;
 
847
      if( m & ltMask ) score+=4;    /* Increase score for a < constraint */
 
848
      if( m & gtMask ) score+=8;    /* Increase score for a > constraint */
 
849
      if( score==0 && inMask ) score = 16; /* Default score for IN constraint */
 
850
 
 
851
      /* Give bonus points if this index can be used for sorting
 
852
      */
 
853
      if( i==0 && score!=16 && ppOrderBy && *ppOrderBy ){
 
854
        int base = pTabList->a[0].iCursor;
 
855
        if( isSortingIndex(pParse, pIdx, pTab, base, *ppOrderBy, nEq, &bRev) ){
 
856
          score += 2;
 
857
        }
 
858
      }
 
859
 
 
860
      /* Check to see if we can get away with using just the index without
 
861
      ** ever reading the table.  If that is the case, then add one bonus
 
862
      ** point to the score.
 
863
      */
 
864
      if( score && pTabItem->colUsed < (((Bitmask)1)<<(BMS-1)) ){
 
865
        for(m=0, j=0; j<pIdx->nColumn; j++){
 
866
          int x = pIdx->aiColumn[j];
 
867
          if( x<BMS-1 ){
 
868
            m |= ((Bitmask)1)<<x;
 
869
          }
 
870
        }
 
871
        if( (pTabItem->colUsed & m)==pTabItem->colUsed ){
 
872
          score++;
 
873
        }
 
874
      }
 
875
 
 
876
      /* If the score for this index is the best we have seen so far, then
 
877
      ** save it
 
878
      */
 
879
      if( score>bestScore ){
 
880
        pBestIdx = pIdx;
 
881
        bestScore = score;
 
882
        bestRev = bRev;
 
883
      }
 
884
    }
 
885
    pLevel->pIdx = pBestIdx;
 
886
    pLevel->score = bestScore;
 
887
    pLevel->bRev = bestRev;
 
888
    loopMask |= mask;
 
889
    if( pBestIdx ){
 
890
      pLevel->iIdxCur = pParse->nTab++;
 
891
    }
 
892
  }
 
893
 
 
894
  /* Check to see if the ORDER BY clause is or can be satisfied by the
 
895
  ** use of an index on the first table.
 
896
  */
 
897
  if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
 
898
    Index *pIdx;             /* Index derived from the WHERE clause */
 
899
    Table *pTab;             /* Left-most table in the FROM clause */
 
900
    int bRev = 0;            /* True to reverse the output order */
 
901
    int iCur;                /* Btree-cursor that will be used by pTab */
 
902
    WhereLevel *pLevel0 = &pWInfo->a[0];
 
903
 
 
904
    pTab = pTabList->a[0].pTab;
 
905
    pIdx = pLevel0->pIdx;
 
906
    iCur = pTabList->a[0].iCursor;
 
907
    if( pIdx==0 && sortableByRowid(iCur, *ppOrderBy, &bRev) ){
 
908
      /* The ORDER BY clause specifies ROWID order, which is what we
 
909
      ** were going to be doing anyway...
 
910
      */
 
911
      *ppOrderBy = 0;
 
912
      pLevel0->bRev = bRev;
 
913
    }else if( pLevel0->score==16 ){
 
914
      /* If there is already an IN index on the left-most table,
 
915
      ** it will not give the correct sort order.
 
916
      ** So, pretend that no suitable index is found.
 
917
      */
 
918
    }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
 
919
      /* If the left-most column is accessed using its ROWID, then do
 
920
      ** not try to sort by index.  But do delete the ORDER BY clause
 
921
      ** if it is redundant.
 
922
      */
 
923
    }else if( (pLevel0->score&2)!=0 ){
 
924
      /* The index that was selected for searching will cause rows to
 
925
      ** appear in sorted order.
 
926
      */
 
927
      *ppOrderBy = 0;
 
928
    }
 
929
  }
 
930
 
 
931
  /* Open all tables in the pTabList and any indices selected for
 
932
  ** searching those tables.
 
933
  */
 
934
  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
 
935
  pLevel = pWInfo->a;
 
936
  for(i=0, pTabItem=pTabList->a; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
 
937
    Table *pTab;
 
938
    Index *pIx;
 
939
    int iIdxCur = pLevel->iIdxCur;
 
940
 
 
941
    pTab = pTabItem->pTab;
 
942
    if( pTab->isTransient || pTab->pSelect ) continue;
 
943
    if( (pLevel->score & 1)==0 ){
 
944
      sqlite3OpenTableForReading(v, pTabItem->iCursor, pTab);
 
945
    }
 
946
    pLevel->iTabCur = pTabItem->iCursor;
 
947
    if( (pIx = pLevel->pIdx)!=0 ){
 
948
      sqlite3VdbeAddOp(v, OP_Integer, pIx->iDb, 0);
 
949
      sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
 
950
                     (char*)&pIx->keyInfo, P3_KEYINFO);
 
951
    }
 
952
    if( (pLevel->score & 1)!=0 ){
 
953
      sqlite3VdbeAddOp(v, OP_KeyAsData, iIdxCur, 1);
 
954
      sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
 
955
    }
 
956
    sqlite3CodeVerifySchema(pParse, pTab->iDb);
 
957
  }
 
958
  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
 
959
 
 
960
  /* Generate the code to do the search
 
961
  */
 
962
  loopMask = 0;
 
963
  pLevel = pWInfo->a;
 
964
  pTabItem = pTabList->a;
 
965
  for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
 
966
    int j, k;
 
967
    int iCur = pTabItem->iCursor;  /* The VDBE cursor for the table */
 
968
    Index *pIdx;       /* The index we will be using */
 
969
    int iIdxCur;       /* The VDBE cursor for the index */
 
970
    int omitTable;     /* True if we use the index only */
 
971
 
 
972
    pIdx = pLevel->pIdx;
 
973
    iIdxCur = pLevel->iIdxCur;
 
974
    pLevel->inOp = OP_Noop;
 
975
 
 
976
    /* Check to see if it is appropriate to omit the use of the table
 
977
    ** here and use its index instead.
 
978
    */
 
979
    omitTable = (pLevel->score&1)!=0;
 
980
 
 
981
    /* If this is the right table of a LEFT OUTER JOIN, allocate and
 
982
    ** initialize a memory cell that records if this table matches any
 
983
    ** row of the left table of the join.
 
984
    */
 
985
    if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
 
986
      if( !pParse->nMem ) pParse->nMem++;
 
987
      pLevel->iLeftJoin = pParse->nMem++;
 
988
      sqlite3VdbeAddOp(v, OP_String8, 0, 0);
 
989
      sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
 
990
      VdbeComment((v, "# init LEFT JOIN no-match flag"));
 
991
    }
 
992
 
 
993
    if( i<ARRAYSIZE(iDirectEq) && (k = iDirectEq[i])>=0 ){
 
994
      /* Case 1:  We can directly reference a single row using an
 
995
      **          equality comparison against the ROWID field.  Or
 
996
      **          we reference multiple rows using a "rowid IN (...)"
 
997
      **          construct.
 
998
      */
 
999
      assert( k<nExpr );
 
1000
      pTerm = &aExpr[k];
 
1001
      assert( pTerm->p!=0 );
 
1002
      assert( pTerm->idxLeft==iCur );
 
1003
      assert( omitTable==0 );
 
1004
      brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
 
1005
      codeEqualityTerm(pParse, pTerm, brk, pLevel);
 
1006
      cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
 
1007
      sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
 
1008
      sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
 
1009
      VdbeComment((v, "pk"));
 
1010
      pLevel->op = OP_Noop;
 
1011
    }else if( pIdx!=0 && pLevel->score>3 && (pLevel->score&0x0c)==0 ){
 
1012
      /* Case 2:  There is an index and all terms of the WHERE clause that
 
1013
      **          refer to the index using the "==" or "IN" operators.
 
1014
      */
 
1015
      int start;
 
1016
      int nColumn = (pLevel->score+16)/32;
 
1017
      brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
 
1018
 
 
1019
      /* For each column of the index, find the term of the WHERE clause that
 
1020
      ** constraints that column.  If the WHERE clause term is X=expr, then
 
1021
      ** evaluation expr and leave the result on the stack */
 
1022
      for(j=0; j<nColumn; j++){
 
1023
        for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
 
1024
          Expr *pX = pTerm->p;
 
1025
          if( pX==0 ) continue;
 
1026
          if( pTerm->idxLeft==iCur
 
1027
             && (pTerm->prereqRight & loopMask)==pTerm->prereqRight 
 
1028
             && pX->pLeft->iColumn==pIdx->aiColumn[j]
 
1029
             && (pX->op==TK_EQ || pX->op==TK_IN)
 
1030
          ){
 
1031
            char idxaff = pIdx->pTable->aCol[pX->pLeft->iColumn].affinity;
 
1032
            if( sqlite3IndexAffinityOk(pX, idxaff) ){
 
1033
              codeEqualityTerm(pParse, pTerm, brk, pLevel);
 
1034
              break;
 
1035
            }
 
1036
          }
 
1037
        }
 
1038
      }
 
1039
      pLevel->iMem = pParse->nMem++;
 
1040
      cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
 
1041
      buildIndexProbe(v, nColumn, brk, pIdx);
 
1042
      sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
 
1043
 
 
1044
      /* Generate code (1) to move to the first matching element of the table.
 
1045
      ** Then generate code (2) that jumps to "brk" after the cursor is past
 
1046
      ** the last matching element of the table.  The code (1) is executed
 
1047
      ** once to initialize the search, the code (2) is executed before each
 
1048
      ** iteration of the scan to see if the scan has finished. */
 
1049
      if( pLevel->bRev ){
 
1050
        /* Scan in reverse order */
 
1051
        sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
 
1052
        start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
 
1053
        sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
 
1054
        pLevel->op = OP_Prev;
 
1055
      }else{
 
1056
        /* Scan in the forward order */
 
1057
        sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
 
1058
        start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
 
1059
        sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
 
1060
        pLevel->op = OP_Next;
 
1061
      }
 
1062
      sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
 
1063
      sqlite3VdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
 
1064
      if( !omitTable ){
 
1065
        sqlite3VdbeAddOp(v, OP_IdxRecno, iIdxCur, 0);
 
1066
        sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
 
1067
      }
 
1068
      pLevel->p1 = iIdxCur;
 
1069
      pLevel->p2 = start;
 
1070
    }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
 
1071
      /* Case 3:  We have an inequality comparison against the ROWID field.
 
1072
      */
 
1073
      int testOp = OP_Noop;
 
1074
      int start;
 
1075
      int bRev = pLevel->bRev;
 
1076
 
 
1077
      assert( omitTable==0 );
 
1078
      brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
 
1079
      cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
 
1080
      if( bRev ){
 
1081
        int t = iDirectGt[i];
 
1082
        iDirectGt[i] = iDirectLt[i];
 
1083
        iDirectLt[i] = t;
 
1084
      }
 
1085
      if( iDirectGt[i]>=0 ){
 
1086
        Expr *pX;
 
1087
        k = iDirectGt[i];
 
1088
        assert( k<nExpr );
 
1089
        pTerm = &aExpr[k];
 
1090
        pX = pTerm->p;
 
1091
        assert( pX!=0 );
 
1092
        assert( pTerm->idxLeft==iCur );
 
1093
        sqlite3ExprCode(pParse, pX->pRight);
 
1094
        sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
 
1095
        sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
 
1096
        VdbeComment((v, "pk"));
 
1097
        disableTerm(pLevel, &pTerm->p);
 
1098
      }else{
 
1099
        sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
 
1100
      }
 
1101
      if( iDirectLt[i]>=0 ){
 
1102
        Expr *pX;
 
1103
        k = iDirectLt[i];
 
1104
        assert( k<nExpr );
 
1105
        pTerm = &aExpr[k];
 
1106
        pX = pTerm->p;
 
1107
        assert( pX!=0 );
 
1108
        assert( pTerm->idxLeft==iCur );
 
1109
        sqlite3ExprCode(pParse, pX->pRight);
 
1110
        pLevel->iMem = pParse->nMem++;
 
1111
        sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
 
1112
        if( pX->op==TK_LT || pX->op==TK_GT ){
 
1113
          testOp = bRev ? OP_Le : OP_Ge;
 
1114
        }else{
 
1115
          testOp = bRev ? OP_Lt : OP_Gt;
 
1116
        }
 
1117
        disableTerm(pLevel, &pTerm->p);
 
1118
      }
 
1119
      start = sqlite3VdbeCurrentAddr(v);
 
1120
      pLevel->op = bRev ? OP_Prev : OP_Next;
 
1121
      pLevel->p1 = iCur;
 
1122
      pLevel->p2 = start;
 
1123
      if( testOp!=OP_Noop ){
 
1124
        sqlite3VdbeAddOp(v, OP_Recno, iCur, 0);
 
1125
        sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
 
1126
        sqlite3VdbeAddOp(v, testOp, (int)(('n'<<8)&0x0000FF00), brk);
 
1127
      }
 
1128
    }else if( pIdx==0 ){
 
1129
      /* Case 4:  There is no usable index.  We must do a complete
 
1130
      **          scan of the entire database table.
 
1131
      */
 
1132
      int start;
 
1133
      int opRewind;
 
1134
 
 
1135
      assert( omitTable==0 );
 
1136
      brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
 
1137
      cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
 
1138
      if( pLevel->bRev ){
 
1139
        opRewind = OP_Last;
 
1140
        pLevel->op = OP_Prev;
 
1141
      }else{
 
1142
        opRewind = OP_Rewind;
 
1143
        pLevel->op = OP_Next;
 
1144
      }
 
1145
      sqlite3VdbeAddOp(v, opRewind, iCur, brk);
 
1146
      start = sqlite3VdbeCurrentAddr(v);
 
1147
      pLevel->p1 = iCur;
 
1148
      pLevel->p2 = start;
 
1149
    }else{
 
1150
      /* Case 5: The WHERE clause term that refers to the right-most
 
1151
      **         column of the index is an inequality.  For example, if
 
1152
      **         the index is on (x,y,z) and the WHERE clause is of the
 
1153
      **         form "x=5 AND y<10" then this case is used.  Only the
 
1154
      **         right-most column can be an inequality - the rest must
 
1155
      **         use the "==" operator.
 
1156
      **
 
1157
      **         This case is also used when there are no WHERE clause
 
1158
      **         constraints but an index is selected anyway, in order
 
1159
      **         to force the output order to conform to an ORDER BY.
 
1160
      */
 
1161
      int score = pLevel->score;
 
1162
      int nEqColumn = score/32;
 
1163
      int start;
 
1164
      int leFlag=0, geFlag=0;
 
1165
      int testOp;
 
1166
 
 
1167
      /* Evaluate the equality constraints
 
1168
      */
 
1169
      for(j=0; j<nEqColumn; j++){
 
1170
        int iIdxCol = pIdx->aiColumn[j];
 
1171
        for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
 
1172
          Expr *pX = pTerm->p;
 
1173
          if( pX==0 ) continue;
 
1174
          if( pTerm->idxLeft==iCur
 
1175
             && pX->op==TK_EQ
 
1176
             && (pTerm->prereqRight & loopMask)==pTerm->prereqRight 
 
1177
             && pX->pLeft->iColumn==iIdxCol
 
1178
          ){
 
1179
            sqlite3ExprCode(pParse, pX->pRight);
 
1180
            disableTerm(pLevel, &pTerm->p);
 
1181
            break;
 
1182
          }
 
1183
        }
 
1184
      }
 
1185
 
 
1186
      /* Duplicate the equality term values because they will all be
 
1187
      ** used twice: once to make the termination key and once to make the
 
1188
      ** start key.
 
1189
      */
 
1190
      for(j=0; j<nEqColumn; j++){
 
1191
        sqlite3VdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
 
1192
      }
 
1193
 
 
1194
      /* Labels for the beginning and end of the loop
 
1195
      */
 
1196
      cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
 
1197
      brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
 
1198
 
 
1199
      /* Generate the termination key.  This is the key value that
 
1200
      ** will end the search.  There is no termination key if there
 
1201
      ** are no equality terms and no "X<..." term.
 
1202
      **
 
1203
      ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
 
1204
      ** key computed here really ends up being the start key.
 
1205
      */
 
1206
      if( (score & 4)!=0 ){
 
1207
        for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
 
1208
          Expr *pX = pTerm->p;
 
1209
          if( pX==0 ) continue;
 
1210
          if( pTerm->idxLeft==iCur
 
1211
             && (pX->op==TK_LT || pX->op==TK_LE)
 
1212
             && (pTerm->prereqRight & loopMask)==pTerm->prereqRight 
 
1213
             && pX->pLeft->iColumn==pIdx->aiColumn[j]
 
1214
          ){
 
1215
            sqlite3ExprCode(pParse, pX->pRight);
 
1216
            leFlag = pX->op==TK_LE;
 
1217
            disableTerm(pLevel, &pTerm->p);
 
1218
            break;
 
1219
          }
 
1220
        }
 
1221
        testOp = OP_IdxGE;
 
1222
      }else{
 
1223
        testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
 
1224
        leFlag = 1;
 
1225
      }
 
1226
      if( testOp!=OP_Noop ){
 
1227
        int nCol = nEqColumn + ((score & 4)!=0);
 
1228
        pLevel->iMem = pParse->nMem++;
 
1229
        buildIndexProbe(v, nCol, brk, pIdx);
 
1230
        if( pLevel->bRev ){
 
1231
          int op = leFlag ? OP_MoveLe : OP_MoveLt;
 
1232
          sqlite3VdbeAddOp(v, op, iIdxCur, brk);
 
1233
        }else{
 
1234
          sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
 
1235
        }
 
1236
      }else if( pLevel->bRev ){
 
1237
        sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
 
1238
      }
 
1239
 
 
1240
      /* Generate the start key.  This is the key that defines the lower
 
1241
      ** bound on the search.  There is no start key if there are no
 
1242
      ** equality terms and if there is no "X>..." term.  In
 
1243
      ** that case, generate a "Rewind" instruction in place of the
 
1244
      ** start key search.
 
1245
      **
 
1246
      ** 2002-Dec-04: In the case of a reverse-order search, the so-called
 
1247
      ** "start" key really ends up being used as the termination key.
 
1248
      */
 
1249
      if( (score & 8)!=0 ){
 
1250
        for(pTerm=aExpr, k=0; k<nExpr; k++, pTerm++){
 
1251
          Expr *pX = pTerm->p;
 
1252
          if( pX==0 ) continue;
 
1253
          if( pTerm->idxLeft==iCur
 
1254
             && (pX->op==TK_GT || pX->op==TK_GE)
 
1255
             && (pTerm->prereqRight & loopMask)==pTerm->prereqRight 
 
1256
             && pX->pLeft->iColumn==pIdx->aiColumn[j]
 
1257
          ){
 
1258
            sqlite3ExprCode(pParse, pX->pRight);
 
1259
            geFlag = pX->op==TK_GE;
 
1260
            disableTerm(pLevel, &pTerm->p);
 
1261
            break;
 
1262
          }
 
1263
        }
 
1264
      }else{
 
1265
        geFlag = 1;
 
1266
      }
 
1267
      if( nEqColumn>0 || (score&8)!=0 ){
 
1268
        int nCol = nEqColumn + ((score&8)!=0);
 
1269
        buildIndexProbe(v, nCol, brk, pIdx);
 
1270
        if( pLevel->bRev ){
 
1271
          pLevel->iMem = pParse->nMem++;
 
1272
          sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
 
1273
          testOp = OP_IdxLT;
 
1274
        }else{
 
1275
          int op = geFlag ? OP_MoveGe : OP_MoveGt;
 
1276
          sqlite3VdbeAddOp(v, op, iIdxCur, brk);
 
1277
        }
 
1278
      }else if( pLevel->bRev ){
 
1279
        testOp = OP_Noop;
 
1280
      }else{
 
1281
        sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
 
1282
      }
 
1283
 
 
1284
      /* Generate the the top of the loop.  If there is a termination
 
1285
      ** key we have to test for that key and abort at the top of the
 
1286
      ** loop.
 
1287
      */
 
1288
      start = sqlite3VdbeCurrentAddr(v);
 
1289
      if( testOp!=OP_Noop ){
 
1290
        sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
 
1291
        sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
 
1292
        if( (leFlag && !pLevel->bRev) || (!geFlag && pLevel->bRev) ){
 
1293
          sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
 
1294
        }
 
1295
      }
 
1296
      sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
 
1297
      sqlite3VdbeAddOp(v, OP_IdxIsNull, nEqColumn + ((score&4)!=0), cont);
 
1298
      if( !omitTable ){
 
1299
        sqlite3VdbeAddOp(v, OP_IdxRecno, iIdxCur, 0);
 
1300
        sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
 
1301
      }
 
1302
 
 
1303
      /* Record the instruction used to terminate the loop.
 
1304
      */
 
1305
      pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
 
1306
      pLevel->p1 = iIdxCur;
 
1307
      pLevel->p2 = start;
 
1308
    }
 
1309
    loopMask |= getMask(&maskSet, iCur);
 
1310
 
 
1311
    /* Insert code to test every subexpression that can be completely
 
1312
    ** computed using the current set of tables.
 
1313
    */
 
1314
    for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
 
1315
      if( pTerm->p==0 ) continue;
 
1316
      if( (pTerm->prereqAll & loopMask)!=pTerm->prereqAll ) continue;
 
1317
      if( pLevel->iLeftJoin && !ExprHasProperty(pTerm->p,EP_FromJoin) ){
 
1318
        continue;
 
1319
      }
 
1320
      sqlite3ExprIfFalse(pParse, pTerm->p, cont, 1);
 
1321
      pTerm->p = 0;
 
1322
    }
 
1323
    brk = cont;
 
1324
 
 
1325
    /* For a LEFT OUTER JOIN, generate code that will record the fact that
 
1326
    ** at least one row of the right table has matched the left table.  
 
1327
    */
 
1328
    if( pLevel->iLeftJoin ){
 
1329
      pLevel->top = sqlite3VdbeCurrentAddr(v);
 
1330
      sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
 
1331
      sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
 
1332
      VdbeComment((v, "# record LEFT JOIN hit"));
 
1333
      for(pTerm=aExpr, j=0; j<nExpr; j++, pTerm++){
 
1334
        if( pTerm->p==0 ) continue;
 
1335
        if( (pTerm->prereqAll & loopMask)!=pTerm->prereqAll ) continue;
 
1336
        sqlite3ExprIfFalse(pParse, pTerm->p, cont, 1);
 
1337
        pTerm->p = 0;
 
1338
      }
 
1339
    }
 
1340
  }
 
1341
  pWInfo->iContinue = cont;
 
1342
  freeMaskSet(&maskSet);
 
1343
  return pWInfo;
 
1344
}
 
1345
 
 
1346
/*
 
1347
** Generate the end of the WHERE loop.  See comments on 
 
1348
** sqlite3WhereBegin() for additional information.
 
1349
*/
 
1350
void sqlite3WhereEnd(WhereInfo *pWInfo){
 
1351
  Vdbe *v = pWInfo->pParse->pVdbe;
 
1352
  int i;
 
1353
  WhereLevel *pLevel;
 
1354
  SrcList *pTabList = pWInfo->pTabList;
 
1355
  struct SrcList_item *pTabItem;
 
1356
 
 
1357
  /* Generate loop termination code.
 
1358
  */
 
1359
  for(i=pTabList->nSrc-1; i>=0; i--){
 
1360
    pLevel = &pWInfo->a[i];
 
1361
    sqlite3VdbeResolveLabel(v, pLevel->cont);
 
1362
    if( pLevel->op!=OP_Noop ){
 
1363
      sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
 
1364
    }
 
1365
    sqlite3VdbeResolveLabel(v, pLevel->brk);
 
1366
    if( pLevel->inOp!=OP_Noop ){
 
1367
      sqlite3VdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
 
1368
    }
 
1369
    if( pLevel->iLeftJoin ){
 
1370
      int addr;
 
1371
      addr = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
 
1372
      sqlite3VdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iIdxCur>=0));
 
1373
      sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
 
1374
      if( pLevel->iIdxCur>=0 ){
 
1375
        sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
 
1376
      }
 
1377
      sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
 
1378
    }
 
1379
  }
 
1380
 
 
1381
  /* The "break" point is here, just past the end of the outer loop.
 
1382
  ** Set it.
 
1383
  */
 
1384
  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
 
1385
 
 
1386
  /* Close all of the cursors that were opend by sqlite3WhereBegin.
 
1387
  */
 
1388
  pLevel = pWInfo->a;
 
1389
  pTabItem = pTabList->a;
 
1390
  for(i=0; i<pTabList->nSrc; i++, pTabItem++, pLevel++){
 
1391
    Table *pTab = pTabItem->pTab;
 
1392
    assert( pTab!=0 );
 
1393
    if( pTab->isTransient || pTab->pSelect ) continue;
 
1394
    if( (pLevel->score & 1)==0 ){
 
1395
      sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
 
1396
    }
 
1397
    if( pLevel->pIdx!=0 ){
 
1398
      sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
 
1399
    }
 
1400
 
 
1401
    /* Make cursor substitutions for cases where we want to use
 
1402
    ** just the index and never reference the table.
 
1403
    ** 
 
1404
    ** Calls to the code generator in between sqlite3WhereBegin and
 
1405
    ** sqlite3WhereEnd will have created code that references the table
 
1406
    ** directly.  This loop scans all that code looking for opcodes
 
1407
    ** that reference the table and converts them into opcodes that
 
1408
    ** reference the index.
 
1409
    */
 
1410
    if( pLevel->score & 1 ){
 
1411
      int i, j, last;
 
1412
      VdbeOp *pOp;
 
1413
      Index *pIdx = pLevel->pIdx;
 
1414
 
 
1415
      assert( pIdx!=0 );
 
1416
      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
 
1417
      last = sqlite3VdbeCurrentAddr(v);
 
1418
      for(i=pWInfo->iTop; i<last; i++, pOp++){
 
1419
        if( pOp->p1!=pLevel->iTabCur ) continue;
 
1420
        if( pOp->opcode==OP_Column ){
 
1421
          pOp->p1 = pLevel->iIdxCur;
 
1422
          for(j=0; j<pIdx->nColumn; j++){
 
1423
            if( pOp->p2==pIdx->aiColumn[j] ){
 
1424
              pOp->p2 = j;
 
1425
              break;
 
1426
            }
 
1427
          }
 
1428
        }else if( pOp->opcode==OP_Recno ){
 
1429
          pOp->p1 = pLevel->iIdxCur;
 
1430
          pOp->opcode = OP_IdxRecno;
 
1431
        }else if( pOp->opcode==OP_NullRow ){
 
1432
          pOp->opcode = OP_Noop;
 
1433
        }
 
1434
      }
 
1435
    }
 
1436
  }
 
1437
 
 
1438
  /* Final cleanup
 
1439
  */
 
1440
  sqliteFree(pWInfo);
 
1441
  return;
 
1442
}