persistentstorage/sql/SQLite/where.c
changeset 0 08ec8eefde2f
equal deleted inserted replaced
-1:000000000000 0:08ec8eefde2f
       
     1 /*
       
     2 ** 2001 September 15
       
     3 **
       
     4 ** The author disclaims copyright to this source code.  In place of
       
     5 ** a legal notice, here is a blessing:
       
     6 **
       
     7 **    May you do good and not evil.
       
     8 **    May you find forgiveness for yourself and forgive others.
       
     9 **    May you share freely, never taking more than you give.
       
    10 **
       
    11 *************************************************************************
       
    12 ** This module contains C code that generates VDBE code used to process
       
    13 ** the WHERE clause of SQL statements.  This module is responsible for
       
    14 ** generating the code that loops through a table looking for applicable
       
    15 ** rows.  Indices are selected and used to speed the search when doing
       
    16 ** so is applicable.  Because this module is responsible for selecting
       
    17 ** indices, you might also think of this module as the "query optimizer".
       
    18 **
       
    19 ** $Id: where.c,v 1.319 2008/08/01 17:37:41 danielk1977 Exp $
       
    20 */
       
    21 #include "sqliteInt.h"
       
    22 
       
    23 /*
       
    24 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
       
    25 */
       
    26 #define BMS  (sizeof(Bitmask)*8)
       
    27 
       
    28 /*
       
    29 ** Trace output macros
       
    30 */
       
    31 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
       
    32 int sqlite3WhereTrace = 0;
       
    33 #endif
       
    34 #if 0
       
    35 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
       
    36 #else
       
    37 # define WHERETRACE(X)
       
    38 #endif
       
    39 
       
    40 /* Forward reference
       
    41 */
       
    42 typedef struct WhereClause WhereClause;
       
    43 typedef struct ExprMaskSet ExprMaskSet;
       
    44 
       
    45 /*
       
    46 ** The query generator uses an array of instances of this structure to
       
    47 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
       
    48 ** clause subexpression is separated from the others by an AND operator.
       
    49 **
       
    50 ** All WhereTerms are collected into a single WhereClause structure.  
       
    51 ** The following identity holds:
       
    52 **
       
    53 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
       
    54 **
       
    55 ** When a term is of the form:
       
    56 **
       
    57 **              X <op> <expr>
       
    58 **
       
    59 ** where X is a column name and <op> is one of certain operators,
       
    60 ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
       
    61 ** cursor number and column number for X.  WhereTerm.operator records
       
    62 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
       
    63 ** use of a bitmask encoding for the operator allows us to search
       
    64 ** quickly for terms that match any of several different operators.
       
    65 **
       
    66 ** prereqRight and prereqAll record sets of cursor numbers,
       
    67 ** but they do so indirectly.  A single ExprMaskSet structure translates
       
    68 ** cursor number into bits and the translated bit is stored in the prereq
       
    69 ** fields.  The translation is used in order to maximize the number of
       
    70 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
       
    71 ** spread out over the non-negative integers.  For example, the cursor
       
    72 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The ExprMaskSet
       
    73 ** translates these sparse cursor numbers into consecutive integers
       
    74 ** beginning with 0 in order to make the best possible use of the available
       
    75 ** bits in the Bitmask.  So, in the example above, the cursor numbers
       
    76 ** would be mapped into integers 0 through 7.
       
    77 */
       
    78 typedef struct WhereTerm WhereTerm;
       
    79 struct WhereTerm {
       
    80   Expr *pExpr;            /* Pointer to the subexpression */
       
    81   i16 iParent;            /* Disable pWC->a[iParent] when this term disabled */
       
    82   i16 leftCursor;         /* Cursor number of X in "X <op> <expr>" */
       
    83   i16 leftColumn;         /* Column number of X in "X <op> <expr>" */
       
    84   u16 eOperator;          /* A WO_xx value describing <op> */
       
    85   u8 flags;               /* Bit flags.  See below */
       
    86   u8 nChild;              /* Number of children that must disable us */
       
    87   WhereClause *pWC;       /* The clause this term is part of */
       
    88   Bitmask prereqRight;    /* Bitmask of tables used by pRight */
       
    89   Bitmask prereqAll;      /* Bitmask of tables referenced by p */
       
    90 };
       
    91 
       
    92 /*
       
    93 ** Allowed values of WhereTerm.flags
       
    94 */
       
    95 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
       
    96 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
       
    97 #define TERM_CODED      0x04   /* This term is already coded */
       
    98 #define TERM_COPIED     0x08   /* Has a child */
       
    99 #define TERM_OR_OK      0x10   /* Used during OR-clause processing */
       
   100 
       
   101 /*
       
   102 ** An instance of the following structure holds all information about a
       
   103 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
       
   104 */
       
   105 struct WhereClause {
       
   106   Parse *pParse;           /* The parser context */
       
   107   ExprMaskSet *pMaskSet;   /* Mapping of table indices to bitmasks */
       
   108   int nTerm;               /* Number of terms */
       
   109   int nSlot;               /* Number of entries in a[] */
       
   110   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
       
   111   WhereTerm aStatic[10];   /* Initial static space for a[] */
       
   112 };
       
   113 
       
   114 /*
       
   115 ** An instance of the following structure keeps track of a mapping
       
   116 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
       
   117 **
       
   118 ** The VDBE cursor numbers are small integers contained in 
       
   119 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
       
   120 ** clause, the cursor numbers might not begin with 0 and they might
       
   121 ** contain gaps in the numbering sequence.  But we want to make maximum
       
   122 ** use of the bits in our bitmasks.  This structure provides a mapping
       
   123 ** from the sparse cursor numbers into consecutive integers beginning
       
   124 ** with 0.
       
   125 **
       
   126 ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
       
   127 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
       
   128 **
       
   129 ** For example, if the WHERE clause expression used these VDBE
       
   130 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  ExprMaskSet structure
       
   131 ** would map those cursor numbers into bits 0 through 5.
       
   132 **
       
   133 ** Note that the mapping is not necessarily ordered.  In the example
       
   134 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
       
   135 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
       
   136 ** does not really matter.  What is important is that sparse cursor
       
   137 ** numbers all get mapped into bit numbers that begin with 0 and contain
       
   138 ** no gaps.
       
   139 */
       
   140 struct ExprMaskSet {
       
   141   int n;                        /* Number of assigned cursor values */
       
   142   int ix[sizeof(Bitmask)*8];    /* Cursor assigned to each bit */
       
   143 };
       
   144 
       
   145 
       
   146 /*
       
   147 ** Bitmasks for the operators that indices are able to exploit.  An
       
   148 ** OR-ed combination of these values can be used when searching for
       
   149 ** terms in the where clause.
       
   150 */
       
   151 #define WO_IN     1
       
   152 #define WO_EQ     2
       
   153 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
       
   154 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
       
   155 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
       
   156 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
       
   157 #define WO_MATCH  64
       
   158 #define WO_ISNULL 128
       
   159 
       
   160 /*
       
   161 ** Value for flags returned by bestIndex().  
       
   162 **
       
   163 ** The least significant byte is reserved as a mask for WO_ values above.
       
   164 ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
       
   165 ** But if the table is the right table of a left join, WhereLevel.flags
       
   166 ** is set to WO_IN|WO_EQ.  The WhereLevel.flags field can then be used as
       
   167 ** the "op" parameter to findTerm when we are resolving equality constraints.
       
   168 ** ISNULL constraints will then not be used on the right table of a left
       
   169 ** join.  Tickets #2177 and #2189.
       
   170 */
       
   171 #define WHERE_ROWID_EQ     0x000100   /* rowid=EXPR or rowid IN (...) */
       
   172 #define WHERE_ROWID_RANGE  0x000200   /* rowid<EXPR and/or rowid>EXPR */
       
   173 #define WHERE_COLUMN_EQ    0x001000   /* x=EXPR or x IN (...) */
       
   174 #define WHERE_COLUMN_RANGE 0x002000   /* x<EXPR and/or x>EXPR */
       
   175 #define WHERE_COLUMN_IN    0x004000   /* x IN (...) */
       
   176 #define WHERE_TOP_LIMIT    0x010000   /* x<EXPR or x<=EXPR constraint */
       
   177 #define WHERE_BTM_LIMIT    0x020000   /* x>EXPR or x>=EXPR constraint */
       
   178 #define WHERE_IDX_ONLY     0x080000   /* Use index only - omit table */
       
   179 #define WHERE_ORDERBY      0x100000   /* Output will appear in correct order */
       
   180 #define WHERE_REVERSE      0x200000   /* Scan in reverse order */
       
   181 #define WHERE_UNIQUE       0x400000   /* Selects no more than one row */
       
   182 #define WHERE_VIRTUALTABLE 0x800000   /* Use virtual-table processing */
       
   183 
       
   184 /*
       
   185 ** Initialize a preallocated WhereClause structure.
       
   186 */
       
   187 static void whereClauseInit(
       
   188   WhereClause *pWC,        /* The WhereClause to be initialized */
       
   189   Parse *pParse,           /* The parsing context */
       
   190   ExprMaskSet *pMaskSet    /* Mapping from table indices to bitmasks */
       
   191 ){
       
   192   pWC->pParse = pParse;
       
   193   pWC->pMaskSet = pMaskSet;
       
   194   pWC->nTerm = 0;
       
   195   pWC->nSlot = ArraySize(pWC->aStatic);
       
   196   pWC->a = pWC->aStatic;
       
   197 }
       
   198 
       
   199 /*
       
   200 ** Deallocate a WhereClause structure.  The WhereClause structure
       
   201 ** itself is not freed.  This routine is the inverse of whereClauseInit().
       
   202 */
       
   203 static void whereClauseClear(WhereClause *pWC){
       
   204   int i;
       
   205   WhereTerm *a;
       
   206   sqlite3 *db = pWC->pParse->db;
       
   207   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
       
   208     if( a->flags & TERM_DYNAMIC ){
       
   209       sqlite3ExprDelete(db, a->pExpr);
       
   210     }
       
   211   }
       
   212   if( pWC->a!=pWC->aStatic ){
       
   213     sqlite3DbFree(db, pWC->a);
       
   214   }
       
   215 }
       
   216 
       
   217 /*
       
   218 ** Add a new entries to the WhereClause structure.  Increase the allocated
       
   219 ** space as necessary.
       
   220 **
       
   221 ** If the flags argument includes TERM_DYNAMIC, then responsibility
       
   222 ** for freeing the expression p is assumed by the WhereClause object.
       
   223 **
       
   224 ** WARNING:  This routine might reallocate the space used to store
       
   225 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
       
   226 ** calling this routine.  Such pointers may be reinitialized by referencing
       
   227 ** the pWC->a[] array.
       
   228 */
       
   229 static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
       
   230   WhereTerm *pTerm;
       
   231   int idx;
       
   232   if( pWC->nTerm>=pWC->nSlot ){
       
   233     WhereTerm *pOld = pWC->a;
       
   234     sqlite3 *db = pWC->pParse->db;
       
   235     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
       
   236     if( pWC->a==0 ){
       
   237       if( flags & TERM_DYNAMIC ){
       
   238         sqlite3ExprDelete(db, p);
       
   239       }
       
   240       pWC->a = pOld;
       
   241       return 0;
       
   242     }
       
   243     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
       
   244     if( pOld!=pWC->aStatic ){
       
   245       sqlite3DbFree(db, pOld);
       
   246     }
       
   247     pWC->nSlot *= 2;
       
   248   }
       
   249   pTerm = &pWC->a[idx = pWC->nTerm];
       
   250   pWC->nTerm++;
       
   251   pTerm->pExpr = p;
       
   252   pTerm->flags = flags;
       
   253   pTerm->pWC = pWC;
       
   254   pTerm->iParent = -1;
       
   255   return idx;
       
   256 }
       
   257 
       
   258 /*
       
   259 ** This routine identifies subexpressions in the WHERE clause where
       
   260 ** each subexpression is separated by the AND operator or some other
       
   261 ** operator specified in the op parameter.  The WhereClause structure
       
   262 ** is filled with pointers to subexpressions.  For example:
       
   263 **
       
   264 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
       
   265 **           \________/     \_______________/     \________________/
       
   266 **            slot[0]            slot[1]               slot[2]
       
   267 **
       
   268 ** The original WHERE clause in pExpr is unaltered.  All this routine
       
   269 ** does is make slot[] entries point to substructure within pExpr.
       
   270 **
       
   271 ** In the previous sentence and in the diagram, "slot[]" refers to
       
   272 ** the WhereClause.a[] array.  This array grows as needed to contain
       
   273 ** all terms of the WHERE clause.
       
   274 */
       
   275 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
       
   276   if( pExpr==0 ) return;
       
   277   if( pExpr->op!=op ){
       
   278     whereClauseInsert(pWC, pExpr, 0);
       
   279   }else{
       
   280     whereSplit(pWC, pExpr->pLeft, op);
       
   281     whereSplit(pWC, pExpr->pRight, op);
       
   282   }
       
   283 }
       
   284 
       
   285 /*
       
   286 ** Initialize an expression mask set
       
   287 */
       
   288 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
       
   289 
       
   290 /*
       
   291 ** Return the bitmask for the given cursor number.  Return 0 if
       
   292 ** iCursor is not in the set.
       
   293 */
       
   294 static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
       
   295   int i;
       
   296   for(i=0; i<pMaskSet->n; i++){
       
   297     if( pMaskSet->ix[i]==iCursor ){
       
   298       return ((Bitmask)1)<<i;
       
   299     }
       
   300   }
       
   301   return 0;
       
   302 }
       
   303 
       
   304 /*
       
   305 ** Create a new mask for cursor iCursor.
       
   306 **
       
   307 ** There is one cursor per table in the FROM clause.  The number of
       
   308 ** tables in the FROM clause is limited by a test early in the
       
   309 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
       
   310 ** array will never overflow.
       
   311 */
       
   312 static void createMask(ExprMaskSet *pMaskSet, int iCursor){
       
   313   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
       
   314   pMaskSet->ix[pMaskSet->n++] = iCursor;
       
   315 }
       
   316 
       
   317 /*
       
   318 ** This routine walks (recursively) an expression tree and generates
       
   319 ** a bitmask indicating which tables are used in that expression
       
   320 ** tree.
       
   321 **
       
   322 ** In order for this routine to work, the calling function must have
       
   323 ** previously invoked sqlite3ExprResolveNames() on the expression.  See
       
   324 ** the header comment on that routine for additional information.
       
   325 ** The sqlite3ExprResolveNames() routines looks for column names and
       
   326 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
       
   327 ** the VDBE cursor number of the table.  This routine just has to
       
   328 ** translate the cursor numbers into bitmask values and OR all
       
   329 ** the bitmasks together.
       
   330 */
       
   331 static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
       
   332 static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
       
   333 static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
       
   334   Bitmask mask = 0;
       
   335   if( p==0 ) return 0;
       
   336   if( p->op==TK_COLUMN ){
       
   337     mask = getMask(pMaskSet, p->iTable);
       
   338     return mask;
       
   339   }
       
   340   mask = exprTableUsage(pMaskSet, p->pRight);
       
   341   mask |= exprTableUsage(pMaskSet, p->pLeft);
       
   342   mask |= exprListTableUsage(pMaskSet, p->pList);
       
   343   mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
       
   344   return mask;
       
   345 }
       
   346 static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
       
   347   int i;
       
   348   Bitmask mask = 0;
       
   349   if( pList ){
       
   350     for(i=0; i<pList->nExpr; i++){
       
   351       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
       
   352     }
       
   353   }
       
   354   return mask;
       
   355 }
       
   356 static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
       
   357   Bitmask mask = 0;
       
   358   while( pS ){
       
   359     mask |= exprListTableUsage(pMaskSet, pS->pEList);
       
   360     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
       
   361     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
       
   362     mask |= exprTableUsage(pMaskSet, pS->pWhere);
       
   363     mask |= exprTableUsage(pMaskSet, pS->pHaving);
       
   364     pS = pS->pPrior;
       
   365   }
       
   366   return mask;
       
   367 }
       
   368 
       
   369 /*
       
   370 ** Return TRUE if the given operator is one of the operators that is
       
   371 ** allowed for an indexable WHERE clause term.  The allowed operators are
       
   372 ** "=", "<", ">", "<=", ">=", and "IN".
       
   373 */
       
   374 static int allowedOp(int op){
       
   375   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
       
   376   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
       
   377   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
       
   378   assert( TK_GE==TK_EQ+4 );
       
   379   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
       
   380 }
       
   381 
       
   382 /*
       
   383 ** Swap two objects of type T.
       
   384 */
       
   385 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
       
   386 
       
   387 /*
       
   388 ** Commute a comparison operator.  Expressions of the form "X op Y"
       
   389 ** are converted into "Y op X".
       
   390 **
       
   391 ** If a collation sequence is associated with either the left or right
       
   392 ** side of the comparison, it remains associated with the same side after
       
   393 ** the commutation. So "Y collate NOCASE op X" becomes 
       
   394 ** "X collate NOCASE op Y". This is because any collation sequence on
       
   395 ** the left hand side of a comparison overrides any collation sequence 
       
   396 ** attached to the right. For the same reason the EP_ExpCollate flag
       
   397 ** is not commuted.
       
   398 */
       
   399 static void exprCommute(Expr *pExpr){
       
   400   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
       
   401   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
       
   402   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
       
   403   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
       
   404   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
       
   405   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
       
   406   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
       
   407   if( pExpr->op>=TK_GT ){
       
   408     assert( TK_LT==TK_GT+2 );
       
   409     assert( TK_GE==TK_LE+2 );
       
   410     assert( TK_GT>TK_EQ );
       
   411     assert( TK_GT<TK_LE );
       
   412     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
       
   413     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
       
   414   }
       
   415 }
       
   416 
       
   417 /*
       
   418 ** Translate from TK_xx operator to WO_xx bitmask.
       
   419 */
       
   420 static int operatorMask(int op){
       
   421   int c;
       
   422   assert( allowedOp(op) );
       
   423   if( op==TK_IN ){
       
   424     c = WO_IN;
       
   425   }else if( op==TK_ISNULL ){
       
   426     c = WO_ISNULL;
       
   427   }else{
       
   428     c = WO_EQ<<(op-TK_EQ);
       
   429   }
       
   430   assert( op!=TK_ISNULL || c==WO_ISNULL );
       
   431   assert( op!=TK_IN || c==WO_IN );
       
   432   assert( op!=TK_EQ || c==WO_EQ );
       
   433   assert( op!=TK_LT || c==WO_LT );
       
   434   assert( op!=TK_LE || c==WO_LE );
       
   435   assert( op!=TK_GT || c==WO_GT );
       
   436   assert( op!=TK_GE || c==WO_GE );
       
   437   return c;
       
   438 }
       
   439 
       
   440 /*
       
   441 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
       
   442 ** where X is a reference to the iColumn of table iCur and <op> is one of
       
   443 ** the WO_xx operator codes specified by the op parameter.
       
   444 ** Return a pointer to the term.  Return 0 if not found.
       
   445 */
       
   446 static WhereTerm *findTerm(
       
   447   WhereClause *pWC,     /* The WHERE clause to be searched */
       
   448   int iCur,             /* Cursor number of LHS */
       
   449   int iColumn,          /* Column number of LHS */
       
   450   Bitmask notReady,     /* RHS must not overlap with this mask */
       
   451   u16 op,               /* Mask of WO_xx values describing operator */
       
   452   Index *pIdx           /* Must be compatible with this index, if not NULL */
       
   453 ){
       
   454   WhereTerm *pTerm;
       
   455   int k;
       
   456   assert( iCur>=0 );
       
   457   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
       
   458     if( pTerm->leftCursor==iCur
       
   459        && (pTerm->prereqRight & notReady)==0
       
   460        && pTerm->leftColumn==iColumn
       
   461        && (pTerm->eOperator & op)!=0
       
   462     ){
       
   463       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
       
   464         Expr *pX = pTerm->pExpr;
       
   465         CollSeq *pColl;
       
   466         char idxaff;
       
   467         int j;
       
   468         Parse *pParse = pWC->pParse;
       
   469 
       
   470         idxaff = pIdx->pTable->aCol[iColumn].affinity;
       
   471         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
       
   472 
       
   473         /* Figure out the collation sequence required from an index for
       
   474         ** it to be useful for optimising expression pX. Store this
       
   475         ** value in variable pColl.
       
   476         */
       
   477         assert(pX->pLeft);
       
   478         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
       
   479         if( !pColl ){
       
   480           pColl = pParse->db->pDfltColl;
       
   481         }
       
   482 
       
   483         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
       
   484           if( NEVER(j>=pIdx->nColumn) ) return 0;
       
   485         }
       
   486         if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
       
   487       }
       
   488       return pTerm;
       
   489     }
       
   490   }
       
   491   return 0;
       
   492 }
       
   493 
       
   494 /* Forward reference */
       
   495 static void exprAnalyze(SrcList*, WhereClause*, int);
       
   496 
       
   497 /*
       
   498 ** Call exprAnalyze on all terms in a WHERE clause.  
       
   499 **
       
   500 **
       
   501 */
       
   502 static void exprAnalyzeAll(
       
   503   SrcList *pTabList,       /* the FROM clause */
       
   504   WhereClause *pWC         /* the WHERE clause to be analyzed */
       
   505 ){
       
   506   int i;
       
   507   for(i=pWC->nTerm-1; i>=0; i--){
       
   508     exprAnalyze(pTabList, pWC, i);
       
   509   }
       
   510 }
       
   511 
       
   512 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
       
   513 /*
       
   514 ** Check to see if the given expression is a LIKE or GLOB operator that
       
   515 ** can be optimized using inequality constraints.  Return TRUE if it is
       
   516 ** so and false if not.
       
   517 **
       
   518 ** In order for the operator to be optimizible, the RHS must be a string
       
   519 ** literal that does not begin with a wildcard.  
       
   520 */
       
   521 static int isLikeOrGlob(
       
   522   sqlite3 *db,      /* The database */
       
   523   Expr *pExpr,      /* Test this expression */
       
   524   int *pnPattern,   /* Number of non-wildcard prefix characters */
       
   525   int *pisComplete, /* True if the only wildcard is % in the last character */
       
   526   int *pnoCase      /* True if uppercase is equivalent to lowercase */
       
   527 ){
       
   528   const char *z;
       
   529   Expr *pRight, *pLeft;
       
   530   ExprList *pList;
       
   531   int c, cnt;
       
   532   char wc[3];
       
   533   CollSeq *pColl;
       
   534 
       
   535   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
       
   536     return 0;
       
   537   }
       
   538 #ifdef SQLITE_EBCDIC
       
   539   if( *pnoCase ) return 0;
       
   540 #endif
       
   541   pList = pExpr->pList;
       
   542   pRight = pList->a[0].pExpr;
       
   543   if( pRight->op!=TK_STRING
       
   544    && (pRight->op!=TK_REGISTER || pRight->iColumn!=TK_STRING) ){
       
   545     return 0;
       
   546   }
       
   547   pLeft = pList->a[1].pExpr;
       
   548   if( pLeft->op!=TK_COLUMN ){
       
   549     return 0;
       
   550   }
       
   551   pColl = pLeft->pColl;
       
   552   assert( pColl!=0 || pLeft->iColumn==-1 );
       
   553   if( pColl==0 ){
       
   554     /* No collation is defined for the ROWID.  Use the default. */
       
   555     pColl = db->pDfltColl;
       
   556   }
       
   557   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
       
   558       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
       
   559     return 0;
       
   560   }
       
   561   sqlite3DequoteExpr(db, pRight);
       
   562   z = (char *)pRight->token.z;
       
   563   cnt = 0;
       
   564   if( z ){
       
   565     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
       
   566   }
       
   567   if( cnt==0 || 255==(u8)z[cnt] ){
       
   568     return 0;
       
   569   }
       
   570   *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
       
   571   *pnPattern = cnt;
       
   572   return 1;
       
   573 }
       
   574 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
       
   575 
       
   576 
       
   577 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
   578 /*
       
   579 ** Check to see if the given expression is of the form
       
   580 **
       
   581 **         column MATCH expr
       
   582 **
       
   583 ** If it is then return TRUE.  If not, return FALSE.
       
   584 */
       
   585 static int isMatchOfColumn(
       
   586   Expr *pExpr      /* Test this expression */
       
   587 ){
       
   588   ExprList *pList;
       
   589 
       
   590   if( pExpr->op!=TK_FUNCTION ){
       
   591     return 0;
       
   592   }
       
   593   if( pExpr->token.n!=5 ||
       
   594        sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
       
   595     return 0;
       
   596   }
       
   597   pList = pExpr->pList;
       
   598   if( pList->nExpr!=2 ){
       
   599     return 0;
       
   600   }
       
   601   if( pList->a[1].pExpr->op != TK_COLUMN ){
       
   602     return 0;
       
   603   }
       
   604   return 1;
       
   605 }
       
   606 #endif /* SQLITE_OMIT_VIRTUALTABLE */
       
   607 
       
   608 /*
       
   609 ** If the pBase expression originated in the ON or USING clause of
       
   610 ** a join, then transfer the appropriate markings over to derived.
       
   611 */
       
   612 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
       
   613   pDerived->flags |= pBase->flags & EP_FromJoin;
       
   614   pDerived->iRightJoinTable = pBase->iRightJoinTable;
       
   615 }
       
   616 
       
   617 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
       
   618 /*
       
   619 ** Return TRUE if the given term of an OR clause can be converted
       
   620 ** into an IN clause.  The iCursor and iColumn define the left-hand
       
   621 ** side of the IN clause.
       
   622 **
       
   623 ** The context is that we have multiple OR-connected equality terms
       
   624 ** like this:
       
   625 **
       
   626 **           a=<expr1> OR  a=<expr2> OR b=<expr3>  OR ...
       
   627 **
       
   628 ** The pOrTerm input to this routine corresponds to a single term of
       
   629 ** this OR clause.  In order for the term to be a candidate for
       
   630 ** conversion to an IN operator, the following must be true:
       
   631 **
       
   632 **     *  The left-hand side of the term must be the column which
       
   633 **        is identified by iCursor and iColumn.
       
   634 **
       
   635 **     *  If the right-hand side is also a column, then the affinities
       
   636 **        of both right and left sides must be such that no type
       
   637 **        conversions are required on the right.  (Ticket #2249)
       
   638 **
       
   639 ** If both of these conditions are true, then return true.  Otherwise
       
   640 ** return false.
       
   641 */
       
   642 static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
       
   643   int affLeft, affRight;
       
   644   assert( pOrTerm->eOperator==WO_EQ );
       
   645   if( pOrTerm->leftCursor!=iCursor ){
       
   646     return 0;
       
   647   }
       
   648   if( pOrTerm->leftColumn!=iColumn ){
       
   649     return 0;
       
   650   }
       
   651   affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
       
   652   if( affRight==0 ){
       
   653     return 1;
       
   654   }
       
   655   affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
       
   656   if( affRight!=affLeft ){
       
   657     return 0;
       
   658   }
       
   659   return 1;
       
   660 }
       
   661 
       
   662 /*
       
   663 ** Return true if the given term of an OR clause can be ignored during
       
   664 ** a check to make sure all OR terms are candidates for optimization.
       
   665 ** In other words, return true if a call to the orTermIsOptCandidate()
       
   666 ** above returned false but it is not necessary to disqualify the
       
   667 ** optimization.
       
   668 **
       
   669 ** Suppose the original OR phrase was this:
       
   670 **
       
   671 **           a=4  OR  a=11  OR  a=b
       
   672 **
       
   673 ** During analysis, the third term gets flipped around and duplicate
       
   674 ** so that we are left with this:
       
   675 **
       
   676 **           a=4  OR  a=11  OR  a=b  OR  b=a
       
   677 **
       
   678 ** Since the last two terms are duplicates, only one of them
       
   679 ** has to qualify in order for the whole phrase to qualify.  When
       
   680 ** this routine is called, we know that pOrTerm did not qualify.
       
   681 ** This routine merely checks to see if pOrTerm has a duplicate that
       
   682 ** might qualify.  If there is a duplicate that has not yet been
       
   683 ** disqualified, then return true.  If there are no duplicates, or
       
   684 ** the duplicate has also been disqualified, return false.
       
   685 */
       
   686 static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
       
   687   if( pOrTerm->flags & TERM_COPIED ){
       
   688     /* This is the original term.  The duplicate is to the left had
       
   689     ** has not yet been analyzed and thus has not yet been disqualified. */
       
   690     return 1;
       
   691   }
       
   692   if( (pOrTerm->flags & TERM_VIRTUAL)!=0
       
   693      && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
       
   694     /* This is a duplicate term.  The original qualified so this one
       
   695     ** does not have to. */
       
   696     return 1;
       
   697   }
       
   698   /* This is either a singleton term or else it is a duplicate for
       
   699   ** which the original did not qualify.  Either way we are done for. */
       
   700   return 0;
       
   701 }
       
   702 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
       
   703 
       
   704 /*
       
   705 ** The input to this routine is an WhereTerm structure with only the
       
   706 ** "pExpr" field filled in.  The job of this routine is to analyze the
       
   707 ** subexpression and populate all the other fields of the WhereTerm
       
   708 ** structure.
       
   709 **
       
   710 ** If the expression is of the form "<expr> <op> X" it gets commuted
       
   711 ** to the standard form of "X <op> <expr>".  If the expression is of
       
   712 ** the form "X <op> Y" where both X and Y are columns, then the original
       
   713 ** expression is unchanged and a new virtual expression of the form
       
   714 ** "Y <op> X" is added to the WHERE clause and analyzed separately.
       
   715 */
       
   716 static void exprAnalyze(
       
   717   SrcList *pSrc,            /* the FROM clause */
       
   718   WhereClause *pWC,         /* the WHERE clause */
       
   719   int idxTerm               /* Index of the term to be analyzed */
       
   720 ){
       
   721   WhereTerm *pTerm;
       
   722   ExprMaskSet *pMaskSet;
       
   723   Expr *pExpr;
       
   724   Bitmask prereqLeft;
       
   725   Bitmask prereqAll;
       
   726   Bitmask extraRight = 0;
       
   727   int nPattern;
       
   728   int isComplete;
       
   729   int noCase;
       
   730   int op;
       
   731   Parse *pParse = pWC->pParse;
       
   732   sqlite3 *db = pParse->db;
       
   733 
       
   734   if( db->mallocFailed ){
       
   735     return;
       
   736   }
       
   737   pTerm = &pWC->a[idxTerm];
       
   738   pMaskSet = pWC->pMaskSet;
       
   739   pExpr = pTerm->pExpr;
       
   740   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
       
   741   op = pExpr->op;
       
   742   if( op==TK_IN ){
       
   743     assert( pExpr->pRight==0 );
       
   744     pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
       
   745                           | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
       
   746   }else if( op==TK_ISNULL ){
       
   747     pTerm->prereqRight = 0;
       
   748   }else{
       
   749     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
       
   750   }
       
   751   prereqAll = exprTableUsage(pMaskSet, pExpr);
       
   752   if( ExprHasProperty(pExpr, EP_FromJoin) ){
       
   753     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
       
   754     prereqAll |= x;
       
   755     extraRight = x-1;  /* ON clause terms may not be used with an index
       
   756                        ** on left table of a LEFT JOIN.  Ticket #3015 */
       
   757   }
       
   758   pTerm->prereqAll = prereqAll;
       
   759   pTerm->leftCursor = -1;
       
   760   pTerm->iParent = -1;
       
   761   pTerm->eOperator = 0;
       
   762   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
       
   763     Expr *pLeft = pExpr->pLeft;
       
   764     Expr *pRight = pExpr->pRight;
       
   765     if( pLeft->op==TK_COLUMN ){
       
   766       pTerm->leftCursor = pLeft->iTable;
       
   767       pTerm->leftColumn = pLeft->iColumn;
       
   768       pTerm->eOperator = operatorMask(op);
       
   769     }
       
   770     if( pRight && pRight->op==TK_COLUMN ){
       
   771       WhereTerm *pNew;
       
   772       Expr *pDup;
       
   773       if( pTerm->leftCursor>=0 ){
       
   774         int idxNew;
       
   775         pDup = sqlite3ExprDup(db, pExpr);
       
   776         if( db->mallocFailed ){
       
   777           sqlite3ExprDelete(db, pDup);
       
   778           return;
       
   779         }
       
   780         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
       
   781         if( idxNew==0 ) return;
       
   782         pNew = &pWC->a[idxNew];
       
   783         pNew->iParent = idxTerm;
       
   784         pTerm = &pWC->a[idxTerm];
       
   785         pTerm->nChild = 1;
       
   786         pTerm->flags |= TERM_COPIED;
       
   787       }else{
       
   788         pDup = pExpr;
       
   789         pNew = pTerm;
       
   790       }
       
   791       exprCommute(pDup);
       
   792       pLeft = pDup->pLeft;
       
   793       pNew->leftCursor = pLeft->iTable;
       
   794       pNew->leftColumn = pLeft->iColumn;
       
   795       pNew->prereqRight = prereqLeft;
       
   796       pNew->prereqAll = prereqAll;
       
   797       pNew->eOperator = operatorMask(pDup->op);
       
   798     }
       
   799   }
       
   800 
       
   801 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
       
   802   /* If a term is the BETWEEN operator, create two new virtual terms
       
   803   ** that define the range that the BETWEEN implements.
       
   804   */
       
   805   else if( pExpr->op==TK_BETWEEN ){
       
   806     ExprList *pList = pExpr->pList;
       
   807     int i;
       
   808     static const u8 ops[] = {TK_GE, TK_LE};
       
   809     assert( pList!=0 );
       
   810     assert( pList->nExpr==2 );
       
   811     for(i=0; i<2; i++){
       
   812       Expr *pNewExpr;
       
   813       int idxNew;
       
   814       pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
       
   815                              sqlite3ExprDup(db, pList->a[i].pExpr), 0);
       
   816       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
       
   817       exprAnalyze(pSrc, pWC, idxNew);
       
   818       pTerm = &pWC->a[idxTerm];
       
   819       pWC->a[idxNew].iParent = idxTerm;
       
   820     }
       
   821     pTerm->nChild = 2;
       
   822   }
       
   823 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
       
   824 
       
   825 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
       
   826   /* Attempt to convert OR-connected terms into an IN operator so that
       
   827   ** they can make use of indices.  Example:
       
   828   **
       
   829   **      x = expr1  OR  expr2 = x  OR  x = expr3
       
   830   **
       
   831   ** is converted into
       
   832   **
       
   833   **      x IN (expr1,expr2,expr3)
       
   834   **
       
   835   ** This optimization must be omitted if OMIT_SUBQUERY is defined because
       
   836   ** the compiler for the the IN operator is part of sub-queries.
       
   837   */
       
   838   else if( pExpr->op==TK_OR ){
       
   839     int ok;
       
   840     int i, j;
       
   841     int iColumn, iCursor;
       
   842     WhereClause sOr;
       
   843     WhereTerm *pOrTerm;
       
   844 
       
   845     assert( (pTerm->flags & TERM_DYNAMIC)==0 );
       
   846     whereClauseInit(&sOr, pWC->pParse, pMaskSet);
       
   847     whereSplit(&sOr, pExpr, TK_OR);
       
   848     exprAnalyzeAll(pSrc, &sOr);
       
   849     assert( sOr.nTerm>=2 );
       
   850     j = 0;
       
   851     if( db->mallocFailed ) goto or_not_possible;
       
   852     do{
       
   853       assert( j<sOr.nTerm );
       
   854       iColumn = sOr.a[j].leftColumn;
       
   855       iCursor = sOr.a[j].leftCursor;
       
   856       ok = iCursor>=0;
       
   857       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
       
   858         if( pOrTerm->eOperator!=WO_EQ ){
       
   859           goto or_not_possible;
       
   860         }
       
   861         if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
       
   862           pOrTerm->flags |= TERM_OR_OK;
       
   863         }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
       
   864           pOrTerm->flags &= ~TERM_OR_OK;
       
   865         }else{
       
   866           ok = 0;
       
   867         }
       
   868       }
       
   869     }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
       
   870     if( ok ){
       
   871       ExprList *pList = 0;
       
   872       Expr *pNew, *pDup;
       
   873       Expr *pLeft = 0;
       
   874       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0; i--, pOrTerm++){
       
   875         if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
       
   876         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
       
   877         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
       
   878         pLeft = pOrTerm->pExpr->pLeft;
       
   879       }
       
   880       assert( pLeft!=0 );
       
   881       pDup = sqlite3ExprDup(db, pLeft);
       
   882       pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
       
   883       if( pNew ){
       
   884         int idxNew;
       
   885         transferJoinMarkings(pNew, pExpr);
       
   886         pNew->pList = pList;
       
   887         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
       
   888         exprAnalyze(pSrc, pWC, idxNew);
       
   889         pTerm = &pWC->a[idxTerm];
       
   890         pWC->a[idxNew].iParent = idxTerm;
       
   891         pTerm->nChild = 1;
       
   892       }else{
       
   893         sqlite3ExprListDelete(db, pList);
       
   894       }
       
   895     }
       
   896 or_not_possible:
       
   897     whereClauseClear(&sOr);
       
   898   }
       
   899 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
       
   900 
       
   901 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
       
   902   /* Add constraints to reduce the search space on a LIKE or GLOB
       
   903   ** operator.
       
   904   **
       
   905   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
       
   906   **
       
   907   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
       
   908   **
       
   909   ** The last character of the prefix "abc" is incremented to form the
       
   910   ** termination condition "abd".
       
   911   */
       
   912   if( isLikeOrGlob(db, pExpr, &nPattern, &isComplete, &noCase) ){
       
   913     Expr *pLeft, *pRight;
       
   914     Expr *pStr1, *pStr2;
       
   915     Expr *pNewExpr1, *pNewExpr2;
       
   916     int idxNew1, idxNew2;
       
   917 
       
   918     pLeft = pExpr->pList->a[1].pExpr;
       
   919     pRight = pExpr->pList->a[0].pExpr;
       
   920     pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
       
   921     if( pStr1 ){
       
   922       sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
       
   923       pStr1->token.n = nPattern;
       
   924       pStr1->flags = EP_Dequoted;
       
   925     }
       
   926     pStr2 = sqlite3ExprDup(db, pStr1);
       
   927     if( !db->mallocFailed ){
       
   928       u8 c, *pC;
       
   929       assert( pStr2->token.dyn );
       
   930       pC = (u8*)&pStr2->token.z[nPattern-1];
       
   931       c = *pC;
       
   932       if( noCase ){
       
   933         if( c=='@' ) isComplete = 0;
       
   934         c = sqlite3UpperToLower[c];
       
   935       }
       
   936       *pC = c + 1;
       
   937     }
       
   938     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
       
   939     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
       
   940     exprAnalyze(pSrc, pWC, idxNew1);
       
   941     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
       
   942     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
       
   943     exprAnalyze(pSrc, pWC, idxNew2);
       
   944     pTerm = &pWC->a[idxTerm];
       
   945     if( isComplete ){
       
   946       pWC->a[idxNew1].iParent = idxTerm;
       
   947       pWC->a[idxNew2].iParent = idxTerm;
       
   948       pTerm->nChild = 2;
       
   949     }
       
   950   }
       
   951 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
       
   952 
       
   953 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
   954   /* Add a WO_MATCH auxiliary term to the constraint set if the
       
   955   ** current expression is of the form:  column MATCH expr.
       
   956   ** This information is used by the xBestIndex methods of
       
   957   ** virtual tables.  The native query optimizer does not attempt
       
   958   ** to do anything with MATCH functions.
       
   959   */
       
   960   if( isMatchOfColumn(pExpr) ){
       
   961     int idxNew;
       
   962     Expr *pRight, *pLeft;
       
   963     WhereTerm *pNewTerm;
       
   964     Bitmask prereqColumn, prereqExpr;
       
   965 
       
   966     pRight = pExpr->pList->a[0].pExpr;
       
   967     pLeft = pExpr->pList->a[1].pExpr;
       
   968     prereqExpr = exprTableUsage(pMaskSet, pRight);
       
   969     prereqColumn = exprTableUsage(pMaskSet, pLeft);
       
   970     if( (prereqExpr & prereqColumn)==0 ){
       
   971       Expr *pNewExpr;
       
   972       pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
       
   973       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
       
   974       pNewTerm = &pWC->a[idxNew];
       
   975       pNewTerm->prereqRight = prereqExpr;
       
   976       pNewTerm->leftCursor = pLeft->iTable;
       
   977       pNewTerm->leftColumn = pLeft->iColumn;
       
   978       pNewTerm->eOperator = WO_MATCH;
       
   979       pNewTerm->iParent = idxTerm;
       
   980       pTerm = &pWC->a[idxTerm];
       
   981       pTerm->nChild = 1;
       
   982       pTerm->flags |= TERM_COPIED;
       
   983       pNewTerm->prereqAll = pTerm->prereqAll;
       
   984     }
       
   985   }
       
   986 #endif /* SQLITE_OMIT_VIRTUALTABLE */
       
   987 
       
   988   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
       
   989   ** an index for tables to the left of the join.
       
   990   */
       
   991   pTerm->prereqRight |= extraRight;
       
   992 }
       
   993 
       
   994 /*
       
   995 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
       
   996 ** a reference to any table other than the iBase table.
       
   997 */
       
   998 static int referencesOtherTables(
       
   999   ExprList *pList,          /* Search expressions in ths list */
       
  1000   ExprMaskSet *pMaskSet,    /* Mapping from tables to bitmaps */
       
  1001   int iFirst,               /* Be searching with the iFirst-th expression */
       
  1002   int iBase                 /* Ignore references to this table */
       
  1003 ){
       
  1004   Bitmask allowed = ~getMask(pMaskSet, iBase);
       
  1005   while( iFirst<pList->nExpr ){
       
  1006     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
       
  1007       return 1;
       
  1008     }
       
  1009   }
       
  1010   return 0;
       
  1011 }
       
  1012 
       
  1013 
       
  1014 /*
       
  1015 ** This routine decides if pIdx can be used to satisfy the ORDER BY
       
  1016 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
       
  1017 ** ORDER BY clause, this routine returns 0.
       
  1018 **
       
  1019 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
       
  1020 ** left-most table in the FROM clause of that same SELECT statement and
       
  1021 ** the table has a cursor number of "base".  pIdx is an index on pTab.
       
  1022 **
       
  1023 ** nEqCol is the number of columns of pIdx that are used as equality
       
  1024 ** constraints.  Any of these columns may be missing from the ORDER BY
       
  1025 ** clause and the match can still be a success.
       
  1026 **
       
  1027 ** All terms of the ORDER BY that match against the index must be either
       
  1028 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
       
  1029 ** index do not need to satisfy this constraint.)  The *pbRev value is
       
  1030 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
       
  1031 ** the ORDER BY clause is all ASC.
       
  1032 */
       
  1033 static int isSortingIndex(
       
  1034   Parse *pParse,          /* Parsing context */
       
  1035   ExprMaskSet *pMaskSet,  /* Mapping from table indices to bitmaps */
       
  1036   Index *pIdx,            /* The index we are testing */
       
  1037   int base,               /* Cursor number for the table to be sorted */
       
  1038   ExprList *pOrderBy,     /* The ORDER BY clause */
       
  1039   int nEqCol,             /* Number of index columns with == constraints */
       
  1040   int *pbRev              /* Set to 1 if ORDER BY is DESC */
       
  1041 ){
       
  1042   int i, j;                       /* Loop counters */
       
  1043   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
       
  1044   int nTerm;                      /* Number of ORDER BY terms */
       
  1045   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
       
  1046   sqlite3 *db = pParse->db;
       
  1047 
       
  1048   assert( pOrderBy!=0 );
       
  1049   nTerm = pOrderBy->nExpr;
       
  1050   assert( nTerm>0 );
       
  1051 
       
  1052   /* Match terms of the ORDER BY clause against columns of
       
  1053   ** the index.
       
  1054   **
       
  1055   ** Note that indices have pIdx->nColumn regular columns plus
       
  1056   ** one additional column containing the rowid.  The rowid column
       
  1057   ** of the index is also allowed to match against the ORDER BY
       
  1058   ** clause.
       
  1059   */
       
  1060   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
       
  1061     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
       
  1062     CollSeq *pColl;    /* The collating sequence of pExpr */
       
  1063     int termSortOrder; /* Sort order for this term */
       
  1064     int iColumn;       /* The i-th column of the index.  -1 for rowid */
       
  1065     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
       
  1066     const char *zColl; /* Name of the collating sequence for i-th index term */
       
  1067 
       
  1068     pExpr = pTerm->pExpr;
       
  1069     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
       
  1070       /* Can not use an index sort on anything that is not a column in the
       
  1071       ** left-most table of the FROM clause */
       
  1072       break;
       
  1073     }
       
  1074     pColl = sqlite3ExprCollSeq(pParse, pExpr);
       
  1075     if( !pColl ){
       
  1076       pColl = db->pDfltColl;
       
  1077     }
       
  1078     if( i<pIdx->nColumn ){
       
  1079       iColumn = pIdx->aiColumn[i];
       
  1080       if( iColumn==pIdx->pTable->iPKey ){
       
  1081         iColumn = -1;
       
  1082       }
       
  1083       iSortOrder = pIdx->aSortOrder[i];
       
  1084       zColl = pIdx->azColl[i];
       
  1085     }else{
       
  1086       iColumn = -1;
       
  1087       iSortOrder = 0;
       
  1088       zColl = pColl->zName;
       
  1089     }
       
  1090     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
       
  1091       /* Term j of the ORDER BY clause does not match column i of the index */
       
  1092       if( i<nEqCol ){
       
  1093         /* If an index column that is constrained by == fails to match an
       
  1094         ** ORDER BY term, that is OK.  Just ignore that column of the index
       
  1095         */
       
  1096         continue;
       
  1097       }else if( i==pIdx->nColumn ){
       
  1098         /* Index column i is the rowid.  All other terms match. */
       
  1099         break;
       
  1100       }else{
       
  1101         /* If an index column fails to match and is not constrained by ==
       
  1102         ** then the index cannot satisfy the ORDER BY constraint.
       
  1103         */
       
  1104         return 0;
       
  1105       }
       
  1106     }
       
  1107     assert( pIdx->aSortOrder!=0 );
       
  1108     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
       
  1109     assert( iSortOrder==0 || iSortOrder==1 );
       
  1110     termSortOrder = iSortOrder ^ pTerm->sortOrder;
       
  1111     if( i>nEqCol ){
       
  1112       if( termSortOrder!=sortOrder ){
       
  1113         /* Indices can only be used if all ORDER BY terms past the
       
  1114         ** equality constraints are all either DESC or ASC. */
       
  1115         return 0;
       
  1116       }
       
  1117     }else{
       
  1118       sortOrder = termSortOrder;
       
  1119     }
       
  1120     j++;
       
  1121     pTerm++;
       
  1122     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
       
  1123       /* If the indexed column is the primary key and everything matches
       
  1124       ** so far and none of the ORDER BY terms to the right reference other
       
  1125       ** tables in the join, then we are assured that the index can be used 
       
  1126       ** to sort because the primary key is unique and so none of the other
       
  1127       ** columns will make any difference
       
  1128       */
       
  1129       j = nTerm;
       
  1130     }
       
  1131   }
       
  1132 
       
  1133   *pbRev = sortOrder!=0;
       
  1134   if( j>=nTerm ){
       
  1135     /* All terms of the ORDER BY clause are covered by this index so
       
  1136     ** this index can be used for sorting. */
       
  1137     return 1;
       
  1138   }
       
  1139   if( pIdx->onError!=OE_None && i==pIdx->nColumn
       
  1140       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
       
  1141     /* All terms of this index match some prefix of the ORDER BY clause
       
  1142     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
       
  1143     ** clause reference other tables in a join.  If this is all true then
       
  1144     ** the order by clause is superfluous. */
       
  1145     return 1;
       
  1146   }
       
  1147   return 0;
       
  1148 }
       
  1149 
       
  1150 /*
       
  1151 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
       
  1152 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
       
  1153 ** true for reverse ROWID and false for forward ROWID order.
       
  1154 */
       
  1155 static int sortableByRowid(
       
  1156   int base,               /* Cursor number for table to be sorted */
       
  1157   ExprList *pOrderBy,     /* The ORDER BY clause */
       
  1158   ExprMaskSet *pMaskSet,  /* Mapping from tables to bitmaps */
       
  1159   int *pbRev              /* Set to 1 if ORDER BY is DESC */
       
  1160 ){
       
  1161   Expr *p;
       
  1162 
       
  1163   assert( pOrderBy!=0 );
       
  1164   assert( pOrderBy->nExpr>0 );
       
  1165   p = pOrderBy->a[0].pExpr;
       
  1166   if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
       
  1167     && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
       
  1168     *pbRev = pOrderBy->a[0].sortOrder;
       
  1169     return 1;
       
  1170   }
       
  1171   return 0;
       
  1172 }
       
  1173 
       
  1174 /*
       
  1175 ** Prepare a crude estimate of the logarithm of the input value.
       
  1176 ** The results need not be exact.  This is only used for estimating
       
  1177 ** the total cost of performing operations with O(logN) or O(NlogN)
       
  1178 ** complexity.  Because N is just a guess, it is no great tragedy if
       
  1179 ** logN is a little off.
       
  1180 */
       
  1181 static double estLog(double N){
       
  1182   double logN = 1;
       
  1183   double x = 10;
       
  1184   while( N>x ){
       
  1185     logN += 1;
       
  1186     x *= 10;
       
  1187   }
       
  1188   return logN;
       
  1189 }
       
  1190 
       
  1191 /*
       
  1192 ** Two routines for printing the content of an sqlite3_index_info
       
  1193 ** structure.  Used for testing and debugging only.  If neither
       
  1194 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
       
  1195 ** are no-ops.
       
  1196 */
       
  1197 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
       
  1198 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
       
  1199   int i;
       
  1200   if( !sqlite3WhereTrace ) return;
       
  1201   for(i=0; i<p->nConstraint; i++){
       
  1202     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
       
  1203        i,
       
  1204        p->aConstraint[i].iColumn,
       
  1205        p->aConstraint[i].iTermOffset,
       
  1206        p->aConstraint[i].op,
       
  1207        p->aConstraint[i].usable);
       
  1208   }
       
  1209   for(i=0; i<p->nOrderBy; i++){
       
  1210     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
       
  1211        i,
       
  1212        p->aOrderBy[i].iColumn,
       
  1213        p->aOrderBy[i].desc);
       
  1214   }
       
  1215 }
       
  1216 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
       
  1217   int i;
       
  1218   if( !sqlite3WhereTrace ) return;
       
  1219   for(i=0; i<p->nConstraint; i++){
       
  1220     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
       
  1221        i,
       
  1222        p->aConstraintUsage[i].argvIndex,
       
  1223        p->aConstraintUsage[i].omit);
       
  1224   }
       
  1225   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
       
  1226   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
       
  1227   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
       
  1228   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
       
  1229 }
       
  1230 #else
       
  1231 #define TRACE_IDX_INPUTS(A)
       
  1232 #define TRACE_IDX_OUTPUTS(A)
       
  1233 #endif
       
  1234 
       
  1235 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
  1236 /*
       
  1237 ** Compute the best index for a virtual table.
       
  1238 **
       
  1239 ** The best index is computed by the xBestIndex method of the virtual
       
  1240 ** table module.  This routine is really just a wrapper that sets up
       
  1241 ** the sqlite3_index_info structure that is used to communicate with
       
  1242 ** xBestIndex.
       
  1243 **
       
  1244 ** In a join, this routine might be called multiple times for the
       
  1245 ** same virtual table.  The sqlite3_index_info structure is created
       
  1246 ** and initialized on the first invocation and reused on all subsequent
       
  1247 ** invocations.  The sqlite3_index_info structure is also used when
       
  1248 ** code is generated to access the virtual table.  The whereInfoDelete() 
       
  1249 ** routine takes care of freeing the sqlite3_index_info structure after
       
  1250 ** everybody has finished with it.
       
  1251 */
       
  1252 static double bestVirtualIndex(
       
  1253   Parse *pParse,                 /* The parsing context */
       
  1254   WhereClause *pWC,              /* The WHERE clause */
       
  1255   struct SrcList_item *pSrc,     /* The FROM clause term to search */
       
  1256   Bitmask notReady,              /* Mask of cursors that are not available */
       
  1257   ExprList *pOrderBy,            /* The order by clause */
       
  1258   int orderByUsable,             /* True if we can potential sort */
       
  1259   sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
       
  1260 ){
       
  1261   Table *pTab = pSrc->pTab;
       
  1262   sqlite3_vtab *pVtab = pTab->pVtab;
       
  1263   sqlite3_index_info *pIdxInfo;
       
  1264   struct sqlite3_index_constraint *pIdxCons;
       
  1265   struct sqlite3_index_orderby *pIdxOrderBy;
       
  1266   struct sqlite3_index_constraint_usage *pUsage;
       
  1267   WhereTerm *pTerm;
       
  1268   int i, j;
       
  1269   int nOrderBy;
       
  1270   int rc;
       
  1271 
       
  1272   /* If the sqlite3_index_info structure has not been previously
       
  1273   ** allocated and initialized for this virtual table, then allocate
       
  1274   ** and initialize it now
       
  1275   */
       
  1276   pIdxInfo = *ppIdxInfo;
       
  1277   if( pIdxInfo==0 ){
       
  1278     WhereTerm *pTerm;
       
  1279     int nTerm;
       
  1280     WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
       
  1281 
       
  1282     /* Count the number of possible WHERE clause constraints referring
       
  1283     ** to this virtual table */
       
  1284     for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
       
  1285       if( pTerm->leftCursor != pSrc->iCursor ) continue;
       
  1286       if( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
       
  1287       testcase( pTerm->eOperator==WO_IN );
       
  1288       testcase( pTerm->eOperator==WO_ISNULL );
       
  1289       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
       
  1290       nTerm++;
       
  1291     }
       
  1292 
       
  1293     /* If the ORDER BY clause contains only columns in the current 
       
  1294     ** virtual table then allocate space for the aOrderBy part of
       
  1295     ** the sqlite3_index_info structure.
       
  1296     */
       
  1297     nOrderBy = 0;
       
  1298     if( pOrderBy ){
       
  1299       for(i=0; i<pOrderBy->nExpr; i++){
       
  1300         Expr *pExpr = pOrderBy->a[i].pExpr;
       
  1301         if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
       
  1302       }
       
  1303       if( i==pOrderBy->nExpr ){
       
  1304         nOrderBy = pOrderBy->nExpr;
       
  1305       }
       
  1306     }
       
  1307 
       
  1308     /* Allocate the sqlite3_index_info structure
       
  1309     */
       
  1310     pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
       
  1311                              + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
       
  1312                              + sizeof(*pIdxOrderBy)*nOrderBy );
       
  1313     if( pIdxInfo==0 ){
       
  1314       sqlite3ErrorMsg(pParse, "out of memory");
       
  1315       return 0.0;
       
  1316     }
       
  1317     *ppIdxInfo = pIdxInfo;
       
  1318 
       
  1319     /* Initialize the structure.  The sqlite3_index_info structure contains
       
  1320     ** many fields that are declared "const" to prevent xBestIndex from
       
  1321     ** changing them.  We have to do some funky casting in order to
       
  1322     ** initialize those fields.
       
  1323     */
       
  1324     pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
       
  1325     pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
       
  1326     pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
       
  1327     *(int*)&pIdxInfo->nConstraint = nTerm;
       
  1328     *(int*)&pIdxInfo->nOrderBy = nOrderBy;
       
  1329     *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
       
  1330     *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
       
  1331     *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
       
  1332                                                                      pUsage;
       
  1333 
       
  1334     for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
       
  1335       if( pTerm->leftCursor != pSrc->iCursor ) continue;
       
  1336       if( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
       
  1337       testcase( pTerm->eOperator==WO_IN );
       
  1338       testcase( pTerm->eOperator==WO_ISNULL );
       
  1339       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
       
  1340       pIdxCons[j].iColumn = pTerm->leftColumn;
       
  1341       pIdxCons[j].iTermOffset = i;
       
  1342       pIdxCons[j].op = pTerm->eOperator;
       
  1343       /* The direct assignment in the previous line is possible only because
       
  1344       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
       
  1345       ** following asserts verify this fact. */
       
  1346       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
       
  1347       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
       
  1348       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
       
  1349       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
       
  1350       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
       
  1351       assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
       
  1352       assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
       
  1353       j++;
       
  1354     }
       
  1355     for(i=0; i<nOrderBy; i++){
       
  1356       Expr *pExpr = pOrderBy->a[i].pExpr;
       
  1357       pIdxOrderBy[i].iColumn = pExpr->iColumn;
       
  1358       pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
       
  1359     }
       
  1360   }
       
  1361 
       
  1362   /* At this point, the sqlite3_index_info structure that pIdxInfo points
       
  1363   ** to will have been initialized, either during the current invocation or
       
  1364   ** during some prior invocation.  Now we just have to customize the
       
  1365   ** details of pIdxInfo for the current invocation and pass it to
       
  1366   ** xBestIndex.
       
  1367   */
       
  1368 
       
  1369   /* The module name must be defined. Also, by this point there must
       
  1370   ** be a pointer to an sqlite3_vtab structure. Otherwise
       
  1371   ** sqlite3ViewGetColumnNames() would have picked up the error. 
       
  1372   */
       
  1373   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
       
  1374   assert( pVtab );
       
  1375 #if 0
       
  1376   if( pTab->pVtab==0 ){
       
  1377     sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
       
  1378         pTab->azModuleArg[0], pTab->zName);
       
  1379     return 0.0;
       
  1380   }
       
  1381 #endif
       
  1382 
       
  1383   /* Set the aConstraint[].usable fields and initialize all 
       
  1384   ** output variables to zero.
       
  1385   **
       
  1386   ** aConstraint[].usable is true for constraints where the right-hand
       
  1387   ** side contains only references to tables to the left of the current
       
  1388   ** table.  In other words, if the constraint is of the form:
       
  1389   **
       
  1390   **           column = expr
       
  1391   **
       
  1392   ** and we are evaluating a join, then the constraint on column is 
       
  1393   ** only valid if all tables referenced in expr occur to the left
       
  1394   ** of the table containing column.
       
  1395   **
       
  1396   ** The aConstraints[] array contains entries for all constraints
       
  1397   ** on the current table.  That way we only have to compute it once
       
  1398   ** even though we might try to pick the best index multiple times.
       
  1399   ** For each attempt at picking an index, the order of tables in the
       
  1400   ** join might be different so we have to recompute the usable flag
       
  1401   ** each time.
       
  1402   */
       
  1403   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
       
  1404   pUsage = pIdxInfo->aConstraintUsage;
       
  1405   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
       
  1406     j = pIdxCons->iTermOffset;
       
  1407     pTerm = &pWC->a[j];
       
  1408     pIdxCons->usable =  (pTerm->prereqRight & notReady)==0;
       
  1409   }
       
  1410   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
       
  1411   if( pIdxInfo->needToFreeIdxStr ){
       
  1412     sqlite3_free(pIdxInfo->idxStr);
       
  1413   }
       
  1414   pIdxInfo->idxStr = 0;
       
  1415   pIdxInfo->idxNum = 0;
       
  1416   pIdxInfo->needToFreeIdxStr = 0;
       
  1417   pIdxInfo->orderByConsumed = 0;
       
  1418   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
       
  1419   nOrderBy = pIdxInfo->nOrderBy;
       
  1420   if( pIdxInfo->nOrderBy && !orderByUsable ){
       
  1421     *(int*)&pIdxInfo->nOrderBy = 0;
       
  1422   }
       
  1423 
       
  1424   (void)sqlite3SafetyOff(pParse->db);
       
  1425   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
       
  1426   TRACE_IDX_INPUTS(pIdxInfo);
       
  1427   rc = pVtab->pModule->xBestIndex(pVtab, pIdxInfo);
       
  1428   TRACE_IDX_OUTPUTS(pIdxInfo);
       
  1429   (void)sqlite3SafetyOn(pParse->db);
       
  1430 
       
  1431   if( rc!=SQLITE_OK ){
       
  1432     if( rc==SQLITE_NOMEM ){
       
  1433       pParse->db->mallocFailed = 1;
       
  1434     }else if( !pVtab->zErrMsg ){
       
  1435       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
       
  1436     }else{
       
  1437       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
       
  1438     }
       
  1439   }
       
  1440   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
       
  1441   pVtab->zErrMsg = 0;
       
  1442 
       
  1443   for(i=0; i<pIdxInfo->nConstraint; i++){
       
  1444     if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
       
  1445       sqlite3ErrorMsg(pParse, 
       
  1446           "table %s: xBestIndex returned an invalid plan", pTab->zName);
       
  1447       return 0.0;
       
  1448     }
       
  1449   }
       
  1450 
       
  1451   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
       
  1452   return pIdxInfo->estimatedCost;
       
  1453 }
       
  1454 #endif /* SQLITE_OMIT_VIRTUALTABLE */
       
  1455 
       
  1456 /*
       
  1457 ** Find the best index for accessing a particular table.  Return a pointer
       
  1458 ** to the index, flags that describe how the index should be used, the
       
  1459 ** number of equality constraints, and the "cost" for this index.
       
  1460 **
       
  1461 ** The lowest cost index wins.  The cost is an estimate of the amount of
       
  1462 ** CPU and disk I/O need to process the request using the selected index.
       
  1463 ** Factors that influence cost include:
       
  1464 **
       
  1465 **    *  The estimated number of rows that will be retrieved.  (The
       
  1466 **       fewer the better.)
       
  1467 **
       
  1468 **    *  Whether or not sorting must occur.
       
  1469 **
       
  1470 **    *  Whether or not there must be separate lookups in the
       
  1471 **       index and in the main table.
       
  1472 **
       
  1473 */
       
  1474 static double bestIndex(
       
  1475   Parse *pParse,              /* The parsing context */
       
  1476   WhereClause *pWC,           /* The WHERE clause */
       
  1477   struct SrcList_item *pSrc,  /* The FROM clause term to search */
       
  1478   Bitmask notReady,           /* Mask of cursors that are not available */
       
  1479   ExprList *pOrderBy,         /* The order by clause */
       
  1480   Index **ppIndex,            /* Make *ppIndex point to the best index */
       
  1481   int *pFlags,                /* Put flags describing this choice in *pFlags */
       
  1482   int *pnEq                   /* Put the number of == or IN constraints here */
       
  1483 ){
       
  1484   WhereTerm *pTerm;
       
  1485   Index *bestIdx = 0;         /* Index that gives the lowest cost */
       
  1486   double lowestCost;          /* The cost of using bestIdx */
       
  1487   int bestFlags = 0;          /* Flags associated with bestIdx */
       
  1488   int bestNEq = 0;            /* Best value for nEq */
       
  1489   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
       
  1490   Index *pProbe;              /* An index we are evaluating */
       
  1491   int rev;                    /* True to scan in reverse order */
       
  1492   int flags;                  /* Flags associated with pProbe */
       
  1493   int nEq;                    /* Number of == or IN constraints */
       
  1494   int eqTermMask;             /* Mask of valid equality operators */
       
  1495   double cost;                /* Cost of using pProbe */
       
  1496 
       
  1497   WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName, notReady));
       
  1498   lowestCost = SQLITE_BIG_DBL;
       
  1499   pProbe = pSrc->pTab->pIndex;
       
  1500 
       
  1501   /* If the table has no indices and there are no terms in the where
       
  1502   ** clause that refer to the ROWID, then we will never be able to do
       
  1503   ** anything other than a full table scan on this table.  We might as
       
  1504   ** well put it first in the join order.  That way, perhaps it can be
       
  1505   ** referenced by other tables in the join.
       
  1506   */
       
  1507   if( pProbe==0 &&
       
  1508      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
       
  1509      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
       
  1510     *pFlags = 0;
       
  1511     *ppIndex = 0;
       
  1512     *pnEq = 0;
       
  1513     return 0.0;
       
  1514   }
       
  1515 
       
  1516   /* Check for a rowid=EXPR or rowid IN (...) constraints
       
  1517   */
       
  1518   pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
       
  1519   if( pTerm ){
       
  1520     Expr *pExpr;
       
  1521     *ppIndex = 0;
       
  1522     bestFlags = WHERE_ROWID_EQ;
       
  1523     if( pTerm->eOperator & WO_EQ ){
       
  1524       /* Rowid== is always the best pick.  Look no further.  Because only
       
  1525       ** a single row is generated, output is always in sorted order */
       
  1526       *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
       
  1527       *pnEq = 1;
       
  1528       WHERETRACE(("... best is rowid\n"));
       
  1529       return 0.0;
       
  1530     }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
       
  1531       /* Rowid IN (LIST): cost is NlogN where N is the number of list
       
  1532       ** elements.  */
       
  1533       lowestCost = pExpr->pList->nExpr;
       
  1534       lowestCost *= estLog(lowestCost);
       
  1535     }else{
       
  1536       /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
       
  1537       ** in the result of the inner select.  We have no way to estimate
       
  1538       ** that value so make a wild guess. */
       
  1539       lowestCost = 200;
       
  1540     }
       
  1541     WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
       
  1542   }
       
  1543 
       
  1544   /* Estimate the cost of a table scan.  If we do not know how many
       
  1545   ** entries are in the table, use 1 million as a guess.
       
  1546   */
       
  1547   cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
       
  1548   WHERETRACE(("... table scan base cost: %.9g\n", cost));
       
  1549   flags = WHERE_ROWID_RANGE;
       
  1550 
       
  1551   /* Check for constraints on a range of rowids in a table scan.
       
  1552   */
       
  1553   pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
       
  1554   if( pTerm ){
       
  1555     if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
       
  1556       flags |= WHERE_TOP_LIMIT;
       
  1557       cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds or rows */
       
  1558     }
       
  1559     if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
       
  1560       flags |= WHERE_BTM_LIMIT;
       
  1561       cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
       
  1562     }
       
  1563     WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
       
  1564   }else{
       
  1565     flags = 0;
       
  1566   }
       
  1567 
       
  1568   /* If the table scan does not satisfy the ORDER BY clause, increase
       
  1569   ** the cost by NlogN to cover the expense of sorting. */
       
  1570   if( pOrderBy ){
       
  1571     if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
       
  1572       flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
       
  1573       if( rev ){
       
  1574         flags |= WHERE_REVERSE;
       
  1575       }
       
  1576     }else{
       
  1577       cost += cost*estLog(cost);
       
  1578       WHERETRACE(("... sorting increases cost to %.9g\n", cost));
       
  1579     }
       
  1580   }
       
  1581   if( cost<lowestCost ){
       
  1582     lowestCost = cost;
       
  1583     bestFlags = flags;
       
  1584   }
       
  1585 
       
  1586   /* If the pSrc table is the right table of a LEFT JOIN then we may not
       
  1587   ** use an index to satisfy IS NULL constraints on that table.  This is
       
  1588   ** because columns might end up being NULL if the table does not match -
       
  1589   ** a circumstance which the index cannot help us discover.  Ticket #2177.
       
  1590   */
       
  1591   if( (pSrc->jointype & JT_LEFT)!=0 ){
       
  1592     eqTermMask = WO_EQ|WO_IN;
       
  1593   }else{
       
  1594     eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
       
  1595   }
       
  1596 
       
  1597   /* Look at each index.
       
  1598   */
       
  1599   for(; pProbe; pProbe=pProbe->pNext){
       
  1600     int i;                       /* Loop counter */
       
  1601     double inMultiplier = 1;
       
  1602 
       
  1603     WHERETRACE(("... index %s:\n", pProbe->zName));
       
  1604 
       
  1605     /* Count the number of columns in the index that are satisfied
       
  1606     ** by x=EXPR constraints or x IN (...) constraints.
       
  1607     */
       
  1608     flags = 0;
       
  1609     for(i=0; i<pProbe->nColumn; i++){
       
  1610       int j = pProbe->aiColumn[i];
       
  1611       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
       
  1612       if( pTerm==0 ) break;
       
  1613       flags |= WHERE_COLUMN_EQ;
       
  1614       if( pTerm->eOperator & WO_IN ){
       
  1615         Expr *pExpr = pTerm->pExpr;
       
  1616         flags |= WHERE_COLUMN_IN;
       
  1617         if( pExpr->pSelect!=0 ){
       
  1618           inMultiplier *= 25;
       
  1619         }else if( ALWAYS(pExpr->pList) ){
       
  1620           inMultiplier *= pExpr->pList->nExpr + 1;
       
  1621         }
       
  1622       }
       
  1623     }
       
  1624     cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
       
  1625     nEq = i;
       
  1626     if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
       
  1627          && nEq==pProbe->nColumn ){
       
  1628       flags |= WHERE_UNIQUE;
       
  1629     }
       
  1630     WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
       
  1631 
       
  1632     /* Look for range constraints
       
  1633     */
       
  1634     if( nEq<pProbe->nColumn ){
       
  1635       int j = pProbe->aiColumn[nEq];
       
  1636       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
       
  1637       if( pTerm ){
       
  1638         flags |= WHERE_COLUMN_RANGE;
       
  1639         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
       
  1640           flags |= WHERE_TOP_LIMIT;
       
  1641           cost /= 3;
       
  1642         }
       
  1643         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
       
  1644           flags |= WHERE_BTM_LIMIT;
       
  1645           cost /= 3;
       
  1646         }
       
  1647         WHERETRACE(("...... range reduces cost to %.9g\n", cost));
       
  1648       }
       
  1649     }
       
  1650 
       
  1651     /* Add the additional cost of sorting if that is a factor.
       
  1652     */
       
  1653     if( pOrderBy ){
       
  1654       if( (flags & WHERE_COLUMN_IN)==0 &&
       
  1655            isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
       
  1656         if( flags==0 ){
       
  1657           flags = WHERE_COLUMN_RANGE;
       
  1658         }
       
  1659         flags |= WHERE_ORDERBY;
       
  1660         if( rev ){
       
  1661           flags |= WHERE_REVERSE;
       
  1662         }
       
  1663       }else{
       
  1664         cost += cost*estLog(cost);
       
  1665         WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
       
  1666       }
       
  1667     }
       
  1668 
       
  1669     /* Check to see if we can get away with using just the index without
       
  1670     ** ever reading the table.  If that is the case, then halve the
       
  1671     ** cost of this index.
       
  1672     */
       
  1673     if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
       
  1674       Bitmask m = pSrc->colUsed;
       
  1675       int j;
       
  1676       for(j=0; j<pProbe->nColumn; j++){
       
  1677         int x = pProbe->aiColumn[j];
       
  1678         if( x<BMS-1 ){
       
  1679           m &= ~(((Bitmask)1)<<x);
       
  1680         }
       
  1681       }
       
  1682       if( m==0 ){
       
  1683         flags |= WHERE_IDX_ONLY;
       
  1684         cost /= 2;
       
  1685         WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
       
  1686       }
       
  1687     }
       
  1688 
       
  1689     /* If this index has achieved the lowest cost so far, then use it.
       
  1690     */
       
  1691     if( flags && cost < lowestCost ){
       
  1692       bestIdx = pProbe;
       
  1693       lowestCost = cost;
       
  1694       bestFlags = flags;
       
  1695       bestNEq = nEq;
       
  1696     }
       
  1697   }
       
  1698 
       
  1699   /* Report the best result
       
  1700   */
       
  1701   *ppIndex = bestIdx;
       
  1702   WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
       
  1703         bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
       
  1704   *pFlags = bestFlags | eqTermMask;
       
  1705   *pnEq = bestNEq;
       
  1706   return lowestCost;
       
  1707 }
       
  1708 
       
  1709 
       
  1710 /*
       
  1711 ** Disable a term in the WHERE clause.  Except, do not disable the term
       
  1712 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
       
  1713 ** or USING clause of that join.
       
  1714 **
       
  1715 ** Consider the term t2.z='ok' in the following queries:
       
  1716 **
       
  1717 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
       
  1718 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
       
  1719 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
       
  1720 **
       
  1721 ** The t2.z='ok' is disabled in the in (2) because it originates
       
  1722 ** in the ON clause.  The term is disabled in (3) because it is not part
       
  1723 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
       
  1724 **
       
  1725 ** Disabling a term causes that term to not be tested in the inner loop
       
  1726 ** of the join.  Disabling is an optimization.  When terms are satisfied
       
  1727 ** by indices, we disable them to prevent redundant tests in the inner
       
  1728 ** loop.  We would get the correct results if nothing were ever disabled,
       
  1729 ** but joins might run a little slower.  The trick is to disable as much
       
  1730 ** as we can without disabling too much.  If we disabled in (1), we'd get
       
  1731 ** the wrong answer.  See ticket #813.
       
  1732 */
       
  1733 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
       
  1734   if( pTerm
       
  1735       && ALWAYS((pTerm->flags & TERM_CODED)==0)
       
  1736       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
       
  1737   ){
       
  1738     pTerm->flags |= TERM_CODED;
       
  1739     if( pTerm->iParent>=0 ){
       
  1740       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
       
  1741       if( (--pOther->nChild)==0 ){
       
  1742         disableTerm(pLevel, pOther);
       
  1743       }
       
  1744     }
       
  1745   }
       
  1746 }
       
  1747 
       
  1748 /*
       
  1749 ** Apply the affinities associated with the first n columns of index
       
  1750 ** pIdx to the values in the n registers starting at base.
       
  1751 */
       
  1752 static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
       
  1753   if( n>0 ){
       
  1754     Vdbe *v = pParse->pVdbe;
       
  1755     assert( v!=0 );
       
  1756     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
       
  1757     sqlite3IndexAffinityStr(v, pIdx);
       
  1758     sqlite3ExprCacheAffinityChange(pParse, base, n);
       
  1759   }
       
  1760 }
       
  1761 
       
  1762 
       
  1763 /*
       
  1764 ** Generate code for a single equality term of the WHERE clause.  An equality
       
  1765 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
       
  1766 ** coded.
       
  1767 **
       
  1768 ** The current value for the constraint is left in register iReg.
       
  1769 **
       
  1770 ** For a constraint of the form X=expr, the expression is evaluated and its
       
  1771 ** result is left on the stack.  For constraints of the form X IN (...)
       
  1772 ** this routine sets up a loop that will iterate over all values of X.
       
  1773 */
       
  1774 static int codeEqualityTerm(
       
  1775   Parse *pParse,      /* The parsing context */
       
  1776   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
       
  1777   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
       
  1778   int iTarget         /* Attempt to leave results in this register */
       
  1779 ){
       
  1780   Expr *pX = pTerm->pExpr;
       
  1781   Vdbe *v = pParse->pVdbe;
       
  1782   int iReg;                  /* Register holding results */
       
  1783 
       
  1784   if( iTarget<=0 ){
       
  1785     iReg = iTarget = sqlite3GetTempReg(pParse);
       
  1786   }
       
  1787   if( pX->op==TK_EQ ){
       
  1788     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
       
  1789   }else if( pX->op==TK_ISNULL ){
       
  1790     iReg = iTarget;
       
  1791     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
       
  1792 #ifndef SQLITE_OMIT_SUBQUERY
       
  1793   }else{
       
  1794     int eType;
       
  1795     int iTab;
       
  1796     struct InLoop *pIn;
       
  1797 
       
  1798     assert( pX->op==TK_IN );
       
  1799     iReg = iTarget;
       
  1800     eType = sqlite3FindInIndex(pParse, pX, 0);
       
  1801     iTab = pX->iTable;
       
  1802     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
       
  1803     VdbeComment((v, "%.*s", pX->span.n, pX->span.z));
       
  1804     if( pLevel->nIn==0 ){
       
  1805       pLevel->nxt = sqlite3VdbeMakeLabel(v);
       
  1806     }
       
  1807     pLevel->nIn++;
       
  1808     pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop,
       
  1809                                     sizeof(pLevel->aInLoop[0])*pLevel->nIn);
       
  1810     pIn = pLevel->aInLoop;
       
  1811     if( pIn ){
       
  1812       pIn += pLevel->nIn - 1;
       
  1813       pIn->iCur = iTab;
       
  1814       if( eType==IN_INDEX_ROWID ){
       
  1815         pIn->topAddr = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
       
  1816       }else{
       
  1817         pIn->topAddr = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
       
  1818       }
       
  1819       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
       
  1820     }else{
       
  1821       pLevel->nIn = 0;
       
  1822     }
       
  1823 #endif
       
  1824   }
       
  1825   disableTerm(pLevel, pTerm);
       
  1826   return iReg;
       
  1827 }
       
  1828 
       
  1829 /*
       
  1830 ** Generate code that will evaluate all == and IN constraints for an
       
  1831 ** index.  The values for all constraints are left on the stack.
       
  1832 **
       
  1833 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
       
  1834 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
       
  1835 ** The index has as many as three equality constraints, but in this
       
  1836 ** example, the third "c" value is an inequality.  So only two 
       
  1837 ** constraints are coded.  This routine will generate code to evaluate
       
  1838 ** a==5 and b IN (1,2,3).  The current values for a and b will be left
       
  1839 ** on the stack - a is the deepest and b the shallowest.
       
  1840 **
       
  1841 ** In the example above nEq==2.  But this subroutine works for any value
       
  1842 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
       
  1843 ** The only thing it does is allocate the pLevel->iMem memory cell.
       
  1844 **
       
  1845 ** This routine always allocates at least one memory cell and puts
       
  1846 ** the address of that memory cell in pLevel->iMem.  The code that
       
  1847 ** calls this routine will use pLevel->iMem to store the termination
       
  1848 ** key value of the loop.  If one or more IN operators appear, then
       
  1849 ** this routine allocates an additional nEq memory cells for internal
       
  1850 ** use.
       
  1851 */
       
  1852 static int codeAllEqualityTerms(
       
  1853   Parse *pParse,        /* Parsing context */
       
  1854   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
       
  1855   WhereClause *pWC,     /* The WHERE clause */
       
  1856   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
       
  1857   int nExtraReg         /* Number of extra registers to allocate */
       
  1858 ){
       
  1859   int nEq = pLevel->nEq;        /* The number of == or IN constraints to code */
       
  1860   Vdbe *v = pParse->pVdbe;      /* The virtual machine under construction */
       
  1861   Index *pIdx = pLevel->pIdx;   /* The index being used for this loop */
       
  1862   int iCur = pLevel->iTabCur;   /* The cursor of the table */
       
  1863   WhereTerm *pTerm;             /* A single constraint term */
       
  1864   int j;                        /* Loop counter */
       
  1865   int regBase;                  /* Base register */
       
  1866 
       
  1867   /* Figure out how many memory cells we will need then allocate them.
       
  1868   ** We always need at least one used to store the loop terminator
       
  1869   ** value.  If there are IN operators we'll need one for each == or
       
  1870   ** IN constraint.
       
  1871   */
       
  1872   pLevel->iMem = pParse->nMem + 1;
       
  1873   regBase = pParse->nMem + 2;
       
  1874   pParse->nMem += pLevel->nEq + 2 + nExtraReg;
       
  1875 
       
  1876   /* Evaluate the equality constraints
       
  1877   */
       
  1878   assert( pIdx->nColumn>=nEq );
       
  1879   for(j=0; j<nEq; j++){
       
  1880     int r1;
       
  1881     int k = pIdx->aiColumn[j];
       
  1882     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
       
  1883     if( NEVER(pTerm==0) ) break;
       
  1884     assert( (pTerm->flags & TERM_CODED)==0 );
       
  1885     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
       
  1886     if( r1!=regBase+j ){
       
  1887       sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
       
  1888     }
       
  1889     testcase( pTerm->eOperator & WO_ISNULL );
       
  1890     testcase( pTerm->eOperator & WO_IN );
       
  1891     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
       
  1892       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->brk);
       
  1893     }
       
  1894   }
       
  1895   return regBase;
       
  1896 }
       
  1897 
       
  1898 #if defined(SQLITE_TEST)
       
  1899 /*
       
  1900 ** The following variable holds a text description of query plan generated
       
  1901 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
       
  1902 ** overwrites the previous.  This information is used for testing and
       
  1903 ** analysis only.
       
  1904 */
       
  1905 char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
       
  1906 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
       
  1907 
       
  1908 #endif /* SQLITE_TEST */
       
  1909 
       
  1910 
       
  1911 /*
       
  1912 ** Free a WhereInfo structure
       
  1913 */
       
  1914 static void whereInfoFree(WhereInfo *pWInfo){
       
  1915   if( pWInfo ){
       
  1916     int i;
       
  1917     sqlite3 *db = pWInfo->pParse->db;
       
  1918     for(i=0; i<pWInfo->nLevel; i++){
       
  1919       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
       
  1920       if( pInfo ){
       
  1921         assert( pInfo->needToFreeIdxStr==0 );
       
  1922         sqlite3DbFree(db, pInfo);
       
  1923       }
       
  1924     }
       
  1925     sqlite3DbFree(db, pWInfo);
       
  1926   }
       
  1927 }
       
  1928 
       
  1929 
       
  1930 /*
       
  1931 ** Generate the beginning of the loop used for WHERE clause processing.
       
  1932 ** The return value is a pointer to an opaque structure that contains
       
  1933 ** information needed to terminate the loop.  Later, the calling routine
       
  1934 ** should invoke sqlite3WhereEnd() with the return value of this function
       
  1935 ** in order to complete the WHERE clause processing.
       
  1936 **
       
  1937 ** If an error occurs, this routine returns NULL.
       
  1938 **
       
  1939 ** The basic idea is to do a nested loop, one loop for each table in
       
  1940 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
       
  1941 ** same as a SELECT with only a single table in the FROM clause.)  For
       
  1942 ** example, if the SQL is this:
       
  1943 **
       
  1944 **       SELECT * FROM t1, t2, t3 WHERE ...;
       
  1945 **
       
  1946 ** Then the code generated is conceptually like the following:
       
  1947 **
       
  1948 **      foreach row1 in t1 do       \    Code generated
       
  1949 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
       
  1950 **          foreach row3 in t3 do   /
       
  1951 **            ...
       
  1952 **          end                     \    Code generated
       
  1953 **        end                        |-- by sqlite3WhereEnd()
       
  1954 **      end                         /
       
  1955 **
       
  1956 ** Note that the loops might not be nested in the order in which they
       
  1957 ** appear in the FROM clause if a different order is better able to make
       
  1958 ** use of indices.  Note also that when the IN operator appears in
       
  1959 ** the WHERE clause, it might result in additional nested loops for
       
  1960 ** scanning through all values on the right-hand side of the IN.
       
  1961 **
       
  1962 ** There are Btree cursors associated with each table.  t1 uses cursor
       
  1963 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
       
  1964 ** And so forth.  This routine generates code to open those VDBE cursors
       
  1965 ** and sqlite3WhereEnd() generates the code to close them.
       
  1966 **
       
  1967 ** The code that sqlite3WhereBegin() generates leaves the cursors named
       
  1968 ** in pTabList pointing at their appropriate entries.  The [...] code
       
  1969 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
       
  1970 ** data from the various tables of the loop.
       
  1971 **
       
  1972 ** If the WHERE clause is empty, the foreach loops must each scan their
       
  1973 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
       
  1974 ** the tables have indices and there are terms in the WHERE clause that
       
  1975 ** refer to those indices, a complete table scan can be avoided and the
       
  1976 ** code will run much faster.  Most of the work of this routine is checking
       
  1977 ** to see if there are indices that can be used to speed up the loop.
       
  1978 **
       
  1979 ** Terms of the WHERE clause are also used to limit which rows actually
       
  1980 ** make it to the "..." in the middle of the loop.  After each "foreach",
       
  1981 ** terms of the WHERE clause that use only terms in that loop and outer
       
  1982 ** loops are evaluated and if false a jump is made around all subsequent
       
  1983 ** inner loops (or around the "..." if the test occurs within the inner-
       
  1984 ** most loop)
       
  1985 **
       
  1986 ** OUTER JOINS
       
  1987 **
       
  1988 ** An outer join of tables t1 and t2 is conceptally coded as follows:
       
  1989 **
       
  1990 **    foreach row1 in t1 do
       
  1991 **      flag = 0
       
  1992 **      foreach row2 in t2 do
       
  1993 **        start:
       
  1994 **          ...
       
  1995 **          flag = 1
       
  1996 **      end
       
  1997 **      if flag==0 then
       
  1998 **        move the row2 cursor to a null row
       
  1999 **        goto start
       
  2000 **      fi
       
  2001 **    end
       
  2002 **
       
  2003 ** ORDER BY CLAUSE PROCESSING
       
  2004 **
       
  2005 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
       
  2006 ** if there is one.  If there is no ORDER BY clause or if this routine
       
  2007 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
       
  2008 **
       
  2009 ** If an index can be used so that the natural output order of the table
       
  2010 ** scan is correct for the ORDER BY clause, then that index is used and
       
  2011 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
       
  2012 ** unnecessary sort of the result set if an index appropriate for the
       
  2013 ** ORDER BY clause already exists.
       
  2014 **
       
  2015 ** If the where clause loops cannot be arranged to provide the correct
       
  2016 ** output order, then the *ppOrderBy is unchanged.
       
  2017 */
       
  2018 WhereInfo *sqlite3WhereBegin(
       
  2019   Parse *pParse,        /* The parser context */
       
  2020   SrcList *pTabList,    /* A list of all tables to be scanned */
       
  2021   Expr *pWhere,         /* The WHERE clause */
       
  2022   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
       
  2023   u8 wflags             /* One of the WHERE_* flags defined in sqliteInt.h */
       
  2024 ){
       
  2025   int i;                     /* Loop counter */
       
  2026   WhereInfo *pWInfo;         /* Will become the return value of this function */
       
  2027   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
       
  2028   int brk, cont = 0;         /* Addresses used during code generation */
       
  2029   Bitmask notReady;          /* Cursors that are not yet positioned */
       
  2030   WhereTerm *pTerm;          /* A single term in the WHERE clause */
       
  2031   ExprMaskSet maskSet;       /* The expression mask set */
       
  2032   WhereClause wc;            /* The WHERE clause is divided into these terms */
       
  2033   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
       
  2034   WhereLevel *pLevel;             /* A single level in the pWInfo list */
       
  2035   int iFrom;                      /* First unused FROM clause element */
       
  2036   int andFlags;              /* AND-ed combination of all wc.a[].flags */
       
  2037   sqlite3 *db;               /* Database connection */
       
  2038   ExprList *pOrderBy = 0;
       
  2039 
       
  2040   /* The number of tables in the FROM clause is limited by the number of
       
  2041   ** bits in a Bitmask 
       
  2042   */
       
  2043   if( pTabList->nSrc>BMS ){
       
  2044     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
       
  2045     return 0;
       
  2046   }
       
  2047 
       
  2048   if( ppOrderBy ){
       
  2049     pOrderBy = *ppOrderBy;
       
  2050   }
       
  2051 
       
  2052   /* Split the WHERE clause into separate subexpressions where each
       
  2053   ** subexpression is separated by an AND operator.
       
  2054   */
       
  2055   initMaskSet(&maskSet);
       
  2056   whereClauseInit(&wc, pParse, &maskSet);
       
  2057   sqlite3ExprCodeConstants(pParse, pWhere);
       
  2058   whereSplit(&wc, pWhere, TK_AND);
       
  2059     
       
  2060   /* Allocate and initialize the WhereInfo structure that will become the
       
  2061   ** return value.
       
  2062   */
       
  2063   db = pParse->db;
       
  2064   pWInfo = sqlite3DbMallocZero(db,  
       
  2065                       sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
       
  2066   if( db->mallocFailed ){
       
  2067     goto whereBeginNoMem;
       
  2068   }
       
  2069   pWInfo->nLevel = pTabList->nSrc;
       
  2070   pWInfo->pParse = pParse;
       
  2071   pWInfo->pTabList = pTabList;
       
  2072   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
       
  2073 
       
  2074   /* Special case: a WHERE clause that is constant.  Evaluate the
       
  2075   ** expression and either jump over all of the code or fall thru.
       
  2076   */
       
  2077   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
       
  2078     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
       
  2079     pWhere = 0;
       
  2080   }
       
  2081 
       
  2082   /* Assign a bit from the bitmask to every term in the FROM clause.
       
  2083   **
       
  2084   ** When assigning bitmask values to FROM clause cursors, it must be
       
  2085   ** the case that if X is the bitmask for the N-th FROM clause term then
       
  2086   ** the bitmask for all FROM clause terms to the left of the N-th term
       
  2087   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
       
  2088   ** its Expr.iRightJoinTable value to find the bitmask of the right table
       
  2089   ** of the join.  Subtracting one from the right table bitmask gives a
       
  2090   ** bitmask for all tables to the left of the join.  Knowing the bitmask
       
  2091   ** for all tables to the left of a left join is important.  Ticket #3015.
       
  2092   */
       
  2093   for(i=0; i<pTabList->nSrc; i++){
       
  2094     createMask(&maskSet, pTabList->a[i].iCursor);
       
  2095   }
       
  2096 #ifndef NDEBUG
       
  2097   {
       
  2098     Bitmask toTheLeft = 0;
       
  2099     for(i=0; i<pTabList->nSrc; i++){
       
  2100       Bitmask m = getMask(&maskSet, pTabList->a[i].iCursor);
       
  2101       assert( (m-1)==toTheLeft );
       
  2102       toTheLeft |= m;
       
  2103     }
       
  2104   }
       
  2105 #endif
       
  2106 
       
  2107   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
       
  2108   ** add new virtual terms onto the end of the WHERE clause.  We do not
       
  2109   ** want to analyze these virtual terms, so start analyzing at the end
       
  2110   ** and work forward so that the added virtual terms are never processed.
       
  2111   */
       
  2112   exprAnalyzeAll(pTabList, &wc);
       
  2113   if( db->mallocFailed ){
       
  2114     goto whereBeginNoMem;
       
  2115   }
       
  2116 
       
  2117   /* Chose the best index to use for each table in the FROM clause.
       
  2118   **
       
  2119   ** This loop fills in the following fields:
       
  2120   **
       
  2121   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
       
  2122   **   pWInfo->a[].flags     WHERE_xxx flags associated with pIdx
       
  2123   **   pWInfo->a[].nEq       The number of == and IN constraints
       
  2124   **   pWInfo->a[].iFrom     When term of the FROM clause is being coded
       
  2125   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
       
  2126   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
       
  2127   **
       
  2128   ** This loop also figures out the nesting order of tables in the FROM
       
  2129   ** clause.
       
  2130   */
       
  2131   notReady = ~(Bitmask)0;
       
  2132   pTabItem = pTabList->a;
       
  2133   pLevel = pWInfo->a;
       
  2134   andFlags = ~0;
       
  2135   WHERETRACE(("*** Optimizer Start ***\n"));
       
  2136   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
       
  2137     Index *pIdx;                /* Index for FROM table at pTabItem */
       
  2138     int flags;                  /* Flags asssociated with pIdx */
       
  2139     int nEq;                    /* Number of == or IN constraints */
       
  2140     double cost;                /* The cost for pIdx */
       
  2141     int j;                      /* For looping over FROM tables */
       
  2142     Index *pBest = 0;           /* The best index seen so far */
       
  2143     int bestFlags = 0;          /* Flags associated with pBest */
       
  2144     int bestNEq = 0;            /* nEq associated with pBest */
       
  2145     double lowestCost;          /* Cost of the pBest */
       
  2146     int bestJ = 0;              /* The value of j */
       
  2147     Bitmask m;                  /* Bitmask value for j or bestJ */
       
  2148     int once = 0;               /* True when first table is seen */
       
  2149     sqlite3_index_info *pIndex; /* Current virtual index */
       
  2150 
       
  2151     lowestCost = SQLITE_BIG_DBL;
       
  2152     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
       
  2153       int doNotReorder;  /* True if this table should not be reordered */
       
  2154 
       
  2155       doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
       
  2156       if( once && doNotReorder ) break;
       
  2157       m = getMask(&maskSet, pTabItem->iCursor);
       
  2158       if( (m & notReady)==0 ){
       
  2159         if( j==iFrom ) iFrom++;
       
  2160         continue;
       
  2161       }
       
  2162       assert( pTabItem->pTab );
       
  2163 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
  2164       if( IsVirtual(pTabItem->pTab) ){
       
  2165         sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
       
  2166         cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
       
  2167                                 ppOrderBy ? *ppOrderBy : 0, i==0,
       
  2168                                 ppIdxInfo);
       
  2169         flags = WHERE_VIRTUALTABLE;
       
  2170         pIndex = *ppIdxInfo;
       
  2171         if( pIndex && pIndex->orderByConsumed ){
       
  2172           flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
       
  2173         }
       
  2174         pIdx = 0;
       
  2175         nEq = 0;
       
  2176         if( (SQLITE_BIG_DBL/2.0)<cost ){
       
  2177           /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
       
  2178           ** inital value of lowestCost in this loop. If it is, then
       
  2179           ** the (cost<lowestCost) test below will never be true and
       
  2180           ** pLevel->pBestIdx never set.
       
  2181           */ 
       
  2182           cost = (SQLITE_BIG_DBL/2.0);
       
  2183         }
       
  2184       }else 
       
  2185 #endif
       
  2186       {
       
  2187         cost = bestIndex(pParse, &wc, pTabItem, notReady,
       
  2188                          (i==0 && ppOrderBy) ? *ppOrderBy : 0,
       
  2189                          &pIdx, &flags, &nEq);
       
  2190         pIndex = 0;
       
  2191       }
       
  2192       if( cost<lowestCost ){
       
  2193         once = 1;
       
  2194         lowestCost = cost;
       
  2195         pBest = pIdx;
       
  2196         bestFlags = flags;
       
  2197         bestNEq = nEq;
       
  2198         bestJ = j;
       
  2199         pLevel->pBestIdx = pIndex;
       
  2200       }
       
  2201       if( doNotReorder ) break;
       
  2202     }
       
  2203     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
       
  2204            pLevel-pWInfo->a));
       
  2205     if( (bestFlags & WHERE_ORDERBY)!=0 ){
       
  2206       *ppOrderBy = 0;
       
  2207     }
       
  2208     andFlags &= bestFlags;
       
  2209     pLevel->flags = bestFlags;
       
  2210     pLevel->pIdx = pBest;
       
  2211     pLevel->nEq = bestNEq;
       
  2212     pLevel->aInLoop = 0;
       
  2213     pLevel->nIn = 0;
       
  2214     if( pBest ){
       
  2215       pLevel->iIdxCur = pParse->nTab++;
       
  2216     }else{
       
  2217       pLevel->iIdxCur = -1;
       
  2218     }
       
  2219     notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
       
  2220     pLevel->iFrom = bestJ;
       
  2221   }
       
  2222   WHERETRACE(("*** Optimizer Finished ***\n"));
       
  2223 
       
  2224   /* If the total query only selects a single row, then the ORDER BY
       
  2225   ** clause is irrelevant.
       
  2226   */
       
  2227   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
       
  2228     *ppOrderBy = 0;
       
  2229   }
       
  2230 
       
  2231   /* If the caller is an UPDATE or DELETE statement that is requesting
       
  2232   ** to use a one-pass algorithm, determine if this is appropriate.
       
  2233   ** The one-pass algorithm only works if the WHERE clause constraints
       
  2234   ** the statement to update a single row.
       
  2235   */
       
  2236   assert( (wflags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
       
  2237   if( (wflags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
       
  2238     pWInfo->okOnePass = 1;
       
  2239     pWInfo->a[0].flags &= ~WHERE_IDX_ONLY;
       
  2240   }
       
  2241 
       
  2242   /* Open all tables in the pTabList and any indices selected for
       
  2243   ** searching those tables.
       
  2244   */
       
  2245   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
       
  2246   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
       
  2247     Table *pTab;     /* Table to open */
       
  2248     Index *pIx;      /* Index used to access pTab (if any) */
       
  2249     int iDb;         /* Index of database containing table/index */
       
  2250     int iIdxCur = pLevel->iIdxCur;
       
  2251 
       
  2252 #ifndef SQLITE_OMIT_EXPLAIN
       
  2253     if( pParse->explain==2 ){
       
  2254       char *zMsg;
       
  2255       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
       
  2256       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
       
  2257       if( pItem->zAlias ){
       
  2258         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
       
  2259       }
       
  2260       if( (pIx = pLevel->pIdx)!=0 ){
       
  2261         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s", zMsg, pIx->zName);
       
  2262       }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
       
  2263         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
       
  2264       }
       
  2265 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
  2266       else if( pLevel->pBestIdx ){
       
  2267         sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
       
  2268         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
       
  2269                     pBestIdx->idxNum, pBestIdx->idxStr);
       
  2270       }
       
  2271 #endif
       
  2272       if( pLevel->flags & WHERE_ORDERBY ){
       
  2273         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
       
  2274       }
       
  2275       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
       
  2276     }
       
  2277 #endif /* SQLITE_OMIT_EXPLAIN */
       
  2278     pTabItem = &pTabList->a[pLevel->iFrom];
       
  2279     pTab = pTabItem->pTab;
       
  2280     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
       
  2281     if( pTab->isEphem || pTab->pSelect ) continue;
       
  2282 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
  2283     if( pLevel->pBestIdx ){
       
  2284       int iCur = pTabItem->iCursor;
       
  2285       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
       
  2286                         (const char*)pTab->pVtab, P4_VTAB);
       
  2287     }else
       
  2288 #endif
       
  2289     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
       
  2290       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
       
  2291       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
       
  2292       if( !pWInfo->okOnePass && pTab->nCol<(sizeof(Bitmask)*8) ){
       
  2293         Bitmask b = pTabItem->colUsed;
       
  2294         int n = 0;
       
  2295         for(; b; b=b>>1, n++){}
       
  2296         sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-2, n);
       
  2297         assert( n<=pTab->nCol );
       
  2298       }
       
  2299     }else{
       
  2300       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
       
  2301     }
       
  2302     pLevel->iTabCur = pTabItem->iCursor;
       
  2303     if( (pIx = pLevel->pIdx)!=0 ){
       
  2304       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
       
  2305       assert( pIx->pSchema==pTab->pSchema );
       
  2306       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIx->nColumn+1);
       
  2307       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
       
  2308                         (char*)pKey, P4_KEYINFO_HANDOFF);
       
  2309       VdbeComment((v, "%s", pIx->zName));
       
  2310     }
       
  2311     sqlite3CodeVerifySchema(pParse, iDb);
       
  2312   }
       
  2313   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
       
  2314 
       
  2315   /* Generate the code to do the search.  Each iteration of the for
       
  2316   ** loop below generates code for a single nested loop of the VM
       
  2317   ** program.
       
  2318   */
       
  2319   notReady = ~(Bitmask)0;
       
  2320   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
       
  2321     int j;
       
  2322     int iCur = pTabItem->iCursor;  /* The VDBE cursor for the table */
       
  2323     Index *pIdx;       /* The index we will be using */
       
  2324     int nxt;           /* Where to jump to continue with the next IN case */
       
  2325     int iIdxCur;       /* The VDBE cursor for the index */
       
  2326     int omitTable;     /* True if we use the index only */
       
  2327     int bRev;          /* True if we need to scan in reverse order */
       
  2328 
       
  2329     pTabItem = &pTabList->a[pLevel->iFrom];
       
  2330     iCur = pTabItem->iCursor;
       
  2331     pIdx = pLevel->pIdx;
       
  2332     iIdxCur = pLevel->iIdxCur;
       
  2333     bRev = (pLevel->flags & WHERE_REVERSE)!=0;
       
  2334     omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
       
  2335 
       
  2336     /* Create labels for the "break" and "continue" instructions
       
  2337     ** for the current loop.  Jump to brk to break out of a loop.
       
  2338     ** Jump to cont to go immediately to the next iteration of the
       
  2339     ** loop.
       
  2340     **
       
  2341     ** When there is an IN operator, we also have a "nxt" label that
       
  2342     ** means to continue with the next IN value combination.  When
       
  2343     ** there are no IN operators in the constraints, the "nxt" label
       
  2344     ** is the same as "brk".
       
  2345     */
       
  2346     brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
       
  2347     cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
       
  2348 
       
  2349     /* If this is the right table of a LEFT OUTER JOIN, allocate and
       
  2350     ** initialize a memory cell that records if this table matches any
       
  2351     ** row of the left table of the join.
       
  2352     */
       
  2353     if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
       
  2354       pLevel->iLeftJoin = ++pParse->nMem;
       
  2355       sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
       
  2356       VdbeComment((v, "init LEFT JOIN no-match flag"));
       
  2357     }
       
  2358 
       
  2359 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
  2360     if( pLevel->pBestIdx ){
       
  2361       /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
       
  2362       **          to access the data.
       
  2363       */
       
  2364       int j;
       
  2365       int iReg;   /* P3 Value for OP_VFilter */
       
  2366       sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
       
  2367       int nConstraint = pBestIdx->nConstraint;
       
  2368       struct sqlite3_index_constraint_usage *aUsage =
       
  2369                                                   pBestIdx->aConstraintUsage;
       
  2370       const struct sqlite3_index_constraint *aConstraint =
       
  2371                                                   pBestIdx->aConstraint;
       
  2372 
       
  2373       iReg = sqlite3GetTempRange(pParse, nConstraint+2);
       
  2374       pParse->disableColCache++;
       
  2375       for(j=1; j<=nConstraint; j++){
       
  2376         int k;
       
  2377         for(k=0; k<nConstraint; k++){
       
  2378           if( aUsage[k].argvIndex==j ){
       
  2379             int iTerm = aConstraint[k].iTermOffset;
       
  2380             assert( pParse->disableColCache );
       
  2381             sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight, iReg+j+1);
       
  2382             break;
       
  2383           }
       
  2384         }
       
  2385         if( k==nConstraint ) break;
       
  2386       }
       
  2387       assert( pParse->disableColCache );
       
  2388       pParse->disableColCache--;
       
  2389       sqlite3VdbeAddOp2(v, OP_Integer, pBestIdx->idxNum, iReg);
       
  2390       sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
       
  2391       sqlite3VdbeAddOp4(v, OP_VFilter, iCur, brk, iReg, pBestIdx->idxStr,
       
  2392                         pBestIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
       
  2393       sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
       
  2394       pBestIdx->needToFreeIdxStr = 0;
       
  2395       for(j=0; j<nConstraint; j++){
       
  2396         if( aUsage[j].omit ){
       
  2397           int iTerm = aConstraint[j].iTermOffset;
       
  2398           disableTerm(pLevel, &wc.a[iTerm]);
       
  2399         }
       
  2400       }
       
  2401       pLevel->op = OP_VNext;
       
  2402       pLevel->p1 = iCur;
       
  2403       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
       
  2404     }else
       
  2405 #endif /* SQLITE_OMIT_VIRTUALTABLE */
       
  2406 
       
  2407     if( pLevel->flags & WHERE_ROWID_EQ ){
       
  2408       /* Case 1:  We can directly reference a single row using an
       
  2409       **          equality comparison against the ROWID field.  Or
       
  2410       **          we reference multiple rows using a "rowid IN (...)"
       
  2411       **          construct.
       
  2412       */
       
  2413       int r1;
       
  2414       pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
       
  2415       assert( pTerm!=0 );
       
  2416       assert( pTerm->pExpr!=0 );
       
  2417       assert( pTerm->leftCursor==iCur );
       
  2418       assert( omitTable==0 );
       
  2419       r1 = codeEqualityTerm(pParse, pTerm, pLevel, 0);
       
  2420       nxt = pLevel->nxt;
       
  2421       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, nxt);
       
  2422       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, nxt, r1);
       
  2423       VdbeComment((v, "pk"));
       
  2424       pLevel->op = OP_Noop;
       
  2425     }else if( pLevel->flags & WHERE_ROWID_RANGE ){
       
  2426       /* Case 2:  We have an inequality comparison against the ROWID field.
       
  2427       */
       
  2428       int testOp = OP_Noop;
       
  2429       int start;
       
  2430       WhereTerm *pStart, *pEnd;
       
  2431 
       
  2432       assert( omitTable==0 );
       
  2433       pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
       
  2434       pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
       
  2435       if( bRev ){
       
  2436         pTerm = pStart;
       
  2437         pStart = pEnd;
       
  2438         pEnd = pTerm;
       
  2439       }
       
  2440       if( pStart ){
       
  2441         Expr *pX;
       
  2442         int r1, regFree1;
       
  2443         pX = pStart->pExpr;
       
  2444         assert( pX!=0 );
       
  2445         assert( pStart->leftCursor==iCur );
       
  2446         r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &regFree1);
       
  2447         sqlite3VdbeAddOp3(v, OP_ForceInt, r1, brk, 
       
  2448                              pX->op==TK_LE || pX->op==TK_GT);
       
  2449         sqlite3VdbeAddOp3(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk, r1);
       
  2450         VdbeComment((v, "pk"));
       
  2451         sqlite3ReleaseTempReg(pParse, regFree1);
       
  2452         disableTerm(pLevel, pStart);
       
  2453       }else{
       
  2454         sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
       
  2455       }
       
  2456       if( pEnd ){
       
  2457         Expr *pX;
       
  2458         pX = pEnd->pExpr;
       
  2459         assert( pX!=0 );
       
  2460         assert( pEnd->leftCursor==iCur );
       
  2461         pLevel->iMem = ++pParse->nMem;
       
  2462         sqlite3ExprCode(pParse, pX->pRight, pLevel->iMem);
       
  2463         if( pX->op==TK_LT || pX->op==TK_GT ){
       
  2464           testOp = bRev ? OP_Le : OP_Ge;
       
  2465         }else{
       
  2466           testOp = bRev ? OP_Lt : OP_Gt;
       
  2467         }
       
  2468         disableTerm(pLevel, pEnd);
       
  2469       }
       
  2470       start = sqlite3VdbeCurrentAddr(v);
       
  2471       pLevel->op = bRev ? OP_Prev : OP_Next;
       
  2472       pLevel->p1 = iCur;
       
  2473       pLevel->p2 = start;
       
  2474       if( testOp!=OP_Noop ){
       
  2475         int r1 = sqlite3GetTempReg(pParse);
       
  2476         sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
       
  2477         /* sqlite3VdbeAddOp2(v, OP_SCopy, pLevel->iMem, 0); */
       
  2478         sqlite3VdbeAddOp3(v, testOp, pLevel->iMem, brk, r1);
       
  2479         sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
       
  2480         sqlite3ReleaseTempReg(pParse, r1);
       
  2481       }
       
  2482     }else if( pLevel->flags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
       
  2483       /* Case 3: A scan using an index.
       
  2484       **
       
  2485       **         The WHERE clause may contain zero or more equality 
       
  2486       **         terms ("==" or "IN" operators) that refer to the N
       
  2487       **         left-most columns of the index. It may also contain
       
  2488       **         inequality constraints (>, <, >= or <=) on the indexed
       
  2489       **         column that immediately follows the N equalities. Only 
       
  2490       **         the right-most column can be an inequality - the rest must
       
  2491       **         use the "==" and "IN" operators. For example, if the 
       
  2492       **         index is on (x,y,z), then the following clauses are all 
       
  2493       **         optimized:
       
  2494       **
       
  2495       **            x=5
       
  2496       **            x=5 AND y=10
       
  2497       **            x=5 AND y<10
       
  2498       **            x=5 AND y>5 AND y<10
       
  2499       **            x=5 AND y=5 AND z<=10
       
  2500       **
       
  2501       **         The z<10 term of the following cannot be used, only
       
  2502       **         the x=5 term:
       
  2503       **
       
  2504       **            x=5 AND z<10
       
  2505       **
       
  2506       **         N may be zero if there are inequality constraints.
       
  2507       **         If there are no inequality constraints, then N is at
       
  2508       **         least one.
       
  2509       **
       
  2510       **         This case is also used when there are no WHERE clause
       
  2511       **         constraints but an index is selected anyway, in order
       
  2512       **         to force the output order to conform to an ORDER BY.
       
  2513       */  
       
  2514       int aStartOp[] = {
       
  2515         0,
       
  2516         0,
       
  2517         OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
       
  2518         OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
       
  2519         OP_MoveGt,           /* 4: (start_constraints  && !startEq && !bRev) */
       
  2520         OP_MoveLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
       
  2521         OP_MoveGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
       
  2522         OP_MoveLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
       
  2523       };
       
  2524       int aEndOp[] = {
       
  2525         OP_Noop,             /* 0: (!end_constraints) */
       
  2526         OP_IdxGE,            /* 1: (end_constraints && !bRev) */
       
  2527         OP_IdxLT             /* 2: (end_constraints && bRev) */
       
  2528       };
       
  2529       int nEq = pLevel->nEq;
       
  2530       int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
       
  2531       int regBase;                 /* Base register holding constraint values */
       
  2532       int r1;                      /* Temp register */
       
  2533       WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
       
  2534       WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
       
  2535       int startEq;                 /* True if range start uses ==, >= or <= */
       
  2536       int endEq;                   /* True if range end uses ==, >= or <= */
       
  2537       int start_constraints;       /* Start of range is constrained */
       
  2538       int k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
       
  2539       int nConstraint;             /* Number of constraint terms */
       
  2540       int op;
       
  2541 
       
  2542       /* Generate code to evaluate all constraint terms using == or IN
       
  2543       ** and store the values of those terms in an array of registers
       
  2544       ** starting at regBase.
       
  2545       */
       
  2546       regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 2);
       
  2547       nxt = pLevel->nxt;
       
  2548 
       
  2549       /* If this loop satisfies a sort order (pOrderBy) request that 
       
  2550       ** was passed to this function to implement a "SELECT min(x) ..." 
       
  2551       ** query, then the caller will only allow the loop to run for
       
  2552       ** a single iteration. This means that the first row returned
       
  2553       ** should not have a NULL value stored in 'x'. If column 'x' is
       
  2554       ** the first one after the nEq equality constraints in the index,
       
  2555       ** this requires some special handling.
       
  2556       */
       
  2557       if( (wflags&WHERE_ORDERBY_MIN)!=0
       
  2558        && (pLevel->flags&WHERE_ORDERBY)
       
  2559        && (pIdx->nColumn>nEq)
       
  2560       ){
       
  2561         assert( pOrderBy->nExpr==1 );
       
  2562         assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] );
       
  2563         isMinQuery = 1;
       
  2564       }
       
  2565 
       
  2566       /* Find any inequality constraint terms for the start and end 
       
  2567       ** of the range. 
       
  2568       */
       
  2569       if( pLevel->flags & WHERE_TOP_LIMIT ){
       
  2570         pRangeEnd = findTerm(&wc, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
       
  2571       }
       
  2572       if( pLevel->flags & WHERE_BTM_LIMIT ){
       
  2573         pRangeStart = findTerm(&wc, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
       
  2574       }
       
  2575 
       
  2576       /* If we are doing a reverse order scan on an ascending index, or
       
  2577       ** a forward order scan on a descending index, interchange the 
       
  2578       ** start and end terms (pRangeStart and pRangeEnd).
       
  2579       */
       
  2580       if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
       
  2581         SWAP(WhereTerm *, pRangeEnd, pRangeStart);
       
  2582       }
       
  2583 
       
  2584       testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
       
  2585       testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
       
  2586       testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
       
  2587       testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
       
  2588       startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
       
  2589       endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
       
  2590       start_constraints = pRangeStart || nEq>0;
       
  2591 
       
  2592       /* Seek the index cursor to the start of the range. */
       
  2593       nConstraint = nEq;
       
  2594       if( pRangeStart ){
       
  2595         int dcc = pParse->disableColCache;
       
  2596         if( pRangeEnd ){
       
  2597           pParse->disableColCache++;
       
  2598         }
       
  2599         sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
       
  2600         pParse->disableColCache = dcc;
       
  2601         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
       
  2602         nConstraint++;
       
  2603       }else if( isMinQuery ){
       
  2604         sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
       
  2605         nConstraint++;
       
  2606         startEq = 0;
       
  2607         start_constraints = 1;
       
  2608       }
       
  2609       codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
       
  2610       op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
       
  2611       assert( op!=0 );
       
  2612       testcase( op==OP_Rewind );
       
  2613       testcase( op==OP_Last );
       
  2614       testcase( op==OP_MoveGt );
       
  2615       testcase( op==OP_MoveGe );
       
  2616       testcase( op==OP_MoveLe );
       
  2617       testcase( op==OP_MoveLt );
       
  2618       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase, 
       
  2619                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
       
  2620 
       
  2621       /* Load the value for the inequality constraint at the end of the
       
  2622       ** range (if any).
       
  2623       */
       
  2624       nConstraint = nEq;
       
  2625       if( pRangeEnd ){
       
  2626         sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
       
  2627         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
       
  2628         codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
       
  2629         nConstraint++;
       
  2630       }
       
  2631 
       
  2632       /* Top of the loop body */
       
  2633       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
       
  2634 
       
  2635       /* Check if the index cursor is past the end of the range. */
       
  2636       op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
       
  2637       testcase( op==OP_Noop );
       
  2638       testcase( op==OP_IdxGE );
       
  2639       testcase( op==OP_IdxLT );
       
  2640       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase,
       
  2641                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
       
  2642       sqlite3VdbeChangeP5(v, endEq!=bRev);
       
  2643 
       
  2644       /* If there are inequality constraints, check that the value
       
  2645       ** of the table column that the inequality contrains is not NULL.
       
  2646       ** If it is, jump to the next iteration of the loop.
       
  2647       */
       
  2648       r1 = sqlite3GetTempReg(pParse);
       
  2649       testcase( pLevel->flags & WHERE_BTM_LIMIT );
       
  2650       testcase( pLevel->flags & WHERE_TOP_LIMIT );
       
  2651       if( pLevel->flags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
       
  2652         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
       
  2653         sqlite3VdbeAddOp2(v, OP_IsNull, r1, cont);
       
  2654       }
       
  2655 
       
  2656       /* Seek the table cursor, if required */
       
  2657       if( !omitTable ){
       
  2658         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
       
  2659         sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1);  /* Deferred seek */
       
  2660       }
       
  2661       sqlite3ReleaseTempReg(pParse, r1);
       
  2662 
       
  2663       /* Record the instruction used to terminate the loop. Disable 
       
  2664       ** WHERE clause terms made redundant by the index range scan.
       
  2665       */
       
  2666       pLevel->op = bRev ? OP_Prev : OP_Next;
       
  2667       pLevel->p1 = iIdxCur;
       
  2668       disableTerm(pLevel, pRangeStart);
       
  2669       disableTerm(pLevel, pRangeEnd);
       
  2670     }else{
       
  2671       /* Case 4:  There is no usable index.  We must do a complete
       
  2672       **          scan of the entire table.
       
  2673       */
       
  2674       assert( omitTable==0 );
       
  2675       assert( bRev==0 );
       
  2676       pLevel->op = OP_Next;
       
  2677       pLevel->p1 = iCur;
       
  2678       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, brk);
       
  2679     }
       
  2680     notReady &= ~getMask(&maskSet, iCur);
       
  2681 
       
  2682     /* Insert code to test every subexpression that can be completely
       
  2683     ** computed using the current set of tables.
       
  2684     */
       
  2685     for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
       
  2686       Expr *pE;
       
  2687       testcase( pTerm->flags & TERM_VIRTUAL );
       
  2688       testcase( pTerm->flags & TERM_CODED );
       
  2689       if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
       
  2690       if( (pTerm->prereqAll & notReady)!=0 ) continue;
       
  2691       pE = pTerm->pExpr;
       
  2692       assert( pE!=0 );
       
  2693       if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
       
  2694         continue;
       
  2695       }
       
  2696       sqlite3ExprIfFalse(pParse, pE, cont, SQLITE_JUMPIFNULL);
       
  2697       pTerm->flags |= TERM_CODED;
       
  2698     }
       
  2699 
       
  2700     /* For a LEFT OUTER JOIN, generate code that will record the fact that
       
  2701     ** at least one row of the right table has matched the left table.  
       
  2702     */
       
  2703     if( pLevel->iLeftJoin ){
       
  2704       pLevel->top = sqlite3VdbeCurrentAddr(v);
       
  2705       sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
       
  2706       VdbeComment((v, "record LEFT JOIN hit"));
       
  2707       sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
       
  2708       sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
       
  2709       for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
       
  2710         testcase( pTerm->flags & TERM_VIRTUAL );
       
  2711         testcase( pTerm->flags & TERM_CODED );
       
  2712         if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
       
  2713         if( (pTerm->prereqAll & notReady)!=0 ) continue;
       
  2714         assert( pTerm->pExpr );
       
  2715         sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, SQLITE_JUMPIFNULL);
       
  2716         pTerm->flags |= TERM_CODED;
       
  2717       }
       
  2718     }
       
  2719   }
       
  2720 
       
  2721 #ifdef SQLITE_TEST  /* For testing and debugging use only */
       
  2722   /* Record in the query plan information about the current table
       
  2723   ** and the index used to access it (if any).  If the table itself
       
  2724   ** is not used, its name is just '{}'.  If no index is used
       
  2725   ** the index is listed as "{}".  If the primary key is used the
       
  2726   ** index name is '*'.
       
  2727   */
       
  2728   for(i=0; i<pTabList->nSrc; i++){
       
  2729     char *z;
       
  2730     int n;
       
  2731     pLevel = &pWInfo->a[i];
       
  2732     pTabItem = &pTabList->a[pLevel->iFrom];
       
  2733     z = pTabItem->zAlias;
       
  2734     if( z==0 ) z = pTabItem->pTab->zName;
       
  2735     n = strlen(z);
       
  2736     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
       
  2737       if( pLevel->flags & WHERE_IDX_ONLY ){
       
  2738         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
       
  2739         nQPlan += 2;
       
  2740       }else{
       
  2741         memcpy(&sqlite3_query_plan[nQPlan], z, n);
       
  2742         nQPlan += n;
       
  2743       }
       
  2744       sqlite3_query_plan[nQPlan++] = ' ';
       
  2745     }
       
  2746     testcase( pLevel->flags & WHERE_ROWID_EQ );
       
  2747     testcase( pLevel->flags & WHERE_ROWID_RANGE );
       
  2748     if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
       
  2749       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
       
  2750       nQPlan += 2;
       
  2751     }else if( pLevel->pIdx==0 ){
       
  2752       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
       
  2753       nQPlan += 3;
       
  2754     }else{
       
  2755       n = strlen(pLevel->pIdx->zName);
       
  2756       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
       
  2757         memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
       
  2758         nQPlan += n;
       
  2759         sqlite3_query_plan[nQPlan++] = ' ';
       
  2760       }
       
  2761     }
       
  2762   }
       
  2763   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
       
  2764     sqlite3_query_plan[--nQPlan] = 0;
       
  2765   }
       
  2766   sqlite3_query_plan[nQPlan] = 0;
       
  2767   nQPlan = 0;
       
  2768 #endif /* SQLITE_TEST // Testing and debugging use only */
       
  2769 
       
  2770   /* Record the continuation address in the WhereInfo structure.  Then
       
  2771   ** clean up and return.
       
  2772   */
       
  2773   pWInfo->iContinue = cont;
       
  2774   whereClauseClear(&wc);
       
  2775   return pWInfo;
       
  2776 
       
  2777   /* Jump here if malloc fails */
       
  2778 whereBeginNoMem:
       
  2779   whereClauseClear(&wc);
       
  2780   whereInfoFree(pWInfo);
       
  2781   return 0;
       
  2782 }
       
  2783 
       
  2784 /*
       
  2785 ** Generate the end of the WHERE loop.  See comments on 
       
  2786 ** sqlite3WhereBegin() for additional information.
       
  2787 */
       
  2788 void sqlite3WhereEnd(WhereInfo *pWInfo){
       
  2789   Parse *pParse = pWInfo->pParse;
       
  2790   Vdbe *v = pParse->pVdbe;
       
  2791   int i;
       
  2792   WhereLevel *pLevel;
       
  2793   SrcList *pTabList = pWInfo->pTabList;
       
  2794   sqlite3 *db = pParse->db;
       
  2795 
       
  2796   /* Generate loop termination code.
       
  2797   */
       
  2798   sqlite3ExprClearColumnCache(pParse, -1);
       
  2799   for(i=pTabList->nSrc-1; i>=0; i--){
       
  2800     pLevel = &pWInfo->a[i];
       
  2801     sqlite3VdbeResolveLabel(v, pLevel->cont);
       
  2802     if( pLevel->op!=OP_Noop ){
       
  2803       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
       
  2804     }
       
  2805     if( pLevel->nIn ){
       
  2806       struct InLoop *pIn;
       
  2807       int j;
       
  2808       sqlite3VdbeResolveLabel(v, pLevel->nxt);
       
  2809       for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
       
  2810         sqlite3VdbeJumpHere(v, pIn->topAddr+1);
       
  2811         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->topAddr);
       
  2812         sqlite3VdbeJumpHere(v, pIn->topAddr-1);
       
  2813       }
       
  2814       sqlite3DbFree(db, pLevel->aInLoop);
       
  2815     }
       
  2816     sqlite3VdbeResolveLabel(v, pLevel->brk);
       
  2817     if( pLevel->iLeftJoin ){
       
  2818       int addr;
       
  2819       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
       
  2820       sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
       
  2821       if( pLevel->iIdxCur>=0 ){
       
  2822         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
       
  2823       }
       
  2824       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->top);
       
  2825       sqlite3VdbeJumpHere(v, addr);
       
  2826     }
       
  2827   }
       
  2828 
       
  2829   /* The "break" point is here, just past the end of the outer loop.
       
  2830   ** Set it.
       
  2831   */
       
  2832   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
       
  2833 
       
  2834   /* Close all of the cursors that were opened by sqlite3WhereBegin.
       
  2835   */
       
  2836   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
       
  2837     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
       
  2838     Table *pTab = pTabItem->pTab;
       
  2839     assert( pTab!=0 );
       
  2840     if( pTab->isEphem || pTab->pSelect ) continue;
       
  2841     if( !pWInfo->okOnePass && (pLevel->flags & WHERE_IDX_ONLY)==0 ){
       
  2842       sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
       
  2843     }
       
  2844     if( pLevel->pIdx!=0 ){
       
  2845       sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
       
  2846     }
       
  2847 
       
  2848     /* If this scan uses an index, make code substitutions to read data
       
  2849     ** from the index in preference to the table. Sometimes, this means
       
  2850     ** the table need never be read from. This is a performance boost,
       
  2851     ** as the vdbe level waits until the table is read before actually
       
  2852     ** seeking the table cursor to the record corresponding to the current
       
  2853     ** position in the index.
       
  2854     ** 
       
  2855     ** Calls to the code generator in between sqlite3WhereBegin and
       
  2856     ** sqlite3WhereEnd will have created code that references the table
       
  2857     ** directly.  This loop scans all that code looking for opcodes
       
  2858     ** that reference the table and converts them into opcodes that
       
  2859     ** reference the index.
       
  2860     */
       
  2861     if( pLevel->pIdx ){
       
  2862       int k, j, last;
       
  2863       VdbeOp *pOp;
       
  2864       Index *pIdx = pLevel->pIdx;
       
  2865       int useIndexOnly = pLevel->flags & WHERE_IDX_ONLY;
       
  2866 
       
  2867       assert( pIdx!=0 );
       
  2868       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
       
  2869       last = sqlite3VdbeCurrentAddr(v);
       
  2870       for(k=pWInfo->iTop; k<last; k++, pOp++){
       
  2871         if( pOp->p1!=pLevel->iTabCur ) continue;
       
  2872         if( pOp->opcode==OP_Column ){
       
  2873           for(j=0; j<pIdx->nColumn; j++){
       
  2874             if( pOp->p2==pIdx->aiColumn[j] ){
       
  2875               pOp->p2 = j;
       
  2876               pOp->p1 = pLevel->iIdxCur;
       
  2877               break;
       
  2878             }
       
  2879           }
       
  2880           assert(!useIndexOnly || j<pIdx->nColumn);
       
  2881         }else if( pOp->opcode==OP_Rowid ){
       
  2882           pOp->p1 = pLevel->iIdxCur;
       
  2883           pOp->opcode = OP_IdxRowid;
       
  2884         }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
       
  2885           pOp->opcode = OP_Noop;
       
  2886         }
       
  2887       }
       
  2888     }
       
  2889   }
       
  2890 
       
  2891   /* Final cleanup
       
  2892   */
       
  2893   whereInfoFree(pWInfo);
       
  2894   return;
       
  2895 }