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 responsible 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.328 2008/11/03 09:06:06 danielk1977 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 ** Trace output macros
00030 */
00031 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
00032 int sqlite3WhereTrace = 0;
00033 #endif
00034 #if 0
00035 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
00036 #else
00037 # define WHERETRACE(X)
00038 #endif
00039 
00040 /* Forward reference
00041 */
00042 typedef struct WhereClause WhereClause;
00043 typedef struct ExprMaskSet ExprMaskSet;
00044 
00045 /*
00046 ** The query generator uses an array of instances of this structure to
00047 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
00048 ** clause subexpression is separated from the others by an AND operator.
00049 **
00050 ** All WhereTerms are collected into a single WhereClause structure.  
00051 ** The following identity holds:
00052 **
00053 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
00054 **
00055 ** When a term is of the form:
00056 **
00057 **              X <op> <expr>
00058 **
00059 ** where X is a column name and <op> is one of certain operators,
00060 ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
00061 ** cursor number and column number for X.  WhereTerm.operator records
00062 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
00063 ** use of a bitmask encoding for the operator allows us to search
00064 ** quickly for terms that match any of several different operators.
00065 **
00066 ** prereqRight and prereqAll record sets of cursor numbers,
00067 ** but they do so indirectly.  A single ExprMaskSet structure translates
00068 ** cursor number into bits and the translated bit is stored in the prereq
00069 ** fields.  The translation is used in order to maximize the number of
00070 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
00071 ** spread out over the non-negative integers.  For example, the cursor
00072 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The ExprMaskSet
00073 ** translates these sparse cursor numbers into consecutive integers
00074 ** beginning with 0 in order to make the best possible use of the available
00075 ** bits in the Bitmask.  So, in the example above, the cursor numbers
00076 ** would be mapped into integers 0 through 7.
00077 */
00078 typedef struct WhereTerm WhereTerm;
00079 struct WhereTerm {
00080   Expr *pExpr;            /* Pointer to the subexpression */
00081   i16 iParent;            /* Disable pWC->a[iParent] when this term disabled */
00082   i16 leftCursor;         /* Cursor number of X in "X <op> <expr>" */
00083   i16 leftColumn;         /* Column number of X in "X <op> <expr>" */
00084   u16 eOperator;          /* A WO_xx value describing <op> */
00085   u8 flags;               /* Bit flags.  See below */
00086   u8 nChild;              /* Number of children that must disable us */
00087   WhereClause *pWC;       /* The clause this term is part of */
00088   Bitmask prereqRight;    /* Bitmask of tables used by pRight */
00089   Bitmask prereqAll;      /* Bitmask of tables referenced by p */
00090 };
00091 
00092 /*
00093 ** Allowed values of WhereTerm.flags
00094 */
00095 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
00096 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
00097 #define TERM_CODED      0x04   /* This term is already coded */
00098 #define TERM_COPIED     0x08   /* Has a child */
00099 #define TERM_OR_OK      0x10   /* Used during OR-clause processing */
00100 
00101 /*
00102 ** An instance of the following structure holds all information about a
00103 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
00104 */
00105 struct WhereClause {
00106   Parse *pParse;           /* The parser context */
00107   ExprMaskSet *pMaskSet;   /* Mapping of table indices to bitmasks */
00108   int nTerm;               /* Number of terms */
00109   int nSlot;               /* Number of entries in a[] */
00110   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
00111   WhereTerm aStatic[10];   /* Initial static space for a[] */
00112 };
00113 
00114 /*
00115 ** An instance of the following structure keeps track of a mapping
00116 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
00117 **
00118 ** The VDBE cursor numbers are small integers contained in 
00119 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
00120 ** clause, the cursor numbers might not begin with 0 and they might
00121 ** contain gaps in the numbering sequence.  But we want to make maximum
00122 ** use of the bits in our bitmasks.  This structure provides a mapping
00123 ** from the sparse cursor numbers into consecutive integers beginning
00124 ** with 0.
00125 **
00126 ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
00127 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
00128 **
00129 ** For example, if the WHERE clause expression used these VDBE
00130 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  ExprMaskSet structure
00131 ** would map those cursor numbers into bits 0 through 5.
00132 **
00133 ** Note that the mapping is not necessarily ordered.  In the example
00134 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
00135 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
00136 ** does not really matter.  What is important is that sparse cursor
00137 ** numbers all get mapped into bit numbers that begin with 0 and contain
00138 ** no gaps.
00139 */
00140 struct ExprMaskSet {
00141   int n;                        /* Number of assigned cursor values */
00142   int ix[sizeof(Bitmask)*8];    /* Cursor assigned to each bit */
00143 };
00144 
00145 
00146 /*
00147 ** Bitmasks for the operators that indices are able to exploit.  An
00148 ** OR-ed combination of these values can be used when searching for
00149 ** terms in the where clause.
00150 */
00151 #define WO_IN     1
00152 #define WO_EQ     2
00153 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
00154 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
00155 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
00156 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
00157 #define WO_MATCH  64
00158 #define WO_ISNULL 128
00159 
00160 /*
00161 ** Value for flags returned by bestIndex().  
00162 **
00163 ** The least significant byte is reserved as a mask for WO_ values above.
00164 ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
00165 ** But if the table is the right table of a left join, WhereLevel.flags
00166 ** is set to WO_IN|WO_EQ.  The WhereLevel.flags field can then be used as
00167 ** the "op" parameter to findTerm when we are resolving equality constraints.
00168 ** ISNULL constraints will then not be used on the right table of a left
00169 ** join.  Tickets #2177 and #2189.
00170 */
00171 #define WHERE_ROWID_EQ     0x000100   /* rowid=EXPR or rowid IN (...) */
00172 #define WHERE_ROWID_RANGE  0x000200   /* rowid<EXPR and/or rowid>EXPR */
00173 #define WHERE_COLUMN_EQ    0x001000   /* x=EXPR or x IN (...) */
00174 #define WHERE_COLUMN_RANGE 0x002000   /* x<EXPR and/or x>EXPR */
00175 #define WHERE_COLUMN_IN    0x004000   /* x IN (...) */
00176 #define WHERE_TOP_LIMIT    0x010000   /* x<EXPR or x<=EXPR constraint */
00177 #define WHERE_BTM_LIMIT    0x020000   /* x>EXPR or x>=EXPR constraint */
00178 #define WHERE_IDX_ONLY     0x080000   /* Use index only - omit table */
00179 #define WHERE_ORDERBY      0x100000   /* Output will appear in correct order */
00180 #define WHERE_REVERSE      0x200000   /* Scan in reverse order */
00181 #define WHERE_UNIQUE       0x400000   /* Selects no more than one row */
00182 #define WHERE_VIRTUALTABLE 0x800000   /* Use virtual-table processing */
00183 
00184 /*
00185 ** Initialize a preallocated WhereClause structure.
00186 */
00187 static void whereClauseInit(
00188   WhereClause *pWC,        /* The WhereClause to be initialized */
00189   Parse *pParse,           /* The parsing context */
00190   ExprMaskSet *pMaskSet    /* Mapping from table indices to bitmasks */
00191 ){
00192   pWC->pParse = pParse;
00193   pWC->pMaskSet = pMaskSet;
00194   pWC->nTerm = 0;
00195   pWC->nSlot = ArraySize(pWC->aStatic);
00196   pWC->a = pWC->aStatic;
00197 }
00198 
00199 /*
00200 ** Deallocate a WhereClause structure.  The WhereClause structure
00201 ** itself is not freed.  This routine is the inverse of whereClauseInit().
00202 */
00203 static void whereClauseClear(WhereClause *pWC){
00204   int i;
00205   WhereTerm *a;
00206   sqlite3 *db = pWC->pParse->db;
00207   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
00208     if( a->flags & TERM_DYNAMIC ){
00209       sqlite3ExprDelete(db, a->pExpr);
00210     }
00211   }
00212   if( pWC->a!=pWC->aStatic ){
00213     sqlite3DbFree(db, pWC->a);
00214   }
00215 }
00216 
00217 /*
00218 ** Add a new entries to the WhereClause structure.  Increase the allocated
00219 ** space as necessary.
00220 **
00221 ** If the flags argument includes TERM_DYNAMIC, then responsibility
00222 ** for freeing the expression p is assumed by the WhereClause object.
00223 **
00224 ** WARNING:  This routine might reallocate the space used to store
00225 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
00226 ** calling this routine.  Such pointers may be reinitialized by referencing
00227 ** the pWC->a[] array.
00228 */
00229 static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
00230   WhereTerm *pTerm;
00231   int idx;
00232   if( pWC->nTerm>=pWC->nSlot ){
00233     WhereTerm *pOld = pWC->a;
00234     sqlite3 *db = pWC->pParse->db;
00235     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
00236     if( pWC->a==0 ){
00237       if( flags & TERM_DYNAMIC ){
00238         sqlite3ExprDelete(db, p);
00239       }
00240       pWC->a = pOld;
00241       return 0;
00242     }
00243     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
00244     if( pOld!=pWC->aStatic ){
00245       sqlite3DbFree(db, pOld);
00246     }
00247     pWC->nSlot *= 2;
00248   }
00249   pTerm = &pWC->a[idx = pWC->nTerm];
00250   pWC->nTerm++;
00251   pTerm->pExpr = p;
00252   pTerm->flags = flags;
00253   pTerm->pWC = pWC;
00254   pTerm->iParent = -1;
00255   return idx;
00256 }
00257 
00258 /*
00259 ** This routine identifies subexpressions in the WHERE clause where
00260 ** each subexpression is separated by the AND operator or some other
00261 ** operator specified in the op parameter.  The WhereClause structure
00262 ** is filled with pointers to subexpressions.  For example:
00263 **
00264 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
00265 **           \________/     \_______________/     \________________/
00266 **            slot[0]            slot[1]               slot[2]
00267 **
00268 ** The original WHERE clause in pExpr is unaltered.  All this routine
00269 ** does is make slot[] entries point to substructure within pExpr.
00270 **
00271 ** In the previous sentence and in the diagram, "slot[]" refers to
00272 ** the WhereClause.a[] array.  This array grows as needed to contain
00273 ** all terms of the WHERE clause.
00274 */
00275 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
00276   if( pExpr==0 ) return;
00277   if( pExpr->op!=op ){
00278     whereClauseInsert(pWC, pExpr, 0);
00279   }else{
00280     whereSplit(pWC, pExpr->pLeft, op);
00281     whereSplit(pWC, pExpr->pRight, op);
00282   }
00283 }
00284 
00285 /*
00286 ** Initialize an expression mask set
00287 */
00288 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
00289 
00290 /*
00291 ** Return the bitmask for the given cursor number.  Return 0 if
00292 ** iCursor is not in the set.
00293 */
00294 static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
00295   int i;
00296   for(i=0; i<pMaskSet->n; i++){
00297     if( pMaskSet->ix[i]==iCursor ){
00298       return ((Bitmask)1)<<i;
00299     }
00300   }
00301   return 0;
00302 }
00303 
00304 /*
00305 ** Create a new mask for cursor iCursor.
00306 **
00307 ** There is one cursor per table in the FROM clause.  The number of
00308 ** tables in the FROM clause is limited by a test early in the
00309 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
00310 ** array will never overflow.
00311 */
00312 static void createMask(ExprMaskSet *pMaskSet, int iCursor){
00313   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
00314   pMaskSet->ix[pMaskSet->n++] = iCursor;
00315 }
00316 
00317 /*
00318 ** This routine walks (recursively) an expression tree and generates
00319 ** a bitmask indicating which tables are used in that expression
00320 ** tree.
00321 **
00322 ** In order for this routine to work, the calling function must have
00323 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
00324 ** the header comment on that routine for additional information.
00325 ** The sqlite3ResolveExprNames() routines looks for column names and
00326 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
00327 ** the VDBE cursor number of the table.  This routine just has to
00328 ** translate the cursor numbers into bitmask values and OR all
00329 ** the bitmasks together.
00330 */
00331 static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
00332 static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
00333 static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
00334   Bitmask mask = 0;
00335   if( p==0 ) return 0;
00336   if( p->op==TK_COLUMN ){
00337     mask = getMask(pMaskSet, p->iTable);
00338     return mask;
00339   }
00340   mask = exprTableUsage(pMaskSet, p->pRight);
00341   mask |= exprTableUsage(pMaskSet, p->pLeft);
00342   mask |= exprListTableUsage(pMaskSet, p->pList);
00343   mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
00344   return mask;
00345 }
00346 static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
00347   int i;
00348   Bitmask mask = 0;
00349   if( pList ){
00350     for(i=0; i<pList->nExpr; i++){
00351       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
00352     }
00353   }
00354   return mask;
00355 }
00356 static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
00357   Bitmask mask = 0;
00358   while( pS ){
00359     mask |= exprListTableUsage(pMaskSet, pS->pEList);
00360     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
00361     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
00362     mask |= exprTableUsage(pMaskSet, pS->pWhere);
00363     mask |= exprTableUsage(pMaskSet, pS->pHaving);
00364     pS = pS->pPrior;
00365   }
00366   return mask;
00367 }
00368 
00369 /*
00370 ** Return TRUE if the given operator is one of the operators that is
00371 ** allowed for an indexable WHERE clause term.  The allowed operators are
00372 ** "=", "<", ">", "<=", ">=", and "IN".
00373 */
00374 static int allowedOp(int op){
00375   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
00376   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
00377   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
00378   assert( TK_GE==TK_EQ+4 );
00379   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
00380 }
00381 
00382 /*
00383 ** Swap two objects of type T.
00384 */
00385 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
00386 
00387 /*
00388 ** Commute a comparison operator.  Expressions of the form "X op Y"
00389 ** are converted into "Y op X".
00390 **
00391 ** If a collation sequence is associated with either the left or right
00392 ** side of the comparison, it remains associated with the same side after
00393 ** the commutation. So "Y collate NOCASE op X" becomes 
00394 ** "X collate NOCASE op Y". This is because any collation sequence on
00395 ** the left hand side of a comparison overrides any collation sequence 
00396 ** attached to the right. For the same reason the EP_ExpCollate flag
00397 ** is not commuted.
00398 */
00399 static void exprCommute(Parse *pParse, Expr *pExpr){
00400   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
00401   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
00402   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
00403   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
00404   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
00405   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
00406   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
00407   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
00408   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
00409   if( pExpr->op>=TK_GT ){
00410     assert( TK_LT==TK_GT+2 );
00411     assert( TK_GE==TK_LE+2 );
00412     assert( TK_GT>TK_EQ );
00413     assert( TK_GT<TK_LE );
00414     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
00415     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
00416   }
00417 }
00418 
00419 /*
00420 ** Translate from TK_xx operator to WO_xx bitmask.
00421 */
00422 static int operatorMask(int op){
00423   int c;
00424   assert( allowedOp(op) );
00425   if( op==TK_IN ){
00426     c = WO_IN;
00427   }else if( op==TK_ISNULL ){
00428     c = WO_ISNULL;
00429   }else{
00430     c = WO_EQ<<(op-TK_EQ);
00431   }
00432   assert( op!=TK_ISNULL || c==WO_ISNULL );
00433   assert( op!=TK_IN || c==WO_IN );
00434   assert( op!=TK_EQ || c==WO_EQ );
00435   assert( op!=TK_LT || c==WO_LT );
00436   assert( op!=TK_LE || c==WO_LE );
00437   assert( op!=TK_GT || c==WO_GT );
00438   assert( op!=TK_GE || c==WO_GE );
00439   return c;
00440 }
00441 
00442 /*
00443 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
00444 ** where X is a reference to the iColumn of table iCur and <op> is one of
00445 ** the WO_xx operator codes specified by the op parameter.
00446 ** Return a pointer to the term.  Return 0 if not found.
00447 */
00448 static WhereTerm *findTerm(
00449   WhereClause *pWC,     /* The WHERE clause to be searched */
00450   int iCur,             /* Cursor number of LHS */
00451   int iColumn,          /* Column number of LHS */
00452   Bitmask notReady,     /* RHS must not overlap with this mask */
00453   u16 op,               /* Mask of WO_xx values describing operator */
00454   Index *pIdx           /* Must be compatible with this index, if not NULL */
00455 ){
00456   WhereTerm *pTerm;
00457   int k;
00458   assert( iCur>=0 );
00459   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
00460     if( pTerm->leftCursor==iCur
00461        && (pTerm->prereqRight & notReady)==0
00462        && pTerm->leftColumn==iColumn
00463        && (pTerm->eOperator & op)!=0
00464     ){
00465       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
00466         Expr *pX = pTerm->pExpr;
00467         CollSeq *pColl;
00468         char idxaff;
00469         int j;
00470         Parse *pParse = pWC->pParse;
00471 
00472         idxaff = pIdx->pTable->aCol[iColumn].affinity;
00473         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
00474 
00475         /* Figure out the collation sequence required from an index for
00476         ** it to be useful for optimising expression pX. Store this
00477         ** value in variable pColl.
00478         */
00479         assert(pX->pLeft);
00480         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
00481         if( !pColl ){
00482           pColl = pParse->db->pDfltColl;
00483         }
00484 
00485         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
00486           if( NEVER(j>=pIdx->nColumn) ) return 0;
00487         }
00488         if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
00489       }
00490       return pTerm;
00491     }
00492   }
00493   return 0;
00494 }
00495 
00496 /* Forward reference */
00497 static void exprAnalyze(SrcList*, WhereClause*, int);
00498 
00499 /*
00500 ** Call exprAnalyze on all terms in a WHERE clause.  
00501 **
00502 **
00503 */
00504 static void exprAnalyzeAll(
00505   SrcList *pTabList,       /* the FROM clause */
00506   WhereClause *pWC         /* the WHERE clause to be analyzed */
00507 ){
00508   int i;
00509   for(i=pWC->nTerm-1; i>=0; i--){
00510     exprAnalyze(pTabList, pWC, i);
00511   }
00512 }
00513 
00514 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
00515 /*
00516 ** Check to see if the given expression is a LIKE or GLOB operator that
00517 ** can be optimized using inequality constraints.  Return TRUE if it is
00518 ** so and false if not.
00519 **
00520 ** In order for the operator to be optimizible, the RHS must be a string
00521 ** literal that does not begin with a wildcard.  
00522 */
00523 static int isLikeOrGlob(
00524   Parse *pParse,    /* Parsing and code generating context */
00525   Expr *pExpr,      /* Test this expression */
00526   int *pnPattern,   /* Number of non-wildcard prefix characters */
00527   int *pisComplete, /* True if the only wildcard is % in the last character */
00528   int *pnoCase      /* True if uppercase is equivalent to lowercase */
00529 ){
00530   const char *z;
00531   Expr *pRight, *pLeft;
00532   ExprList *pList;
00533   int c, cnt;
00534   char wc[3];
00535   CollSeq *pColl;
00536   sqlite3 *db = pParse->db;
00537 
00538   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
00539     return 0;
00540   }
00541 #ifdef SQLITE_EBCDIC
00542   if( *pnoCase ) return 0;
00543 #endif
00544   pList = pExpr->pList;
00545   pRight = pList->a[0].pExpr;
00546   if( pRight->op!=TK_STRING
00547    && (pRight->op!=TK_REGISTER || pRight->iColumn!=TK_STRING) ){
00548     return 0;
00549   }
00550   pLeft = pList->a[1].pExpr;
00551   if( pLeft->op!=TK_COLUMN ){
00552     return 0;
00553   }
00554   pColl = sqlite3ExprCollSeq(pParse, pLeft);
00555   assert( pColl!=0 || pLeft->iColumn==-1 );
00556   if( pColl==0 ){
00557     /* No collation is defined for the ROWID.  Use the default. */
00558     pColl = db->pDfltColl;
00559   }
00560   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
00561       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
00562     return 0;
00563   }
00564   sqlite3DequoteExpr(db, pRight);
00565   z = (char *)pRight->token.z;
00566   cnt = 0;
00567   if( z ){
00568     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
00569   }
00570   if( cnt==0 || 255==(u8)z[cnt] ){
00571     return 0;
00572   }
00573   *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
00574   *pnPattern = cnt;
00575   return 1;
00576 }
00577 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
00578 
00579 
00580 #ifndef SQLITE_OMIT_VIRTUALTABLE
00581 /*
00582 ** Check to see if the given expression is of the form
00583 **
00584 **         column MATCH expr
00585 **
00586 ** If it is then return TRUE.  If not, return FALSE.
00587 */
00588 static int isMatchOfColumn(
00589   Expr *pExpr      /* Test this expression */
00590 ){
00591   ExprList *pList;
00592 
00593   if( pExpr->op!=TK_FUNCTION ){
00594     return 0;
00595   }
00596   if( pExpr->token.n!=5 ||
00597        sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
00598     return 0;
00599   }
00600   pList = pExpr->pList;
00601   if( pList->nExpr!=2 ){
00602     return 0;
00603   }
00604   if( pList->a[1].pExpr->op != TK_COLUMN ){
00605     return 0;
00606   }
00607   return 1;
00608 }
00609 #endif /* SQLITE_OMIT_VIRTUALTABLE */
00610 
00611 /*
00612 ** If the pBase expression originated in the ON or USING clause of
00613 ** a join, then transfer the appropriate markings over to derived.
00614 */
00615 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
00616   pDerived->flags |= pBase->flags & EP_FromJoin;
00617   pDerived->iRightJoinTable = pBase->iRightJoinTable;
00618 }
00619 
00620 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
00621 /*
00622 ** Return TRUE if the given term of an OR clause can be converted
00623 ** into an IN clause.  The iCursor and iColumn define the left-hand
00624 ** side of the IN clause.
00625 **
00626 ** The context is that we have multiple OR-connected equality terms
00627 ** like this:
00628 **
00629 **           a=<expr1> OR  a=<expr2> OR b=<expr3>  OR ...
00630 **
00631 ** The pOrTerm input to this routine corresponds to a single term of
00632 ** this OR clause.  In order for the term to be a candidate for
00633 ** conversion to an IN operator, the following must be true:
00634 **
00635 **     *  The left-hand side of the term must be the column which
00636 **        is identified by iCursor and iColumn.
00637 **
00638 **     *  If the right-hand side is also a column, then the affinities
00639 **        of both right and left sides must be such that no type
00640 **        conversions are required on the right.  (Ticket #2249)
00641 **
00642 ** If both of these conditions are true, then return true.  Otherwise
00643 ** return false.
00644 */
00645 static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
00646   int affLeft, affRight;
00647   assert( pOrTerm->eOperator==WO_EQ );
00648   if( pOrTerm->leftCursor!=iCursor ){
00649     return 0;
00650   }
00651   if( pOrTerm->leftColumn!=iColumn ){
00652     return 0;
00653   }
00654   affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
00655   if( affRight==0 ){
00656     return 1;
00657   }
00658   affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
00659   if( affRight!=affLeft ){
00660     return 0;
00661   }
00662   return 1;
00663 }
00664 
00665 /*
00666 ** Return true if the given term of an OR clause can be ignored during
00667 ** a check to make sure all OR terms are candidates for optimization.
00668 ** In other words, return true if a call to the orTermIsOptCandidate()
00669 ** above returned false but it is not necessary to disqualify the
00670 ** optimization.
00671 **
00672 ** Suppose the original OR phrase was this:
00673 **
00674 **           a=4  OR  a=11  OR  a=b
00675 **
00676 ** During analysis, the third term gets flipped around and duplicate
00677 ** so that we are left with this:
00678 **
00679 **           a=4  OR  a=11  OR  a=b  OR  b=a
00680 **
00681 ** Since the last two terms are duplicates, only one of them
00682 ** has to qualify in order for the whole phrase to qualify.  When
00683 ** this routine is called, we know that pOrTerm did not qualify.
00684 ** This routine merely checks to see if pOrTerm has a duplicate that
00685 ** might qualify.  If there is a duplicate that has not yet been
00686 ** disqualified, then return true.  If there are no duplicates, or
00687 ** the duplicate has also been disqualified, return false.
00688 */
00689 static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
00690   if( pOrTerm->flags & TERM_COPIED ){
00691     /* This is the original term.  The duplicate is to the left had
00692     ** has not yet been analyzed and thus has not yet been disqualified. */
00693     return 1;
00694   }
00695   if( (pOrTerm->flags & TERM_VIRTUAL)!=0
00696      && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
00697     /* This is a duplicate term.  The original qualified so this one
00698     ** does not have to. */
00699     return 1;
00700   }
00701   /* This is either a singleton term or else it is a duplicate for
00702   ** which the original did not qualify.  Either way we are done for. */
00703   return 0;
00704 }
00705 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
00706 
00707 /*
00708 ** The input to this routine is an WhereTerm structure with only the
00709 ** "pExpr" field filled in.  The job of this routine is to analyze the
00710 ** subexpression and populate all the other fields of the WhereTerm
00711 ** structure.
00712 **
00713 ** If the expression is of the form "<expr> <op> X" it gets commuted
00714 ** to the standard form of "X <op> <expr>".  If the expression is of
00715 ** the form "X <op> Y" where both X and Y are columns, then the original
00716 ** expression is unchanged and a new virtual expression of the form
00717 ** "Y <op> X" is added to the WHERE clause and analyzed separately.
00718 */
00719 static void exprAnalyze(
00720   SrcList *pSrc,            /* the FROM clause */
00721   WhereClause *pWC,         /* the WHERE clause */
00722   int idxTerm               /* Index of the term to be analyzed */
00723 ){
00724   WhereTerm *pTerm;
00725   ExprMaskSet *pMaskSet;
00726   Expr *pExpr;
00727   Bitmask prereqLeft;
00728   Bitmask prereqAll;
00729   Bitmask extraRight = 0;
00730   int nPattern;
00731   int isComplete;
00732   int noCase;
00733   int op;
00734   Parse *pParse = pWC->pParse;
00735   sqlite3 *db = pParse->db;
00736 
00737   if( db->mallocFailed ){
00738     return;
00739   }
00740   pTerm = &pWC->a[idxTerm];
00741   pMaskSet = pWC->pMaskSet;
00742   pExpr = pTerm->pExpr;
00743   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
00744   op = pExpr->op;
00745   if( op==TK_IN ){
00746     assert( pExpr->pRight==0 );
00747     pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
00748                           | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
00749   }else if( op==TK_ISNULL ){
00750     pTerm->prereqRight = 0;
00751   }else{
00752     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
00753   }
00754   prereqAll = exprTableUsage(pMaskSet, pExpr);
00755   if( ExprHasProperty(pExpr, EP_FromJoin) ){
00756     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
00757     prereqAll |= x;
00758     extraRight = x-1;  /* ON clause terms may not be used with an index
00759                        ** on left table of a LEFT JOIN.  Ticket #3015 */
00760   }
00761   pTerm->prereqAll = prereqAll;
00762   pTerm->leftCursor = -1;
00763   pTerm->iParent = -1;
00764   pTerm->eOperator = 0;
00765   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
00766     Expr *pLeft = pExpr->pLeft;
00767     Expr *pRight = pExpr->pRight;
00768     if( pLeft->op==TK_COLUMN ){
00769       pTerm->leftCursor = pLeft->iTable;
00770       pTerm->leftColumn = pLeft->iColumn;
00771       pTerm->eOperator = operatorMask(op);
00772     }
00773     if( pRight && pRight->op==TK_COLUMN ){
00774       WhereTerm *pNew;
00775       Expr *pDup;
00776       if( pTerm->leftCursor>=0 ){
00777         int idxNew;
00778         pDup = sqlite3ExprDup(db, pExpr);
00779         if( db->mallocFailed ){
00780           sqlite3ExprDelete(db, pDup);
00781           return;
00782         }
00783         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
00784         if( idxNew==0 ) return;
00785         pNew = &pWC->a[idxNew];
00786         pNew->iParent = idxTerm;
00787         pTerm = &pWC->a[idxTerm];
00788         pTerm->nChild = 1;
00789         pTerm->flags |= TERM_COPIED;
00790       }else{
00791         pDup = pExpr;
00792         pNew = pTerm;
00793       }
00794       exprCommute(pParse, pDup);
00795       pLeft = pDup->pLeft;
00796       pNew->leftCursor = pLeft->iTable;
00797       pNew->leftColumn = pLeft->iColumn;
00798       pNew->prereqRight = prereqLeft;
00799       pNew->prereqAll = prereqAll;
00800       pNew->eOperator = operatorMask(pDup->op);
00801     }
00802   }
00803 
00804 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
00805   /* If a term is the BETWEEN operator, create two new virtual terms
00806   ** that define the range that the BETWEEN implements.
00807   */
00808   else if( pExpr->op==TK_BETWEEN ){
00809     ExprList *pList = pExpr->pList;
00810     int i;
00811     static const u8 ops[] = {TK_GE, TK_LE};
00812     assert( pList!=0 );
00813     assert( pList->nExpr==2 );
00814     for(i=0; i<2; i++){
00815       Expr *pNewExpr;
00816       int idxNew;
00817       pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
00818                              sqlite3ExprDup(db, pList->a[i].pExpr), 0);
00819       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
00820       exprAnalyze(pSrc, pWC, idxNew);
00821       pTerm = &pWC->a[idxTerm];
00822       pWC->a[idxNew].iParent = idxTerm;
00823     }
00824     pTerm->nChild = 2;
00825   }
00826 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
00827 
00828 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
00829   /* Attempt to convert OR-connected terms into an IN operator so that
00830   ** they can make use of indices.  Example:
00831   **
00832   **      x = expr1  OR  expr2 = x  OR  x = expr3
00833   **
00834   ** is converted into
00835   **
00836   **      x IN (expr1,expr2,expr3)
00837   **
00838   ** This optimization must be omitted if OMIT_SUBQUERY is defined because
00839   ** the compiler for the the IN operator is part of sub-queries.
00840   */
00841   else if( pExpr->op==TK_OR ){
00842     int ok;
00843     int i, j;
00844     int iColumn, iCursor;
00845     WhereClause sOr;
00846     WhereTerm *pOrTerm;
00847 
00848     assert( (pTerm->flags & TERM_DYNAMIC)==0 );
00849     whereClauseInit(&sOr, pWC->pParse, pMaskSet);
00850     whereSplit(&sOr, pExpr, TK_OR);
00851     exprAnalyzeAll(pSrc, &sOr);
00852     assert( sOr.nTerm>=2 );
00853     j = 0;
00854     if( db->mallocFailed ) goto or_not_possible;
00855     do{
00856       assert( j<sOr.nTerm );
00857       iColumn = sOr.a[j].leftColumn;
00858       iCursor = sOr.a[j].leftCursor;
00859       ok = iCursor>=0;
00860       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
00861         if( pOrTerm->eOperator!=WO_EQ ){
00862           goto or_not_possible;
00863         }
00864         if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
00865           pOrTerm->flags |= TERM_OR_OK;
00866         }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
00867           pOrTerm->flags &= ~TERM_OR_OK;
00868         }else{
00869           ok = 0;
00870         }
00871       }
00872     }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
00873     if( ok ){
00874       ExprList *pList = 0;
00875       Expr *pNew, *pDup;
00876       Expr *pLeft = 0;
00877       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0; i--, pOrTerm++){
00878         if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
00879         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
00880         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
00881         pLeft = pOrTerm->pExpr->pLeft;
00882       }
00883       assert( pLeft!=0 );
00884       pDup = sqlite3ExprDup(db, pLeft);
00885       pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
00886       if( pNew ){
00887         int idxNew;
00888         transferJoinMarkings(pNew, pExpr);
00889         pNew->pList = pList;
00890         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
00891         exprAnalyze(pSrc, pWC, idxNew);
00892         pTerm = &pWC->a[idxTerm];
00893         pWC->a[idxNew].iParent = idxTerm;
00894         pTerm->nChild = 1;
00895       }else{
00896         sqlite3ExprListDelete(db, pList);
00897       }
00898     }
00899 or_not_possible:
00900     whereClauseClear(&sOr);
00901   }
00902 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
00903 
00904 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
00905   /* Add constraints to reduce the search space on a LIKE or GLOB
00906   ** operator.
00907   **
00908   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
00909   **
00910   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
00911   **
00912   ** The last character of the prefix "abc" is incremented to form the
00913   ** termination condition "abd".
00914   */
00915   if( isLikeOrGlob(pParse, pExpr, &nPattern, &isComplete, &noCase) ){
00916     Expr *pLeft, *pRight;
00917     Expr *pStr1, *pStr2;
00918     Expr *pNewExpr1, *pNewExpr2;
00919     int idxNew1, idxNew2;
00920 
00921     pLeft = pExpr->pList->a[1].pExpr;
00922     pRight = pExpr->pList->a[0].pExpr;
00923     pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
00924     if( pStr1 ){
00925       sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
00926       pStr1->token.n = nPattern;
00927       pStr1->flags = EP_Dequoted;
00928     }
00929     pStr2 = sqlite3ExprDup(db, pStr1);
00930     if( !db->mallocFailed ){
00931       u8 c, *pC;
00932       assert( pStr2->token.dyn );
00933       pC = (u8*)&pStr2->token.z[nPattern-1];
00934       c = *pC;
00935       if( noCase ){
00936         if( c=='@' ) isComplete = 0;
00937         c = sqlite3UpperToLower[c];
00938       }
00939       *pC = c + 1;
00940     }
00941     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
00942     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
00943     exprAnalyze(pSrc, pWC, idxNew1);
00944     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
00945     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
00946     exprAnalyze(pSrc, pWC, idxNew2);
00947     pTerm = &pWC->a[idxTerm];
00948     if( isComplete ){
00949       pWC->a[idxNew1].iParent = idxTerm;
00950       pWC->a[idxNew2].iParent = idxTerm;
00951       pTerm->nChild = 2;
00952     }
00953   }
00954 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
00955 
00956 #ifndef SQLITE_OMIT_VIRTUALTABLE
00957   /* Add a WO_MATCH auxiliary term to the constraint set if the
00958   ** current expression is of the form:  column MATCH expr.
00959   ** This information is used by the xBestIndex methods of
00960   ** virtual tables.  The native query optimizer does not attempt
00961   ** to do anything with MATCH functions.
00962   */
00963   if( isMatchOfColumn(pExpr) ){
00964     int idxNew;
00965     Expr *pRight, *pLeft;
00966     WhereTerm *pNewTerm;
00967     Bitmask prereqColumn, prereqExpr;
00968 
00969     pRight = pExpr->pList->a[0].pExpr;
00970     pLeft = pExpr->pList->a[1].pExpr;
00971     prereqExpr = exprTableUsage(pMaskSet, pRight);
00972     prereqColumn = exprTableUsage(pMaskSet, pLeft);
00973     if( (prereqExpr & prereqColumn)==0 ){
00974       Expr *pNewExpr;
00975       pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
00976       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
00977       pNewTerm = &pWC->a[idxNew];
00978       pNewTerm->prereqRight = prereqExpr;
00979       pNewTerm->leftCursor = pLeft->iTable;
00980       pNewTerm->leftColumn = pLeft->iColumn;
00981       pNewTerm->eOperator = WO_MATCH;
00982       pNewTerm->iParent = idxTerm;
00983       pTerm = &pWC->a[idxTerm];
00984       pTerm->nChild = 1;
00985       pTerm->flags |= TERM_COPIED;
00986       pNewTerm->prereqAll = pTerm->prereqAll;
00987     }
00988   }
00989 #endif /* SQLITE_OMIT_VIRTUALTABLE */
00990 
00991   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
00992   ** an index for tables to the left of the join.
00993   */
00994   pTerm->prereqRight |= extraRight;
00995 }
00996 
00997 /*
00998 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
00999 ** a reference to any table other than the iBase table.
01000 */
01001 static int referencesOtherTables(
01002   ExprList *pList,          /* Search expressions in ths list */
01003   ExprMaskSet *pMaskSet,    /* Mapping from tables to bitmaps */
01004   int iFirst,               /* Be searching with the iFirst-th expression */
01005   int iBase                 /* Ignore references to this table */
01006 ){
01007   Bitmask allowed = ~getMask(pMaskSet, iBase);
01008   while( iFirst<pList->nExpr ){
01009     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
01010       return 1;
01011     }
01012   }
01013   return 0;
01014 }
01015 
01016 
01017 /*
01018 ** This routine decides if pIdx can be used to satisfy the ORDER BY
01019 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
01020 ** ORDER BY clause, this routine returns 0.
01021 **
01022 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
01023 ** left-most table in the FROM clause of that same SELECT statement and
01024 ** the table has a cursor number of "base".  pIdx is an index on pTab.
01025 **
01026 ** nEqCol is the number of columns of pIdx that are used as equality
01027 ** constraints.  Any of these columns may be missing from the ORDER BY
01028 ** clause and the match can still be a success.
01029 **
01030 ** All terms of the ORDER BY that match against the index must be either
01031 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
01032 ** index do not need to satisfy this constraint.)  The *pbRev value is
01033 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
01034 ** the ORDER BY clause is all ASC.
01035 */
01036 static int isSortingIndex(
01037   Parse *pParse,          /* Parsing context */
01038   ExprMaskSet *pMaskSet,  /* Mapping from table indices to bitmaps */
01039   Index *pIdx,            /* The index we are testing */
01040   int base,               /* Cursor number for the table to be sorted */
01041   ExprList *pOrderBy,     /* The ORDER BY clause */
01042   int nEqCol,             /* Number of index columns with == constraints */
01043   int *pbRev              /* Set to 1 if ORDER BY is DESC */
01044 ){
01045   int i, j;                       /* Loop counters */
01046   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
01047   int nTerm;                      /* Number of ORDER BY terms */
01048   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
01049   sqlite3 *db = pParse->db;
01050 
01051   assert( pOrderBy!=0 );
01052   nTerm = pOrderBy->nExpr;
01053   assert( nTerm>0 );
01054 
01055   /* Match terms of the ORDER BY clause against columns of
01056   ** the index.
01057   **
01058   ** Note that indices have pIdx->nColumn regular columns plus
01059   ** one additional column containing the rowid.  The rowid column
01060   ** of the index is also allowed to match against the ORDER BY
01061   ** clause.
01062   */
01063   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
01064     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
01065     CollSeq *pColl;    /* The collating sequence of pExpr */
01066     int termSortOrder; /* Sort order for this term */
01067     int iColumn;       /* The i-th column of the index.  -1 for rowid */
01068     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
01069     const char *zColl; /* Name of the collating sequence for i-th index term */
01070 
01071     pExpr = pTerm->pExpr;
01072     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
01073       /* Can not use an index sort on anything that is not a column in the
01074       ** left-most table of the FROM clause */
01075       break;
01076     }
01077     pColl = sqlite3ExprCollSeq(pParse, pExpr);
01078     if( !pColl ){
01079       pColl = db->pDfltColl;
01080     }
01081     if( i<pIdx->nColumn ){
01082       iColumn = pIdx->aiColumn[i];
01083       if( iColumn==pIdx->pTable->iPKey ){
01084         iColumn = -1;
01085       }
01086       iSortOrder = pIdx->aSortOrder[i];
01087       zColl = pIdx->azColl[i];
01088     }else{
01089       iColumn = -1;
01090       iSortOrder = 0;
01091       zColl = pColl->zName;
01092     }
01093     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
01094       /* Term j of the ORDER BY clause does not match column i of the index */
01095       if( i<nEqCol ){
01096         /* If an index column that is constrained by == fails to match an
01097         ** ORDER BY term, that is OK.  Just ignore that column of the index
01098         */
01099         continue;
01100       }else if( i==pIdx->nColumn ){
01101         /* Index column i is the rowid.  All other terms match. */
01102         break;
01103       }else{
01104         /* If an index column fails to match and is not constrained by ==
01105         ** then the index cannot satisfy the ORDER BY constraint.
01106         */
01107         return 0;
01108       }
01109     }
01110     assert( pIdx->aSortOrder!=0 );
01111     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
01112     assert( iSortOrder==0 || iSortOrder==1 );
01113     termSortOrder = iSortOrder ^ pTerm->sortOrder;
01114     if( i>nEqCol ){
01115       if( termSortOrder!=sortOrder ){
01116         /* Indices can only be used if all ORDER BY terms past the
01117         ** equality constraints are all either DESC or ASC. */
01118         return 0;
01119       }
01120     }else{
01121       sortOrder = termSortOrder;
01122     }
01123     j++;
01124     pTerm++;
01125     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
01126       /* If the indexed column is the primary key and everything matches
01127       ** so far and none of the ORDER BY terms to the right reference other
01128       ** tables in the join, then we are assured that the index can be used 
01129       ** to sort because the primary key is unique and so none of the other
01130       ** columns will make any difference
01131       */
01132       j = nTerm;
01133     }
01134   }
01135 
01136   *pbRev = sortOrder!=0;
01137   if( j>=nTerm ){
01138     /* All terms of the ORDER BY clause are covered by this index so
01139     ** this index can be used for sorting. */
01140     return 1;
01141   }
01142   if( pIdx->onError!=OE_None && i==pIdx->nColumn
01143       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
01144     /* All terms of this index match some prefix of the ORDER BY clause
01145     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
01146     ** clause reference other tables in a join.  If this is all true then
01147     ** the order by clause is superfluous. */
01148     return 1;
01149   }
01150   return 0;
01151 }
01152 
01153 /*
01154 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
01155 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
01156 ** true for reverse ROWID and false for forward ROWID order.
01157 */
01158 static int sortableByRowid(
01159   int base,               /* Cursor number for table to be sorted */
01160   ExprList *pOrderBy,     /* The ORDER BY clause */
01161   ExprMaskSet *pMaskSet,  /* Mapping from tables to bitmaps */
01162   int *pbRev              /* Set to 1 if ORDER BY is DESC */
01163 ){
01164   Expr *p;
01165 
01166   assert( pOrderBy!=0 );
01167   assert( pOrderBy->nExpr>0 );
01168   p = pOrderBy->a[0].pExpr;
01169   if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
01170     && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
01171     *pbRev = pOrderBy->a[0].sortOrder;
01172     return 1;
01173   }
01174   return 0;
01175 }
01176 
01177 /*
01178 ** Prepare a crude estimate of the logarithm of the input value.
01179 ** The results need not be exact.  This is only used for estimating
01180 ** the total cost of performing operations with O(logN) or O(NlogN)
01181 ** complexity.  Because N is just a guess, it is no great tragedy if
01182 ** logN is a little off.
01183 */
01184 static double estLog(double N){
01185   double logN = 1;
01186   double x = 10;
01187   while( N>x ){
01188     logN += 1;
01189     x *= 10;
01190   }
01191   return logN;
01192 }
01193 
01194 /*
01195 ** Two routines for printing the content of an sqlite3_index_info
01196 ** structure.  Used for testing and debugging only.  If neither
01197 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
01198 ** are no-ops.
01199 */
01200 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
01201 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
01202   int i;
01203   if( !sqlite3WhereTrace ) return;
01204   for(i=0; i<p->nConstraint; i++){
01205     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
01206        i,
01207        p->aConstraint[i].iColumn,
01208        p->aConstraint[i].iTermOffset,
01209        p->aConstraint[i].op,
01210        p->aConstraint[i].usable);
01211   }
01212   for(i=0; i<p->nOrderBy; i++){
01213     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
01214        i,
01215        p->aOrderBy[i].iColumn,
01216        p->aOrderBy[i].desc);
01217   }
01218 }
01219 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
01220   int i;
01221   if( !sqlite3WhereTrace ) return;
01222   for(i=0; i<p->nConstraint; i++){
01223     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
01224        i,
01225        p->aConstraintUsage[i].argvIndex,
01226        p->aConstraintUsage[i].omit);
01227   }
01228   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
01229   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
01230   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
01231   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
01232 }
01233 #else
01234 #define TRACE_IDX_INPUTS(A)
01235 #define TRACE_IDX_OUTPUTS(A)
01236 #endif
01237 
01238 #ifndef SQLITE_OMIT_VIRTUALTABLE
01239 /*
01240 ** Compute the best index for a virtual table.
01241 **
01242 ** The best index is computed by the xBestIndex method of the virtual
01243 ** table module.  This routine is really just a wrapper that sets up
01244 ** the sqlite3_index_info structure that is used to communicate with
01245 ** xBestIndex.
01246 **
01247 ** In a join, this routine might be called multiple times for the
01248 ** same virtual table.  The sqlite3_index_info structure is created
01249 ** and initialized on the first invocation and reused on all subsequent
01250 ** invocations.  The sqlite3_index_info structure is also used when
01251 ** code is generated to access the virtual table.  The whereInfoDelete() 
01252 ** routine takes care of freeing the sqlite3_index_info structure after
01253 ** everybody has finished with it.
01254 */
01255 static double bestVirtualIndex(
01256   Parse *pParse,                 /* The parsing context */
01257   WhereClause *pWC,              /* The WHERE clause */
01258   struct SrcList_item *pSrc,     /* The FROM clause term to search */
01259   Bitmask notReady,              /* Mask of cursors that are not available */
01260   ExprList *pOrderBy,            /* The order by clause */
01261   int orderByUsable,             /* True if we can potential sort */
01262   sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
01263 ){
01264   Table *pTab = pSrc->pTab;
01265   sqlite3_vtab *pVtab = pTab->pVtab;
01266   sqlite3_index_info *pIdxInfo;
01267   struct sqlite3_index_constraint *pIdxCons;
01268   struct sqlite3_index_orderby *pIdxOrderBy;
01269   struct sqlite3_index_constraint_usage *pUsage;
01270   WhereTerm *pTerm;
01271   int i, j;
01272   int nOrderBy;
01273   int rc;
01274 
01275   /* If the sqlite3_index_info structure has not been previously
01276   ** allocated and initialized for this virtual table, then allocate
01277   ** and initialize it now
01278   */
01279   pIdxInfo = *ppIdxInfo;
01280   if( pIdxInfo==0 ){
01281     WhereTerm *pTerm;
01282     int nTerm;
01283     WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
01284 
01285     /* Count the number of possible WHERE clause constraints referring
01286     ** to this virtual table */
01287     for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
01288       if( pTerm->leftCursor != pSrc->iCursor ) continue;
01289       assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
01290       testcase( pTerm->eOperator==WO_IN );
01291       testcase( pTerm->eOperator==WO_ISNULL );
01292       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
01293       nTerm++;
01294     }
01295 
01296     /* If the ORDER BY clause contains only columns in the current 
01297     ** virtual table then allocate space for the aOrderBy part of
01298     ** the sqlite3_index_info structure.
01299     */
01300     nOrderBy = 0;
01301     if( pOrderBy ){
01302       for(i=0; i<pOrderBy->nExpr; i++){
01303         Expr *pExpr = pOrderBy->a[i].pExpr;
01304         if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
01305       }
01306       if( i==pOrderBy->nExpr ){
01307         nOrderBy = pOrderBy->nExpr;
01308       }
01309     }
01310 
01311     /* Allocate the sqlite3_index_info structure
01312     */
01313     pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
01314                              + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
01315                              + sizeof(*pIdxOrderBy)*nOrderBy );
01316     if( pIdxInfo==0 ){
01317       sqlite3ErrorMsg(pParse, "out of memory");
01318       return 0.0;
01319     }
01320     *ppIdxInfo = pIdxInfo;
01321 
01322     /* Initialize the structure.  The sqlite3_index_info structure contains
01323     ** many fields that are declared "const" to prevent xBestIndex from
01324     ** changing them.  We have to do some funky casting in order to
01325     ** initialize those fields.
01326     */
01327     pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
01328     pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
01329     pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
01330     *(int*)&pIdxInfo->nConstraint = nTerm;
01331     *(int*)&pIdxInfo->nOrderBy = nOrderBy;
01332     *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
01333     *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
01334     *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
01335                                                                      pUsage;
01336 
01337     for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
01338       if( pTerm->leftCursor != pSrc->iCursor ) continue;
01339       assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
01340       testcase( pTerm->eOperator==WO_IN );
01341       testcase( pTerm->eOperator==WO_ISNULL );
01342       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
01343       pIdxCons[j].iColumn = pTerm->leftColumn;
01344       pIdxCons[j].iTermOffset = i;
01345       pIdxCons[j].op = pTerm->eOperator;
01346       /* The direct assignment in the previous line is possible only because
01347       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
01348       ** following asserts verify this fact. */
01349       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
01350       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
01351       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
01352       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
01353       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
01354       assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
01355       assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
01356       j++;
01357     }
01358     for(i=0; i<nOrderBy; i++){
01359       Expr *pExpr = pOrderBy->a[i].pExpr;
01360       pIdxOrderBy[i].iColumn = pExpr->iColumn;
01361       pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
01362     }
01363   }
01364 
01365   /* At this point, the sqlite3_index_info structure that pIdxInfo points
01366   ** to will have been initialized, either during the current invocation or
01367   ** during some prior invocation.  Now we just have to customize the
01368   ** details of pIdxInfo for the current invocation and pass it to
01369   ** xBestIndex.
01370   */
01371 
01372   /* The module name must be defined. Also, by this point there must
01373   ** be a pointer to an sqlite3_vtab structure. Otherwise
01374   ** sqlite3ViewGetColumnNames() would have picked up the error. 
01375   */
01376   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
01377   assert( pVtab );
01378 #if 0
01379   if( pTab->pVtab==0 ){
01380     sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
01381         pTab->azModuleArg[0], pTab->zName);
01382     return 0.0;
01383   }
01384 #endif
01385 
01386   /* Set the aConstraint[].usable fields and initialize all 
01387   ** output variables to zero.
01388   **
01389   ** aConstraint[].usable is true for constraints where the right-hand
01390   ** side contains only references to tables to the left of the current
01391   ** table.  In other words, if the constraint is of the form:
01392   **
01393   **           column = expr
01394   **
01395   ** and we are evaluating a join, then the constraint on column is 
01396   ** only valid if all tables referenced in expr occur to the left
01397   ** of the table containing column.
01398   **
01399   ** The aConstraints[] array contains entries for all constraints
01400   ** on the current table.  That way we only have to compute it once
01401   ** even though we might try to pick the best index multiple times.
01402   ** For each attempt at picking an index, the order of tables in the
01403   ** join might be different so we have to recompute the usable flag
01404   ** each time.
01405   */
01406   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
01407   pUsage = pIdxInfo->aConstraintUsage;
01408   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
01409     j = pIdxCons->iTermOffset;
01410     pTerm = &pWC->a[j];
01411     pIdxCons->usable =  (pTerm->prereqRight & notReady)==0;
01412   }
01413   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
01414   if( pIdxInfo->needToFreeIdxStr ){
01415     sqlite3_free(pIdxInfo->idxStr);
01416   }
01417   pIdxInfo->idxStr = 0;
01418   pIdxInfo->idxNum = 0;
01419   pIdxInfo->needToFreeIdxStr = 0;
01420   pIdxInfo->orderByConsumed = 0;
01421   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
01422   nOrderBy = pIdxInfo->nOrderBy;
01423   if( pIdxInfo->nOrderBy && !orderByUsable ){
01424     *(int*)&pIdxInfo->nOrderBy = 0;
01425   }
01426 
01427   (void)sqlite3SafetyOff(pParse->db);
01428   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
01429   TRACE_IDX_INPUTS(pIdxInfo);
01430   rc = pVtab->pModule->xBestIndex(pVtab, pIdxInfo);
01431   TRACE_IDX_OUTPUTS(pIdxInfo);
01432   (void)sqlite3SafetyOn(pParse->db);
01433 
01434   if( rc!=SQLITE_OK ){
01435     if( rc==SQLITE_NOMEM ){
01436       pParse->db->mallocFailed = 1;
01437     }else if( !pVtab->zErrMsg ){
01438       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
01439     }else{
01440       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
01441     }
01442   }
01443   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
01444   pVtab->zErrMsg = 0;
01445 
01446   for(i=0; i<pIdxInfo->nConstraint; i++){
01447     if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
01448       sqlite3ErrorMsg(pParse, 
01449           "table %s: xBestIndex returned an invalid plan", pTab->zName);
01450       return 0.0;
01451     }
01452   }
01453 
01454   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
01455   return pIdxInfo->estimatedCost;
01456 }
01457 #endif /* SQLITE_OMIT_VIRTUALTABLE */
01458 
01459 /*
01460 ** Find the best index for accessing a particular table.  Return a pointer
01461 ** to the index, flags that describe how the index should be used, the
01462 ** number of equality constraints, and the "cost" for this index.
01463 **
01464 ** The lowest cost index wins.  The cost is an estimate of the amount of
01465 ** CPU and disk I/O need to process the request using the selected index.
01466 ** Factors that influence cost include:
01467 **
01468 **    *  The estimated number of rows that will be retrieved.  (The
01469 **       fewer the better.)
01470 **
01471 **    *  Whether or not sorting must occur.
01472 **
01473 **    *  Whether or not there must be separate lookups in the
01474 **       index and in the main table.
01475 **
01476 ** If there was an INDEXED BY clause attached to the table in the SELECT
01477 ** statement, then this function only considers strategies using the 
01478 ** named index. If one cannot be found, then the returned cost is
01479 ** SQLITE_BIG_DBL. If a strategy can be found that uses the named index, 
01480 ** then the cost is calculated in the usual way.
01481 **
01482 ** If a NOT INDEXED clause was attached to the table in the SELECT 
01483 ** statement, then no indexes are considered. However, the selected 
01484 ** stategy may still take advantage of the tables built-in rowid
01485 ** index.
01486 */
01487 static double bestIndex(
01488   Parse *pParse,              /* The parsing context */
01489   WhereClause *pWC,           /* The WHERE clause */
01490   struct SrcList_item *pSrc,  /* The FROM clause term to search */
01491   Bitmask notReady,           /* Mask of cursors that are not available */
01492   ExprList *pOrderBy,         /* The order by clause */
01493   Index **ppIndex,            /* Make *ppIndex point to the best index */
01494   int *pFlags,                /* Put flags describing this choice in *pFlags */
01495   int *pnEq                   /* Put the number of == or IN constraints here */
01496 ){
01497   WhereTerm *pTerm;
01498   Index *bestIdx = 0;         /* Index that gives the lowest cost */
01499   double lowestCost;          /* The cost of using bestIdx */
01500   int bestFlags = 0;          /* Flags associated with bestIdx */
01501   int bestNEq = 0;            /* Best value for nEq */
01502   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
01503   Index *pProbe;              /* An index we are evaluating */
01504   int rev;                    /* True to scan in reverse order */
01505   int flags;                  /* Flags associated with pProbe */
01506   int nEq;                    /* Number of == or IN constraints */
01507   int eqTermMask;             /* Mask of valid equality operators */
01508   double cost;                /* Cost of using pProbe */
01509 
01510   WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName, notReady));
01511   lowestCost = SQLITE_BIG_DBL;
01512   pProbe = pSrc->pTab->pIndex;
01513   if( pSrc->notIndexed ){
01514     pProbe = 0;
01515   }
01516 
01517   /* If the table has no indices and there are no terms in the where
01518   ** clause that refer to the ROWID, then we will never be able to do
01519   ** anything other than a full table scan on this table.  We might as
01520   ** well put it first in the join order.  That way, perhaps it can be
01521   ** referenced by other tables in the join.
01522   */
01523   if( pProbe==0 &&
01524      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
01525      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
01526     *pFlags = 0;
01527     *ppIndex = 0;
01528     *pnEq = 0;
01529     return 0.0;
01530   }
01531 
01532   /* Check for a rowid=EXPR or rowid IN (...) constraints. If there was
01533   ** an INDEXED BY clause attached to this table, skip this step.
01534   */
01535   if( !pSrc->pIndex ){
01536     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
01537     if( pTerm ){
01538       Expr *pExpr;
01539       *ppIndex = 0;
01540       bestFlags = WHERE_ROWID_EQ;
01541       if( pTerm->eOperator & WO_EQ ){
01542         /* Rowid== is always the best pick.  Look no further.  Because only
01543         ** a single row is generated, output is always in sorted order */
01544         *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
01545         *pnEq = 1;
01546         WHERETRACE(("... best is rowid\n"));
01547         return 0.0;
01548       }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
01549         /* Rowid IN (LIST): cost is NlogN where N is the number of list
01550         ** elements.  */
01551         lowestCost = pExpr->pList->nExpr;
01552         lowestCost *= estLog(lowestCost);
01553       }else{
01554         /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
01555         ** in the result of the inner select.  We have no way to estimate
01556         ** that value so make a wild guess. */
01557         lowestCost = 200;
01558       }
01559       WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
01560     }
01561   
01562     /* Estimate the cost of a table scan.  If we do not know how many
01563     ** entries are in the table, use 1 million as a guess.
01564     */
01565     cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
01566     WHERETRACE(("... table scan base cost: %.9g\n", cost));
01567     flags = WHERE_ROWID_RANGE;
01568   
01569     /* Check for constraints on a range of rowids in a table scan.
01570     */
01571     pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
01572     if( pTerm ){
01573       if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
01574         flags |= WHERE_TOP_LIMIT;
01575         cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds or rows */
01576       }
01577       if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
01578         flags |= WHERE_BTM_LIMIT;
01579         cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
01580       }
01581       WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
01582     }else{
01583       flags = 0;
01584     }
01585   
01586     /* If the table scan does not satisfy the ORDER BY clause, increase
01587     ** the cost by NlogN to cover the expense of sorting. */
01588     if( pOrderBy ){
01589       if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
01590         flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
01591         if( rev ){
01592           flags |= WHERE_REVERSE;
01593         }
01594       }else{
01595         cost += cost*estLog(cost);
01596         WHERETRACE(("... sorting increases cost to %.9g\n", cost));
01597       }
01598     }
01599     if( cost<lowestCost ){
01600       lowestCost = cost;
01601       bestFlags = flags;
01602     }
01603   }
01604 
01605   /* If the pSrc table is the right table of a LEFT JOIN then we may not
01606   ** use an index to satisfy IS NULL constraints on that table.  This is
01607   ** because columns might end up being NULL if the table does not match -
01608   ** a circumstance which the index cannot help us discover.  Ticket #2177.
01609   */
01610   if( (pSrc->jointype & JT_LEFT)!=0 ){
01611     eqTermMask = WO_EQ|WO_IN;
01612   }else{
01613     eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
01614   }
01615 
01616   /* Look at each index.
01617   */
01618   if( pSrc->pIndex ){
01619     pProbe = pSrc->pIndex;
01620   }
01621   for(; pProbe; pProbe=(pSrc->pIndex ? 0 : pProbe->pNext)){
01622     int i;                       /* Loop counter */
01623     double inMultiplier = 1;
01624 
01625     WHERETRACE(("... index %s:\n", pProbe->zName));
01626 
01627     /* Count the number of columns in the index that are satisfied
01628     ** by x=EXPR constraints or x IN (...) constraints.
01629     */
01630     flags = 0;
01631     for(i=0; i<pProbe->nColumn; i++){
01632       int j = pProbe->aiColumn[i];
01633       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
01634       if( pTerm==0 ) break;
01635       flags |= WHERE_COLUMN_EQ;
01636       if( pTerm->eOperator & WO_IN ){
01637         Expr *pExpr = pTerm->pExpr;
01638         flags |= WHERE_COLUMN_IN;
01639         if( pExpr->pSelect!=0 ){
01640           inMultiplier *= 25;
01641         }else if( ALWAYS(pExpr->pList) ){
01642           inMultiplier *= pExpr->pList->nExpr + 1;
01643         }
01644       }
01645     }
01646     cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
01647     nEq = i;
01648     if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
01649          && nEq==pProbe->nColumn ){
01650       flags |= WHERE_UNIQUE;
01651     }
01652     WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
01653 
01654     /* Look for range constraints
01655     */
01656     if( nEq<pProbe->nColumn ){
01657       int j = pProbe->aiColumn[nEq];
01658       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
01659       if( pTerm ){
01660         flags |= WHERE_COLUMN_RANGE;
01661         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
01662           flags |= WHERE_TOP_LIMIT;
01663           cost /= 3;
01664         }
01665         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
01666           flags |= WHERE_BTM_LIMIT;
01667           cost /= 3;
01668         }
01669         WHERETRACE(("...... range reduces cost to %.9g\n", cost));
01670       }
01671     }
01672 
01673     /* Add the additional cost of sorting if that is a factor.
01674     */
01675     if( pOrderBy ){
01676       if( (flags & WHERE_COLUMN_IN)==0 &&
01677            isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
01678         if( flags==0 ){
01679           flags = WHERE_COLUMN_RANGE;
01680         }
01681         flags |= WHERE_ORDERBY;
01682         if( rev ){
01683           flags |= WHERE_REVERSE;
01684         }
01685       }else{
01686         cost += cost*estLog(cost);
01687         WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
01688       }
01689     }
01690 
01691     /* Check to see if we can get away with using just the index without
01692     ** ever reading the table.  If that is the case, then halve the
01693     ** cost of this index.
01694     */
01695     if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
01696       Bitmask m = pSrc->colUsed;
01697       int j;
01698       for(j=0; j<pProbe->nColumn; j++){
01699         int x = pProbe->aiColumn[j];
01700         if( x<BMS-1 ){
01701           m &= ~(((Bitmask)1)<<x);
01702         }
01703       }
01704       if( m==0 ){
01705         flags |= WHERE_IDX_ONLY;
01706         cost /= 2;
01707         WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
01708       }
01709     }
01710 
01711     /* If this index has achieved the lowest cost so far, then use it.
01712     */
01713     if( flags && cost < lowestCost ){
01714       bestIdx = pProbe;
01715       lowestCost = cost;
01716       bestFlags = flags;
01717       bestNEq = nEq;
01718     }
01719   }
01720 
01721   /* Report the best result
01722   */
01723   *ppIndex = bestIdx;
01724   WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
01725         bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
01726   *pFlags = bestFlags | eqTermMask;
01727   *pnEq = bestNEq;
01728   return lowestCost;
01729 }
01730 
01731 
01732 /*
01733 ** Disable a term in the WHERE clause.  Except, do not disable the term
01734 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
01735 ** or USING clause of that join.
01736 **
01737 ** Consider the term t2.z='ok' in the following queries:
01738 **
01739 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
01740 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
01741 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
01742 **
01743 ** The t2.z='ok' is disabled in the in (2) because it originates
01744 ** in the ON clause.  The term is disabled in (3) because it is not part
01745 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
01746 **
01747 ** Disabling a term causes that term to not be tested in the inner loop
01748 ** of the join.  Disabling is an optimization.  When terms are satisfied
01749 ** by indices, we disable them to prevent redundant tests in the inner
01750 ** loop.  We would get the correct results if nothing were ever disabled,
01751 ** but joins might run a little slower.  The trick is to disable as much
01752 ** as we can without disabling too much.  If we disabled in (1), we'd get
01753 ** the wrong answer.  See ticket #813.
01754 */
01755 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
01756   if( pTerm
01757       && ALWAYS((pTerm->flags & TERM_CODED)==0)
01758       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
01759   ){
01760     pTerm->flags |= TERM_CODED;
01761     if( pTerm->iParent>=0 ){
01762       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
01763       if( (--pOther->nChild)==0 ){
01764         disableTerm(pLevel, pOther);
01765       }
01766     }
01767   }
01768 }
01769 
01770 /*
01771 ** Apply the affinities associated with the first n columns of index
01772 ** pIdx to the values in the n registers starting at base.
01773 */
01774 static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
01775   if( n>0 ){
01776     Vdbe *v = pParse->pVdbe;
01777     assert( v!=0 );
01778     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
01779     sqlite3IndexAffinityStr(v, pIdx);
01780     sqlite3ExprCacheAffinityChange(pParse, base, n);
01781   }
01782 }
01783 
01784 
01785 /*
01786 ** Generate code for a single equality term of the WHERE clause.  An equality
01787 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
01788 ** coded.
01789 **
01790 ** The current value for the constraint is left in register iReg.
01791 **
01792 ** For a constraint of the form X=expr, the expression is evaluated and its
01793 ** result is left on the stack.  For constraints of the form X IN (...)
01794 ** this routine sets up a loop that will iterate over all values of X.
01795 */
01796 static int codeEqualityTerm(
01797   Parse *pParse,      /* The parsing context */
01798   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
01799   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
01800   int iTarget         /* Attempt to leave results in this register */
01801 ){
01802   Expr *pX = pTerm->pExpr;
01803   Vdbe *v = pParse->pVdbe;
01804   int iReg;                  /* Register holding results */
01805 
01806   assert( iTarget>0 );
01807   if( pX->op==TK_EQ ){
01808     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
01809   }else if( pX->op==TK_ISNULL ){
01810     iReg = iTarget;
01811     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
01812 #ifndef SQLITE_OMIT_SUBQUERY
01813   }else{
01814     int eType;
01815     int iTab;
01816     struct InLoop *pIn;
01817 
01818     assert( pX->op==TK_IN );
01819     iReg = iTarget;
01820     eType = sqlite3FindInIndex(pParse, pX, 0);
01821     iTab = pX->iTable;
01822     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
01823     VdbeComment((v, "%.*s", pX->span.n, pX->span.z));
01824     if( pLevel->nIn==0 ){
01825       pLevel->nxt = sqlite3VdbeMakeLabel(v);
01826     }
01827     pLevel->nIn++;
01828     pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop,
01829                                     sizeof(pLevel->aInLoop[0])*pLevel->nIn);
01830     pIn = pLevel->aInLoop;
01831     if( pIn ){
01832       pIn += pLevel->nIn - 1;
01833       pIn->iCur = iTab;
01834       if( eType==IN_INDEX_ROWID ){
01835         pIn->topAddr = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
01836       }else{
01837         pIn->topAddr = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
01838       }
01839       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
01840     }else{
01841       pLevel->nIn = 0;
01842     }
01843 #endif
01844   }
01845   disableTerm(pLevel, pTerm);
01846   return iReg;
01847 }
01848 
01849 /*
01850 ** Generate code that will evaluate all == and IN constraints for an
01851 ** index.  The values for all constraints are left on the stack.
01852 **
01853 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
01854 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
01855 ** The index has as many as three equality constraints, but in this
01856 ** example, the third "c" value is an inequality.  So only two 
01857 ** constraints are coded.  This routine will generate code to evaluate
01858 ** a==5 and b IN (1,2,3).  The current values for a and b will be left
01859 ** on the stack - a is the deepest and b the shallowest.
01860 **
01861 ** In the example above nEq==2.  But this subroutine works for any value
01862 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
01863 ** The only thing it does is allocate the pLevel->iMem memory cell.
01864 **
01865 ** This routine always allocates at least one memory cell and puts
01866 ** the address of that memory cell in pLevel->iMem.  The code that
01867 ** calls this routine will use pLevel->iMem to store the termination
01868 ** key value of the loop.  If one or more IN operators appear, then
01869 ** this routine allocates an additional nEq memory cells for internal
01870 ** use.
01871 */
01872 static int codeAllEqualityTerms(
01873   Parse *pParse,        /* Parsing context */
01874   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
01875   WhereClause *pWC,     /* The WHERE clause */
01876   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
01877   int nExtraReg         /* Number of extra registers to allocate */
01878 ){
01879   int nEq = pLevel->nEq;        /* The number of == or IN constraints to code */
01880   Vdbe *v = pParse->pVdbe;      /* The virtual machine under construction */
01881   Index *pIdx = pLevel->pIdx;   /* The index being used for this loop */
01882   int iCur = pLevel->iTabCur;   /* The cursor of the table */
01883   WhereTerm *pTerm;             /* A single constraint term */
01884   int j;                        /* Loop counter */
01885   int regBase;                  /* Base register */
01886 
01887   /* Figure out how many memory cells we will need then allocate them.
01888   ** We always need at least one used to store the loop terminator
01889   ** value.  If there are IN operators we'll need one for each == or
01890   ** IN constraint.
01891   */
01892   pLevel->iMem = pParse->nMem + 1;
01893   regBase = pParse->nMem + 2;
01894   pParse->nMem += pLevel->nEq + 2 + nExtraReg;
01895 
01896   /* Evaluate the equality constraints
01897   */
01898   assert( pIdx->nColumn>=nEq );
01899   for(j=0; j<nEq; j++){
01900     int r1;
01901     int k = pIdx->aiColumn[j];
01902     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
01903     if( NEVER(pTerm==0) ) break;
01904     assert( (pTerm->flags & TERM_CODED)==0 );
01905     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
01906     if( r1!=regBase+j ){
01907       sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
01908     }
01909     testcase( pTerm->eOperator & WO_ISNULL );
01910     testcase( pTerm->eOperator & WO_IN );
01911     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
01912       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->brk);
01913     }
01914   }
01915   return regBase;
01916 }
01917 
01918 #if defined(SQLITE_TEST)
01919 /*
01920 ** The following variable holds a text description of query plan generated
01921 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
01922 ** overwrites the previous.  This information is used for testing and
01923 ** analysis only.
01924 */
01925 char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
01926 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
01927 
01928 #endif /* SQLITE_TEST */
01929 
01930 
01931 /*
01932 ** Free a WhereInfo structure
01933 */
01934 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
01935   if( pWInfo ){
01936     int i;
01937     for(i=0; i<pWInfo->nLevel; i++){
01938       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
01939       if( pInfo ){
01940         assert( pInfo->needToFreeIdxStr==0 );
01941         sqlite3DbFree(db, pInfo);
01942       }
01943     }
01944     sqlite3DbFree(db, pWInfo);
01945   }
01946 }
01947 
01948 
01949 /*
01950 ** Generate the beginning of the loop used for WHERE clause processing.
01951 ** The return value is a pointer to an opaque structure that contains
01952 ** information needed to terminate the loop.  Later, the calling routine
01953 ** should invoke sqlite3WhereEnd() with the return value of this function
01954 ** in order to complete the WHERE clause processing.
01955 **
01956 ** If an error occurs, this routine returns NULL.
01957 **
01958 ** The basic idea is to do a nested loop, one loop for each table in
01959 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
01960 ** same as a SELECT with only a single table in the FROM clause.)  For
01961 ** example, if the SQL is this:
01962 **
01963 **       SELECT * FROM t1, t2, t3 WHERE ...;
01964 **
01965 ** Then the code generated is conceptually like the following:
01966 **
01967 **      foreach row1 in t1 do       \    Code generated
01968 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
01969 **          foreach row3 in t3 do   /
01970 **            ...
01971 **          end                     \    Code generated
01972 **        end                        |-- by sqlite3WhereEnd()
01973 **      end                         /
01974 **
01975 ** Note that the loops might not be nested in the order in which they
01976 ** appear in the FROM clause if a different order is better able to make
01977 ** use of indices.  Note also that when the IN operator appears in
01978 ** the WHERE clause, it might result in additional nested loops for
01979 ** scanning through all values on the right-hand side of the IN.
01980 **
01981 ** There are Btree cursors associated with each table.  t1 uses cursor
01982 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
01983 ** And so forth.  This routine generates code to open those VDBE cursors
01984 ** and sqlite3WhereEnd() generates the code to close them.
01985 **
01986 ** The code that sqlite3WhereBegin() generates leaves the cursors named
01987 ** in pTabList pointing at their appropriate entries.  The [...] code
01988 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
01989 ** data from the various tables of the loop.
01990 **
01991 ** If the WHERE clause is empty, the foreach loops must each scan their
01992 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
01993 ** the tables have indices and there are terms in the WHERE clause that
01994 ** refer to those indices, a complete table scan can be avoided and the
01995 ** code will run much faster.  Most of the work of this routine is checking
01996 ** to see if there are indices that can be used to speed up the loop.
01997 **
01998 ** Terms of the WHERE clause are also used to limit which rows actually
01999 ** make it to the "..." in the middle of the loop.  After each "foreach",
02000 ** terms of the WHERE clause that use only terms in that loop and outer
02001 ** loops are evaluated and if false a jump is made around all subsequent
02002 ** inner loops (or around the "..." if the test occurs within the inner-
02003 ** most loop)
02004 **
02005 ** OUTER JOINS
02006 **
02007 ** An outer join of tables t1 and t2 is conceptally coded as follows:
02008 **
02009 **    foreach row1 in t1 do
02010 **      flag = 0
02011 **      foreach row2 in t2 do
02012 **        start:
02013 **          ...
02014 **          flag = 1
02015 **      end
02016 **      if flag==0 then
02017 **        move the row2 cursor to a null row
02018 **        goto start
02019 **      fi
02020 **    end
02021 **
02022 ** ORDER BY CLAUSE PROCESSING
02023 **
02024 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
02025 ** if there is one.  If there is no ORDER BY clause or if this routine
02026 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
02027 **
02028 ** If an index can be used so that the natural output order of the table
02029 ** scan is correct for the ORDER BY clause, then that index is used and
02030 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
02031 ** unnecessary sort of the result set if an index appropriate for the
02032 ** ORDER BY clause already exists.
02033 **
02034 ** If the where clause loops cannot be arranged to provide the correct
02035 ** output order, then the *ppOrderBy is unchanged.
02036 */
02037 WhereInfo *sqlite3WhereBegin(
02038   Parse *pParse,        /* The parser context */
02039   SrcList *pTabList,    /* A list of all tables to be scanned */
02040   Expr *pWhere,         /* The WHERE clause */
02041   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
02042   u8 wflags             /* One of the WHERE_* flags defined in sqliteInt.h */
02043 ){
02044   int i;                     /* Loop counter */
02045   WhereInfo *pWInfo;         /* Will become the return value of this function */
02046   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
02047   int brk, cont = 0;         /* Addresses used during code generation */
02048   Bitmask notReady;          /* Cursors that are not yet positioned */
02049   WhereTerm *pTerm;          /* A single term in the WHERE clause */
02050   ExprMaskSet maskSet;       /* The expression mask set */
02051   WhereClause wc;            /* The WHERE clause is divided into these terms */
02052   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
02053   WhereLevel *pLevel;             /* A single level in the pWInfo list */
02054   int iFrom;                      /* First unused FROM clause element */
02055   int andFlags;              /* AND-ed combination of all wc.a[].flags */
02056   sqlite3 *db;               /* Database connection */
02057   ExprList *pOrderBy = 0;
02058 
02059   /* The number of tables in the FROM clause is limited by the number of
02060   ** bits in a Bitmask 
02061   */
02062   if( pTabList->nSrc>BMS ){
02063     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
02064     return 0;
02065   }
02066 
02067   if( ppOrderBy ){
02068     pOrderBy = *ppOrderBy;
02069   }
02070 
02071   /* Split the WHERE clause into separate subexpressions where each
02072   ** subexpression is separated by an AND operator.
02073   */
02074   initMaskSet(&maskSet);
02075   whereClauseInit(&wc, pParse, &maskSet);
02076   sqlite3ExprCodeConstants(pParse, pWhere);
02077   whereSplit(&wc, pWhere, TK_AND);
02078     
02079   /* Allocate and initialize the WhereInfo structure that will become the
02080   ** return value.
02081   */
02082   db = pParse->db;
02083   pWInfo = sqlite3DbMallocZero(db,  
02084                       sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
02085   if( db->mallocFailed ){
02086     goto whereBeginError;
02087   }
02088   pWInfo->nLevel = pTabList->nSrc;
02089   pWInfo->pParse = pParse;
02090   pWInfo->pTabList = pTabList;
02091   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
02092 
02093   /* Special case: a WHERE clause that is constant.  Evaluate the
02094   ** expression and either jump over all of the code or fall thru.
02095   */
02096   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
02097     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
02098     pWhere = 0;
02099   }
02100 
02101   /* Assign a bit from the bitmask to every term in the FROM clause.
02102   **
02103   ** When assigning bitmask values to FROM clause cursors, it must be
02104   ** the case that if X is the bitmask for the N-th FROM clause term then
02105   ** the bitmask for all FROM clause terms to the left of the N-th term
02106   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
02107   ** its Expr.iRightJoinTable value to find the bitmask of the right table
02108   ** of the join.  Subtracting one from the right table bitmask gives a
02109   ** bitmask for all tables to the left of the join.  Knowing the bitmask
02110   ** for all tables to the left of a left join is important.  Ticket #3015.
02111   */
02112   for(i=0; i<pTabList->nSrc; i++){
02113     createMask(&maskSet, pTabList->a[i].iCursor);
02114   }
02115 #ifndef NDEBUG
02116   {
02117     Bitmask toTheLeft = 0;
02118     for(i=0; i<pTabList->nSrc; i++){
02119       Bitmask m = getMask(&maskSet, pTabList->a[i].iCursor);
02120       assert( (m-1)==toTheLeft );
02121       toTheLeft |= m;
02122     }
02123   }
02124 #endif
02125 
02126   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
02127   ** add new virtual terms onto the end of the WHERE clause.  We do not
02128   ** want to analyze these virtual terms, so start analyzing at the end
02129   ** and work forward so that the added virtual terms are never processed.
02130   */
02131   exprAnalyzeAll(pTabList, &wc);
02132   if( db->mallocFailed ){
02133     goto whereBeginError;
02134   }
02135 
02136   /* Chose the best index to use for each table in the FROM clause.
02137   **
02138   ** This loop fills in the following fields:
02139   **
02140   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
02141   **   pWInfo->a[].flags     WHERE_xxx flags associated with pIdx
02142   **   pWInfo->a[].nEq       The number of == and IN constraints
02143   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
02144   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
02145   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
02146   **
02147   ** This loop also figures out the nesting order of tables in the FROM
02148   ** clause.
02149   */
02150   notReady = ~(Bitmask)0;
02151   pTabItem = pTabList->a;
02152   pLevel = pWInfo->a;
02153   andFlags = ~0;
02154   WHERETRACE(("*** Optimizer Start ***\n"));
02155   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
02156     Index *pIdx;                /* Index for FROM table at pTabItem */
02157     int flags;                  /* Flags asssociated with pIdx */
02158     int nEq;                    /* Number of == or IN constraints */
02159     double cost;                /* The cost for pIdx */
02160     int j;                      /* For looping over FROM tables */
02161     Index *pBest = 0;           /* The best index seen so far */
02162     int bestFlags = 0;          /* Flags associated with pBest */
02163     int bestNEq = 0;            /* nEq associated with pBest */
02164     double lowestCost;          /* Cost of the pBest */
02165     int bestJ = 0;              /* The value of j */
02166     Bitmask m;                  /* Bitmask value for j or bestJ */
02167     int once = 0;               /* True when first table is seen */
02168     sqlite3_index_info *pIndex; /* Current virtual index */
02169 
02170     lowestCost = SQLITE_BIG_DBL;
02171     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
02172       int doNotReorder;  /* True if this table should not be reordered */
02173 
02174       doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
02175       if( once && doNotReorder ) break;
02176       m = getMask(&maskSet, pTabItem->iCursor);
02177       if( (m & notReady)==0 ){
02178         if( j==iFrom ) iFrom++;
02179         continue;
02180       }
02181       assert( pTabItem->pTab );
02182 #ifndef SQLITE_OMIT_VIRTUALTABLE
02183       if( IsVirtual(pTabItem->pTab) ){
02184         sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
02185         cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
02186                                 ppOrderBy ? *ppOrderBy : 0, i==0,
02187                                 ppIdxInfo);
02188         flags = WHERE_VIRTUALTABLE;
02189         pIndex = *ppIdxInfo;
02190         if( pIndex && pIndex->orderByConsumed ){
02191           flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
02192         }
02193         pIdx = 0;
02194         nEq = 0;
02195         if( (SQLITE_BIG_DBL/2.0)<cost ){
02196           /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
02197           ** inital value of lowestCost in this loop. If it is, then
02198           ** the (cost<lowestCost) test below will never be true and
02199           ** pLevel->pBestIdx never set.
02200           */ 
02201           cost = (SQLITE_BIG_DBL/2.0);
02202         }
02203       }else 
02204 #endif
02205       {
02206         cost = bestIndex(pParse, &wc, pTabItem, notReady,
02207                          (i==0 && ppOrderBy) ? *ppOrderBy : 0,
02208                          &pIdx, &flags, &nEq);
02209         pIndex = 0;
02210       }
02211       if( cost<lowestCost ){
02212         once = 1;
02213         lowestCost = cost;
02214         pBest = pIdx;
02215         bestFlags = flags;
02216         bestNEq = nEq;
02217         bestJ = j;
02218         pLevel->pBestIdx = pIndex;
02219       }
02220       if( doNotReorder ) break;
02221     }
02222     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
02223            pLevel-pWInfo->a));
02224     if( (bestFlags & WHERE_ORDERBY)!=0 ){
02225       *ppOrderBy = 0;
02226     }
02227     andFlags &= bestFlags;
02228     pLevel->flags = bestFlags;
02229     pLevel->pIdx = pBest;
02230     pLevel->nEq = bestNEq;
02231     pLevel->aInLoop = 0;
02232     pLevel->nIn = 0;
02233     if( pBest ){
02234       pLevel->iIdxCur = pParse->nTab++;
02235     }else{
02236       pLevel->iIdxCur = -1;
02237     }
02238     notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
02239     pLevel->iFrom = bestJ;
02240 
02241     /* Check that if the table scanned by this loop iteration had an
02242     ** INDEXED BY clause attached to it, that the named index is being
02243     ** used for the scan. If not, then query compilation has failed.
02244     ** Return an error.
02245     */
02246     pIdx = pTabList->a[bestJ].pIndex;
02247     assert( !pIdx || !pBest || pIdx==pBest );
02248     if( pIdx && pBest!=pIdx ){
02249       sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
02250       goto whereBeginError;
02251     }
02252   }
02253   WHERETRACE(("*** Optimizer Finished ***\n"));
02254 
02255   /* If the total query only selects a single row, then the ORDER BY
02256   ** clause is irrelevant.
02257   */
02258   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
02259     *ppOrderBy = 0;
02260   }
02261 
02262   /* If the caller is an UPDATE or DELETE statement that is requesting
02263   ** to use a one-pass algorithm, determine if this is appropriate.
02264   ** The one-pass algorithm only works if the WHERE clause constraints
02265   ** the statement to update a single row.
02266   */
02267   assert( (wflags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
02268   if( (wflags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
02269     pWInfo->okOnePass = 1;
02270     pWInfo->a[0].flags &= ~WHERE_IDX_ONLY;
02271   }
02272 
02273   /* Open all tables in the pTabList and any indices selected for
02274   ** searching those tables.
02275   */
02276   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
02277   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
02278     Table *pTab;     /* Table to open */
02279     Index *pIx;      /* Index used to access pTab (if any) */
02280     int iDb;         /* Index of database containing table/index */
02281     int iIdxCur = pLevel->iIdxCur;
02282 
02283 #ifndef SQLITE_OMIT_EXPLAIN
02284     if( pParse->explain==2 ){
02285       char *zMsg;
02286       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
02287       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
02288       if( pItem->zAlias ){
02289         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
02290       }
02291       if( (pIx = pLevel->pIdx)!=0 ){
02292         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s", zMsg, pIx->zName);
02293       }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
02294         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
02295       }
02296 #ifndef SQLITE_OMIT_VIRTUALTABLE
02297       else if( pLevel->pBestIdx ){
02298         sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
02299         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
02300                     pBestIdx->idxNum, pBestIdx->idxStr);
02301       }
02302 #endif
02303       if( pLevel->flags & WHERE_ORDERBY ){
02304         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
02305       }
02306       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
02307     }
02308 #endif /* SQLITE_OMIT_EXPLAIN */
02309     pTabItem = &pTabList->a[pLevel->iFrom];
02310     pTab = pTabItem->pTab;
02311     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
02312     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
02313 #ifndef SQLITE_OMIT_VIRTUALTABLE
02314     if( pLevel->pBestIdx ){
02315       int iCur = pTabItem->iCursor;
02316       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
02317                         (const char*)pTab->pVtab, P4_VTAB);
02318     }else
02319 #endif
02320     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
02321       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
02322       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
02323       if( !pWInfo->okOnePass && pTab->nCol<(sizeof(Bitmask)*8) ){
02324         Bitmask b = pTabItem->colUsed;
02325         int n = 0;
02326         for(; b; b=b>>1, n++){}
02327         sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-2, n);
02328         assert( n<=pTab->nCol );
02329       }
02330     }else{
02331       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
02332     }
02333     pLevel->iTabCur = pTabItem->iCursor;
02334     if( (pIx = pLevel->pIdx)!=0 ){
02335       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
02336       assert( pIx->pSchema==pTab->pSchema );
02337       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIx->nColumn+1);
02338       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
02339                         (char*)pKey, P4_KEYINFO_HANDOFF);
02340       VdbeComment((v, "%s", pIx->zName));
02341     }
02342     sqlite3CodeVerifySchema(pParse, iDb);
02343   }
02344   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
02345 
02346   /* Generate the code to do the search.  Each iteration of the for
02347   ** loop below generates code for a single nested loop of the VM
02348   ** program.
02349   */
02350   notReady = ~(Bitmask)0;
02351   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
02352     int j, k;
02353     int iCur = pTabItem->iCursor;  /* The VDBE cursor for the table */
02354     Index *pIdx;       /* The index we will be using */
02355     int nxt;           /* Where to jump to continue with the next IN case */
02356     int iIdxCur;       /* The VDBE cursor for the index */
02357     int omitTable;     /* True if we use the index only */
02358     int bRev;          /* True if we need to scan in reverse order */
02359 
02360     pTabItem = &pTabList->a[pLevel->iFrom];
02361     iCur = pTabItem->iCursor;
02362     pIdx = pLevel->pIdx;
02363     iIdxCur = pLevel->iIdxCur;
02364     bRev = (pLevel->flags & WHERE_REVERSE)!=0;
02365     omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
02366 
02367     /* Create labels for the "break" and "continue" instructions
02368     ** for the current loop.  Jump to brk to break out of a loop.
02369     ** Jump to cont to go immediately to the next iteration of the
02370     ** loop.
02371     **
02372     ** When there is an IN operator, we also have a "nxt" label that
02373     ** means to continue with the next IN value combination.  When
02374     ** there are no IN operators in the constraints, the "nxt" label
02375     ** is the same as "brk".
02376     */
02377     brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
02378     cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
02379 
02380     /* If this is the right table of a LEFT OUTER JOIN, allocate and
02381     ** initialize a memory cell that records if this table matches any
02382     ** row of the left table of the join.
02383     */
02384     if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
02385       pLevel->iLeftJoin = ++pParse->nMem;
02386       sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
02387       VdbeComment((v, "init LEFT JOIN no-match flag"));
02388     }
02389 
02390 #ifndef SQLITE_OMIT_VIRTUALTABLE
02391     if( pLevel->pBestIdx ){
02392       /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
02393       **          to access the data.
02394       */
02395       int j;
02396       int iReg;   /* P3 Value for OP_VFilter */
02397       sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
02398       int nConstraint = pBestIdx->nConstraint;
02399       struct sqlite3_index_constraint_usage *aUsage =
02400                                                   pBestIdx->aConstraintUsage;
02401       const struct sqlite3_index_constraint *aConstraint =
02402                                                   pBestIdx->aConstraint;
02403 
02404       iReg = sqlite3GetTempRange(pParse, nConstraint+2);
02405       pParse->disableColCache++;
02406       for(j=1; j<=nConstraint; j++){
02407         int k;
02408         for(k=0; k<nConstraint; k++){
02409           if( aUsage[k].argvIndex==j ){
02410             int iTerm = aConstraint[k].iTermOffset;
02411             assert( pParse->disableColCache );
02412             sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight, iReg+j+1);
02413             break;
02414           }
02415         }
02416         if( k==nConstraint ) break;
02417       }
02418       assert( pParse->disableColCache );
02419       pParse->disableColCache--;
02420       sqlite3VdbeAddOp2(v, OP_Integer, pBestIdx->idxNum, iReg);
02421       sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
02422       sqlite3VdbeAddOp4(v, OP_VFilter, iCur, brk, iReg, pBestIdx->idxStr,
02423                         pBestIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
02424       sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
02425       pBestIdx->needToFreeIdxStr = 0;
02426       for(j=0; j<nConstraint; j++){
02427         if( aUsage[j].omit ){
02428           int iTerm = aConstraint[j].iTermOffset;
02429           disableTerm(pLevel, &wc.a[iTerm]);
02430         }
02431       }
02432       pLevel->op = OP_VNext;
02433       pLevel->p1 = iCur;
02434       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
02435     }else
02436 #endif /* SQLITE_OMIT_VIRTUALTABLE */
02437 
02438     if( pLevel->flags & WHERE_ROWID_EQ ){
02439       /* Case 1:  We can directly reference a single row using an
02440       **          equality comparison against the ROWID field.  Or
02441       **          we reference multiple rows using a "rowid IN (...)"
02442       **          construct.
02443       */
02444       int r1;
02445       int rtmp = sqlite3GetTempReg(pParse);
02446       pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
02447       assert( pTerm!=0 );
02448       assert( pTerm->pExpr!=0 );
02449       assert( pTerm->leftCursor==iCur );
02450       assert( omitTable==0 );
02451       r1 = codeEqualityTerm(pParse, pTerm, pLevel, rtmp);
02452       nxt = pLevel->nxt;
02453       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, nxt);
02454       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, nxt, r1);
02455       sqlite3ReleaseTempReg(pParse, rtmp);
02456       VdbeComment((v, "pk"));
02457       pLevel->op = OP_Noop;
02458     }else if( pLevel->flags & WHERE_ROWID_RANGE ){
02459       /* Case 2:  We have an inequality comparison against the ROWID field.
02460       */
02461       int testOp = OP_Noop;
02462       int start;
02463       WhereTerm *pStart, *pEnd;
02464 
02465       assert( omitTable==0 );
02466       pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
02467       pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
02468       if( bRev ){
02469         pTerm = pStart;
02470         pStart = pEnd;
02471         pEnd = pTerm;
02472       }
02473       if( pStart ){
02474         Expr *pX;
02475         int r1;
02476         pX = pStart->pExpr;
02477         assert( pX!=0 );
02478         assert( pStart->leftCursor==iCur );
02479 
02480         /* The ForceInt instruction may modify the register that it operates
02481         ** on. For example it may replace a real value with an integer one,
02482         ** or if p3 is true it may increment the register value. For this
02483         ** reason we need to make sure that register r1 is really a newly
02484         ** allocated temporary register, and not part of the column-cache.
02485         ** For this reason we cannot use sqlite3ExprCodeTemp() here.
02486         */
02487         r1 = sqlite3GetTempReg(pParse);
02488         sqlite3ExprCode(pParse, pX->pRight, r1);
02489 
02490         sqlite3VdbeAddOp3(v, OP_ForceInt, r1, brk, 
02491                              pX->op==TK_LE || pX->op==TK_GT);
02492         sqlite3VdbeAddOp3(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk, r1);
02493         VdbeComment((v, "pk"));
02494         sqlite3ReleaseTempReg(pParse, r1);
02495         disableTerm(pLevel, pStart);
02496       }else{
02497         sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
02498       }
02499       if( pEnd ){
02500         Expr *pX;
02501         pX = pEnd->pExpr;
02502         assert( pX!=0 );
02503         assert( pEnd->leftCursor==iCur );
02504         pLevel->iMem = ++pParse->nMem;
02505         sqlite3ExprCode(pParse, pX->pRight, pLevel->iMem);
02506         if( pX->op==TK_LT || pX->op==TK_GT ){
02507           testOp = bRev ? OP_Le : OP_Ge;
02508         }else{
02509           testOp = bRev ? OP_Lt : OP_Gt;
02510         }
02511         disableTerm(pLevel, pEnd);
02512       }
02513       start = sqlite3VdbeCurrentAddr(v);
02514       pLevel->op = bRev ? OP_Prev : OP_Next;
02515       pLevel->p1 = iCur;
02516       pLevel->p2 = start;
02517       if( testOp!=OP_Noop ){
02518         int r1 = sqlite3GetTempReg(pParse);
02519         sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
02520         /* sqlite3VdbeAddOp2(v, OP_SCopy, pLevel->iMem, 0); */
02521         sqlite3VdbeAddOp3(v, testOp, pLevel->iMem, brk, r1);
02522         sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
02523         sqlite3ReleaseTempReg(pParse, r1);
02524       }
02525     }else if( pLevel->flags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
02526       /* Case 3: A scan using an index.
02527       **
02528       **         The WHERE clause may contain zero or more equality 
02529       **         terms ("==" or "IN" operators) that refer to the N
02530       **         left-most columns of the index. It may also contain
02531       **         inequality constraints (>, <, >= or <=) on the indexed
02532       **         column that immediately follows the N equalities. Only 
02533       **         the right-most column can be an inequality - the rest must
02534       **         use the "==" and "IN" operators. For example, if the 
02535       **         index is on (x,y,z), then the following clauses are all 
02536       **         optimized:
02537       **
02538       **            x=5
02539       **            x=5 AND y=10
02540       **            x=5 AND y<10
02541       **            x=5 AND y>5 AND y<10
02542       **            x=5 AND y=5 AND z<=10
02543       **
02544       **         The z<10 term of the following cannot be used, only
02545       **         the x=5 term:
02546       **
02547       **            x=5 AND z<10
02548       **
02549       **         N may be zero if there are inequality constraints.
02550       **         If there are no inequality constraints, then N is at
02551       **         least one.
02552       **
02553       **         This case is also used when there are no WHERE clause
02554       **         constraints but an index is selected anyway, in order
02555       **         to force the output order to conform to an ORDER BY.
02556       */  
02557       int aStartOp[] = {
02558         0,
02559         0,
02560         OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
02561         OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
02562         OP_MoveGt,           /* 4: (start_constraints  && !startEq && !bRev) */
02563         OP_MoveLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
02564         OP_MoveGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
02565         OP_MoveLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
02566       };
02567       int aEndOp[] = {
02568         OP_Noop,             /* 0: (!end_constraints) */
02569         OP_IdxGE,            /* 1: (end_constraints && !bRev) */
02570         OP_IdxLT             /* 2: (end_constraints && bRev) */
02571       };
02572       int nEq = pLevel->nEq;
02573       int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
02574       int regBase;                 /* Base register holding constraint values */
02575       int r1;                      /* Temp register */
02576       WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
02577       WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
02578       int startEq;                 /* True if range start uses ==, >= or <= */
02579       int endEq;                   /* True if range end uses ==, >= or <= */
02580       int start_constraints;       /* Start of range is constrained */
02581       int k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
02582       int nConstraint;             /* Number of constraint terms */
02583       int op;
02584 
02585       /* Generate code to evaluate all constraint terms using == or IN
02586       ** and store the values of those terms in an array of registers
02587       ** starting at regBase.
02588       */
02589       regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 2);
02590       nxt = pLevel->nxt;
02591 
02592       /* If this loop satisfies a sort order (pOrderBy) request that 
02593       ** was passed to this function to implement a "SELECT min(x) ..." 
02594       ** query, then the caller will only allow the loop to run for
02595       ** a single iteration. This means that the first row returned
02596       ** should not have a NULL value stored in 'x'. If column 'x' is
02597       ** the first one after the nEq equality constraints in the index,
02598       ** this requires some special handling.
02599       */
02600       if( (wflags&WHERE_ORDERBY_MIN)!=0
02601        && (pLevel->flags&WHERE_ORDERBY)
02602        && (pIdx->nColumn>nEq)
02603       ){
02604         assert( pOrderBy->nExpr==1 );
02605         assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] );
02606         isMinQuery = 1;
02607       }
02608 
02609       /* Find any inequality constraint terms for the start and end 
02610       ** of the range. 
02611       */
02612       if( pLevel->flags & WHERE_TOP_LIMIT ){
02613         pRangeEnd = findTerm(&wc, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
02614       }
02615       if( pLevel->flags & WHERE_BTM_LIMIT ){
02616         pRangeStart = findTerm(&wc, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
02617       }
02618 
02619       /* If we are doing a reverse order scan on an ascending index, or
02620       ** a forward order scan on a descending index, interchange the 
02621       ** start and end terms (pRangeStart and pRangeEnd).
02622       */
02623       if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
02624         SWAP(WhereTerm *, pRangeEnd, pRangeStart);
02625       }
02626 
02627       testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
02628       testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
02629       testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
02630       testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
02631       startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
02632       endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
02633       start_constraints = pRangeStart || nEq>0;
02634 
02635       /* Seek the index cursor to the start of the range. */
02636       nConstraint = nEq;
02637       if( pRangeStart ){
02638         int dcc = pParse->disableColCache;
02639         if( pRangeEnd ){
02640           pParse->disableColCache++;
02641         }
02642         sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
02643         pParse->disableColCache = dcc;
02644         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
02645         nConstraint++;
02646       }else if( isMinQuery ){
02647         sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
02648         nConstraint++;
02649         startEq = 0;
02650         start_constraints = 1;
02651       }
02652       codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
02653       op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
02654       assert( op!=0 );
02655       testcase( op==OP_Rewind );
02656       testcase( op==OP_Last );
02657       testcase( op==OP_MoveGt );
02658       testcase( op==OP_MoveGe );
02659       testcase( op==OP_MoveLe );
02660       testcase( op==OP_MoveLt );
02661       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase, 
02662                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
02663 
02664       /* Load the value for the inequality constraint at the end of the
02665       ** range (if any).
02666       */
02667       nConstraint = nEq;
02668       if( pRangeEnd ){
02669         sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
02670         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
02671         codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
02672         nConstraint++;
02673       }
02674 
02675       /* Top of the loop body */
02676       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
02677 
02678       /* Check if the index cursor is past the end of the range. */
02679       op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
02680       testcase( op==OP_Noop );
02681       testcase( op==OP_IdxGE );
02682       testcase( op==OP_IdxLT );
02683       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase,
02684                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
02685       sqlite3VdbeChangeP5(v, endEq!=bRev);
02686 
02687       /* If there are inequality constraints, check that the value
02688       ** of the table column that the inequality contrains is not NULL.
02689       ** If it is, jump to the next iteration of the loop.
02690       */
02691       r1 = sqlite3GetTempReg(pParse);
02692       testcase( pLevel->flags & WHERE_BTM_LIMIT );
02693       testcase( pLevel->flags & WHERE_TOP_LIMIT );
02694       if( pLevel->flags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
02695         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
02696         sqlite3VdbeAddOp2(v, OP_IsNull, r1, cont);
02697       }
02698 
02699       /* Seek the table cursor, if required */
02700       if( !omitTable ){
02701         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
02702         sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1);  /* Deferred seek */
02703       }
02704       sqlite3ReleaseTempReg(pParse, r1);
02705 
02706       /* Record the instruction used to terminate the loop. Disable 
02707       ** WHERE clause terms made redundant by the index range scan.
02708       */
02709       pLevel->op = bRev ? OP_Prev : OP_Next;
02710       pLevel->p1 = iIdxCur;
02711       disableTerm(pLevel, pRangeStart);
02712       disableTerm(pLevel, pRangeEnd);
02713     }else{
02714       /* Case 4:  There is no usable index.  We must do a complete
02715       **          scan of the entire table.
02716       */
02717       assert( omitTable==0 );
02718       assert( bRev==0 );
02719       pLevel->op = OP_Next;
02720       pLevel->p1 = iCur;
02721       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, brk);
02722       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
02723     }
02724     notReady &= ~getMask(&maskSet, iCur);
02725 
02726     /* Insert code to test every subexpression that can be completely
02727     ** computed using the current set of tables.
02728     */
02729     k = 0;
02730     for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
02731       Expr *pE;
02732       testcase( pTerm->flags & TERM_VIRTUAL );
02733       testcase( pTerm->flags & TERM_CODED );
02734       if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
02735       if( (pTerm->prereqAll & notReady)!=0 ) continue;
02736       pE = pTerm->pExpr;
02737       assert( pE!=0 );
02738       if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
02739         continue;
02740       }
02741       pParse->disableColCache += k;
02742       sqlite3ExprIfFalse(pParse, pE, cont, SQLITE_JUMPIFNULL);
02743       pParse->disableColCache -= k;
02744       k = 1;
02745       pTerm->flags |= TERM_CODED;
02746     }
02747 
02748     /* For a LEFT OUTER JOIN, generate code that will record the fact that
02749     ** at least one row of the right table has matched the left table.  
02750     */
02751     if( pLevel->iLeftJoin ){
02752       pLevel->top = sqlite3VdbeCurrentAddr(v);
02753       sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
02754       VdbeComment((v, "record LEFT JOIN hit"));
02755       sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
02756       sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
02757       for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
02758         testcase( pTerm->flags & TERM_VIRTUAL );
02759         testcase( pTerm->flags & TERM_CODED );
02760         if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
02761         if( (pTerm->prereqAll & notReady)!=0 ) continue;
02762         assert( pTerm->pExpr );
02763         sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, SQLITE_JUMPIFNULL);
02764         pTerm->flags |= TERM_CODED;
02765       }
02766     }
02767   }
02768 
02769 #ifdef SQLITE_TEST  /* For testing and debugging use only */
02770   /* Record in the query plan information about the current table
02771   ** and the index used to access it (if any).  If the table itself
02772   ** is not used, its name is just '{}'.  If no index is used
02773   ** the index is listed as "{}".  If the primary key is used the
02774   ** index name is '*'.
02775   */
02776   for(i=0; i<pTabList->nSrc; i++){
02777     char *z;
02778     int n;
02779     pLevel = &pWInfo->a[i];
02780     pTabItem = &pTabList->a[pLevel->iFrom];
02781     z = pTabItem->zAlias;
02782     if( z==0 ) z = pTabItem->pTab->zName;
02783     n = strlen(z);
02784     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
02785       if( pLevel->flags & WHERE_IDX_ONLY ){
02786         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
02787         nQPlan += 2;
02788       }else{
02789         memcpy(&sqlite3_query_plan[nQPlan], z, n);
02790         nQPlan += n;
02791       }
02792       sqlite3_query_plan[nQPlan++] = ' ';
02793     }
02794     testcase( pLevel->flags & WHERE_ROWID_EQ );
02795     testcase( pLevel->flags & WHERE_ROWID_RANGE );
02796     if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
02797       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
02798       nQPlan += 2;
02799     }else if( pLevel->pIdx==0 ){
02800       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
02801       nQPlan += 3;
02802     }else{
02803       n = strlen(pLevel->pIdx->zName);
02804       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
02805         memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
02806         nQPlan += n;
02807         sqlite3_query_plan[nQPlan++] = ' ';
02808       }
02809     }
02810   }
02811   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
02812     sqlite3_query_plan[--nQPlan] = 0;
02813   }
02814   sqlite3_query_plan[nQPlan] = 0;
02815   nQPlan = 0;
02816 #endif /* SQLITE_TEST // Testing and debugging use only */
02817 
02818   /* Record the continuation address in the WhereInfo structure.  Then
02819   ** clean up and return.
02820   */
02821   pWInfo->iContinue = cont;
02822   whereClauseClear(&wc);
02823   return pWInfo;
02824 
02825   /* Jump here if malloc fails */
02826 whereBeginError:
02827   whereClauseClear(&wc);
02828   whereInfoFree(db, pWInfo);
02829   return 0;
02830 }
02831 
02832 /*
02833 ** Generate the end of the WHERE loop.  See comments on 
02834 ** sqlite3WhereBegin() for additional information.
02835 */
02836 void sqlite3WhereEnd(WhereInfo *pWInfo){
02837   Parse *pParse = pWInfo->pParse;
02838   Vdbe *v = pParse->pVdbe;
02839   int i;
02840   WhereLevel *pLevel;
02841   SrcList *pTabList = pWInfo->pTabList;
02842   sqlite3 *db = pParse->db;
02843 
02844   /* Generate loop termination code.
02845   */
02846   sqlite3ExprClearColumnCache(pParse, -1);
02847   for(i=pTabList->nSrc-1; i>=0; i--){
02848     pLevel = &pWInfo->a[i];
02849     sqlite3VdbeResolveLabel(v, pLevel->cont);
02850     if( pLevel->op!=OP_Noop ){
02851       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
02852       sqlite3VdbeChangeP5(v, pLevel->p5);
02853     }
02854     if( pLevel->nIn ){
02855       struct InLoop *pIn;
02856       int j;
02857       sqlite3VdbeResolveLabel(v, pLevel->nxt);
02858       for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
02859         sqlite3VdbeJumpHere(v, pIn->topAddr+1);
02860         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->topAddr);
02861         sqlite3VdbeJumpHere(v, pIn->topAddr-1);
02862       }
02863       sqlite3DbFree(db, pLevel->aInLoop);
02864     }
02865     sqlite3VdbeResolveLabel(v, pLevel->brk);
02866     if( pLevel->iLeftJoin ){
02867       int addr;
02868       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
02869       sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
02870       if( pLevel->iIdxCur>=0 ){
02871         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
02872       }
02873       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->top);
02874       sqlite3VdbeJumpHere(v, addr);
02875     }
02876   }
02877 
02878   /* The "break" point is here, just past the end of the outer loop.
02879   ** Set it.
02880   */
02881   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
02882 
02883   /* Close all of the cursors that were opened by sqlite3WhereBegin.
02884   */
02885   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
02886     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
02887     Table *pTab = pTabItem->pTab;
02888     assert( pTab!=0 );
02889     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
02890     if( !pWInfo->okOnePass && (pLevel->flags & WHERE_IDX_ONLY)==0 ){
02891       sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
02892     }
02893     if( pLevel->pIdx!=0 ){
02894       sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
02895     }
02896 
02897     /* If this scan uses an index, make code substitutions to read data
02898     ** from the index in preference to the table. Sometimes, this means
02899     ** the table need never be read from. This is a performance boost,
02900     ** as the vdbe level waits until the table is read before actually
02901     ** seeking the table cursor to the record corresponding to the current
02902     ** position in the index.
02903     ** 
02904     ** Calls to the code generator in between sqlite3WhereBegin and
02905     ** sqlite3WhereEnd will have created code that references the table
02906     ** directly.  This loop scans all that code looking for opcodes
02907     ** that reference the table and converts them into opcodes that
02908     ** reference the index.
02909     */
02910     if( pLevel->pIdx ){
02911       int k, j, last;
02912       VdbeOp *pOp;
02913       Index *pIdx = pLevel->pIdx;
02914       int useIndexOnly = pLevel->flags & WHERE_IDX_ONLY;
02915 
02916       assert( pIdx!=0 );
02917       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
02918       last = sqlite3VdbeCurrentAddr(v);
02919       for(k=pWInfo->iTop; k<last; k++, pOp++){
02920         if( pOp->p1!=pLevel->iTabCur ) continue;
02921         if( pOp->opcode==OP_Column ){
02922           for(j=0; j<pIdx->nColumn; j++){
02923             if( pOp->p2==pIdx->aiColumn[j] ){
02924               pOp->p2 = j;
02925               pOp->p1 = pLevel->iIdxCur;
02926               break;
02927             }
02928           }
02929           assert(!useIndexOnly || j<pIdx->nColumn);
02930         }else if( pOp->opcode==OP_Rowid ){
02931           pOp->p1 = pLevel->iIdxCur;
02932           pOp->opcode = OP_IdxRowid;
02933         }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
02934           pOp->opcode = OP_Noop;
02935         }
02936       }
02937     }
02938   }
02939 
02940   /* Final cleanup
02941   */
02942   whereInfoFree(db, pWInfo);
02943   return;
02944 }

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:57 2011 by Doxygen 1.6.1