Back to index

lightning-sunbird  0.9+nobinonly
where.c
Go to the documentation of this file.
00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** This module contains C code that generates VDBE code used to process
00013 ** the WHERE clause of SQL statements.  This module is reponsible for
00014 ** generating the code that loops through a table looking for applicable
00015 ** rows.  Indices are selected and used to speed the search when doing
00016 ** so is applicable.  Because this module is responsible for selecting
00017 ** indices, you might also think of this module as the "query optimizer".
00018 **
00019 ** $Id: where.c,v 1.208 2006/05/11 13:26:26 drh Exp $
00020 */
00021 #include "sqliteInt.h"
00022 
00023 /*
00024 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
00025 */
00026 #define BMS  (sizeof(Bitmask)*8)
00027 
00028 /*
00029 ** Determine the number of elements in an array.
00030 */
00031 #define ARRAYSIZE(X)  (sizeof(X)/sizeof(X[0]))
00032 
00033 /*
00034 ** Trace output macros
00035 */
00036 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
00037 int sqlite3_where_trace = 0;
00038 # define TRACE(X)  if(sqlite3_where_trace) sqlite3DebugPrintf X
00039 #else
00040 # define TRACE(X)
00041 #endif
00042 
00043 /* Forward reference
00044 */
00045 typedef struct WhereClause WhereClause;
00046 
00047 /*
00048 ** The query generator uses an array of instances of this structure to
00049 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
00050 ** clause subexpression is separated from the others by an AND operator.
00051 **
00052 ** All WhereTerms are collected into a single WhereClause structure.  
00053 ** The following identity holds:
00054 **
00055 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
00056 **
00057 ** When a term is of the form:
00058 **
00059 **              X <op> <expr>
00060 **
00061 ** where X is a column name and <op> is one of certain operators,
00062 ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
00063 ** cursor number and column number for X.  WhereTerm.operator records
00064 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
00065 ** use of a bitmask encoding for the operator allows us to search
00066 ** quickly for terms that match any of several different operators.
00067 **
00068 ** prereqRight and prereqAll record sets of cursor numbers,
00069 ** but they do so indirectly.  A single ExprMaskSet structure translates
00070 ** cursor number into bits and the translated bit is stored in the prereq
00071 ** fields.  The translation is used in order to maximize the number of
00072 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
00073 ** spread out over the non-negative integers.  For example, the cursor
00074 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The ExprMaskSet
00075 ** translates these sparse cursor numbers into consecutive integers
00076 ** beginning with 0 in order to make the best possible use of the available
00077 ** bits in the Bitmask.  So, in the example above, the cursor numbers
00078 ** would be mapped into integers 0 through 7.
00079 */
00080 typedef struct WhereTerm WhereTerm;
00081 struct WhereTerm {
00082   Expr *pExpr;            /* Pointer to the subexpression */
00083   i16 iParent;            /* Disable pWC->a[iParent] when this term disabled */
00084   i16 leftCursor;         /* Cursor number of X in "X <op> <expr>" */
00085   i16 leftColumn;         /* Column number of X in "X <op> <expr>" */
00086   u16 eOperator;          /* A WO_xx value describing <op> */
00087   u8 flags;               /* Bit flags.  See below */
00088   u8 nChild;              /* Number of children that must disable us */
00089   WhereClause *pWC;       /* The clause this term is part of */
00090   Bitmask prereqRight;    /* Bitmask of tables used by pRight */
00091   Bitmask prereqAll;      /* Bitmask of tables referenced by p */
00092 };
00093 
00094 /*
00095 ** Allowed values of WhereTerm.flags
00096 */
00097 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(pExpr) */
00098 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
00099 #define TERM_CODED      0x04   /* This term is already coded */
00100 #define TERM_COPIED     0x08   /* Has a child */
00101 #define TERM_OR_OK      0x10   /* Used during OR-clause processing */
00102 
00103 /*
00104 ** An instance of the following structure holds all information about a
00105 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
00106 */
00107 struct WhereClause {
00108   Parse *pParse;           /* The parser context */
00109   int nTerm;               /* Number of terms */
00110   int nSlot;               /* Number of entries in a[] */
00111   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
00112   WhereTerm aStatic[10];   /* Initial static space for a[] */
00113 };
00114 
00115 /*
00116 ** An instance of the following structure keeps track of a mapping
00117 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
00118 **
00119 ** The VDBE cursor numbers are small integers contained in 
00120 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
00121 ** clause, the cursor numbers might not begin with 0 and they might
00122 ** contain gaps in the numbering sequence.  But we want to make maximum
00123 ** use of the bits in our bitmasks.  This structure provides a mapping
00124 ** from the sparse cursor numbers into consecutive integers beginning
00125 ** with 0.
00126 **
00127 ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
00128 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
00129 **
00130 ** For example, if the WHERE clause expression used these VDBE
00131 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  ExprMaskSet structure
00132 ** would map those cursor numbers into bits 0 through 5.
00133 **
00134 ** Note that the mapping is not necessarily ordered.  In the example
00135 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
00136 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
00137 ** does not really matter.  What is important is that sparse cursor
00138 ** numbers all get mapped into bit numbers that begin with 0 and contain
00139 ** no gaps.
00140 */
00141 typedef struct ExprMaskSet ExprMaskSet;
00142 struct ExprMaskSet {
00143   int n;                        /* Number of assigned cursor values */
00144   int ix[sizeof(Bitmask)*8];    /* Cursor assigned to each bit */
00145 };
00146 
00147 
00148 /*
00149 ** Bitmasks for the operators that indices are able to exploit.  An
00150 ** OR-ed combination of these values can be used when searching for
00151 ** terms in the where clause.
00152 */
00153 #define WO_IN     1
00154 #define WO_EQ     2
00155 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
00156 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
00157 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
00158 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
00159 
00160 /*
00161 ** Value for flags returned by bestIndex()
00162 */
00163 #define WHERE_ROWID_EQ       0x0001   /* rowid=EXPR or rowid IN (...) */
00164 #define WHERE_ROWID_RANGE    0x0002   /* rowid<EXPR and/or rowid>EXPR */
00165 #define WHERE_COLUMN_EQ      0x0010   /* x=EXPR or x IN (...) */
00166 #define WHERE_COLUMN_RANGE   0x0020   /* x<EXPR and/or x>EXPR */
00167 #define WHERE_COLUMN_IN      0x0040   /* x IN (...) */
00168 #define WHERE_TOP_LIMIT      0x0100   /* x<EXPR or x<=EXPR constraint */
00169 #define WHERE_BTM_LIMIT      0x0200   /* x>EXPR or x>=EXPR constraint */
00170 #define WHERE_IDX_ONLY       0x0800   /* Use index only - omit table */
00171 #define WHERE_ORDERBY        0x1000   /* Output will appear in correct order */
00172 #define WHERE_REVERSE        0x2000   /* Scan in reverse order */
00173 #define WHERE_UNIQUE         0x4000   /* Selects no more than one row */
00174 
00175 /*
00176 ** Initialize a preallocated WhereClause structure.
00177 */
00178 static void whereClauseInit(WhereClause *pWC, Parse *pParse){
00179   pWC->pParse = pParse;
00180   pWC->nTerm = 0;
00181   pWC->nSlot = ARRAYSIZE(pWC->aStatic);
00182   pWC->a = pWC->aStatic;
00183 }
00184 
00185 /*
00186 ** Deallocate a WhereClause structure.  The WhereClause structure
00187 ** itself is not freed.  This routine is the inverse of whereClauseInit().
00188 */
00189 static void whereClauseClear(WhereClause *pWC){
00190   int i;
00191   WhereTerm *a;
00192   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
00193     if( a->flags & TERM_DYNAMIC ){
00194       sqlite3ExprDelete(a->pExpr);
00195     }
00196   }
00197   if( pWC->a!=pWC->aStatic ){
00198     sqliteFree(pWC->a);
00199   }
00200 }
00201 
00202 /*
00203 ** Add a new entries to the WhereClause structure.  Increase the allocated
00204 ** space as necessary.
00205 **
00206 ** WARNING:  This routine might reallocate the space used to store
00207 ** WhereTerms.  All pointers to WhereTerms should be invalided after
00208 ** calling this routine.  Such pointers may be reinitialized by referencing
00209 ** the pWC->a[] array.
00210 */
00211 static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
00212   WhereTerm *pTerm;
00213   int idx;
00214   if( pWC->nTerm>=pWC->nSlot ){
00215     WhereTerm *pOld = pWC->a;
00216     pWC->a = sqliteMalloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
00217     if( pWC->a==0 ) return 0;
00218     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
00219     if( pOld!=pWC->aStatic ){
00220       sqliteFree(pOld);
00221     }
00222     pWC->nSlot *= 2;
00223   }
00224   pTerm = &pWC->a[idx = pWC->nTerm];
00225   pWC->nTerm++;
00226   pTerm->pExpr = p;
00227   pTerm->flags = flags;
00228   pTerm->pWC = pWC;
00229   pTerm->iParent = -1;
00230   return idx;
00231 }
00232 
00233 /*
00234 ** This routine identifies subexpressions in the WHERE clause where
00235 ** each subexpression is separated by the AND operator or some other
00236 ** operator specified in the op parameter.  The WhereClause structure
00237 ** is filled with pointers to subexpressions.  For example:
00238 **
00239 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
00240 **           \________/     \_______________/     \________________/
00241 **            slot[0]            slot[1]               slot[2]
00242 **
00243 ** The original WHERE clause in pExpr is unaltered.  All this routine
00244 ** does is make slot[] entries point to substructure within pExpr.
00245 **
00246 ** In the previous sentence and in the diagram, "slot[]" refers to
00247 ** the WhereClause.a[] array.  This array grows as needed to contain
00248 ** all terms of the WHERE clause.
00249 */
00250 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
00251   if( pExpr==0 ) return;
00252   if( pExpr->op!=op ){
00253     whereClauseInsert(pWC, pExpr, 0);
00254   }else{
00255     whereSplit(pWC, pExpr->pLeft, op);
00256     whereSplit(pWC, pExpr->pRight, op);
00257   }
00258 }
00259 
00260 /*
00261 ** Initialize an expression mask set
00262 */
00263 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
00264 
00265 /*
00266 ** Return the bitmask for the given cursor number.  Return 0 if
00267 ** iCursor is not in the set.
00268 */
00269 static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
00270   int i;
00271   for(i=0; i<pMaskSet->n; i++){
00272     if( pMaskSet->ix[i]==iCursor ){
00273       return ((Bitmask)1)<<i;
00274     }
00275   }
00276   return 0;
00277 }
00278 
00279 /*
00280 ** Create a new mask for cursor iCursor.
00281 **
00282 ** There is one cursor per table in the FROM clause.  The number of
00283 ** tables in the FROM clause is limited by a test early in the
00284 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
00285 ** array will never overflow.
00286 */
00287 static void createMask(ExprMaskSet *pMaskSet, int iCursor){
00288   assert( pMaskSet->n < ARRAYSIZE(pMaskSet->ix) );
00289   pMaskSet->ix[pMaskSet->n++] = iCursor;
00290 }
00291 
00292 /*
00293 ** This routine walks (recursively) an expression tree and generates
00294 ** a bitmask indicating which tables are used in that expression
00295 ** tree.
00296 **
00297 ** In order for this routine to work, the calling function must have
00298 ** previously invoked sqlite3ExprResolveNames() on the expression.  See
00299 ** the header comment on that routine for additional information.
00300 ** The sqlite3ExprResolveNames() routines looks for column names and
00301 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
00302 ** the VDBE cursor number of the table.  This routine just has to
00303 ** translate the cursor numbers into bitmask values and OR all
00304 ** the bitmasks together.
00305 */
00306 static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
00307 static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
00308 static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
00309   Bitmask mask = 0;
00310   if( p==0 ) return 0;
00311   if( p->op==TK_COLUMN ){
00312     mask = getMask(pMaskSet, p->iTable);
00313     return mask;
00314   }
00315   mask = exprTableUsage(pMaskSet, p->pRight);
00316   mask |= exprTableUsage(pMaskSet, p->pLeft);
00317   mask |= exprListTableUsage(pMaskSet, p->pList);
00318   mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
00319   return mask;
00320 }
00321 static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
00322   int i;
00323   Bitmask mask = 0;
00324   if( pList ){
00325     for(i=0; i<pList->nExpr; i++){
00326       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
00327     }
00328   }
00329   return mask;
00330 }
00331 static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
00332   Bitmask mask;
00333   if( pS==0 ){
00334     mask = 0;
00335   }else{
00336     mask = exprListTableUsage(pMaskSet, pS->pEList);
00337     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
00338     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
00339     mask |= exprTableUsage(pMaskSet, pS->pWhere);
00340     mask |= exprTableUsage(pMaskSet, pS->pHaving);
00341   }
00342   return mask;
00343 }
00344 
00345 /*
00346 ** Return TRUE if the given operator is one of the operators that is
00347 ** allowed for an indexable WHERE clause term.  The allowed operators are
00348 ** "=", "<", ">", "<=", ">=", and "IN".
00349 */
00350 static int allowedOp(int op){
00351   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
00352   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
00353   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
00354   assert( TK_GE==TK_EQ+4 );
00355   return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
00356 }
00357 
00358 /*
00359 ** Swap two objects of type T.
00360 */
00361 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
00362 
00363 /*
00364 ** Commute a comparision operator.  Expressions of the form "X op Y"
00365 ** are converted into "Y op X".
00366 */
00367 static void exprCommute(Expr *pExpr){
00368   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
00369   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
00370   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
00371   if( pExpr->op>=TK_GT ){
00372     assert( TK_LT==TK_GT+2 );
00373     assert( TK_GE==TK_LE+2 );
00374     assert( TK_GT>TK_EQ );
00375     assert( TK_GT<TK_LE );
00376     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
00377     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
00378   }
00379 }
00380 
00381 /*
00382 ** Translate from TK_xx operator to WO_xx bitmask.
00383 */
00384 static int operatorMask(int op){
00385   int c;
00386   assert( allowedOp(op) );
00387   if( op==TK_IN ){
00388     c = WO_IN;
00389   }else{
00390     c = WO_EQ<<(op-TK_EQ);
00391   }
00392   assert( op!=TK_IN || c==WO_IN );
00393   assert( op!=TK_EQ || c==WO_EQ );
00394   assert( op!=TK_LT || c==WO_LT );
00395   assert( op!=TK_LE || c==WO_LE );
00396   assert( op!=TK_GT || c==WO_GT );
00397   assert( op!=TK_GE || c==WO_GE );
00398   return c;
00399 }
00400 
00401 /*
00402 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
00403 ** where X is a reference to the iColumn of table iCur and <op> is one of
00404 ** the WO_xx operator codes specified by the op parameter.
00405 ** Return a pointer to the term.  Return 0 if not found.
00406 */
00407 static WhereTerm *findTerm(
00408   WhereClause *pWC,     /* The WHERE clause to be searched */
00409   int iCur,             /* Cursor number of LHS */
00410   int iColumn,          /* Column number of LHS */
00411   Bitmask notReady,     /* RHS must not overlap with this mask */
00412   u16 op,               /* Mask of WO_xx values describing operator */
00413   Index *pIdx           /* Must be compatible with this index, if not NULL */
00414 ){
00415   WhereTerm *pTerm;
00416   int k;
00417   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
00418     if( pTerm->leftCursor==iCur
00419        && (pTerm->prereqRight & notReady)==0
00420        && pTerm->leftColumn==iColumn
00421        && (pTerm->eOperator & op)!=0
00422     ){
00423       if( iCur>=0 && pIdx ){
00424         Expr *pX = pTerm->pExpr;
00425         CollSeq *pColl;
00426         char idxaff;
00427         int j;
00428         Parse *pParse = pWC->pParse;
00429 
00430         idxaff = pIdx->pTable->aCol[iColumn].affinity;
00431         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
00432         pColl = sqlite3ExprCollSeq(pParse, pX->pLeft);
00433         if( !pColl ){
00434           if( pX->pRight ){
00435             pColl = sqlite3ExprCollSeq(pParse, pX->pRight);
00436           }
00437           if( !pColl ){
00438             pColl = pParse->db->pDfltColl;
00439           }
00440         }
00441         for(j=0; j<pIdx->nColumn && pIdx->aiColumn[j]!=iColumn; j++){}
00442         assert( j<pIdx->nColumn );
00443         if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
00444       }
00445       return pTerm;
00446     }
00447   }
00448   return 0;
00449 }
00450 
00451 /* Forward reference */
00452 static void exprAnalyze(SrcList*, ExprMaskSet*, WhereClause*, int);
00453 
00454 /*
00455 ** Call exprAnalyze on all terms in a WHERE clause.  
00456 **
00457 **
00458 */
00459 static void exprAnalyzeAll(
00460   SrcList *pTabList,       /* the FROM clause */
00461   ExprMaskSet *pMaskSet,   /* table masks */
00462   WhereClause *pWC         /* the WHERE clause to be analyzed */
00463 ){
00464   int i;
00465   for(i=pWC->nTerm-1; i>=0; i--){
00466     exprAnalyze(pTabList, pMaskSet, pWC, i);
00467   }
00468 }
00469 
00470 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
00471 /*
00472 ** Check to see if the given expression is a LIKE or GLOB operator that
00473 ** can be optimized using inequality constraints.  Return TRUE if it is
00474 ** so and false if not.
00475 **
00476 ** In order for the operator to be optimizible, the RHS must be a string
00477 ** literal that does not begin with a wildcard.  
00478 */
00479 static int isLikeOrGlob(
00480   sqlite3 *db,      /* The database */
00481   Expr *pExpr,      /* Test this expression */
00482   int *pnPattern,   /* Number of non-wildcard prefix characters */
00483   int *pisComplete  /* True if the only wildcard is % in the last character */
00484 ){
00485   const char *z;
00486   Expr *pRight, *pLeft;
00487   ExprList *pList;
00488   int c, cnt;
00489   int noCase;
00490   char wc[3];
00491   CollSeq *pColl;
00492 
00493   if( !sqlite3IsLikeFunction(db, pExpr, &noCase, wc) ){
00494     return 0;
00495   }
00496   pList = pExpr->pList;
00497   pRight = pList->a[0].pExpr;
00498   if( pRight->op!=TK_STRING ){
00499     return 0;
00500   }
00501   pLeft = pList->a[1].pExpr;
00502   if( pLeft->op!=TK_COLUMN ){
00503     return 0;
00504   }
00505   pColl = pLeft->pColl;
00506   if( pColl==0 ){
00507     pColl = db->pDfltColl;
00508   }
00509   if( (pColl->type!=SQLITE_COLL_BINARY || noCase) &&
00510       (pColl->type!=SQLITE_COLL_NOCASE || !noCase) ){
00511     return 0;
00512   }
00513   sqlite3DequoteExpr(pRight);
00514   z = (char *)pRight->token.z;
00515   for(cnt=0; (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2]; cnt++){}
00516   if( cnt==0 || 255==(u8)z[cnt] ){
00517     return 0;
00518   }
00519   *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
00520   *pnPattern = cnt;
00521   return 1;
00522 }
00523 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
00524 
00525 /*
00526 ** If the pBase expression originated in the ON or USING clause of
00527 ** a join, then transfer the appropriate markings over to derived.
00528 */
00529 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
00530   pDerived->flags |= pBase->flags & EP_FromJoin;
00531   pDerived->iRightJoinTable = pBase->iRightJoinTable;
00532 }
00533 
00534 
00535 /*
00536 ** The input to this routine is an WhereTerm structure with only the
00537 ** "pExpr" field filled in.  The job of this routine is to analyze the
00538 ** subexpression and populate all the other fields of the WhereTerm
00539 ** structure.
00540 **
00541 ** If the expression is of the form "<expr> <op> X" it gets commuted
00542 ** to the standard form of "X <op> <expr>".  If the expression is of
00543 ** the form "X <op> Y" where both X and Y are columns, then the original
00544 ** expression is unchanged and a new virtual expression of the form
00545 ** "Y <op> X" is added to the WHERE clause and analyzed separately.
00546 */
00547 static void exprAnalyze(
00548   SrcList *pSrc,            /* the FROM clause */
00549   ExprMaskSet *pMaskSet,    /* table masks */
00550   WhereClause *pWC,         /* the WHERE clause */
00551   int idxTerm               /* Index of the term to be analyzed */
00552 ){
00553   WhereTerm *pTerm = &pWC->a[idxTerm];
00554   Expr *pExpr = pTerm->pExpr;
00555   Bitmask prereqLeft;
00556   Bitmask prereqAll;
00557   int nPattern;
00558   int isComplete;
00559 
00560   if( sqlite3MallocFailed() ) return;
00561   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
00562   if( pExpr->op==TK_IN ){
00563     assert( pExpr->pRight==0 );
00564     pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
00565                           | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
00566   }else{
00567     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
00568   }
00569   prereqAll = exprTableUsage(pMaskSet, pExpr);
00570   if( ExprHasProperty(pExpr, EP_FromJoin) ){
00571     prereqAll |= getMask(pMaskSet, pExpr->iRightJoinTable);
00572   }
00573   pTerm->prereqAll = prereqAll;
00574   pTerm->leftCursor = -1;
00575   pTerm->iParent = -1;
00576   pTerm->eOperator = 0;
00577   if( allowedOp(pExpr->op) && (pTerm->prereqRight & prereqLeft)==0 ){
00578     Expr *pLeft = pExpr->pLeft;
00579     Expr *pRight = pExpr->pRight;
00580     if( pLeft->op==TK_COLUMN ){
00581       pTerm->leftCursor = pLeft->iTable;
00582       pTerm->leftColumn = pLeft->iColumn;
00583       pTerm->eOperator = operatorMask(pExpr->op);
00584     }
00585     if( pRight && pRight->op==TK_COLUMN ){
00586       WhereTerm *pNew;
00587       Expr *pDup;
00588       if( pTerm->leftCursor>=0 ){
00589         int idxNew;
00590         pDup = sqlite3ExprDup(pExpr);
00591         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
00592         if( idxNew==0 ) return;
00593         pNew = &pWC->a[idxNew];
00594         pNew->iParent = idxTerm;
00595         pTerm = &pWC->a[idxTerm];
00596         pTerm->nChild = 1;
00597         pTerm->flags |= TERM_COPIED;
00598       }else{
00599         pDup = pExpr;
00600         pNew = pTerm;
00601       }
00602       exprCommute(pDup);
00603       pLeft = pDup->pLeft;
00604       pNew->leftCursor = pLeft->iTable;
00605       pNew->leftColumn = pLeft->iColumn;
00606       pNew->prereqRight = prereqLeft;
00607       pNew->prereqAll = prereqAll;
00608       pNew->eOperator = operatorMask(pDup->op);
00609     }
00610   }
00611 
00612 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
00613   /* If a term is the BETWEEN operator, create two new virtual terms
00614   ** that define the range that the BETWEEN implements.
00615   */
00616   else if( pExpr->op==TK_BETWEEN ){
00617     ExprList *pList = pExpr->pList;
00618     int i;
00619     static const u8 ops[] = {TK_GE, TK_LE};
00620     assert( pList!=0 );
00621     assert( pList->nExpr==2 );
00622     for(i=0; i<2; i++){
00623       Expr *pNewExpr;
00624       int idxNew;
00625       pNewExpr = sqlite3Expr(ops[i], sqlite3ExprDup(pExpr->pLeft),
00626                              sqlite3ExprDup(pList->a[i].pExpr), 0);
00627       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
00628       exprAnalyze(pSrc, pMaskSet, pWC, idxNew);
00629       pTerm = &pWC->a[idxTerm];
00630       pWC->a[idxNew].iParent = idxTerm;
00631     }
00632     pTerm->nChild = 2;
00633   }
00634 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
00635 
00636 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
00637   /* Attempt to convert OR-connected terms into an IN operator so that
00638   ** they can make use of indices.  Example:
00639   **
00640   **      x = expr1  OR  expr2 = x  OR  x = expr3
00641   **
00642   ** is converted into
00643   **
00644   **      x IN (expr1,expr2,expr3)
00645   **
00646   ** This optimization must be omitted if OMIT_SUBQUERY is defined because
00647   ** the compiler for the the IN operator is part of sub-queries.
00648   */
00649   else if( pExpr->op==TK_OR ){
00650     int ok;
00651     int i, j;
00652     int iColumn, iCursor;
00653     WhereClause sOr;
00654     WhereTerm *pOrTerm;
00655 
00656     assert( (pTerm->flags & TERM_DYNAMIC)==0 );
00657     whereClauseInit(&sOr, pWC->pParse);
00658     whereSplit(&sOr, pExpr, TK_OR);
00659     exprAnalyzeAll(pSrc, pMaskSet, &sOr);
00660     assert( sOr.nTerm>0 );
00661     j = 0;
00662     do{
00663       iColumn = sOr.a[j].leftColumn;
00664       iCursor = sOr.a[j].leftCursor;
00665       ok = iCursor>=0;
00666       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
00667         if( pOrTerm->eOperator!=WO_EQ ){
00668           goto or_not_possible;
00669         }
00670         if( pOrTerm->leftCursor==iCursor && pOrTerm->leftColumn==iColumn ){
00671           pOrTerm->flags |= TERM_OR_OK;
00672         }else if( (pOrTerm->flags & TERM_COPIED)!=0 ||
00673                     ((pOrTerm->flags & TERM_VIRTUAL)!=0 &&
00674                      (sOr.a[pOrTerm->iParent].flags & TERM_OR_OK)!=0) ){
00675           pOrTerm->flags &= ~TERM_OR_OK;
00676         }else{
00677           ok = 0;
00678         }
00679       }
00680     }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<sOr.nTerm );
00681     if( ok ){
00682       ExprList *pList = 0;
00683       Expr *pNew, *pDup;
00684       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
00685         if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
00686         pDup = sqlite3ExprDup(pOrTerm->pExpr->pRight);
00687         pList = sqlite3ExprListAppend(pList, pDup, 0);
00688       }
00689       pDup = sqlite3Expr(TK_COLUMN, 0, 0, 0);
00690       if( pDup ){
00691         pDup->iTable = iCursor;
00692         pDup->iColumn = iColumn;
00693       }
00694       pNew = sqlite3Expr(TK_IN, pDup, 0, 0);
00695       if( pNew ){
00696         int idxNew;
00697         transferJoinMarkings(pNew, pExpr);
00698         pNew->pList = pList;
00699         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
00700         exprAnalyze(pSrc, pMaskSet, pWC, idxNew);
00701         pTerm = &pWC->a[idxTerm];
00702         pWC->a[idxNew].iParent = idxTerm;
00703         pTerm->nChild = 1;
00704       }else{
00705         sqlite3ExprListDelete(pList);
00706       }
00707     }
00708 or_not_possible:
00709     whereClauseClear(&sOr);
00710   }
00711 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
00712 
00713 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
00714   /* Add constraints to reduce the search space on a LIKE or GLOB
00715   ** operator.
00716   */
00717   if( isLikeOrGlob(pWC->pParse->db, pExpr, &nPattern, &isComplete) ){
00718     Expr *pLeft, *pRight;
00719     Expr *pStr1, *pStr2;
00720     Expr *pNewExpr1, *pNewExpr2;
00721     int idxNew1, idxNew2;
00722 
00723     pLeft = pExpr->pList->a[1].pExpr;
00724     pRight = pExpr->pList->a[0].pExpr;
00725     pStr1 = sqlite3Expr(TK_STRING, 0, 0, 0);
00726     if( pStr1 ){
00727       sqlite3TokenCopy(&pStr1->token, &pRight->token);
00728       pStr1->token.n = nPattern;
00729     }
00730     pStr2 = sqlite3ExprDup(pStr1);
00731     if( pStr2 ){
00732       assert( pStr2->token.dyn );
00733       ++*(u8*)&pStr2->token.z[nPattern-1];
00734     }
00735     pNewExpr1 = sqlite3Expr(TK_GE, sqlite3ExprDup(pLeft), pStr1, 0);
00736     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
00737     exprAnalyze(pSrc, pMaskSet, pWC, idxNew1);
00738     pNewExpr2 = sqlite3Expr(TK_LT, sqlite3ExprDup(pLeft), pStr2, 0);
00739     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
00740     exprAnalyze(pSrc, pMaskSet, pWC, idxNew2);
00741     pTerm = &pWC->a[idxTerm];
00742     if( isComplete ){
00743       pWC->a[idxNew1].iParent = idxTerm;
00744       pWC->a[idxNew2].iParent = idxTerm;
00745       pTerm->nChild = 2;
00746     }
00747   }
00748 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
00749 }
00750 
00751 
00752 /*
00753 ** This routine decides if pIdx can be used to satisfy the ORDER BY
00754 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
00755 ** ORDER BY clause, this routine returns 0.
00756 **
00757 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
00758 ** left-most table in the FROM clause of that same SELECT statement and
00759 ** the table has a cursor number of "base".  pIdx is an index on pTab.
00760 **
00761 ** nEqCol is the number of columns of pIdx that are used as equality
00762 ** constraints.  Any of these columns may be missing from the ORDER BY
00763 ** clause and the match can still be a success.
00764 **
00765 ** All terms of the ORDER BY that match against the index must be either
00766 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
00767 ** index do not need to satisfy this constraint.)  The *pbRev value is
00768 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
00769 ** the ORDER BY clause is all ASC.
00770 */
00771 static int isSortingIndex(
00772   Parse *pParse,          /* Parsing context */
00773   Index *pIdx,            /* The index we are testing */
00774   int base,               /* Cursor number for the table to be sorted */
00775   ExprList *pOrderBy,     /* The ORDER BY clause */
00776   int nEqCol,             /* Number of index columns with == constraints */
00777   int *pbRev              /* Set to 1 if ORDER BY is DESC */
00778 ){
00779   int i, j;                       /* Loop counters */
00780   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
00781   int nTerm;                      /* Number of ORDER BY terms */
00782   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
00783   sqlite3 *db = pParse->db;
00784 
00785   assert( pOrderBy!=0 );
00786   nTerm = pOrderBy->nExpr;
00787   assert( nTerm>0 );
00788 
00789   /* Match terms of the ORDER BY clause against columns of
00790   ** the index.
00791   */
00792   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<pIdx->nColumn; i++){
00793     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
00794     CollSeq *pColl;    /* The collating sequence of pExpr */
00795     int termSortOrder; /* Sort order for this term */
00796 
00797     pExpr = pTerm->pExpr;
00798     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
00799       /* Can not use an index sort on anything that is not a column in the
00800       ** left-most table of the FROM clause */
00801       return 0;
00802     }
00803     pColl = sqlite3ExprCollSeq(pParse, pExpr);
00804     if( !pColl ) pColl = db->pDfltColl;
00805     if( pExpr->iColumn!=pIdx->aiColumn[i] || 
00806         sqlite3StrICmp(pColl->zName, pIdx->azColl[i]) ){
00807       /* Term j of the ORDER BY clause does not match column i of the index */
00808       if( i<nEqCol ){
00809         /* If an index column that is constrained by == fails to match an
00810         ** ORDER BY term, that is OK.  Just ignore that column of the index
00811         */
00812         continue;
00813       }else{
00814         /* If an index column fails to match and is not constrained by ==
00815         ** then the index cannot satisfy the ORDER BY constraint.
00816         */
00817         return 0;
00818       }
00819     }
00820     assert( pIdx->aSortOrder!=0 );
00821     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
00822     assert( pIdx->aSortOrder[i]==0 || pIdx->aSortOrder[i]==1 );
00823     termSortOrder = pIdx->aSortOrder[i] ^ pTerm->sortOrder;
00824     if( i>nEqCol ){
00825       if( termSortOrder!=sortOrder ){
00826         /* Indices can only be used if all ORDER BY terms past the
00827         ** equality constraints are all either DESC or ASC. */
00828         return 0;
00829       }
00830     }else{
00831       sortOrder = termSortOrder;
00832     }
00833     j++;
00834     pTerm++;
00835   }
00836 
00837   /* The index can be used for sorting if all terms of the ORDER BY clause
00838   ** are covered.
00839   */
00840   if( j>=nTerm ){
00841     *pbRev = sortOrder!=0;
00842     return 1;
00843   }
00844   return 0;
00845 }
00846 
00847 /*
00848 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
00849 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
00850 ** true for reverse ROWID and false for forward ROWID order.
00851 */
00852 static int sortableByRowid(
00853   int base,               /* Cursor number for table to be sorted */
00854   ExprList *pOrderBy,     /* The ORDER BY clause */
00855   int *pbRev              /* Set to 1 if ORDER BY is DESC */
00856 ){
00857   Expr *p;
00858 
00859   assert( pOrderBy!=0 );
00860   assert( pOrderBy->nExpr>0 );
00861   p = pOrderBy->a[0].pExpr;
00862   if( pOrderBy->nExpr==1 && p->op==TK_COLUMN && p->iTable==base
00863           && p->iColumn==-1 ){
00864     *pbRev = pOrderBy->a[0].sortOrder;
00865     return 1;
00866   }
00867   return 0;
00868 }
00869 
00870 /*
00871 ** Prepare a crude estimate of the logarithm of the input value.
00872 ** The results need not be exact.  This is only used for estimating
00873 ** the total cost of performing operatings with O(logN) or O(NlogN)
00874 ** complexity.  Because N is just a guess, it is no great tragedy if
00875 ** logN is a little off.
00876 */
00877 static double estLog(double N){
00878   double logN = 1;
00879   double x = 10;
00880   while( N>x ){
00881     logN += 1;
00882     x *= 10;
00883   }
00884   return logN;
00885 }
00886 
00887 /*
00888 ** Find the best index for accessing a particular table.  Return a pointer
00889 ** to the index, flags that describe how the index should be used, the
00890 ** number of equality constraints, and the "cost" for this index.
00891 **
00892 ** The lowest cost index wins.  The cost is an estimate of the amount of
00893 ** CPU and disk I/O need to process the request using the selected index.
00894 ** Factors that influence cost include:
00895 **
00896 **    *  The estimated number of rows that will be retrieved.  (The
00897 **       fewer the better.)
00898 **
00899 **    *  Whether or not sorting must occur.
00900 **
00901 **    *  Whether or not there must be separate lookups in the
00902 **       index and in the main table.
00903 **
00904 */
00905 static double bestIndex(
00906   Parse *pParse,              /* The parsing context */
00907   WhereClause *pWC,           /* The WHERE clause */
00908   struct SrcList_item *pSrc,  /* The FROM clause term to search */
00909   Bitmask notReady,           /* Mask of cursors that are not available */
00910   ExprList *pOrderBy,         /* The order by clause */
00911   Index **ppIndex,            /* Make *ppIndex point to the best index */
00912   int *pFlags,                /* Put flags describing this choice in *pFlags */
00913   int *pnEq                   /* Put the number of == or IN constraints here */
00914 ){
00915   WhereTerm *pTerm;
00916   Index *bestIdx = 0;         /* Index that gives the lowest cost */
00917   double lowestCost;          /* The cost of using bestIdx */
00918   int bestFlags = 0;          /* Flags associated with bestIdx */
00919   int bestNEq = 0;            /* Best value for nEq */
00920   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
00921   Index *pProbe;              /* An index we are evaluating */
00922   int rev;                    /* True to scan in reverse order */
00923   int flags;                  /* Flags associated with pProbe */
00924   int nEq;                    /* Number of == or IN constraints */
00925   double cost;                /* Cost of using pProbe */
00926 
00927   TRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
00928   lowestCost = SQLITE_BIG_DBL;
00929   pProbe = pSrc->pTab->pIndex;
00930 
00931   /* If the table has no indices and there are no terms in the where
00932   ** clause that refer to the ROWID, then we will never be able to do
00933   ** anything other than a full table scan on this table.  We might as
00934   ** well put it first in the join order.  That way, perhaps it can be
00935   ** referenced by other tables in the join.
00936   */
00937   if( pProbe==0 &&
00938      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
00939      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, &rev)) ){
00940     *pFlags = 0;
00941     *ppIndex = 0;
00942     *pnEq = 0;
00943     return 0.0;
00944   }
00945 
00946   /* Check for a rowid=EXPR or rowid IN (...) constraints
00947   */
00948   pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
00949   if( pTerm ){
00950     Expr *pExpr;
00951     *ppIndex = 0;
00952     bestFlags = WHERE_ROWID_EQ;
00953     if( pTerm->eOperator & WO_EQ ){
00954       /* Rowid== is always the best pick.  Look no further.  Because only
00955       ** a single row is generated, output is always in sorted order */
00956       *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
00957       *pnEq = 1;
00958       TRACE(("... best is rowid\n"));
00959       return 0.0;
00960     }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
00961       /* Rowid IN (LIST): cost is NlogN where N is the number of list
00962       ** elements.  */
00963       lowestCost = pExpr->pList->nExpr;
00964       lowestCost *= estLog(lowestCost);
00965     }else{
00966       /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
00967       ** in the result of the inner select.  We have no way to estimate
00968       ** that value so make a wild guess. */
00969       lowestCost = 200;
00970     }
00971     TRACE(("... rowid IN cost: %.9g\n", lowestCost));
00972   }
00973 
00974   /* Estimate the cost of a table scan.  If we do not know how many
00975   ** entries are in the table, use 1 million as a guess.
00976   */
00977   cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
00978   TRACE(("... table scan base cost: %.9g\n", cost));
00979   flags = WHERE_ROWID_RANGE;
00980 
00981   /* Check for constraints on a range of rowids in a table scan.
00982   */
00983   pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
00984   if( pTerm ){
00985     if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
00986       flags |= WHERE_TOP_LIMIT;
00987       cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds or rows */
00988     }
00989     if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
00990       flags |= WHERE_BTM_LIMIT;
00991       cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
00992     }
00993     TRACE(("... rowid range reduces cost to %.9g\n", cost));
00994   }else{
00995     flags = 0;
00996   }
00997 
00998   /* If the table scan does not satisfy the ORDER BY clause, increase
00999   ** the cost by NlogN to cover the expense of sorting. */
01000   if( pOrderBy ){
01001     if( sortableByRowid(iCur, pOrderBy, &rev) ){
01002       flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
01003       if( rev ){
01004         flags |= WHERE_REVERSE;
01005       }
01006     }else{
01007       cost += cost*estLog(cost);
01008       TRACE(("... sorting increases cost to %.9g\n", cost));
01009     }
01010   }
01011   if( cost<lowestCost ){
01012     lowestCost = cost;
01013     bestFlags = flags;
01014   }
01015 
01016   /* Look at each index.
01017   */
01018   for(; pProbe; pProbe=pProbe->pNext){
01019     int i;                       /* Loop counter */
01020     double inMultiplier = 1;
01021 
01022     TRACE(("... index %s:\n", pProbe->zName));
01023 
01024     /* Count the number of columns in the index that are satisfied
01025     ** by x=EXPR constraints or x IN (...) constraints.
01026     */
01027     flags = 0;
01028     for(i=0; i<pProbe->nColumn; i++){
01029       int j = pProbe->aiColumn[i];
01030       pTerm = findTerm(pWC, iCur, j, notReady, WO_EQ|WO_IN, pProbe);
01031       if( pTerm==0 ) break;
01032       flags |= WHERE_COLUMN_EQ;
01033       if( pTerm->eOperator & WO_IN ){
01034         Expr *pExpr = pTerm->pExpr;
01035         flags |= WHERE_COLUMN_IN;
01036         if( pExpr->pSelect!=0 ){
01037           inMultiplier *= 25;
01038         }else if( pExpr->pList!=0 ){
01039           inMultiplier *= pExpr->pList->nExpr + 1;
01040         }
01041       }
01042     }
01043     cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
01044     nEq = i;
01045     if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
01046          && nEq==pProbe->nColumn ){
01047       flags |= WHERE_UNIQUE;
01048     }
01049     TRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n", nEq, inMultiplier, cost));
01050 
01051     /* Look for range constraints
01052     */
01053     if( nEq<pProbe->nColumn ){
01054       int j = pProbe->aiColumn[nEq];
01055       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
01056       if( pTerm ){
01057         flags |= WHERE_COLUMN_RANGE;
01058         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
01059           flags |= WHERE_TOP_LIMIT;
01060           cost /= 3;
01061         }
01062         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
01063           flags |= WHERE_BTM_LIMIT;
01064           cost /= 3;
01065         }
01066         TRACE(("...... range reduces cost to %.9g\n", cost));
01067       }
01068     }
01069 
01070     /* Add the additional cost of sorting if that is a factor.
01071     */
01072     if( pOrderBy ){
01073       if( (flags & WHERE_COLUMN_IN)==0 &&
01074            isSortingIndex(pParse,pProbe,iCur,pOrderBy,nEq,&rev) ){
01075         if( flags==0 ){
01076           flags = WHERE_COLUMN_RANGE;
01077         }
01078         flags |= WHERE_ORDERBY;
01079         if( rev ){
01080           flags |= WHERE_REVERSE;
01081         }
01082       }else{
01083         cost += cost*estLog(cost);
01084         TRACE(("...... orderby increases cost to %.9g\n", cost));
01085       }
01086     }
01087 
01088     /* Check to see if we can get away with using just the index without
01089     ** ever reading the table.  If that is the case, then halve the
01090     ** cost of this index.
01091     */
01092     if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
01093       Bitmask m = pSrc->colUsed;
01094       int j;
01095       for(j=0; j<pProbe->nColumn; j++){
01096         int x = pProbe->aiColumn[j];
01097         if( x<BMS-1 ){
01098           m &= ~(((Bitmask)1)<<x);
01099         }
01100       }
01101       if( m==0 ){
01102         flags |= WHERE_IDX_ONLY;
01103         cost /= 2;
01104         TRACE(("...... idx-only reduces cost to %.9g\n", cost));
01105       }
01106     }
01107 
01108     /* If this index has achieved the lowest cost so far, then use it.
01109     */
01110     if( cost < lowestCost ){
01111       bestIdx = pProbe;
01112       lowestCost = cost;
01113       assert( flags!=0 );
01114       bestFlags = flags;
01115       bestNEq = nEq;
01116     }
01117   }
01118 
01119   /* Report the best result
01120   */
01121   *ppIndex = bestIdx;
01122   TRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
01123         bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
01124   *pFlags = bestFlags;
01125   *pnEq = bestNEq;
01126   return lowestCost;
01127 }
01128 
01129 
01130 /*
01131 ** Disable a term in the WHERE clause.  Except, do not disable the term
01132 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
01133 ** or USING clause of that join.
01134 **
01135 ** Consider the term t2.z='ok' in the following queries:
01136 **
01137 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
01138 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
01139 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
01140 **
01141 ** The t2.z='ok' is disabled in the in (2) because it originates
01142 ** in the ON clause.  The term is disabled in (3) because it is not part
01143 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
01144 **
01145 ** Disabling a term causes that term to not be tested in the inner loop
01146 ** of the join.  Disabling is an optimization.  When terms are satisfied
01147 ** by indices, we disable them to prevent redundant tests in the inner
01148 ** loop.  We would get the correct results if nothing were ever disabled,
01149 ** but joins might run a little slower.  The trick is to disable as much
01150 ** as we can without disabling too much.  If we disabled in (1), we'd get
01151 ** the wrong answer.  See ticket #813.
01152 */
01153 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
01154   if( pTerm
01155       && (pTerm->flags & TERM_CODED)==0
01156       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
01157   ){
01158     pTerm->flags |= TERM_CODED;
01159     if( pTerm->iParent>=0 ){
01160       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
01161       if( (--pOther->nChild)==0 ){
01162         disableTerm(pLevel, pOther);
01163       }
01164     }
01165   }
01166 }
01167 
01168 /*
01169 ** Generate code that builds a probe for an index.  Details:
01170 **
01171 **    *  Check the top nColumn entries on the stack.  If any
01172 **       of those entries are NULL, jump immediately to brk,
01173 **       which is the loop exit, since no index entry will match
01174 **       if any part of the key is NULL. Pop (nColumn+nExtra) 
01175 **       elements from the stack.
01176 **
01177 **    *  Construct a probe entry from the top nColumn entries in
01178 **       the stack with affinities appropriate for index pIdx. 
01179 **       Only nColumn elements are popped from the stack in this case
01180 **       (by OP_MakeRecord).
01181 **
01182 */
01183 static void buildIndexProbe(
01184   Vdbe *v, 
01185   int nColumn, 
01186   int nExtra, 
01187   int brk, 
01188   Index *pIdx
01189 ){
01190   sqlite3VdbeAddOp(v, OP_NotNull, -nColumn, sqlite3VdbeCurrentAddr(v)+3);
01191   sqlite3VdbeAddOp(v, OP_Pop, nColumn+nExtra, 0);
01192   sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
01193   sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
01194   sqlite3IndexAffinityStr(v, pIdx);
01195 }
01196 
01197 
01198 /*
01199 ** Generate code for a single equality term of the WHERE clause.  An equality
01200 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
01201 ** coded.
01202 **
01203 ** The current value for the constraint is left on the top of the stack.
01204 **
01205 ** For a constraint of the form X=expr, the expression is evaluated and its
01206 ** result is left on the stack.  For constraints of the form X IN (...)
01207 ** this routine sets up a loop that will iterate over all values of X.
01208 */
01209 static void codeEqualityTerm(
01210   Parse *pParse,      /* The parsing context */
01211   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
01212   int brk,            /* Jump here to abandon the loop */
01213   WhereLevel *pLevel  /* When level of the FROM clause we are working on */
01214 ){
01215   Expr *pX = pTerm->pExpr;
01216   if( pX->op!=TK_IN ){
01217     assert( pX->op==TK_EQ );
01218     sqlite3ExprCode(pParse, pX->pRight);
01219 #ifndef SQLITE_OMIT_SUBQUERY
01220   }else{
01221     int iTab;
01222     int *aIn;
01223     Vdbe *v = pParse->pVdbe;
01224 
01225     sqlite3CodeSubselect(pParse, pX);
01226     iTab = pX->iTable;
01227     sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
01228     VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
01229     pLevel->nIn++;
01230     sqliteReallocOrFree((void**)&pLevel->aInLoop,
01231                                  sizeof(pLevel->aInLoop[0])*2*pLevel->nIn);
01232     aIn = pLevel->aInLoop;
01233     if( aIn ){
01234       aIn += pLevel->nIn*2 - 2;
01235       aIn[0] = iTab;
01236       aIn[1] = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
01237     }else{
01238       pLevel->nIn = 0;
01239     }
01240 #endif
01241   }
01242   disableTerm(pLevel, pTerm);
01243 }
01244 
01245 /*
01246 ** Generate code that will evaluate all == and IN constraints for an
01247 ** index.  The values for all constraints are left on the stack.
01248 **
01249 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
01250 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
01251 ** The index has as many as three equality constraints, but in this
01252 ** example, the third "c" value is an inequality.  So only two 
01253 ** constraints are coded.  This routine will generate code to evaluate
01254 ** a==5 and b IN (1,2,3).  The current values for a and b will be left
01255 ** on the stack - a is the deepest and b the shallowest.
01256 **
01257 ** In the example above nEq==2.  But this subroutine works for any value
01258 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
01259 ** The only thing it does is allocate the pLevel->iMem memory cell.
01260 **
01261 ** This routine always allocates at least one memory cell and puts
01262 ** the address of that memory cell in pLevel->iMem.  The code that
01263 ** calls this routine will use pLevel->iMem to store the termination
01264 ** key value of the loop.  If one or more IN operators appear, then
01265 ** this routine allocates an additional nEq memory cells for internal
01266 ** use.
01267 */
01268 static void codeAllEqualityTerms(
01269   Parse *pParse,        /* Parsing context */
01270   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
01271   WhereClause *pWC,     /* The WHERE clause */
01272   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
01273   int brk               /* Jump here to end the loop */
01274 ){
01275   int nEq = pLevel->nEq;        /* The number of == or IN constraints to code */
01276   int termsInMem = 0;           /* If true, store value in mem[] cells */
01277   Vdbe *v = pParse->pVdbe;      /* The virtual machine under construction */
01278   Index *pIdx = pLevel->pIdx;   /* The index being used for this loop */
01279   int iCur = pLevel->iTabCur;   /* The cursor of the table */
01280   WhereTerm *pTerm;             /* A single constraint term */
01281   int j;                        /* Loop counter */
01282 
01283   /* Figure out how many memory cells we will need then allocate them.
01284   ** We always need at least one used to store the loop terminator
01285   ** value.  If there are IN operators we'll need one for each == or
01286   ** IN constraint.
01287   */
01288   pLevel->iMem = pParse->nMem++;
01289   if( pLevel->flags & WHERE_COLUMN_IN ){
01290     pParse->nMem += pLevel->nEq;
01291     termsInMem = 1;
01292   }
01293 
01294   /* Evaluate the equality constraints
01295   */
01296   for(j=0; j<pIdx->nColumn; j++){
01297     int k = pIdx->aiColumn[j];
01298     pTerm = findTerm(pWC, iCur, k, notReady, WO_EQ|WO_IN, pIdx);
01299     if( pTerm==0 ) break;
01300     assert( (pTerm->flags & TERM_CODED)==0 );
01301     codeEqualityTerm(pParse, pTerm, brk, pLevel);
01302     if( termsInMem ){
01303       sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1);
01304     }
01305   }
01306   assert( j==nEq );
01307 
01308   /* Make sure all the constraint values are on the top of the stack
01309   */
01310   if( termsInMem ){
01311     for(j=0; j<nEq; j++){
01312       sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem+j+1, 0);
01313     }
01314   }
01315 }
01316 
01317 #if defined(SQLITE_TEST)
01318 /*
01319 ** The following variable holds a text description of query plan generated
01320 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
01321 ** overwrites the previous.  This information is used for testing and
01322 ** analysis only.
01323 */
01324 char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
01325 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
01326 
01327 #endif /* SQLITE_TEST */
01328 
01329 
01330 
01331 /*
01332 ** Generate the beginning of the loop used for WHERE clause processing.
01333 ** The return value is a pointer to an opaque structure that contains
01334 ** information needed to terminate the loop.  Later, the calling routine
01335 ** should invoke sqlite3WhereEnd() with the return value of this function
01336 ** in order to complete the WHERE clause processing.
01337 **
01338 ** If an error occurs, this routine returns NULL.
01339 **
01340 ** The basic idea is to do a nested loop, one loop for each table in
01341 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
01342 ** same as a SELECT with only a single table in the FROM clause.)  For
01343 ** example, if the SQL is this:
01344 **
01345 **       SELECT * FROM t1, t2, t3 WHERE ...;
01346 **
01347 ** Then the code generated is conceptually like the following:
01348 **
01349 **      foreach row1 in t1 do       \    Code generated
01350 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
01351 **          foreach row3 in t3 do   /
01352 **            ...
01353 **          end                     \    Code generated
01354 **        end                        |-- by sqlite3WhereEnd()
01355 **      end                         /
01356 **
01357 ** Note that the loops might not be nested in the order in which they
01358 ** appear in the FROM clause if a different order is better able to make
01359 ** use of indices.  Note also that when the IN operator appears in
01360 ** the WHERE clause, it might result in additional nested loops for
01361 ** scanning through all values on the right-hand side of the IN.
01362 **
01363 ** There are Btree cursors associated with each table.  t1 uses cursor
01364 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
01365 ** And so forth.  This routine generates code to open those VDBE cursors
01366 ** and sqlite3WhereEnd() generates the code to close them.
01367 **
01368 ** The code that sqlite3WhereBegin() generates leaves the cursors named
01369 ** in pTabList pointing at their appropriate entries.  The [...] code
01370 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
01371 ** data from the various tables of the loop.
01372 **
01373 ** If the WHERE clause is empty, the foreach loops must each scan their
01374 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
01375 ** the tables have indices and there are terms in the WHERE clause that
01376 ** refer to those indices, a complete table scan can be avoided and the
01377 ** code will run much faster.  Most of the work of this routine is checking
01378 ** to see if there are indices that can be used to speed up the loop.
01379 **
01380 ** Terms of the WHERE clause are also used to limit which rows actually
01381 ** make it to the "..." in the middle of the loop.  After each "foreach",
01382 ** terms of the WHERE clause that use only terms in that loop and outer
01383 ** loops are evaluated and if false a jump is made around all subsequent
01384 ** inner loops (or around the "..." if the test occurs within the inner-
01385 ** most loop)
01386 **
01387 ** OUTER JOINS
01388 **
01389 ** An outer join of tables t1 and t2 is conceptally coded as follows:
01390 **
01391 **    foreach row1 in t1 do
01392 **      flag = 0
01393 **      foreach row2 in t2 do
01394 **        start:
01395 **          ...
01396 **          flag = 1
01397 **      end
01398 **      if flag==0 then
01399 **        move the row2 cursor to a null row
01400 **        goto start
01401 **      fi
01402 **    end
01403 **
01404 ** ORDER BY CLAUSE PROCESSING
01405 **
01406 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
01407 ** if there is one.  If there is no ORDER BY clause or if this routine
01408 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
01409 **
01410 ** If an index can be used so that the natural output order of the table
01411 ** scan is correct for the ORDER BY clause, then that index is used and
01412 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
01413 ** unnecessary sort of the result set if an index appropriate for the
01414 ** ORDER BY clause already exists.
01415 **
01416 ** If the where clause loops cannot be arranged to provide the correct
01417 ** output order, then the *ppOrderBy is unchanged.
01418 */
01419 WhereInfo *sqlite3WhereBegin(
01420   Parse *pParse,        /* The parser context */
01421   SrcList *pTabList,    /* A list of all tables to be scanned */
01422   Expr *pWhere,         /* The WHERE clause */
01423   ExprList **ppOrderBy  /* An ORDER BY clause, or NULL */
01424 ){
01425   int i;                     /* Loop counter */
01426   WhereInfo *pWInfo;         /* Will become the return value of this function */
01427   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
01428   int brk, cont = 0;         /* Addresses used during code generation */
01429   Bitmask notReady;          /* Cursors that are not yet positioned */
01430   WhereTerm *pTerm;          /* A single term in the WHERE clause */
01431   ExprMaskSet maskSet;       /* The expression mask set */
01432   WhereClause wc;            /* The WHERE clause is divided into these terms */
01433   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
01434   WhereLevel *pLevel;             /* A single level in the pWInfo list */
01435   int iFrom;                      /* First unused FROM clause element */
01436   int andFlags;              /* AND-ed combination of all wc.a[].flags */
01437 
01438   /* The number of tables in the FROM clause is limited by the number of
01439   ** bits in a Bitmask 
01440   */
01441   if( pTabList->nSrc>BMS ){
01442     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
01443     return 0;
01444   }
01445 
01446   /* Split the WHERE clause into separate subexpressions where each
01447   ** subexpression is separated by an AND operator.
01448   */
01449   initMaskSet(&maskSet);
01450   whereClauseInit(&wc, pParse);
01451   whereSplit(&wc, pWhere, TK_AND);
01452     
01453   /* Allocate and initialize the WhereInfo structure that will become the
01454   ** return value.
01455   */
01456   pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
01457   if( sqlite3MallocFailed() ){
01458     goto whereBeginNoMem;
01459   }
01460   pWInfo->pParse = pParse;
01461   pWInfo->pTabList = pTabList;
01462   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
01463 
01464   /* Special case: a WHERE clause that is constant.  Evaluate the
01465   ** expression and either jump over all of the code or fall thru.
01466   */
01467   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstant(pWhere)) ){
01468     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
01469     pWhere = 0;
01470   }
01471 
01472   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
01473   ** add new virtual terms onto the end of the WHERE clause.  We do not
01474   ** want to analyze these virtual terms, so start analyzing at the end
01475   ** and work forward so that the added virtual terms are never processed.
01476   */
01477   for(i=0; i<pTabList->nSrc; i++){
01478     createMask(&maskSet, pTabList->a[i].iCursor);
01479   }
01480   exprAnalyzeAll(pTabList, &maskSet, &wc);
01481   if( sqlite3MallocFailed() ){
01482     goto whereBeginNoMem;
01483   }
01484 
01485   /* Chose the best index to use for each table in the FROM clause.
01486   **
01487   ** This loop fills in the following fields:
01488   **
01489   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
01490   **   pWInfo->a[].flags     WHERE_xxx flags associated with pIdx
01491   **   pWInfo->a[].nEq       The number of == and IN constraints
01492   **   pWInfo->a[].iFrom     When term of the FROM clause is being coded
01493   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
01494   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
01495   **
01496   ** This loop also figures out the nesting order of tables in the FROM
01497   ** clause.
01498   */
01499   notReady = ~(Bitmask)0;
01500   pTabItem = pTabList->a;
01501   pLevel = pWInfo->a;
01502   andFlags = ~0;
01503   TRACE(("*** Optimizer Start ***\n"));
01504   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
01505     Index *pIdx;                /* Index for FROM table at pTabItem */
01506     int flags;                  /* Flags asssociated with pIdx */
01507     int nEq;                    /* Number of == or IN constraints */
01508     double cost;                /* The cost for pIdx */
01509     int j;                      /* For looping over FROM tables */
01510     Index *pBest = 0;           /* The best index seen so far */
01511     int bestFlags = 0;          /* Flags associated with pBest */
01512     int bestNEq = 0;            /* nEq associated with pBest */
01513     double lowestCost;          /* Cost of the pBest */
01514     int bestJ = 0;              /* The value of j */
01515     Bitmask m;                  /* Bitmask value for j or bestJ */
01516     int once = 0;               /* True when first table is seen */
01517 
01518     lowestCost = SQLITE_BIG_DBL;
01519     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
01520       if( once && 
01521           ((pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0
01522            || (j>0 && (pTabItem[-1].jointype & (JT_LEFT|JT_CROSS))!=0))
01523       ){
01524         break;
01525       }
01526       m = getMask(&maskSet, pTabItem->iCursor);
01527       if( (m & notReady)==0 ){
01528         if( j==iFrom ) iFrom++;
01529         continue;
01530       }
01531       cost = bestIndex(pParse, &wc, pTabItem, notReady,
01532                        (i==0 && ppOrderBy) ? *ppOrderBy : 0,
01533                        &pIdx, &flags, &nEq);
01534       if( cost<lowestCost ){
01535         once = 1;
01536         lowestCost = cost;
01537         pBest = pIdx;
01538         bestFlags = flags;
01539         bestNEq = nEq;
01540         bestJ = j;
01541       }
01542     }
01543     TRACE(("*** Optimizer choose table %d for loop %d\n", bestJ,
01544            pLevel-pWInfo->a));
01545     if( (bestFlags & WHERE_ORDERBY)!=0 ){
01546       *ppOrderBy = 0;
01547     }
01548     andFlags &= bestFlags;
01549     pLevel->flags = bestFlags;
01550     pLevel->pIdx = pBest;
01551     pLevel->nEq = bestNEq;
01552     pLevel->aInLoop = 0;
01553     pLevel->nIn = 0;
01554     if( pBest ){
01555       pLevel->iIdxCur = pParse->nTab++;
01556     }else{
01557       pLevel->iIdxCur = -1;
01558     }
01559     notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
01560     pLevel->iFrom = bestJ;
01561   }
01562   TRACE(("*** Optimizer Finished ***\n"));
01563 
01564   /* If the total query only selects a single row, then the ORDER BY
01565   ** clause is irrelevant.
01566   */
01567   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
01568     *ppOrderBy = 0;
01569   }
01570 
01571   /* Open all tables in the pTabList and any indices selected for
01572   ** searching those tables.
01573   */
01574   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
01575   pLevel = pWInfo->a;
01576   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
01577     Table *pTab;     /* Table to open */
01578     Index *pIx;      /* Index used to access pTab (if any) */
01579     int iDb;         /* Index of database containing table/index */
01580     int iIdxCur = pLevel->iIdxCur;
01581 
01582 #ifndef SQLITE_OMIT_EXPLAIN
01583     if( pParse->explain==2 ){
01584       char *zMsg;
01585       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
01586       zMsg = sqlite3MPrintf("TABLE %s", pItem->zName);
01587       if( pItem->zAlias ){
01588         zMsg = sqlite3MPrintf("%z AS %s", zMsg, pItem->zAlias);
01589       }
01590       if( (pIx = pLevel->pIdx)!=0 ){
01591         zMsg = sqlite3MPrintf("%z WITH INDEX %s", zMsg, pIx->zName);
01592       }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
01593         zMsg = sqlite3MPrintf("%z USING PRIMARY KEY", zMsg);
01594       }
01595       if( pLevel->flags & WHERE_ORDERBY ){
01596         zMsg = sqlite3MPrintf("%z ORDER BY", zMsg);
01597       }
01598       sqlite3VdbeOp3(v, OP_Explain, i, pLevel->iFrom, zMsg, P3_DYNAMIC);
01599     }
01600 #endif /* SQLITE_OMIT_EXPLAIN */
01601     pTabItem = &pTabList->a[pLevel->iFrom];
01602     pTab = pTabItem->pTab;
01603     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
01604     if( pTab->isTransient || pTab->pSelect ) continue;
01605     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
01606       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, OP_OpenRead);
01607       if( pTab->nCol<(sizeof(Bitmask)*8) ){
01608         Bitmask b = pTabItem->colUsed;
01609         int n = 0;
01610         for(; b; b=b>>1, n++){}
01611         sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-1, n);
01612         assert( n<=pTab->nCol );
01613       }
01614     }else{
01615       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
01616     }
01617     pLevel->iTabCur = pTabItem->iCursor;
01618     if( (pIx = pLevel->pIdx)!=0 ){
01619       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
01620       assert( pIx->pSchema==pTab->pSchema );
01621       sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
01622       VdbeComment((v, "# %s", pIx->zName));
01623       sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
01624                      (char*)pKey, P3_KEYINFO_HANDOFF);
01625     }
01626     if( (pLevel->flags & WHERE_IDX_ONLY)!=0 ){
01627       sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
01628     }
01629     sqlite3CodeVerifySchema(pParse, iDb);
01630   }
01631   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
01632 
01633   /* Generate the code to do the search.  Each iteration of the for
01634   ** loop below generates code for a single nested loop of the VM
01635   ** program.
01636   */
01637   notReady = ~(Bitmask)0;
01638   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
01639     int j;
01640     int iCur = pTabItem->iCursor;  /* The VDBE cursor for the table */
01641     Index *pIdx;       /* The index we will be using */
01642     int iIdxCur;       /* The VDBE cursor for the index */
01643     int omitTable;     /* True if we use the index only */
01644     int bRev;          /* True if we need to scan in reverse order */
01645 
01646     pTabItem = &pTabList->a[pLevel->iFrom];
01647     iCur = pTabItem->iCursor;
01648     pIdx = pLevel->pIdx;
01649     iIdxCur = pLevel->iIdxCur;
01650     bRev = (pLevel->flags & WHERE_REVERSE)!=0;
01651     omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
01652 
01653     /* Create labels for the "break" and "continue" instructions
01654     ** for the current loop.  Jump to brk to break out of a loop.
01655     ** Jump to cont to go immediately to the next iteration of the
01656     ** loop.
01657     */
01658     brk = pLevel->brk = sqlite3VdbeMakeLabel(v);
01659     cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
01660 
01661     /* If this is the right table of a LEFT OUTER JOIN, allocate and
01662     ** initialize a memory cell that records if this table matches any
01663     ** row of the left table of the join.
01664     */
01665     if( pLevel->iFrom>0 && (pTabItem[-1].jointype & JT_LEFT)!=0 ){
01666       if( !pParse->nMem ) pParse->nMem++;
01667       pLevel->iLeftJoin = pParse->nMem++;
01668       sqlite3VdbeAddOp(v, OP_MemInt, 0, pLevel->iLeftJoin);
01669       VdbeComment((v, "# init LEFT JOIN no-match flag"));
01670     }
01671 
01672     if( pLevel->flags & WHERE_ROWID_EQ ){
01673       /* Case 1:  We can directly reference a single row using an
01674       **          equality comparison against the ROWID field.  Or
01675       **          we reference multiple rows using a "rowid IN (...)"
01676       **          construct.
01677       */
01678       pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
01679       assert( pTerm!=0 );
01680       assert( pTerm->pExpr!=0 );
01681       assert( pTerm->leftCursor==iCur );
01682       assert( omitTable==0 );
01683       codeEqualityTerm(pParse, pTerm, brk, pLevel);
01684       sqlite3VdbeAddOp(v, OP_MustBeInt, 1, brk);
01685       sqlite3VdbeAddOp(v, OP_NotExists, iCur, brk);
01686       VdbeComment((v, "pk"));
01687       pLevel->op = OP_Noop;
01688     }else if( pLevel->flags & WHERE_ROWID_RANGE ){
01689       /* Case 2:  We have an inequality comparison against the ROWID field.
01690       */
01691       int testOp = OP_Noop;
01692       int start;
01693       WhereTerm *pStart, *pEnd;
01694 
01695       assert( omitTable==0 );
01696       pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
01697       pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
01698       if( bRev ){
01699         pTerm = pStart;
01700         pStart = pEnd;
01701         pEnd = pTerm;
01702       }
01703       if( pStart ){
01704         Expr *pX;
01705         pX = pStart->pExpr;
01706         assert( pX!=0 );
01707         assert( pStart->leftCursor==iCur );
01708         sqlite3ExprCode(pParse, pX->pRight);
01709         sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
01710         sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
01711         VdbeComment((v, "pk"));
01712         disableTerm(pLevel, pStart);
01713       }else{
01714         sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
01715       }
01716       if( pEnd ){
01717         Expr *pX;
01718         pX = pEnd->pExpr;
01719         assert( pX!=0 );
01720         assert( pEnd->leftCursor==iCur );
01721         sqlite3ExprCode(pParse, pX->pRight);
01722         pLevel->iMem = pParse->nMem++;
01723         sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
01724         if( pX->op==TK_LT || pX->op==TK_GT ){
01725           testOp = bRev ? OP_Le : OP_Ge;
01726         }else{
01727           testOp = bRev ? OP_Lt : OP_Gt;
01728         }
01729         disableTerm(pLevel, pEnd);
01730       }
01731       start = sqlite3VdbeCurrentAddr(v);
01732       pLevel->op = bRev ? OP_Prev : OP_Next;
01733       pLevel->p1 = iCur;
01734       pLevel->p2 = start;
01735       if( testOp!=OP_Noop ){
01736         sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
01737         sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
01738         sqlite3VdbeAddOp(v, testOp, SQLITE_AFF_NUMERIC, brk);
01739       }
01740     }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
01741       /* Case 3: The WHERE clause term that refers to the right-most
01742       **         column of the index is an inequality.  For example, if
01743       **         the index is on (x,y,z) and the WHERE clause is of the
01744       **         form "x=5 AND y<10" then this case is used.  Only the
01745       **         right-most column can be an inequality - the rest must
01746       **         use the "==" and "IN" operators.
01747       **
01748       **         This case is also used when there are no WHERE clause
01749       **         constraints but an index is selected anyway, in order
01750       **         to force the output order to conform to an ORDER BY.
01751       */
01752       int start;
01753       int nEq = pLevel->nEq;
01754       int topEq=0;        /* True if top limit uses ==. False is strictly < */
01755       int btmEq=0;        /* True if btm limit uses ==. False if strictly > */
01756       int topOp, btmOp;   /* Operators for the top and bottom search bounds */
01757       int testOp;
01758       int nNotNull;       /* Number of rows of index that must be non-NULL */
01759       int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
01760       int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
01761 
01762       /* Generate code to evaluate all constraint terms using == or IN
01763       ** and level the values of those terms on the stack.
01764       */
01765       codeAllEqualityTerms(pParse, pLevel, &wc, notReady, brk);
01766 
01767       /* Duplicate the equality term values because they will all be
01768       ** used twice: once to make the termination key and once to make the
01769       ** start key.
01770       */
01771       for(j=0; j<nEq; j++){
01772         sqlite3VdbeAddOp(v, OP_Dup, nEq-1, 0);
01773       }
01774 
01775       /* Figure out what comparison operators to use for top and bottom 
01776       ** search bounds. For an ascending index, the bottom bound is a > or >=
01777       ** operator and the top bound is a < or <= operator.  For a descending
01778       ** index the operators are reversed.
01779       */
01780       nNotNull = nEq + topLimit;
01781       if( pIdx->aSortOrder[nEq]==SQLITE_SO_ASC ){
01782         topOp = WO_LT|WO_LE;
01783         btmOp = WO_GT|WO_GE;
01784       }else{
01785         topOp = WO_GT|WO_GE;
01786         btmOp = WO_LT|WO_LE;
01787         SWAP(int, topLimit, btmLimit);
01788       }
01789 
01790       /* Generate the termination key.  This is the key value that
01791       ** will end the search.  There is no termination key if there
01792       ** are no equality terms and no "X<..." term.
01793       **
01794       ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
01795       ** key computed here really ends up being the start key.
01796       */
01797       if( topLimit ){
01798         Expr *pX;
01799         int k = pIdx->aiColumn[j];
01800         pTerm = findTerm(&wc, iCur, k, notReady, topOp, pIdx);
01801         assert( pTerm!=0 );
01802         pX = pTerm->pExpr;
01803         assert( (pTerm->flags & TERM_CODED)==0 );
01804         sqlite3ExprCode(pParse, pX->pRight);
01805         topEq = pTerm->eOperator & (WO_LE|WO_GE);
01806         disableTerm(pLevel, pTerm);
01807         testOp = OP_IdxGE;
01808       }else{
01809         testOp = nEq>0 ? OP_IdxGE : OP_Noop;
01810         topEq = 1;
01811       }
01812       if( testOp!=OP_Noop ){
01813         int nCol = nEq + topLimit;
01814         pLevel->iMem = pParse->nMem++;
01815         buildIndexProbe(v, nCol, nEq, brk, pIdx);
01816         if( bRev ){
01817           int op = topEq ? OP_MoveLe : OP_MoveLt;
01818           sqlite3VdbeAddOp(v, op, iIdxCur, brk);
01819         }else{
01820           sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
01821         }
01822       }else if( bRev ){
01823         sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
01824       }
01825 
01826       /* Generate the start key.  This is the key that defines the lower
01827       ** bound on the search.  There is no start key if there are no
01828       ** equality terms and if there is no "X>..." term.  In
01829       ** that case, generate a "Rewind" instruction in place of the
01830       ** start key search.
01831       **
01832       ** 2002-Dec-04: In the case of a reverse-order search, the so-called
01833       ** "start" key really ends up being used as the termination key.
01834       */
01835       if( btmLimit ){
01836         Expr *pX;
01837         int k = pIdx->aiColumn[j];
01838         pTerm = findTerm(&wc, iCur, k, notReady, btmOp, pIdx);
01839         assert( pTerm!=0 );
01840         pX = pTerm->pExpr;
01841         assert( (pTerm->flags & TERM_CODED)==0 );
01842         sqlite3ExprCode(pParse, pX->pRight);
01843         btmEq = pTerm->eOperator & (WO_LE|WO_GE);
01844         disableTerm(pLevel, pTerm);
01845       }else{
01846         btmEq = 1;
01847       }
01848       if( nEq>0 || btmLimit ){
01849         int nCol = nEq + btmLimit;
01850         buildIndexProbe(v, nCol, 0, brk, pIdx);
01851         if( bRev ){
01852           pLevel->iMem = pParse->nMem++;
01853           sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
01854           testOp = OP_IdxLT;
01855         }else{
01856           int op = btmEq ? OP_MoveGe : OP_MoveGt;
01857           sqlite3VdbeAddOp(v, op, iIdxCur, brk);
01858         }
01859       }else if( bRev ){
01860         testOp = OP_Noop;
01861       }else{
01862         sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
01863       }
01864 
01865       /* Generate the the top of the loop.  If there is a termination
01866       ** key we have to test for that key and abort at the top of the
01867       ** loop.
01868       */
01869       start = sqlite3VdbeCurrentAddr(v);
01870       if( testOp!=OP_Noop ){
01871         sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
01872         sqlite3VdbeAddOp(v, testOp, iIdxCur, brk);
01873         if( (topEq && !bRev) || (!btmEq && bRev) ){
01874           sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
01875         }
01876       }
01877       sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
01878       sqlite3VdbeAddOp(v, OP_IdxIsNull, nNotNull, cont);
01879       if( !omitTable ){
01880         sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
01881         sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
01882       }
01883 
01884       /* Record the instruction used to terminate the loop.
01885       */
01886       pLevel->op = bRev ? OP_Prev : OP_Next;
01887       pLevel->p1 = iIdxCur;
01888       pLevel->p2 = start;
01889     }else if( pLevel->flags & WHERE_COLUMN_EQ ){
01890       /* Case 4:  There is an index and all terms of the WHERE clause that
01891       **          refer to the index using the "==" or "IN" operators.
01892       */
01893       int start;
01894       int nEq = pLevel->nEq;
01895 
01896       /* Generate code to evaluate all constraint terms using == or IN
01897       ** and leave the values of those terms on the stack.
01898       */
01899       codeAllEqualityTerms(pParse, pLevel, &wc, notReady, brk);
01900 
01901       /* Generate a single key that will be used to both start and terminate
01902       ** the search
01903       */
01904       buildIndexProbe(v, nEq, 0, brk, pIdx);
01905       sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
01906 
01907       /* Generate code (1) to move to the first matching element of the table.
01908       ** Then generate code (2) that jumps to "brk" after the cursor is past
01909       ** the last matching element of the table.  The code (1) is executed
01910       ** once to initialize the search, the code (2) is executed before each
01911       ** iteration of the scan to see if the scan has finished. */
01912       if( bRev ){
01913         /* Scan in reverse order */
01914         sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, brk);
01915         start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
01916         sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, brk);
01917         pLevel->op = OP_Prev;
01918       }else{
01919         /* Scan in the forward order */
01920         sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, brk);
01921         start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
01922         sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, brk, "+", P3_STATIC);
01923         pLevel->op = OP_Next;
01924       }
01925       sqlite3VdbeAddOp(v, OP_RowKey, iIdxCur, 0);
01926       sqlite3VdbeAddOp(v, OP_IdxIsNull, nEq, cont);
01927       if( !omitTable ){
01928         sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
01929         sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
01930       }
01931       pLevel->p1 = iIdxCur;
01932       pLevel->p2 = start;
01933     }else{
01934       /* Case 5:  There is no usable index.  We must do a complete
01935       **          scan of the entire table.
01936       */
01937       assert( omitTable==0 );
01938       assert( bRev==0 );
01939       pLevel->op = OP_Next;
01940       pLevel->p1 = iCur;
01941       pLevel->p2 = 1 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, brk);
01942     }
01943     notReady &= ~getMask(&maskSet, iCur);
01944 
01945     /* Insert code to test every subexpression that can be completely
01946     ** computed using the current set of tables.
01947     */
01948     for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
01949       Expr *pE;
01950       if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
01951       if( (pTerm->prereqAll & notReady)!=0 ) continue;
01952       pE = pTerm->pExpr;
01953       assert( pE!=0 );
01954       if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
01955         continue;
01956       }
01957       sqlite3ExprIfFalse(pParse, pE, cont, 1);
01958       pTerm->flags |= TERM_CODED;
01959     }
01960 
01961     /* For a LEFT OUTER JOIN, generate code that will record the fact that
01962     ** at least one row of the right table has matched the left table.  
01963     */
01964     if( pLevel->iLeftJoin ){
01965       pLevel->top = sqlite3VdbeCurrentAddr(v);
01966       sqlite3VdbeAddOp(v, OP_MemInt, 1, pLevel->iLeftJoin);
01967       VdbeComment((v, "# record LEFT JOIN hit"));
01968       for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
01969         if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
01970         if( (pTerm->prereqAll & notReady)!=0 ) continue;
01971         assert( pTerm->pExpr );
01972         sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
01973         pTerm->flags |= TERM_CODED;
01974       }
01975     }
01976   }
01977 
01978 #ifdef SQLITE_TEST  /* For testing and debugging use only */
01979   /* Record in the query plan information about the current table
01980   ** and the index used to access it (if any).  If the table itself
01981   ** is not used, its name is just '{}'.  If no index is used
01982   ** the index is listed as "{}".  If the primary key is used the
01983   ** index name is '*'.
01984   */
01985   for(i=0; i<pTabList->nSrc; i++){
01986     char *z;
01987     int n;
01988     pLevel = &pWInfo->a[i];
01989     pTabItem = &pTabList->a[pLevel->iFrom];
01990     z = pTabItem->zAlias;
01991     if( z==0 ) z = pTabItem->pTab->zName;
01992     n = strlen(z);
01993     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
01994       if( pLevel->flags & WHERE_IDX_ONLY ){
01995         strcpy(&sqlite3_query_plan[nQPlan], "{}");
01996         nQPlan += 2;
01997       }else{
01998         strcpy(&sqlite3_query_plan[nQPlan], z);
01999         nQPlan += n;
02000       }
02001       sqlite3_query_plan[nQPlan++] = ' ';
02002     }
02003     if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
02004       strcpy(&sqlite3_query_plan[nQPlan], "* ");
02005       nQPlan += 2;
02006     }else if( pLevel->pIdx==0 ){
02007       strcpy(&sqlite3_query_plan[nQPlan], "{} ");
02008       nQPlan += 3;
02009     }else{
02010       n = strlen(pLevel->pIdx->zName);
02011       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
02012         strcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName);
02013         nQPlan += n;
02014         sqlite3_query_plan[nQPlan++] = ' ';
02015       }
02016     }
02017   }
02018   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
02019     sqlite3_query_plan[--nQPlan] = 0;
02020   }
02021   sqlite3_query_plan[nQPlan] = 0;
02022   nQPlan = 0;
02023 #endif /* SQLITE_TEST // Testing and debugging use only */
02024 
02025   /* Record the continuation address in the WhereInfo structure.  Then
02026   ** clean up and return.
02027   */
02028   pWInfo->iContinue = cont;
02029   whereClauseClear(&wc);
02030   return pWInfo;
02031 
02032   /* Jump here if malloc fails */
02033 whereBeginNoMem:
02034   whereClauseClear(&wc);
02035   sqliteFree(pWInfo);
02036   return 0;
02037 }
02038 
02039 /*
02040 ** Generate the end of the WHERE loop.  See comments on 
02041 ** sqlite3WhereBegin() for additional information.
02042 */
02043 void sqlite3WhereEnd(WhereInfo *pWInfo){
02044   Vdbe *v = pWInfo->pParse->pVdbe;
02045   int i;
02046   WhereLevel *pLevel;
02047   SrcList *pTabList = pWInfo->pTabList;
02048 
02049   /* Generate loop termination code.
02050   */
02051   for(i=pTabList->nSrc-1; i>=0; i--){
02052     pLevel = &pWInfo->a[i];
02053     sqlite3VdbeResolveLabel(v, pLevel->cont);
02054     if( pLevel->op!=OP_Noop ){
02055       sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
02056     }
02057     sqlite3VdbeResolveLabel(v, pLevel->brk);
02058     if( pLevel->nIn ){
02059       int *a;
02060       int j;
02061       for(j=pLevel->nIn, a=&pLevel->aInLoop[j*2-2]; j>0; j--, a-=2){
02062         sqlite3VdbeAddOp(v, OP_Next, a[0], a[1]);
02063         sqlite3VdbeJumpHere(v, a[1]-1);
02064       }
02065       sqliteFree(pLevel->aInLoop);
02066     }
02067     if( pLevel->iLeftJoin ){
02068       int addr;
02069       addr = sqlite3VdbeAddOp(v, OP_IfMemPos, pLevel->iLeftJoin, 0);
02070       sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
02071       if( pLevel->iIdxCur>=0 ){
02072         sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
02073       }
02074       sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
02075       sqlite3VdbeJumpHere(v, addr);
02076     }
02077   }
02078 
02079   /* The "break" point is here, just past the end of the outer loop.
02080   ** Set it.
02081   */
02082   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
02083 
02084   /* Close all of the cursors that were opened by sqlite3WhereBegin.
02085   */
02086   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
02087     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
02088     Table *pTab = pTabItem->pTab;
02089     assert( pTab!=0 );
02090     if( pTab->isTransient || pTab->pSelect ) continue;
02091     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
02092       sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
02093     }
02094     if( pLevel->pIdx!=0 ){
02095       sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
02096     }
02097 
02098     /* Make cursor substitutions for cases where we want to use
02099     ** just the index and never reference the table.
02100     ** 
02101     ** Calls to the code generator in between sqlite3WhereBegin and
02102     ** sqlite3WhereEnd will have created code that references the table
02103     ** directly.  This loop scans all that code looking for opcodes
02104     ** that reference the table and converts them into opcodes that
02105     ** reference the index.
02106     */
02107     if( pLevel->flags & WHERE_IDX_ONLY ){
02108       int k, j, last;
02109       VdbeOp *pOp;
02110       Index *pIdx = pLevel->pIdx;
02111 
02112       assert( pIdx!=0 );
02113       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
02114       last = sqlite3VdbeCurrentAddr(v);
02115       for(k=pWInfo->iTop; k<last; k++, pOp++){
02116         if( pOp->p1!=pLevel->iTabCur ) continue;
02117         if( pOp->opcode==OP_Column ){
02118           pOp->p1 = pLevel->iIdxCur;
02119           for(j=0; j<pIdx->nColumn; j++){
02120             if( pOp->p2==pIdx->aiColumn[j] ){
02121               pOp->p2 = j;
02122               break;
02123             }
02124           }
02125         }else if( pOp->opcode==OP_Rowid ){
02126           pOp->p1 = pLevel->iIdxCur;
02127           pOp->opcode = OP_IdxRowid;
02128         }else if( pOp->opcode==OP_NullRow ){
02129           pOp->opcode = OP_Noop;
02130         }
02131       }
02132     }
02133   }
02134 
02135   /* Final cleanup
02136   */
02137   sqliteFree(pWInfo);
02138   return;
02139 }