1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/os/persistentdata/persistentstorage/sql/SQLite364/where.c Fri Jun 15 03:10:57 2012 +0200
1.3 @@ -0,0 +1,2944 @@
1.4 +/*
1.5 +** 2001 September 15
1.6 +**
1.7 +** The author disclaims copyright to this source code. In place of
1.8 +** a legal notice, here is a blessing:
1.9 +**
1.10 +** May you do good and not evil.
1.11 +** May you find forgiveness for yourself and forgive others.
1.12 +** May you share freely, never taking more than you give.
1.13 +**
1.14 +*************************************************************************
1.15 +** This module contains C code that generates VDBE code used to process
1.16 +** the WHERE clause of SQL statements. This module is responsible for
1.17 +** generating the code that loops through a table looking for applicable
1.18 +** rows. Indices are selected and used to speed the search when doing
1.19 +** so is applicable. Because this module is responsible for selecting
1.20 +** indices, you might also think of this module as the "query optimizer".
1.21 +**
1.22 +** $Id: where.c,v 1.326 2008/10/11 16:47:36 drh Exp $
1.23 +*/
1.24 +#include "sqliteInt.h"
1.25 +
1.26 +/*
1.27 +** The number of bits in a Bitmask. "BMS" means "BitMask Size".
1.28 +*/
1.29 +#define BMS (sizeof(Bitmask)*8)
1.30 +
1.31 +/*
1.32 +** Trace output macros
1.33 +*/
1.34 +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
1.35 +int sqlite3WhereTrace = 0;
1.36 +#endif
1.37 +#if 0
1.38 +# define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
1.39 +#else
1.40 +# define WHERETRACE(X)
1.41 +#endif
1.42 +
1.43 +/* Forward reference
1.44 +*/
1.45 +typedef struct WhereClause WhereClause;
1.46 +typedef struct ExprMaskSet ExprMaskSet;
1.47 +
1.48 +/*
1.49 +** The query generator uses an array of instances of this structure to
1.50 +** help it analyze the subexpressions of the WHERE clause. Each WHERE
1.51 +** clause subexpression is separated from the others by an AND operator.
1.52 +**
1.53 +** All WhereTerms are collected into a single WhereClause structure.
1.54 +** The following identity holds:
1.55 +**
1.56 +** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
1.57 +**
1.58 +** When a term is of the form:
1.59 +**
1.60 +** X <op> <expr>
1.61 +**
1.62 +** where X is a column name and <op> is one of certain operators,
1.63 +** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
1.64 +** cursor number and column number for X. WhereTerm.operator records
1.65 +** the <op> using a bitmask encoding defined by WO_xxx below. The
1.66 +** use of a bitmask encoding for the operator allows us to search
1.67 +** quickly for terms that match any of several different operators.
1.68 +**
1.69 +** prereqRight and prereqAll record sets of cursor numbers,
1.70 +** but they do so indirectly. A single ExprMaskSet structure translates
1.71 +** cursor number into bits and the translated bit is stored in the prereq
1.72 +** fields. The translation is used in order to maximize the number of
1.73 +** bits that will fit in a Bitmask. The VDBE cursor numbers might be
1.74 +** spread out over the non-negative integers. For example, the cursor
1.75 +** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The ExprMaskSet
1.76 +** translates these sparse cursor numbers into consecutive integers
1.77 +** beginning with 0 in order to make the best possible use of the available
1.78 +** bits in the Bitmask. So, in the example above, the cursor numbers
1.79 +** would be mapped into integers 0 through 7.
1.80 +*/
1.81 +typedef struct WhereTerm WhereTerm;
1.82 +struct WhereTerm {
1.83 + Expr *pExpr; /* Pointer to the subexpression */
1.84 + i16 iParent; /* Disable pWC->a[iParent] when this term disabled */
1.85 + i16 leftCursor; /* Cursor number of X in "X <op> <expr>" */
1.86 + i16 leftColumn; /* Column number of X in "X <op> <expr>" */
1.87 + u16 eOperator; /* A WO_xx value describing <op> */
1.88 + u8 flags; /* Bit flags. See below */
1.89 + u8 nChild; /* Number of children that must disable us */
1.90 + WhereClause *pWC; /* The clause this term is part of */
1.91 + Bitmask prereqRight; /* Bitmask of tables used by pRight */
1.92 + Bitmask prereqAll; /* Bitmask of tables referenced by p */
1.93 +};
1.94 +
1.95 +/*
1.96 +** Allowed values of WhereTerm.flags
1.97 +*/
1.98 +#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
1.99 +#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
1.100 +#define TERM_CODED 0x04 /* This term is already coded */
1.101 +#define TERM_COPIED 0x08 /* Has a child */
1.102 +#define TERM_OR_OK 0x10 /* Used during OR-clause processing */
1.103 +
1.104 +/*
1.105 +** An instance of the following structure holds all information about a
1.106 +** WHERE clause. Mostly this is a container for one or more WhereTerms.
1.107 +*/
1.108 +struct WhereClause {
1.109 + Parse *pParse; /* The parser context */
1.110 + ExprMaskSet *pMaskSet; /* Mapping of table indices to bitmasks */
1.111 + int nTerm; /* Number of terms */
1.112 + int nSlot; /* Number of entries in a[] */
1.113 + WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
1.114 + WhereTerm aStatic[10]; /* Initial static space for a[] */
1.115 +};
1.116 +
1.117 +/*
1.118 +** An instance of the following structure keeps track of a mapping
1.119 +** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
1.120 +**
1.121 +** The VDBE cursor numbers are small integers contained in
1.122 +** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
1.123 +** clause, the cursor numbers might not begin with 0 and they might
1.124 +** contain gaps in the numbering sequence. But we want to make maximum
1.125 +** use of the bits in our bitmasks. This structure provides a mapping
1.126 +** from the sparse cursor numbers into consecutive integers beginning
1.127 +** with 0.
1.128 +**
1.129 +** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
1.130 +** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
1.131 +**
1.132 +** For example, if the WHERE clause expression used these VDBE
1.133 +** cursors: 4, 5, 8, 29, 57, 73. Then the ExprMaskSet structure
1.134 +** would map those cursor numbers into bits 0 through 5.
1.135 +**
1.136 +** Note that the mapping is not necessarily ordered. In the example
1.137 +** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
1.138 +** 57->5, 73->4. Or one of 719 other combinations might be used. It
1.139 +** does not really matter. What is important is that sparse cursor
1.140 +** numbers all get mapped into bit numbers that begin with 0 and contain
1.141 +** no gaps.
1.142 +*/
1.143 +struct ExprMaskSet {
1.144 + int n; /* Number of assigned cursor values */
1.145 + int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */
1.146 +};
1.147 +
1.148 +
1.149 +/*
1.150 +** Bitmasks for the operators that indices are able to exploit. An
1.151 +** OR-ed combination of these values can be used when searching for
1.152 +** terms in the where clause.
1.153 +*/
1.154 +#define WO_IN 1
1.155 +#define WO_EQ 2
1.156 +#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
1.157 +#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
1.158 +#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
1.159 +#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
1.160 +#define WO_MATCH 64
1.161 +#define WO_ISNULL 128
1.162 +
1.163 +/*
1.164 +** Value for flags returned by bestIndex().
1.165 +**
1.166 +** The least significant byte is reserved as a mask for WO_ values above.
1.167 +** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
1.168 +** But if the table is the right table of a left join, WhereLevel.flags
1.169 +** is set to WO_IN|WO_EQ. The WhereLevel.flags field can then be used as
1.170 +** the "op" parameter to findTerm when we are resolving equality constraints.
1.171 +** ISNULL constraints will then not be used on the right table of a left
1.172 +** join. Tickets #2177 and #2189.
1.173 +*/
1.174 +#define WHERE_ROWID_EQ 0x000100 /* rowid=EXPR or rowid IN (...) */
1.175 +#define WHERE_ROWID_RANGE 0x000200 /* rowid<EXPR and/or rowid>EXPR */
1.176 +#define WHERE_COLUMN_EQ 0x001000 /* x=EXPR or x IN (...) */
1.177 +#define WHERE_COLUMN_RANGE 0x002000 /* x<EXPR and/or x>EXPR */
1.178 +#define WHERE_COLUMN_IN 0x004000 /* x IN (...) */
1.179 +#define WHERE_TOP_LIMIT 0x010000 /* x<EXPR or x<=EXPR constraint */
1.180 +#define WHERE_BTM_LIMIT 0x020000 /* x>EXPR or x>=EXPR constraint */
1.181 +#define WHERE_IDX_ONLY 0x080000 /* Use index only - omit table */
1.182 +#define WHERE_ORDERBY 0x100000 /* Output will appear in correct order */
1.183 +#define WHERE_REVERSE 0x200000 /* Scan in reverse order */
1.184 +#define WHERE_UNIQUE 0x400000 /* Selects no more than one row */
1.185 +#define WHERE_VIRTUALTABLE 0x800000 /* Use virtual-table processing */
1.186 +
1.187 +/*
1.188 +** Initialize a preallocated WhereClause structure.
1.189 +*/
1.190 +static void whereClauseInit(
1.191 + WhereClause *pWC, /* The WhereClause to be initialized */
1.192 + Parse *pParse, /* The parsing context */
1.193 + ExprMaskSet *pMaskSet /* Mapping from table indices to bitmasks */
1.194 +){
1.195 + pWC->pParse = pParse;
1.196 + pWC->pMaskSet = pMaskSet;
1.197 + pWC->nTerm = 0;
1.198 + pWC->nSlot = ArraySize(pWC->aStatic);
1.199 + pWC->a = pWC->aStatic;
1.200 +}
1.201 +
1.202 +/*
1.203 +** Deallocate a WhereClause structure. The WhereClause structure
1.204 +** itself is not freed. This routine is the inverse of whereClauseInit().
1.205 +*/
1.206 +static void whereClauseClear(WhereClause *pWC){
1.207 + int i;
1.208 + WhereTerm *a;
1.209 + sqlite3 *db = pWC->pParse->db;
1.210 + for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
1.211 + if( a->flags & TERM_DYNAMIC ){
1.212 + sqlite3ExprDelete(db, a->pExpr);
1.213 + }
1.214 + }
1.215 + if( pWC->a!=pWC->aStatic ){
1.216 + sqlite3DbFree(db, pWC->a);
1.217 + }
1.218 +}
1.219 +
1.220 +/*
1.221 +** Add a new entries to the WhereClause structure. Increase the allocated
1.222 +** space as necessary.
1.223 +**
1.224 +** If the flags argument includes TERM_DYNAMIC, then responsibility
1.225 +** for freeing the expression p is assumed by the WhereClause object.
1.226 +**
1.227 +** WARNING: This routine might reallocate the space used to store
1.228 +** WhereTerms. All pointers to WhereTerms should be invalidated after
1.229 +** calling this routine. Such pointers may be reinitialized by referencing
1.230 +** the pWC->a[] array.
1.231 +*/
1.232 +static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
1.233 + WhereTerm *pTerm;
1.234 + int idx;
1.235 + if( pWC->nTerm>=pWC->nSlot ){
1.236 + WhereTerm *pOld = pWC->a;
1.237 + sqlite3 *db = pWC->pParse->db;
1.238 + pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
1.239 + if( pWC->a==0 ){
1.240 + if( flags & TERM_DYNAMIC ){
1.241 + sqlite3ExprDelete(db, p);
1.242 + }
1.243 + pWC->a = pOld;
1.244 + return 0;
1.245 + }
1.246 + memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
1.247 + if( pOld!=pWC->aStatic ){
1.248 + sqlite3DbFree(db, pOld);
1.249 + }
1.250 + pWC->nSlot *= 2;
1.251 + }
1.252 + pTerm = &pWC->a[idx = pWC->nTerm];
1.253 + pWC->nTerm++;
1.254 + pTerm->pExpr = p;
1.255 + pTerm->flags = flags;
1.256 + pTerm->pWC = pWC;
1.257 + pTerm->iParent = -1;
1.258 + return idx;
1.259 +}
1.260 +
1.261 +/*
1.262 +** This routine identifies subexpressions in the WHERE clause where
1.263 +** each subexpression is separated by the AND operator or some other
1.264 +** operator specified in the op parameter. The WhereClause structure
1.265 +** is filled with pointers to subexpressions. For example:
1.266 +**
1.267 +** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
1.268 +** \________/ \_______________/ \________________/
1.269 +** slot[0] slot[1] slot[2]
1.270 +**
1.271 +** The original WHERE clause in pExpr is unaltered. All this routine
1.272 +** does is make slot[] entries point to substructure within pExpr.
1.273 +**
1.274 +** In the previous sentence and in the diagram, "slot[]" refers to
1.275 +** the WhereClause.a[] array. This array grows as needed to contain
1.276 +** all terms of the WHERE clause.
1.277 +*/
1.278 +static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
1.279 + if( pExpr==0 ) return;
1.280 + if( pExpr->op!=op ){
1.281 + whereClauseInsert(pWC, pExpr, 0);
1.282 + }else{
1.283 + whereSplit(pWC, pExpr->pLeft, op);
1.284 + whereSplit(pWC, pExpr->pRight, op);
1.285 + }
1.286 +}
1.287 +
1.288 +/*
1.289 +** Initialize an expression mask set
1.290 +*/
1.291 +#define initMaskSet(P) memset(P, 0, sizeof(*P))
1.292 +
1.293 +/*
1.294 +** Return the bitmask for the given cursor number. Return 0 if
1.295 +** iCursor is not in the set.
1.296 +*/
1.297 +static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
1.298 + int i;
1.299 + for(i=0; i<pMaskSet->n; i++){
1.300 + if( pMaskSet->ix[i]==iCursor ){
1.301 + return ((Bitmask)1)<<i;
1.302 + }
1.303 + }
1.304 + return 0;
1.305 +}
1.306 +
1.307 +/*
1.308 +** Create a new mask for cursor iCursor.
1.309 +**
1.310 +** There is one cursor per table in the FROM clause. The number of
1.311 +** tables in the FROM clause is limited by a test early in the
1.312 +** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
1.313 +** array will never overflow.
1.314 +*/
1.315 +static void createMask(ExprMaskSet *pMaskSet, int iCursor){
1.316 + assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
1.317 + pMaskSet->ix[pMaskSet->n++] = iCursor;
1.318 +}
1.319 +
1.320 +/*
1.321 +** This routine walks (recursively) an expression tree and generates
1.322 +** a bitmask indicating which tables are used in that expression
1.323 +** tree.
1.324 +**
1.325 +** In order for this routine to work, the calling function must have
1.326 +** previously invoked sqlite3ResolveExprNames() on the expression. See
1.327 +** the header comment on that routine for additional information.
1.328 +** The sqlite3ResolveExprNames() routines looks for column names and
1.329 +** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
1.330 +** the VDBE cursor number of the table. This routine just has to
1.331 +** translate the cursor numbers into bitmask values and OR all
1.332 +** the bitmasks together.
1.333 +*/
1.334 +static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
1.335 +static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
1.336 +static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
1.337 + Bitmask mask = 0;
1.338 + if( p==0 ) return 0;
1.339 + if( p->op==TK_COLUMN ){
1.340 + mask = getMask(pMaskSet, p->iTable);
1.341 + return mask;
1.342 + }
1.343 + mask = exprTableUsage(pMaskSet, p->pRight);
1.344 + mask |= exprTableUsage(pMaskSet, p->pLeft);
1.345 + mask |= exprListTableUsage(pMaskSet, p->pList);
1.346 + mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
1.347 + return mask;
1.348 +}
1.349 +static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
1.350 + int i;
1.351 + Bitmask mask = 0;
1.352 + if( pList ){
1.353 + for(i=0; i<pList->nExpr; i++){
1.354 + mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
1.355 + }
1.356 + }
1.357 + return mask;
1.358 +}
1.359 +static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
1.360 + Bitmask mask = 0;
1.361 + while( pS ){
1.362 + mask |= exprListTableUsage(pMaskSet, pS->pEList);
1.363 + mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
1.364 + mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
1.365 + mask |= exprTableUsage(pMaskSet, pS->pWhere);
1.366 + mask |= exprTableUsage(pMaskSet, pS->pHaving);
1.367 + pS = pS->pPrior;
1.368 + }
1.369 + return mask;
1.370 +}
1.371 +
1.372 +/*
1.373 +** Return TRUE if the given operator is one of the operators that is
1.374 +** allowed for an indexable WHERE clause term. The allowed operators are
1.375 +** "=", "<", ">", "<=", ">=", and "IN".
1.376 +*/
1.377 +static int allowedOp(int op){
1.378 + assert( TK_GT>TK_EQ && TK_GT<TK_GE );
1.379 + assert( TK_LT>TK_EQ && TK_LT<TK_GE );
1.380 + assert( TK_LE>TK_EQ && TK_LE<TK_GE );
1.381 + assert( TK_GE==TK_EQ+4 );
1.382 + return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
1.383 +}
1.384 +
1.385 +/*
1.386 +** Swap two objects of type T.
1.387 +*/
1.388 +#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
1.389 +
1.390 +/*
1.391 +** Commute a comparison operator. Expressions of the form "X op Y"
1.392 +** are converted into "Y op X".
1.393 +**
1.394 +** If a collation sequence is associated with either the left or right
1.395 +** side of the comparison, it remains associated with the same side after
1.396 +** the commutation. So "Y collate NOCASE op X" becomes
1.397 +** "X collate NOCASE op Y". This is because any collation sequence on
1.398 +** the left hand side of a comparison overrides any collation sequence
1.399 +** attached to the right. For the same reason the EP_ExpCollate flag
1.400 +** is not commuted.
1.401 +*/
1.402 +static void exprCommute(Parse *pParse, Expr *pExpr){
1.403 + u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
1.404 + u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
1.405 + assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
1.406 + pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
1.407 + pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
1.408 + SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
1.409 + pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
1.410 + pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
1.411 + SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
1.412 + if( pExpr->op>=TK_GT ){
1.413 + assert( TK_LT==TK_GT+2 );
1.414 + assert( TK_GE==TK_LE+2 );
1.415 + assert( TK_GT>TK_EQ );
1.416 + assert( TK_GT<TK_LE );
1.417 + assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
1.418 + pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
1.419 + }
1.420 +}
1.421 +
1.422 +/*
1.423 +** Translate from TK_xx operator to WO_xx bitmask.
1.424 +*/
1.425 +static int operatorMask(int op){
1.426 + int c;
1.427 + assert( allowedOp(op) );
1.428 + if( op==TK_IN ){
1.429 + c = WO_IN;
1.430 + }else if( op==TK_ISNULL ){
1.431 + c = WO_ISNULL;
1.432 + }else{
1.433 + c = WO_EQ<<(op-TK_EQ);
1.434 + }
1.435 + assert( op!=TK_ISNULL || c==WO_ISNULL );
1.436 + assert( op!=TK_IN || c==WO_IN );
1.437 + assert( op!=TK_EQ || c==WO_EQ );
1.438 + assert( op!=TK_LT || c==WO_LT );
1.439 + assert( op!=TK_LE || c==WO_LE );
1.440 + assert( op!=TK_GT || c==WO_GT );
1.441 + assert( op!=TK_GE || c==WO_GE );
1.442 + return c;
1.443 +}
1.444 +
1.445 +/*
1.446 +** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
1.447 +** where X is a reference to the iColumn of table iCur and <op> is one of
1.448 +** the WO_xx operator codes specified by the op parameter.
1.449 +** Return a pointer to the term. Return 0 if not found.
1.450 +*/
1.451 +static WhereTerm *findTerm(
1.452 + WhereClause *pWC, /* The WHERE clause to be searched */
1.453 + int iCur, /* Cursor number of LHS */
1.454 + int iColumn, /* Column number of LHS */
1.455 + Bitmask notReady, /* RHS must not overlap with this mask */
1.456 + u16 op, /* Mask of WO_xx values describing operator */
1.457 + Index *pIdx /* Must be compatible with this index, if not NULL */
1.458 +){
1.459 + WhereTerm *pTerm;
1.460 + int k;
1.461 + assert( iCur>=0 );
1.462 + for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
1.463 + if( pTerm->leftCursor==iCur
1.464 + && (pTerm->prereqRight & notReady)==0
1.465 + && pTerm->leftColumn==iColumn
1.466 + && (pTerm->eOperator & op)!=0
1.467 + ){
1.468 + if( pIdx && pTerm->eOperator!=WO_ISNULL ){
1.469 + Expr *pX = pTerm->pExpr;
1.470 + CollSeq *pColl;
1.471 + char idxaff;
1.472 + int j;
1.473 + Parse *pParse = pWC->pParse;
1.474 +
1.475 + idxaff = pIdx->pTable->aCol[iColumn].affinity;
1.476 + if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
1.477 +
1.478 + /* Figure out the collation sequence required from an index for
1.479 + ** it to be useful for optimising expression pX. Store this
1.480 + ** value in variable pColl.
1.481 + */
1.482 + assert(pX->pLeft);
1.483 + pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
1.484 + if( !pColl ){
1.485 + pColl = pParse->db->pDfltColl;
1.486 + }
1.487 +
1.488 + for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
1.489 + if( NEVER(j>=pIdx->nColumn) ) return 0;
1.490 + }
1.491 + if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
1.492 + }
1.493 + return pTerm;
1.494 + }
1.495 + }
1.496 + return 0;
1.497 +}
1.498 +
1.499 +/* Forward reference */
1.500 +static void exprAnalyze(SrcList*, WhereClause*, int);
1.501 +
1.502 +/*
1.503 +** Call exprAnalyze on all terms in a WHERE clause.
1.504 +**
1.505 +**
1.506 +*/
1.507 +static void exprAnalyzeAll(
1.508 + SrcList *pTabList, /* the FROM clause */
1.509 + WhereClause *pWC /* the WHERE clause to be analyzed */
1.510 +){
1.511 + int i;
1.512 + for(i=pWC->nTerm-1; i>=0; i--){
1.513 + exprAnalyze(pTabList, pWC, i);
1.514 + }
1.515 +}
1.516 +
1.517 +#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1.518 +/*
1.519 +** Check to see if the given expression is a LIKE or GLOB operator that
1.520 +** can be optimized using inequality constraints. Return TRUE if it is
1.521 +** so and false if not.
1.522 +**
1.523 +** In order for the operator to be optimizible, the RHS must be a string
1.524 +** literal that does not begin with a wildcard.
1.525 +*/
1.526 +static int isLikeOrGlob(
1.527 + Parse *pParse, /* Parsing and code generating context */
1.528 + Expr *pExpr, /* Test this expression */
1.529 + int *pnPattern, /* Number of non-wildcard prefix characters */
1.530 + int *pisComplete, /* True if the only wildcard is % in the last character */
1.531 + int *pnoCase /* True if uppercase is equivalent to lowercase */
1.532 +){
1.533 + const char *z;
1.534 + Expr *pRight, *pLeft;
1.535 + ExprList *pList;
1.536 + int c, cnt;
1.537 + char wc[3];
1.538 + CollSeq *pColl;
1.539 + sqlite3 *db = pParse->db;
1.540 +
1.541 + if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
1.542 + return 0;
1.543 + }
1.544 +#ifdef SQLITE_EBCDIC
1.545 + if( *pnoCase ) return 0;
1.546 +#endif
1.547 + pList = pExpr->pList;
1.548 + pRight = pList->a[0].pExpr;
1.549 + if( pRight->op!=TK_STRING
1.550 + && (pRight->op!=TK_REGISTER || pRight->iColumn!=TK_STRING) ){
1.551 + return 0;
1.552 + }
1.553 + pLeft = pList->a[1].pExpr;
1.554 + if( pLeft->op!=TK_COLUMN ){
1.555 + return 0;
1.556 + }
1.557 + pColl = sqlite3ExprCollSeq(pParse, pLeft);
1.558 + assert( pColl!=0 || pLeft->iColumn==-1 );
1.559 + if( pColl==0 ){
1.560 + /* No collation is defined for the ROWID. Use the default. */
1.561 + pColl = db->pDfltColl;
1.562 + }
1.563 + if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
1.564 + (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
1.565 + return 0;
1.566 + }
1.567 + sqlite3DequoteExpr(db, pRight);
1.568 + z = (char *)pRight->token.z;
1.569 + cnt = 0;
1.570 + if( z ){
1.571 + while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
1.572 + }
1.573 + if( cnt==0 || 255==(u8)z[cnt] ){
1.574 + return 0;
1.575 + }
1.576 + *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
1.577 + *pnPattern = cnt;
1.578 + return 1;
1.579 +}
1.580 +#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1.581 +
1.582 +
1.583 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.584 +/*
1.585 +** Check to see if the given expression is of the form
1.586 +**
1.587 +** column MATCH expr
1.588 +**
1.589 +** If it is then return TRUE. If not, return FALSE.
1.590 +*/
1.591 +static int isMatchOfColumn(
1.592 + Expr *pExpr /* Test this expression */
1.593 +){
1.594 + ExprList *pList;
1.595 +
1.596 + if( pExpr->op!=TK_FUNCTION ){
1.597 + return 0;
1.598 + }
1.599 + if( pExpr->token.n!=5 ||
1.600 + sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
1.601 + return 0;
1.602 + }
1.603 + pList = pExpr->pList;
1.604 + if( pList->nExpr!=2 ){
1.605 + return 0;
1.606 + }
1.607 + if( pList->a[1].pExpr->op != TK_COLUMN ){
1.608 + return 0;
1.609 + }
1.610 + return 1;
1.611 +}
1.612 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
1.613 +
1.614 +/*
1.615 +** If the pBase expression originated in the ON or USING clause of
1.616 +** a join, then transfer the appropriate markings over to derived.
1.617 +*/
1.618 +static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
1.619 + pDerived->flags |= pBase->flags & EP_FromJoin;
1.620 + pDerived->iRightJoinTable = pBase->iRightJoinTable;
1.621 +}
1.622 +
1.623 +#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1.624 +/*
1.625 +** Return TRUE if the given term of an OR clause can be converted
1.626 +** into an IN clause. The iCursor and iColumn define the left-hand
1.627 +** side of the IN clause.
1.628 +**
1.629 +** The context is that we have multiple OR-connected equality terms
1.630 +** like this:
1.631 +**
1.632 +** a=<expr1> OR a=<expr2> OR b=<expr3> OR ...
1.633 +**
1.634 +** The pOrTerm input to this routine corresponds to a single term of
1.635 +** this OR clause. In order for the term to be a candidate for
1.636 +** conversion to an IN operator, the following must be true:
1.637 +**
1.638 +** * The left-hand side of the term must be the column which
1.639 +** is identified by iCursor and iColumn.
1.640 +**
1.641 +** * If the right-hand side is also a column, then the affinities
1.642 +** of both right and left sides must be such that no type
1.643 +** conversions are required on the right. (Ticket #2249)
1.644 +**
1.645 +** If both of these conditions are true, then return true. Otherwise
1.646 +** return false.
1.647 +*/
1.648 +static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
1.649 + int affLeft, affRight;
1.650 + assert( pOrTerm->eOperator==WO_EQ );
1.651 + if( pOrTerm->leftCursor!=iCursor ){
1.652 + return 0;
1.653 + }
1.654 + if( pOrTerm->leftColumn!=iColumn ){
1.655 + return 0;
1.656 + }
1.657 + affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1.658 + if( affRight==0 ){
1.659 + return 1;
1.660 + }
1.661 + affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1.662 + if( affRight!=affLeft ){
1.663 + return 0;
1.664 + }
1.665 + return 1;
1.666 +}
1.667 +
1.668 +/*
1.669 +** Return true if the given term of an OR clause can be ignored during
1.670 +** a check to make sure all OR terms are candidates for optimization.
1.671 +** In other words, return true if a call to the orTermIsOptCandidate()
1.672 +** above returned false but it is not necessary to disqualify the
1.673 +** optimization.
1.674 +**
1.675 +** Suppose the original OR phrase was this:
1.676 +**
1.677 +** a=4 OR a=11 OR a=b
1.678 +**
1.679 +** During analysis, the third term gets flipped around and duplicate
1.680 +** so that we are left with this:
1.681 +**
1.682 +** a=4 OR a=11 OR a=b OR b=a
1.683 +**
1.684 +** Since the last two terms are duplicates, only one of them
1.685 +** has to qualify in order for the whole phrase to qualify. When
1.686 +** this routine is called, we know that pOrTerm did not qualify.
1.687 +** This routine merely checks to see if pOrTerm has a duplicate that
1.688 +** might qualify. If there is a duplicate that has not yet been
1.689 +** disqualified, then return true. If there are no duplicates, or
1.690 +** the duplicate has also been disqualified, return false.
1.691 +*/
1.692 +static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
1.693 + if( pOrTerm->flags & TERM_COPIED ){
1.694 + /* This is the original term. The duplicate is to the left had
1.695 + ** has not yet been analyzed and thus has not yet been disqualified. */
1.696 + return 1;
1.697 + }
1.698 + if( (pOrTerm->flags & TERM_VIRTUAL)!=0
1.699 + && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
1.700 + /* This is a duplicate term. The original qualified so this one
1.701 + ** does not have to. */
1.702 + return 1;
1.703 + }
1.704 + /* This is either a singleton term or else it is a duplicate for
1.705 + ** which the original did not qualify. Either way we are done for. */
1.706 + return 0;
1.707 +}
1.708 +#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
1.709 +
1.710 +/*
1.711 +** The input to this routine is an WhereTerm structure with only the
1.712 +** "pExpr" field filled in. The job of this routine is to analyze the
1.713 +** subexpression and populate all the other fields of the WhereTerm
1.714 +** structure.
1.715 +**
1.716 +** If the expression is of the form "<expr> <op> X" it gets commuted
1.717 +** to the standard form of "X <op> <expr>". If the expression is of
1.718 +** the form "X <op> Y" where both X and Y are columns, then the original
1.719 +** expression is unchanged and a new virtual expression of the form
1.720 +** "Y <op> X" is added to the WHERE clause and analyzed separately.
1.721 +*/
1.722 +static void exprAnalyze(
1.723 + SrcList *pSrc, /* the FROM clause */
1.724 + WhereClause *pWC, /* the WHERE clause */
1.725 + int idxTerm /* Index of the term to be analyzed */
1.726 +){
1.727 + WhereTerm *pTerm;
1.728 + ExprMaskSet *pMaskSet;
1.729 + Expr *pExpr;
1.730 + Bitmask prereqLeft;
1.731 + Bitmask prereqAll;
1.732 + Bitmask extraRight = 0;
1.733 + int nPattern;
1.734 + int isComplete;
1.735 + int noCase;
1.736 + int op;
1.737 + Parse *pParse = pWC->pParse;
1.738 + sqlite3 *db = pParse->db;
1.739 +
1.740 + if( db->mallocFailed ){
1.741 + return;
1.742 + }
1.743 + pTerm = &pWC->a[idxTerm];
1.744 + pMaskSet = pWC->pMaskSet;
1.745 + pExpr = pTerm->pExpr;
1.746 + prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
1.747 + op = pExpr->op;
1.748 + if( op==TK_IN ){
1.749 + assert( pExpr->pRight==0 );
1.750 + pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
1.751 + | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
1.752 + }else if( op==TK_ISNULL ){
1.753 + pTerm->prereqRight = 0;
1.754 + }else{
1.755 + pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1.756 + }
1.757 + prereqAll = exprTableUsage(pMaskSet, pExpr);
1.758 + if( ExprHasProperty(pExpr, EP_FromJoin) ){
1.759 + Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1.760 + prereqAll |= x;
1.761 + extraRight = x-1; /* ON clause terms may not be used with an index
1.762 + ** on left table of a LEFT JOIN. Ticket #3015 */
1.763 + }
1.764 + pTerm->prereqAll = prereqAll;
1.765 + pTerm->leftCursor = -1;
1.766 + pTerm->iParent = -1;
1.767 + pTerm->eOperator = 0;
1.768 + if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
1.769 + Expr *pLeft = pExpr->pLeft;
1.770 + Expr *pRight = pExpr->pRight;
1.771 + if( pLeft->op==TK_COLUMN ){
1.772 + pTerm->leftCursor = pLeft->iTable;
1.773 + pTerm->leftColumn = pLeft->iColumn;
1.774 + pTerm->eOperator = operatorMask(op);
1.775 + }
1.776 + if( pRight && pRight->op==TK_COLUMN ){
1.777 + WhereTerm *pNew;
1.778 + Expr *pDup;
1.779 + if( pTerm->leftCursor>=0 ){
1.780 + int idxNew;
1.781 + pDup = sqlite3ExprDup(db, pExpr);
1.782 + if( db->mallocFailed ){
1.783 + sqlite3ExprDelete(db, pDup);
1.784 + return;
1.785 + }
1.786 + idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1.787 + if( idxNew==0 ) return;
1.788 + pNew = &pWC->a[idxNew];
1.789 + pNew->iParent = idxTerm;
1.790 + pTerm = &pWC->a[idxTerm];
1.791 + pTerm->nChild = 1;
1.792 + pTerm->flags |= TERM_COPIED;
1.793 + }else{
1.794 + pDup = pExpr;
1.795 + pNew = pTerm;
1.796 + }
1.797 + exprCommute(pParse, pDup);
1.798 + pLeft = pDup->pLeft;
1.799 + pNew->leftCursor = pLeft->iTable;
1.800 + pNew->leftColumn = pLeft->iColumn;
1.801 + pNew->prereqRight = prereqLeft;
1.802 + pNew->prereqAll = prereqAll;
1.803 + pNew->eOperator = operatorMask(pDup->op);
1.804 + }
1.805 + }
1.806 +
1.807 +#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1.808 + /* If a term is the BETWEEN operator, create two new virtual terms
1.809 + ** that define the range that the BETWEEN implements.
1.810 + */
1.811 + else if( pExpr->op==TK_BETWEEN ){
1.812 + ExprList *pList = pExpr->pList;
1.813 + int i;
1.814 + static const u8 ops[] = {TK_GE, TK_LE};
1.815 + assert( pList!=0 );
1.816 + assert( pList->nExpr==2 );
1.817 + for(i=0; i<2; i++){
1.818 + Expr *pNewExpr;
1.819 + int idxNew;
1.820 + pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
1.821 + sqlite3ExprDup(db, pList->a[i].pExpr), 0);
1.822 + idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1.823 + exprAnalyze(pSrc, pWC, idxNew);
1.824 + pTerm = &pWC->a[idxTerm];
1.825 + pWC->a[idxNew].iParent = idxTerm;
1.826 + }
1.827 + pTerm->nChild = 2;
1.828 + }
1.829 +#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1.830 +
1.831 +#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1.832 + /* Attempt to convert OR-connected terms into an IN operator so that
1.833 + ** they can make use of indices. Example:
1.834 + **
1.835 + ** x = expr1 OR expr2 = x OR x = expr3
1.836 + **
1.837 + ** is converted into
1.838 + **
1.839 + ** x IN (expr1,expr2,expr3)
1.840 + **
1.841 + ** This optimization must be omitted if OMIT_SUBQUERY is defined because
1.842 + ** the compiler for the the IN operator is part of sub-queries.
1.843 + */
1.844 + else if( pExpr->op==TK_OR ){
1.845 + int ok;
1.846 + int i, j;
1.847 + int iColumn, iCursor;
1.848 + WhereClause sOr;
1.849 + WhereTerm *pOrTerm;
1.850 +
1.851 + assert( (pTerm->flags & TERM_DYNAMIC)==0 );
1.852 + whereClauseInit(&sOr, pWC->pParse, pMaskSet);
1.853 + whereSplit(&sOr, pExpr, TK_OR);
1.854 + exprAnalyzeAll(pSrc, &sOr);
1.855 + assert( sOr.nTerm>=2 );
1.856 + j = 0;
1.857 + if( db->mallocFailed ) goto or_not_possible;
1.858 + do{
1.859 + assert( j<sOr.nTerm );
1.860 + iColumn = sOr.a[j].leftColumn;
1.861 + iCursor = sOr.a[j].leftCursor;
1.862 + ok = iCursor>=0;
1.863 + for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
1.864 + if( pOrTerm->eOperator!=WO_EQ ){
1.865 + goto or_not_possible;
1.866 + }
1.867 + if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
1.868 + pOrTerm->flags |= TERM_OR_OK;
1.869 + }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
1.870 + pOrTerm->flags &= ~TERM_OR_OK;
1.871 + }else{
1.872 + ok = 0;
1.873 + }
1.874 + }
1.875 + }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
1.876 + if( ok ){
1.877 + ExprList *pList = 0;
1.878 + Expr *pNew, *pDup;
1.879 + Expr *pLeft = 0;
1.880 + for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0; i--, pOrTerm++){
1.881 + if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
1.882 + pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
1.883 + pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
1.884 + pLeft = pOrTerm->pExpr->pLeft;
1.885 + }
1.886 + assert( pLeft!=0 );
1.887 + pDup = sqlite3ExprDup(db, pLeft);
1.888 + pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
1.889 + if( pNew ){
1.890 + int idxNew;
1.891 + transferJoinMarkings(pNew, pExpr);
1.892 + pNew->pList = pList;
1.893 + idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1.894 + exprAnalyze(pSrc, pWC, idxNew);
1.895 + pTerm = &pWC->a[idxTerm];
1.896 + pWC->a[idxNew].iParent = idxTerm;
1.897 + pTerm->nChild = 1;
1.898 + }else{
1.899 + sqlite3ExprListDelete(db, pList);
1.900 + }
1.901 + }
1.902 +or_not_possible:
1.903 + whereClauseClear(&sOr);
1.904 + }
1.905 +#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1.906 +
1.907 +#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1.908 + /* Add constraints to reduce the search space on a LIKE or GLOB
1.909 + ** operator.
1.910 + **
1.911 + ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1.912 + **
1.913 + ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
1.914 + **
1.915 + ** The last character of the prefix "abc" is incremented to form the
1.916 + ** termination condition "abd".
1.917 + */
1.918 + if( isLikeOrGlob(pParse, pExpr, &nPattern, &isComplete, &noCase) ){
1.919 + Expr *pLeft, *pRight;
1.920 + Expr *pStr1, *pStr2;
1.921 + Expr *pNewExpr1, *pNewExpr2;
1.922 + int idxNew1, idxNew2;
1.923 +
1.924 + pLeft = pExpr->pList->a[1].pExpr;
1.925 + pRight = pExpr->pList->a[0].pExpr;
1.926 + pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
1.927 + if( pStr1 ){
1.928 + sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
1.929 + pStr1->token.n = nPattern;
1.930 + pStr1->flags = EP_Dequoted;
1.931 + }
1.932 + pStr2 = sqlite3ExprDup(db, pStr1);
1.933 + if( !db->mallocFailed ){
1.934 + u8 c, *pC;
1.935 + assert( pStr2->token.dyn );
1.936 + pC = (u8*)&pStr2->token.z[nPattern-1];
1.937 + c = *pC;
1.938 + if( noCase ){
1.939 + if( c=='@' ) isComplete = 0;
1.940 + c = sqlite3UpperToLower[c];
1.941 + }
1.942 + *pC = c + 1;
1.943 + }
1.944 + pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
1.945 + idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
1.946 + exprAnalyze(pSrc, pWC, idxNew1);
1.947 + pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
1.948 + idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
1.949 + exprAnalyze(pSrc, pWC, idxNew2);
1.950 + pTerm = &pWC->a[idxTerm];
1.951 + if( isComplete ){
1.952 + pWC->a[idxNew1].iParent = idxTerm;
1.953 + pWC->a[idxNew2].iParent = idxTerm;
1.954 + pTerm->nChild = 2;
1.955 + }
1.956 + }
1.957 +#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1.958 +
1.959 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.960 + /* Add a WO_MATCH auxiliary term to the constraint set if the
1.961 + ** current expression is of the form: column MATCH expr.
1.962 + ** This information is used by the xBestIndex methods of
1.963 + ** virtual tables. The native query optimizer does not attempt
1.964 + ** to do anything with MATCH functions.
1.965 + */
1.966 + if( isMatchOfColumn(pExpr) ){
1.967 + int idxNew;
1.968 + Expr *pRight, *pLeft;
1.969 + WhereTerm *pNewTerm;
1.970 + Bitmask prereqColumn, prereqExpr;
1.971 +
1.972 + pRight = pExpr->pList->a[0].pExpr;
1.973 + pLeft = pExpr->pList->a[1].pExpr;
1.974 + prereqExpr = exprTableUsage(pMaskSet, pRight);
1.975 + prereqColumn = exprTableUsage(pMaskSet, pLeft);
1.976 + if( (prereqExpr & prereqColumn)==0 ){
1.977 + Expr *pNewExpr;
1.978 + pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
1.979 + idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1.980 + pNewTerm = &pWC->a[idxNew];
1.981 + pNewTerm->prereqRight = prereqExpr;
1.982 + pNewTerm->leftCursor = pLeft->iTable;
1.983 + pNewTerm->leftColumn = pLeft->iColumn;
1.984 + pNewTerm->eOperator = WO_MATCH;
1.985 + pNewTerm->iParent = idxTerm;
1.986 + pTerm = &pWC->a[idxTerm];
1.987 + pTerm->nChild = 1;
1.988 + pTerm->flags |= TERM_COPIED;
1.989 + pNewTerm->prereqAll = pTerm->prereqAll;
1.990 + }
1.991 + }
1.992 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
1.993 +
1.994 + /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1.995 + ** an index for tables to the left of the join.
1.996 + */
1.997 + pTerm->prereqRight |= extraRight;
1.998 +}
1.999 +
1.1000 +/*
1.1001 +** Return TRUE if any of the expressions in pList->a[iFirst...] contain
1.1002 +** a reference to any table other than the iBase table.
1.1003 +*/
1.1004 +static int referencesOtherTables(
1.1005 + ExprList *pList, /* Search expressions in ths list */
1.1006 + ExprMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
1.1007 + int iFirst, /* Be searching with the iFirst-th expression */
1.1008 + int iBase /* Ignore references to this table */
1.1009 +){
1.1010 + Bitmask allowed = ~getMask(pMaskSet, iBase);
1.1011 + while( iFirst<pList->nExpr ){
1.1012 + if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
1.1013 + return 1;
1.1014 + }
1.1015 + }
1.1016 + return 0;
1.1017 +}
1.1018 +
1.1019 +
1.1020 +/*
1.1021 +** This routine decides if pIdx can be used to satisfy the ORDER BY
1.1022 +** clause. If it can, it returns 1. If pIdx cannot satisfy the
1.1023 +** ORDER BY clause, this routine returns 0.
1.1024 +**
1.1025 +** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
1.1026 +** left-most table in the FROM clause of that same SELECT statement and
1.1027 +** the table has a cursor number of "base". pIdx is an index on pTab.
1.1028 +**
1.1029 +** nEqCol is the number of columns of pIdx that are used as equality
1.1030 +** constraints. Any of these columns may be missing from the ORDER BY
1.1031 +** clause and the match can still be a success.
1.1032 +**
1.1033 +** All terms of the ORDER BY that match against the index must be either
1.1034 +** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
1.1035 +** index do not need to satisfy this constraint.) The *pbRev value is
1.1036 +** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
1.1037 +** the ORDER BY clause is all ASC.
1.1038 +*/
1.1039 +static int isSortingIndex(
1.1040 + Parse *pParse, /* Parsing context */
1.1041 + ExprMaskSet *pMaskSet, /* Mapping from table indices to bitmaps */
1.1042 + Index *pIdx, /* The index we are testing */
1.1043 + int base, /* Cursor number for the table to be sorted */
1.1044 + ExprList *pOrderBy, /* The ORDER BY clause */
1.1045 + int nEqCol, /* Number of index columns with == constraints */
1.1046 + int *pbRev /* Set to 1 if ORDER BY is DESC */
1.1047 +){
1.1048 + int i, j; /* Loop counters */
1.1049 + int sortOrder = 0; /* XOR of index and ORDER BY sort direction */
1.1050 + int nTerm; /* Number of ORDER BY terms */
1.1051 + struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
1.1052 + sqlite3 *db = pParse->db;
1.1053 +
1.1054 + assert( pOrderBy!=0 );
1.1055 + nTerm = pOrderBy->nExpr;
1.1056 + assert( nTerm>0 );
1.1057 +
1.1058 + /* Match terms of the ORDER BY clause against columns of
1.1059 + ** the index.
1.1060 + **
1.1061 + ** Note that indices have pIdx->nColumn regular columns plus
1.1062 + ** one additional column containing the rowid. The rowid column
1.1063 + ** of the index is also allowed to match against the ORDER BY
1.1064 + ** clause.
1.1065 + */
1.1066 + for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
1.1067 + Expr *pExpr; /* The expression of the ORDER BY pTerm */
1.1068 + CollSeq *pColl; /* The collating sequence of pExpr */
1.1069 + int termSortOrder; /* Sort order for this term */
1.1070 + int iColumn; /* The i-th column of the index. -1 for rowid */
1.1071 + int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
1.1072 + const char *zColl; /* Name of the collating sequence for i-th index term */
1.1073 +
1.1074 + pExpr = pTerm->pExpr;
1.1075 + if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
1.1076 + /* Can not use an index sort on anything that is not a column in the
1.1077 + ** left-most table of the FROM clause */
1.1078 + break;
1.1079 + }
1.1080 + pColl = sqlite3ExprCollSeq(pParse, pExpr);
1.1081 + if( !pColl ){
1.1082 + pColl = db->pDfltColl;
1.1083 + }
1.1084 + if( i<pIdx->nColumn ){
1.1085 + iColumn = pIdx->aiColumn[i];
1.1086 + if( iColumn==pIdx->pTable->iPKey ){
1.1087 + iColumn = -1;
1.1088 + }
1.1089 + iSortOrder = pIdx->aSortOrder[i];
1.1090 + zColl = pIdx->azColl[i];
1.1091 + }else{
1.1092 + iColumn = -1;
1.1093 + iSortOrder = 0;
1.1094 + zColl = pColl->zName;
1.1095 + }
1.1096 + if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
1.1097 + /* Term j of the ORDER BY clause does not match column i of the index */
1.1098 + if( i<nEqCol ){
1.1099 + /* If an index column that is constrained by == fails to match an
1.1100 + ** ORDER BY term, that is OK. Just ignore that column of the index
1.1101 + */
1.1102 + continue;
1.1103 + }else if( i==pIdx->nColumn ){
1.1104 + /* Index column i is the rowid. All other terms match. */
1.1105 + break;
1.1106 + }else{
1.1107 + /* If an index column fails to match and is not constrained by ==
1.1108 + ** then the index cannot satisfy the ORDER BY constraint.
1.1109 + */
1.1110 + return 0;
1.1111 + }
1.1112 + }
1.1113 + assert( pIdx->aSortOrder!=0 );
1.1114 + assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
1.1115 + assert( iSortOrder==0 || iSortOrder==1 );
1.1116 + termSortOrder = iSortOrder ^ pTerm->sortOrder;
1.1117 + if( i>nEqCol ){
1.1118 + if( termSortOrder!=sortOrder ){
1.1119 + /* Indices can only be used if all ORDER BY terms past the
1.1120 + ** equality constraints are all either DESC or ASC. */
1.1121 + return 0;
1.1122 + }
1.1123 + }else{
1.1124 + sortOrder = termSortOrder;
1.1125 + }
1.1126 + j++;
1.1127 + pTerm++;
1.1128 + if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
1.1129 + /* If the indexed column is the primary key and everything matches
1.1130 + ** so far and none of the ORDER BY terms to the right reference other
1.1131 + ** tables in the join, then we are assured that the index can be used
1.1132 + ** to sort because the primary key is unique and so none of the other
1.1133 + ** columns will make any difference
1.1134 + */
1.1135 + j = nTerm;
1.1136 + }
1.1137 + }
1.1138 +
1.1139 + *pbRev = sortOrder!=0;
1.1140 + if( j>=nTerm ){
1.1141 + /* All terms of the ORDER BY clause are covered by this index so
1.1142 + ** this index can be used for sorting. */
1.1143 + return 1;
1.1144 + }
1.1145 + if( pIdx->onError!=OE_None && i==pIdx->nColumn
1.1146 + && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
1.1147 + /* All terms of this index match some prefix of the ORDER BY clause
1.1148 + ** and the index is UNIQUE and no terms on the tail of the ORDER BY
1.1149 + ** clause reference other tables in a join. If this is all true then
1.1150 + ** the order by clause is superfluous. */
1.1151 + return 1;
1.1152 + }
1.1153 + return 0;
1.1154 +}
1.1155 +
1.1156 +/*
1.1157 +** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
1.1158 +** by sorting in order of ROWID. Return true if so and set *pbRev to be
1.1159 +** true for reverse ROWID and false for forward ROWID order.
1.1160 +*/
1.1161 +static int sortableByRowid(
1.1162 + int base, /* Cursor number for table to be sorted */
1.1163 + ExprList *pOrderBy, /* The ORDER BY clause */
1.1164 + ExprMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
1.1165 + int *pbRev /* Set to 1 if ORDER BY is DESC */
1.1166 +){
1.1167 + Expr *p;
1.1168 +
1.1169 + assert( pOrderBy!=0 );
1.1170 + assert( pOrderBy->nExpr>0 );
1.1171 + p = pOrderBy->a[0].pExpr;
1.1172 + if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
1.1173 + && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
1.1174 + *pbRev = pOrderBy->a[0].sortOrder;
1.1175 + return 1;
1.1176 + }
1.1177 + return 0;
1.1178 +}
1.1179 +
1.1180 +/*
1.1181 +** Prepare a crude estimate of the logarithm of the input value.
1.1182 +** The results need not be exact. This is only used for estimating
1.1183 +** the total cost of performing operations with O(logN) or O(NlogN)
1.1184 +** complexity. Because N is just a guess, it is no great tragedy if
1.1185 +** logN is a little off.
1.1186 +*/
1.1187 +static double estLog(double N){
1.1188 + double logN = 1;
1.1189 + double x = 10;
1.1190 + while( N>x ){
1.1191 + logN += 1;
1.1192 + x *= 10;
1.1193 + }
1.1194 + return logN;
1.1195 +}
1.1196 +
1.1197 +/*
1.1198 +** Two routines for printing the content of an sqlite3_index_info
1.1199 +** structure. Used for testing and debugging only. If neither
1.1200 +** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1.1201 +** are no-ops.
1.1202 +*/
1.1203 +#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
1.1204 +static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1.1205 + int i;
1.1206 + if( !sqlite3WhereTrace ) return;
1.1207 + for(i=0; i<p->nConstraint; i++){
1.1208 + sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1.1209 + i,
1.1210 + p->aConstraint[i].iColumn,
1.1211 + p->aConstraint[i].iTermOffset,
1.1212 + p->aConstraint[i].op,
1.1213 + p->aConstraint[i].usable);
1.1214 + }
1.1215 + for(i=0; i<p->nOrderBy; i++){
1.1216 + sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1.1217 + i,
1.1218 + p->aOrderBy[i].iColumn,
1.1219 + p->aOrderBy[i].desc);
1.1220 + }
1.1221 +}
1.1222 +static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1.1223 + int i;
1.1224 + if( !sqlite3WhereTrace ) return;
1.1225 + for(i=0; i<p->nConstraint; i++){
1.1226 + sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1.1227 + i,
1.1228 + p->aConstraintUsage[i].argvIndex,
1.1229 + p->aConstraintUsage[i].omit);
1.1230 + }
1.1231 + sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1.1232 + sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1.1233 + sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1.1234 + sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
1.1235 +}
1.1236 +#else
1.1237 +#define TRACE_IDX_INPUTS(A)
1.1238 +#define TRACE_IDX_OUTPUTS(A)
1.1239 +#endif
1.1240 +
1.1241 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.1242 +/*
1.1243 +** Compute the best index for a virtual table.
1.1244 +**
1.1245 +** The best index is computed by the xBestIndex method of the virtual
1.1246 +** table module. This routine is really just a wrapper that sets up
1.1247 +** the sqlite3_index_info structure that is used to communicate with
1.1248 +** xBestIndex.
1.1249 +**
1.1250 +** In a join, this routine might be called multiple times for the
1.1251 +** same virtual table. The sqlite3_index_info structure is created
1.1252 +** and initialized on the first invocation and reused on all subsequent
1.1253 +** invocations. The sqlite3_index_info structure is also used when
1.1254 +** code is generated to access the virtual table. The whereInfoDelete()
1.1255 +** routine takes care of freeing the sqlite3_index_info structure after
1.1256 +** everybody has finished with it.
1.1257 +*/
1.1258 +static double bestVirtualIndex(
1.1259 + Parse *pParse, /* The parsing context */
1.1260 + WhereClause *pWC, /* The WHERE clause */
1.1261 + struct SrcList_item *pSrc, /* The FROM clause term to search */
1.1262 + Bitmask notReady, /* Mask of cursors that are not available */
1.1263 + ExprList *pOrderBy, /* The order by clause */
1.1264 + int orderByUsable, /* True if we can potential sort */
1.1265 + sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
1.1266 +){
1.1267 + Table *pTab = pSrc->pTab;
1.1268 + sqlite3_vtab *pVtab = pTab->pVtab;
1.1269 + sqlite3_index_info *pIdxInfo;
1.1270 + struct sqlite3_index_constraint *pIdxCons;
1.1271 + struct sqlite3_index_orderby *pIdxOrderBy;
1.1272 + struct sqlite3_index_constraint_usage *pUsage;
1.1273 + WhereTerm *pTerm;
1.1274 + int i, j;
1.1275 + int nOrderBy;
1.1276 + int rc;
1.1277 +
1.1278 + /* If the sqlite3_index_info structure has not been previously
1.1279 + ** allocated and initialized for this virtual table, then allocate
1.1280 + ** and initialize it now
1.1281 + */
1.1282 + pIdxInfo = *ppIdxInfo;
1.1283 + if( pIdxInfo==0 ){
1.1284 + WhereTerm *pTerm;
1.1285 + int nTerm;
1.1286 + WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
1.1287 +
1.1288 + /* Count the number of possible WHERE clause constraints referring
1.1289 + ** to this virtual table */
1.1290 + for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1.1291 + if( pTerm->leftCursor != pSrc->iCursor ) continue;
1.1292 + assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
1.1293 + testcase( pTerm->eOperator==WO_IN );
1.1294 + testcase( pTerm->eOperator==WO_ISNULL );
1.1295 + if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
1.1296 + nTerm++;
1.1297 + }
1.1298 +
1.1299 + /* If the ORDER BY clause contains only columns in the current
1.1300 + ** virtual table then allocate space for the aOrderBy part of
1.1301 + ** the sqlite3_index_info structure.
1.1302 + */
1.1303 + nOrderBy = 0;
1.1304 + if( pOrderBy ){
1.1305 + for(i=0; i<pOrderBy->nExpr; i++){
1.1306 + Expr *pExpr = pOrderBy->a[i].pExpr;
1.1307 + if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
1.1308 + }
1.1309 + if( i==pOrderBy->nExpr ){
1.1310 + nOrderBy = pOrderBy->nExpr;
1.1311 + }
1.1312 + }
1.1313 +
1.1314 + /* Allocate the sqlite3_index_info structure
1.1315 + */
1.1316 + pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1.1317 + + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1.1318 + + sizeof(*pIdxOrderBy)*nOrderBy );
1.1319 + if( pIdxInfo==0 ){
1.1320 + sqlite3ErrorMsg(pParse, "out of memory");
1.1321 + return 0.0;
1.1322 + }
1.1323 + *ppIdxInfo = pIdxInfo;
1.1324 +
1.1325 + /* Initialize the structure. The sqlite3_index_info structure contains
1.1326 + ** many fields that are declared "const" to prevent xBestIndex from
1.1327 + ** changing them. We have to do some funky casting in order to
1.1328 + ** initialize those fields.
1.1329 + */
1.1330 + pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
1.1331 + pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1.1332 + pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1.1333 + *(int*)&pIdxInfo->nConstraint = nTerm;
1.1334 + *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1.1335 + *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
1.1336 + *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
1.1337 + *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
1.1338 + pUsage;
1.1339 +
1.1340 + for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1.1341 + if( pTerm->leftCursor != pSrc->iCursor ) continue;
1.1342 + assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
1.1343 + testcase( pTerm->eOperator==WO_IN );
1.1344 + testcase( pTerm->eOperator==WO_ISNULL );
1.1345 + if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
1.1346 + pIdxCons[j].iColumn = pTerm->leftColumn;
1.1347 + pIdxCons[j].iTermOffset = i;
1.1348 + pIdxCons[j].op = pTerm->eOperator;
1.1349 + /* The direct assignment in the previous line is possible only because
1.1350 + ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1.1351 + ** following asserts verify this fact. */
1.1352 + assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1.1353 + assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1.1354 + assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1.1355 + assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1.1356 + assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1.1357 + assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
1.1358 + assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
1.1359 + j++;
1.1360 + }
1.1361 + for(i=0; i<nOrderBy; i++){
1.1362 + Expr *pExpr = pOrderBy->a[i].pExpr;
1.1363 + pIdxOrderBy[i].iColumn = pExpr->iColumn;
1.1364 + pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
1.1365 + }
1.1366 + }
1.1367 +
1.1368 + /* At this point, the sqlite3_index_info structure that pIdxInfo points
1.1369 + ** to will have been initialized, either during the current invocation or
1.1370 + ** during some prior invocation. Now we just have to customize the
1.1371 + ** details of pIdxInfo for the current invocation and pass it to
1.1372 + ** xBestIndex.
1.1373 + */
1.1374 +
1.1375 + /* The module name must be defined. Also, by this point there must
1.1376 + ** be a pointer to an sqlite3_vtab structure. Otherwise
1.1377 + ** sqlite3ViewGetColumnNames() would have picked up the error.
1.1378 + */
1.1379 + assert( pTab->azModuleArg && pTab->azModuleArg[0] );
1.1380 + assert( pVtab );
1.1381 +#if 0
1.1382 + if( pTab->pVtab==0 ){
1.1383 + sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
1.1384 + pTab->azModuleArg[0], pTab->zName);
1.1385 + return 0.0;
1.1386 + }
1.1387 +#endif
1.1388 +
1.1389 + /* Set the aConstraint[].usable fields and initialize all
1.1390 + ** output variables to zero.
1.1391 + **
1.1392 + ** aConstraint[].usable is true for constraints where the right-hand
1.1393 + ** side contains only references to tables to the left of the current
1.1394 + ** table. In other words, if the constraint is of the form:
1.1395 + **
1.1396 + ** column = expr
1.1397 + **
1.1398 + ** and we are evaluating a join, then the constraint on column is
1.1399 + ** only valid if all tables referenced in expr occur to the left
1.1400 + ** of the table containing column.
1.1401 + **
1.1402 + ** The aConstraints[] array contains entries for all constraints
1.1403 + ** on the current table. That way we only have to compute it once
1.1404 + ** even though we might try to pick the best index multiple times.
1.1405 + ** For each attempt at picking an index, the order of tables in the
1.1406 + ** join might be different so we have to recompute the usable flag
1.1407 + ** each time.
1.1408 + */
1.1409 + pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
1.1410 + pUsage = pIdxInfo->aConstraintUsage;
1.1411 + for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
1.1412 + j = pIdxCons->iTermOffset;
1.1413 + pTerm = &pWC->a[j];
1.1414 + pIdxCons->usable = (pTerm->prereqRight & notReady)==0;
1.1415 + }
1.1416 + memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
1.1417 + if( pIdxInfo->needToFreeIdxStr ){
1.1418 + sqlite3_free(pIdxInfo->idxStr);
1.1419 + }
1.1420 + pIdxInfo->idxStr = 0;
1.1421 + pIdxInfo->idxNum = 0;
1.1422 + pIdxInfo->needToFreeIdxStr = 0;
1.1423 + pIdxInfo->orderByConsumed = 0;
1.1424 + pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
1.1425 + nOrderBy = pIdxInfo->nOrderBy;
1.1426 + if( pIdxInfo->nOrderBy && !orderByUsable ){
1.1427 + *(int*)&pIdxInfo->nOrderBy = 0;
1.1428 + }
1.1429 +
1.1430 + (void)sqlite3SafetyOff(pParse->db);
1.1431 + WHERETRACE(("xBestIndex for %s\n", pTab->zName));
1.1432 + TRACE_IDX_INPUTS(pIdxInfo);
1.1433 + rc = pVtab->pModule->xBestIndex(pVtab, pIdxInfo);
1.1434 + TRACE_IDX_OUTPUTS(pIdxInfo);
1.1435 + (void)sqlite3SafetyOn(pParse->db);
1.1436 +
1.1437 + if( rc!=SQLITE_OK ){
1.1438 + if( rc==SQLITE_NOMEM ){
1.1439 + pParse->db->mallocFailed = 1;
1.1440 + }else if( !pVtab->zErrMsg ){
1.1441 + sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
1.1442 + }else{
1.1443 + sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
1.1444 + }
1.1445 + }
1.1446 + sqlite3DbFree(pParse->db, pVtab->zErrMsg);
1.1447 + pVtab->zErrMsg = 0;
1.1448 +
1.1449 + for(i=0; i<pIdxInfo->nConstraint; i++){
1.1450 + if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
1.1451 + sqlite3ErrorMsg(pParse,
1.1452 + "table %s: xBestIndex returned an invalid plan", pTab->zName);
1.1453 + return 0.0;
1.1454 + }
1.1455 + }
1.1456 +
1.1457 + *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1.1458 + return pIdxInfo->estimatedCost;
1.1459 +}
1.1460 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
1.1461 +
1.1462 +/*
1.1463 +** Find the best index for accessing a particular table. Return a pointer
1.1464 +** to the index, flags that describe how the index should be used, the
1.1465 +** number of equality constraints, and the "cost" for this index.
1.1466 +**
1.1467 +** The lowest cost index wins. The cost is an estimate of the amount of
1.1468 +** CPU and disk I/O need to process the request using the selected index.
1.1469 +** Factors that influence cost include:
1.1470 +**
1.1471 +** * The estimated number of rows that will be retrieved. (The
1.1472 +** fewer the better.)
1.1473 +**
1.1474 +** * Whether or not sorting must occur.
1.1475 +**
1.1476 +** * Whether or not there must be separate lookups in the
1.1477 +** index and in the main table.
1.1478 +**
1.1479 +** If there was an INDEXED BY clause attached to the table in the SELECT
1.1480 +** statement, then this function only considers strategies using the
1.1481 +** named index. If one cannot be found, then the returned cost is
1.1482 +** SQLITE_BIG_DBL. If a strategy can be found that uses the named index,
1.1483 +** then the cost is calculated in the usual way.
1.1484 +**
1.1485 +** If a NOT INDEXED clause was attached to the table in the SELECT
1.1486 +** statement, then no indexes are considered. However, the selected
1.1487 +** stategy may still take advantage of the tables built-in rowid
1.1488 +** index.
1.1489 +*/
1.1490 +static double bestIndex(
1.1491 + Parse *pParse, /* The parsing context */
1.1492 + WhereClause *pWC, /* The WHERE clause */
1.1493 + struct SrcList_item *pSrc, /* The FROM clause term to search */
1.1494 + Bitmask notReady, /* Mask of cursors that are not available */
1.1495 + ExprList *pOrderBy, /* The order by clause */
1.1496 + Index **ppIndex, /* Make *ppIndex point to the best index */
1.1497 + int *pFlags, /* Put flags describing this choice in *pFlags */
1.1498 + int *pnEq /* Put the number of == or IN constraints here */
1.1499 +){
1.1500 + WhereTerm *pTerm;
1.1501 + Index *bestIdx = 0; /* Index that gives the lowest cost */
1.1502 + double lowestCost; /* The cost of using bestIdx */
1.1503 + int bestFlags = 0; /* Flags associated with bestIdx */
1.1504 + int bestNEq = 0; /* Best value for nEq */
1.1505 + int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
1.1506 + Index *pProbe; /* An index we are evaluating */
1.1507 + int rev; /* True to scan in reverse order */
1.1508 + int flags; /* Flags associated with pProbe */
1.1509 + int nEq; /* Number of == or IN constraints */
1.1510 + int eqTermMask; /* Mask of valid equality operators */
1.1511 + double cost; /* Cost of using pProbe */
1.1512 +
1.1513 + WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName, notReady));
1.1514 + lowestCost = SQLITE_BIG_DBL;
1.1515 + pProbe = pSrc->pTab->pIndex;
1.1516 + if( pSrc->notIndexed ){
1.1517 + pProbe = 0;
1.1518 + }
1.1519 +
1.1520 + /* If the table has no indices and there are no terms in the where
1.1521 + ** clause that refer to the ROWID, then we will never be able to do
1.1522 + ** anything other than a full table scan on this table. We might as
1.1523 + ** well put it first in the join order. That way, perhaps it can be
1.1524 + ** referenced by other tables in the join.
1.1525 + */
1.1526 + if( pProbe==0 &&
1.1527 + findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
1.1528 + (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
1.1529 + *pFlags = 0;
1.1530 + *ppIndex = 0;
1.1531 + *pnEq = 0;
1.1532 + return 0.0;
1.1533 + }
1.1534 +
1.1535 + /* Check for a rowid=EXPR or rowid IN (...) constraints. If there was
1.1536 + ** an INDEXED BY clause attached to this table, skip this step.
1.1537 + */
1.1538 + if( !pSrc->pIndex ){
1.1539 + pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1.1540 + if( pTerm ){
1.1541 + Expr *pExpr;
1.1542 + *ppIndex = 0;
1.1543 + bestFlags = WHERE_ROWID_EQ;
1.1544 + if( pTerm->eOperator & WO_EQ ){
1.1545 + /* Rowid== is always the best pick. Look no further. Because only
1.1546 + ** a single row is generated, output is always in sorted order */
1.1547 + *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
1.1548 + *pnEq = 1;
1.1549 + WHERETRACE(("... best is rowid\n"));
1.1550 + return 0.0;
1.1551 + }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
1.1552 + /* Rowid IN (LIST): cost is NlogN where N is the number of list
1.1553 + ** elements. */
1.1554 + lowestCost = pExpr->pList->nExpr;
1.1555 + lowestCost *= estLog(lowestCost);
1.1556 + }else{
1.1557 + /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
1.1558 + ** in the result of the inner select. We have no way to estimate
1.1559 + ** that value so make a wild guess. */
1.1560 + lowestCost = 200;
1.1561 + }
1.1562 + WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
1.1563 + }
1.1564 +
1.1565 + /* Estimate the cost of a table scan. If we do not know how many
1.1566 + ** entries are in the table, use 1 million as a guess.
1.1567 + */
1.1568 + cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
1.1569 + WHERETRACE(("... table scan base cost: %.9g\n", cost));
1.1570 + flags = WHERE_ROWID_RANGE;
1.1571 +
1.1572 + /* Check for constraints on a range of rowids in a table scan.
1.1573 + */
1.1574 + pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
1.1575 + if( pTerm ){
1.1576 + if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
1.1577 + flags |= WHERE_TOP_LIMIT;
1.1578 + cost /= 3; /* Guess that rowid<EXPR eliminates two-thirds or rows */
1.1579 + }
1.1580 + if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
1.1581 + flags |= WHERE_BTM_LIMIT;
1.1582 + cost /= 3; /* Guess that rowid>EXPR eliminates two-thirds of rows */
1.1583 + }
1.1584 + WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
1.1585 + }else{
1.1586 + flags = 0;
1.1587 + }
1.1588 +
1.1589 + /* If the table scan does not satisfy the ORDER BY clause, increase
1.1590 + ** the cost by NlogN to cover the expense of sorting. */
1.1591 + if( pOrderBy ){
1.1592 + if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
1.1593 + flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
1.1594 + if( rev ){
1.1595 + flags |= WHERE_REVERSE;
1.1596 + }
1.1597 + }else{
1.1598 + cost += cost*estLog(cost);
1.1599 + WHERETRACE(("... sorting increases cost to %.9g\n", cost));
1.1600 + }
1.1601 + }
1.1602 + if( cost<lowestCost ){
1.1603 + lowestCost = cost;
1.1604 + bestFlags = flags;
1.1605 + }
1.1606 + }
1.1607 +
1.1608 + /* If the pSrc table is the right table of a LEFT JOIN then we may not
1.1609 + ** use an index to satisfy IS NULL constraints on that table. This is
1.1610 + ** because columns might end up being NULL if the table does not match -
1.1611 + ** a circumstance which the index cannot help us discover. Ticket #2177.
1.1612 + */
1.1613 + if( (pSrc->jointype & JT_LEFT)!=0 ){
1.1614 + eqTermMask = WO_EQ|WO_IN;
1.1615 + }else{
1.1616 + eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
1.1617 + }
1.1618 +
1.1619 + /* Look at each index.
1.1620 + */
1.1621 + if( pSrc->pIndex ){
1.1622 + pProbe = pSrc->pIndex;
1.1623 + }
1.1624 + for(; pProbe; pProbe=(pSrc->pIndex ? 0 : pProbe->pNext)){
1.1625 + int i; /* Loop counter */
1.1626 + double inMultiplier = 1;
1.1627 +
1.1628 + WHERETRACE(("... index %s:\n", pProbe->zName));
1.1629 +
1.1630 + /* Count the number of columns in the index that are satisfied
1.1631 + ** by x=EXPR constraints or x IN (...) constraints.
1.1632 + */
1.1633 + flags = 0;
1.1634 + for(i=0; i<pProbe->nColumn; i++){
1.1635 + int j = pProbe->aiColumn[i];
1.1636 + pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
1.1637 + if( pTerm==0 ) break;
1.1638 + flags |= WHERE_COLUMN_EQ;
1.1639 + if( pTerm->eOperator & WO_IN ){
1.1640 + Expr *pExpr = pTerm->pExpr;
1.1641 + flags |= WHERE_COLUMN_IN;
1.1642 + if( pExpr->pSelect!=0 ){
1.1643 + inMultiplier *= 25;
1.1644 + }else if( ALWAYS(pExpr->pList) ){
1.1645 + inMultiplier *= pExpr->pList->nExpr + 1;
1.1646 + }
1.1647 + }
1.1648 + }
1.1649 + cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
1.1650 + nEq = i;
1.1651 + if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
1.1652 + && nEq==pProbe->nColumn ){
1.1653 + flags |= WHERE_UNIQUE;
1.1654 + }
1.1655 + WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
1.1656 +
1.1657 + /* Look for range constraints
1.1658 + */
1.1659 + if( nEq<pProbe->nColumn ){
1.1660 + int j = pProbe->aiColumn[nEq];
1.1661 + pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
1.1662 + if( pTerm ){
1.1663 + flags |= WHERE_COLUMN_RANGE;
1.1664 + if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
1.1665 + flags |= WHERE_TOP_LIMIT;
1.1666 + cost /= 3;
1.1667 + }
1.1668 + if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
1.1669 + flags |= WHERE_BTM_LIMIT;
1.1670 + cost /= 3;
1.1671 + }
1.1672 + WHERETRACE(("...... range reduces cost to %.9g\n", cost));
1.1673 + }
1.1674 + }
1.1675 +
1.1676 + /* Add the additional cost of sorting if that is a factor.
1.1677 + */
1.1678 + if( pOrderBy ){
1.1679 + if( (flags & WHERE_COLUMN_IN)==0 &&
1.1680 + isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
1.1681 + if( flags==0 ){
1.1682 + flags = WHERE_COLUMN_RANGE;
1.1683 + }
1.1684 + flags |= WHERE_ORDERBY;
1.1685 + if( rev ){
1.1686 + flags |= WHERE_REVERSE;
1.1687 + }
1.1688 + }else{
1.1689 + cost += cost*estLog(cost);
1.1690 + WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
1.1691 + }
1.1692 + }
1.1693 +
1.1694 + /* Check to see if we can get away with using just the index without
1.1695 + ** ever reading the table. If that is the case, then halve the
1.1696 + ** cost of this index.
1.1697 + */
1.1698 + if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
1.1699 + Bitmask m = pSrc->colUsed;
1.1700 + int j;
1.1701 + for(j=0; j<pProbe->nColumn; j++){
1.1702 + int x = pProbe->aiColumn[j];
1.1703 + if( x<BMS-1 ){
1.1704 + m &= ~(((Bitmask)1)<<x);
1.1705 + }
1.1706 + }
1.1707 + if( m==0 ){
1.1708 + flags |= WHERE_IDX_ONLY;
1.1709 + cost /= 2;
1.1710 + WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
1.1711 + }
1.1712 + }
1.1713 +
1.1714 + /* If this index has achieved the lowest cost so far, then use it.
1.1715 + */
1.1716 + if( flags && cost < lowestCost ){
1.1717 + bestIdx = pProbe;
1.1718 + lowestCost = cost;
1.1719 + bestFlags = flags;
1.1720 + bestNEq = nEq;
1.1721 + }
1.1722 + }
1.1723 +
1.1724 + /* Report the best result
1.1725 + */
1.1726 + *ppIndex = bestIdx;
1.1727 + WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
1.1728 + bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
1.1729 + *pFlags = bestFlags | eqTermMask;
1.1730 + *pnEq = bestNEq;
1.1731 + return lowestCost;
1.1732 +}
1.1733 +
1.1734 +
1.1735 +/*
1.1736 +** Disable a term in the WHERE clause. Except, do not disable the term
1.1737 +** if it controls a LEFT OUTER JOIN and it did not originate in the ON
1.1738 +** or USING clause of that join.
1.1739 +**
1.1740 +** Consider the term t2.z='ok' in the following queries:
1.1741 +**
1.1742 +** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
1.1743 +** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
1.1744 +** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
1.1745 +**
1.1746 +** The t2.z='ok' is disabled in the in (2) because it originates
1.1747 +** in the ON clause. The term is disabled in (3) because it is not part
1.1748 +** of a LEFT OUTER JOIN. In (1), the term is not disabled.
1.1749 +**
1.1750 +** Disabling a term causes that term to not be tested in the inner loop
1.1751 +** of the join. Disabling is an optimization. When terms are satisfied
1.1752 +** by indices, we disable them to prevent redundant tests in the inner
1.1753 +** loop. We would get the correct results if nothing were ever disabled,
1.1754 +** but joins might run a little slower. The trick is to disable as much
1.1755 +** as we can without disabling too much. If we disabled in (1), we'd get
1.1756 +** the wrong answer. See ticket #813.
1.1757 +*/
1.1758 +static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
1.1759 + if( pTerm
1.1760 + && ALWAYS((pTerm->flags & TERM_CODED)==0)
1.1761 + && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
1.1762 + ){
1.1763 + pTerm->flags |= TERM_CODED;
1.1764 + if( pTerm->iParent>=0 ){
1.1765 + WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
1.1766 + if( (--pOther->nChild)==0 ){
1.1767 + disableTerm(pLevel, pOther);
1.1768 + }
1.1769 + }
1.1770 + }
1.1771 +}
1.1772 +
1.1773 +/*
1.1774 +** Apply the affinities associated with the first n columns of index
1.1775 +** pIdx to the values in the n registers starting at base.
1.1776 +*/
1.1777 +static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
1.1778 + if( n>0 ){
1.1779 + Vdbe *v = pParse->pVdbe;
1.1780 + assert( v!=0 );
1.1781 + sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
1.1782 + sqlite3IndexAffinityStr(v, pIdx);
1.1783 + sqlite3ExprCacheAffinityChange(pParse, base, n);
1.1784 + }
1.1785 +}
1.1786 +
1.1787 +
1.1788 +/*
1.1789 +** Generate code for a single equality term of the WHERE clause. An equality
1.1790 +** term can be either X=expr or X IN (...). pTerm is the term to be
1.1791 +** coded.
1.1792 +**
1.1793 +** The current value for the constraint is left in register iReg.
1.1794 +**
1.1795 +** For a constraint of the form X=expr, the expression is evaluated and its
1.1796 +** result is left on the stack. For constraints of the form X IN (...)
1.1797 +** this routine sets up a loop that will iterate over all values of X.
1.1798 +*/
1.1799 +static int codeEqualityTerm(
1.1800 + Parse *pParse, /* The parsing context */
1.1801 + WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
1.1802 + WhereLevel *pLevel, /* When level of the FROM clause we are working on */
1.1803 + int iTarget /* Attempt to leave results in this register */
1.1804 +){
1.1805 + Expr *pX = pTerm->pExpr;
1.1806 + Vdbe *v = pParse->pVdbe;
1.1807 + int iReg; /* Register holding results */
1.1808 +
1.1809 + assert( iTarget>0 );
1.1810 + if( pX->op==TK_EQ ){
1.1811 + iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
1.1812 + }else if( pX->op==TK_ISNULL ){
1.1813 + iReg = iTarget;
1.1814 + sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
1.1815 +#ifndef SQLITE_OMIT_SUBQUERY
1.1816 + }else{
1.1817 + int eType;
1.1818 + int iTab;
1.1819 + struct InLoop *pIn;
1.1820 +
1.1821 + assert( pX->op==TK_IN );
1.1822 + iReg = iTarget;
1.1823 + eType = sqlite3FindInIndex(pParse, pX, 0);
1.1824 + iTab = pX->iTable;
1.1825 + sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
1.1826 + VdbeComment((v, "%.*s", pX->span.n, pX->span.z));
1.1827 + if( pLevel->nIn==0 ){
1.1828 + pLevel->nxt = sqlite3VdbeMakeLabel(v);
1.1829 + }
1.1830 + pLevel->nIn++;
1.1831 + pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop,
1.1832 + sizeof(pLevel->aInLoop[0])*pLevel->nIn);
1.1833 + pIn = pLevel->aInLoop;
1.1834 + if( pIn ){
1.1835 + pIn += pLevel->nIn - 1;
1.1836 + pIn->iCur = iTab;
1.1837 + if( eType==IN_INDEX_ROWID ){
1.1838 + pIn->topAddr = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
1.1839 + }else{
1.1840 + pIn->topAddr = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
1.1841 + }
1.1842 + sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
1.1843 + }else{
1.1844 + pLevel->nIn = 0;
1.1845 + }
1.1846 +#endif
1.1847 + }
1.1848 + disableTerm(pLevel, pTerm);
1.1849 + return iReg;
1.1850 +}
1.1851 +
1.1852 +/*
1.1853 +** Generate code that will evaluate all == and IN constraints for an
1.1854 +** index. The values for all constraints are left on the stack.
1.1855 +**
1.1856 +** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
1.1857 +** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
1.1858 +** The index has as many as three equality constraints, but in this
1.1859 +** example, the third "c" value is an inequality. So only two
1.1860 +** constraints are coded. This routine will generate code to evaluate
1.1861 +** a==5 and b IN (1,2,3). The current values for a and b will be left
1.1862 +** on the stack - a is the deepest and b the shallowest.
1.1863 +**
1.1864 +** In the example above nEq==2. But this subroutine works for any value
1.1865 +** of nEq including 0. If nEq==0, this routine is nearly a no-op.
1.1866 +** The only thing it does is allocate the pLevel->iMem memory cell.
1.1867 +**
1.1868 +** This routine always allocates at least one memory cell and puts
1.1869 +** the address of that memory cell in pLevel->iMem. The code that
1.1870 +** calls this routine will use pLevel->iMem to store the termination
1.1871 +** key value of the loop. If one or more IN operators appear, then
1.1872 +** this routine allocates an additional nEq memory cells for internal
1.1873 +** use.
1.1874 +*/
1.1875 +static int codeAllEqualityTerms(
1.1876 + Parse *pParse, /* Parsing context */
1.1877 + WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
1.1878 + WhereClause *pWC, /* The WHERE clause */
1.1879 + Bitmask notReady, /* Which parts of FROM have not yet been coded */
1.1880 + int nExtraReg /* Number of extra registers to allocate */
1.1881 +){
1.1882 + int nEq = pLevel->nEq; /* The number of == or IN constraints to code */
1.1883 + Vdbe *v = pParse->pVdbe; /* The virtual machine under construction */
1.1884 + Index *pIdx = pLevel->pIdx; /* The index being used for this loop */
1.1885 + int iCur = pLevel->iTabCur; /* The cursor of the table */
1.1886 + WhereTerm *pTerm; /* A single constraint term */
1.1887 + int j; /* Loop counter */
1.1888 + int regBase; /* Base register */
1.1889 +
1.1890 + /* Figure out how many memory cells we will need then allocate them.
1.1891 + ** We always need at least one used to store the loop terminator
1.1892 + ** value. If there are IN operators we'll need one for each == or
1.1893 + ** IN constraint.
1.1894 + */
1.1895 + pLevel->iMem = pParse->nMem + 1;
1.1896 + regBase = pParse->nMem + 2;
1.1897 + pParse->nMem += pLevel->nEq + 2 + nExtraReg;
1.1898 +
1.1899 + /* Evaluate the equality constraints
1.1900 + */
1.1901 + assert( pIdx->nColumn>=nEq );
1.1902 + for(j=0; j<nEq; j++){
1.1903 + int r1;
1.1904 + int k = pIdx->aiColumn[j];
1.1905 + pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
1.1906 + if( NEVER(pTerm==0) ) break;
1.1907 + assert( (pTerm->flags & TERM_CODED)==0 );
1.1908 + r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
1.1909 + if( r1!=regBase+j ){
1.1910 + sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
1.1911 + }
1.1912 + testcase( pTerm->eOperator & WO_ISNULL );
1.1913 + testcase( pTerm->eOperator & WO_IN );
1.1914 + if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
1.1915 + sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->brk);
1.1916 + }
1.1917 + }
1.1918 + return regBase;
1.1919 +}
1.1920 +
1.1921 +#if defined(SQLITE_TEST)
1.1922 +/*
1.1923 +** The following variable holds a text description of query plan generated
1.1924 +** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
1.1925 +** overwrites the previous. This information is used for testing and
1.1926 +** analysis only.
1.1927 +*/
1.1928 +char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
1.1929 +static int nQPlan = 0; /* Next free slow in _query_plan[] */
1.1930 +
1.1931 +#endif /* SQLITE_TEST */
1.1932 +
1.1933 +
1.1934 +/*
1.1935 +** Free a WhereInfo structure
1.1936 +*/
1.1937 +static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
1.1938 + if( pWInfo ){
1.1939 + int i;
1.1940 + for(i=0; i<pWInfo->nLevel; i++){
1.1941 + sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
1.1942 + if( pInfo ){
1.1943 + assert( pInfo->needToFreeIdxStr==0 );
1.1944 + sqlite3DbFree(db, pInfo);
1.1945 + }
1.1946 + }
1.1947 + sqlite3DbFree(db, pWInfo);
1.1948 + }
1.1949 +}
1.1950 +
1.1951 +
1.1952 +/*
1.1953 +** Generate the beginning of the loop used for WHERE clause processing.
1.1954 +** The return value is a pointer to an opaque structure that contains
1.1955 +** information needed to terminate the loop. Later, the calling routine
1.1956 +** should invoke sqlite3WhereEnd() with the return value of this function
1.1957 +** in order to complete the WHERE clause processing.
1.1958 +**
1.1959 +** If an error occurs, this routine returns NULL.
1.1960 +**
1.1961 +** The basic idea is to do a nested loop, one loop for each table in
1.1962 +** the FROM clause of a select. (INSERT and UPDATE statements are the
1.1963 +** same as a SELECT with only a single table in the FROM clause.) For
1.1964 +** example, if the SQL is this:
1.1965 +**
1.1966 +** SELECT * FROM t1, t2, t3 WHERE ...;
1.1967 +**
1.1968 +** Then the code generated is conceptually like the following:
1.1969 +**
1.1970 +** foreach row1 in t1 do \ Code generated
1.1971 +** foreach row2 in t2 do |-- by sqlite3WhereBegin()
1.1972 +** foreach row3 in t3 do /
1.1973 +** ...
1.1974 +** end \ Code generated
1.1975 +** end |-- by sqlite3WhereEnd()
1.1976 +** end /
1.1977 +**
1.1978 +** Note that the loops might not be nested in the order in which they
1.1979 +** appear in the FROM clause if a different order is better able to make
1.1980 +** use of indices. Note also that when the IN operator appears in
1.1981 +** the WHERE clause, it might result in additional nested loops for
1.1982 +** scanning through all values on the right-hand side of the IN.
1.1983 +**
1.1984 +** There are Btree cursors associated with each table. t1 uses cursor
1.1985 +** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
1.1986 +** And so forth. This routine generates code to open those VDBE cursors
1.1987 +** and sqlite3WhereEnd() generates the code to close them.
1.1988 +**
1.1989 +** The code that sqlite3WhereBegin() generates leaves the cursors named
1.1990 +** in pTabList pointing at their appropriate entries. The [...] code
1.1991 +** can use OP_Column and OP_Rowid opcodes on these cursors to extract
1.1992 +** data from the various tables of the loop.
1.1993 +**
1.1994 +** If the WHERE clause is empty, the foreach loops must each scan their
1.1995 +** entire tables. Thus a three-way join is an O(N^3) operation. But if
1.1996 +** the tables have indices and there are terms in the WHERE clause that
1.1997 +** refer to those indices, a complete table scan can be avoided and the
1.1998 +** code will run much faster. Most of the work of this routine is checking
1.1999 +** to see if there are indices that can be used to speed up the loop.
1.2000 +**
1.2001 +** Terms of the WHERE clause are also used to limit which rows actually
1.2002 +** make it to the "..." in the middle of the loop. After each "foreach",
1.2003 +** terms of the WHERE clause that use only terms in that loop and outer
1.2004 +** loops are evaluated and if false a jump is made around all subsequent
1.2005 +** inner loops (or around the "..." if the test occurs within the inner-
1.2006 +** most loop)
1.2007 +**
1.2008 +** OUTER JOINS
1.2009 +**
1.2010 +** An outer join of tables t1 and t2 is conceptally coded as follows:
1.2011 +**
1.2012 +** foreach row1 in t1 do
1.2013 +** flag = 0
1.2014 +** foreach row2 in t2 do
1.2015 +** start:
1.2016 +** ...
1.2017 +** flag = 1
1.2018 +** end
1.2019 +** if flag==0 then
1.2020 +** move the row2 cursor to a null row
1.2021 +** goto start
1.2022 +** fi
1.2023 +** end
1.2024 +**
1.2025 +** ORDER BY CLAUSE PROCESSING
1.2026 +**
1.2027 +** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
1.2028 +** if there is one. If there is no ORDER BY clause or if this routine
1.2029 +** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
1.2030 +**
1.2031 +** If an index can be used so that the natural output order of the table
1.2032 +** scan is correct for the ORDER BY clause, then that index is used and
1.2033 +** *ppOrderBy is set to NULL. This is an optimization that prevents an
1.2034 +** unnecessary sort of the result set if an index appropriate for the
1.2035 +** ORDER BY clause already exists.
1.2036 +**
1.2037 +** If the where clause loops cannot be arranged to provide the correct
1.2038 +** output order, then the *ppOrderBy is unchanged.
1.2039 +*/
1.2040 +WhereInfo *sqlite3WhereBegin(
1.2041 + Parse *pParse, /* The parser context */
1.2042 + SrcList *pTabList, /* A list of all tables to be scanned */
1.2043 + Expr *pWhere, /* The WHERE clause */
1.2044 + ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
1.2045 + u8 wflags /* One of the WHERE_* flags defined in sqliteInt.h */
1.2046 +){
1.2047 + int i; /* Loop counter */
1.2048 + WhereInfo *pWInfo; /* Will become the return value of this function */
1.2049 + Vdbe *v = pParse->pVdbe; /* The virtual database engine */
1.2050 + int brk, cont = 0; /* Addresses used during code generation */
1.2051 + Bitmask notReady; /* Cursors that are not yet positioned */
1.2052 + WhereTerm *pTerm; /* A single term in the WHERE clause */
1.2053 + ExprMaskSet maskSet; /* The expression mask set */
1.2054 + WhereClause wc; /* The WHERE clause is divided into these terms */
1.2055 + struct SrcList_item *pTabItem; /* A single entry from pTabList */
1.2056 + WhereLevel *pLevel; /* A single level in the pWInfo list */
1.2057 + int iFrom; /* First unused FROM clause element */
1.2058 + int andFlags; /* AND-ed combination of all wc.a[].flags */
1.2059 + sqlite3 *db; /* Database connection */
1.2060 + ExprList *pOrderBy = 0;
1.2061 +
1.2062 + /* The number of tables in the FROM clause is limited by the number of
1.2063 + ** bits in a Bitmask
1.2064 + */
1.2065 + if( pTabList->nSrc>BMS ){
1.2066 + sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
1.2067 + return 0;
1.2068 + }
1.2069 +
1.2070 + if( ppOrderBy ){
1.2071 + pOrderBy = *ppOrderBy;
1.2072 + }
1.2073 +
1.2074 + /* Split the WHERE clause into separate subexpressions where each
1.2075 + ** subexpression is separated by an AND operator.
1.2076 + */
1.2077 + initMaskSet(&maskSet);
1.2078 + whereClauseInit(&wc, pParse, &maskSet);
1.2079 + sqlite3ExprCodeConstants(pParse, pWhere);
1.2080 + whereSplit(&wc, pWhere, TK_AND);
1.2081 +
1.2082 + /* Allocate and initialize the WhereInfo structure that will become the
1.2083 + ** return value.
1.2084 + */
1.2085 + db = pParse->db;
1.2086 + pWInfo = sqlite3DbMallocZero(db,
1.2087 + sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
1.2088 + if( db->mallocFailed ){
1.2089 + goto whereBeginError;
1.2090 + }
1.2091 + pWInfo->nLevel = pTabList->nSrc;
1.2092 + pWInfo->pParse = pParse;
1.2093 + pWInfo->pTabList = pTabList;
1.2094 + pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
1.2095 +
1.2096 + /* Special case: a WHERE clause that is constant. Evaluate the
1.2097 + ** expression and either jump over all of the code or fall thru.
1.2098 + */
1.2099 + if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
1.2100 + sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
1.2101 + pWhere = 0;
1.2102 + }
1.2103 +
1.2104 + /* Assign a bit from the bitmask to every term in the FROM clause.
1.2105 + **
1.2106 + ** When assigning bitmask values to FROM clause cursors, it must be
1.2107 + ** the case that if X is the bitmask for the N-th FROM clause term then
1.2108 + ** the bitmask for all FROM clause terms to the left of the N-th term
1.2109 + ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
1.2110 + ** its Expr.iRightJoinTable value to find the bitmask of the right table
1.2111 + ** of the join. Subtracting one from the right table bitmask gives a
1.2112 + ** bitmask for all tables to the left of the join. Knowing the bitmask
1.2113 + ** for all tables to the left of a left join is important. Ticket #3015.
1.2114 + */
1.2115 + for(i=0; i<pTabList->nSrc; i++){
1.2116 + createMask(&maskSet, pTabList->a[i].iCursor);
1.2117 + }
1.2118 +#ifndef NDEBUG
1.2119 + {
1.2120 + Bitmask toTheLeft = 0;
1.2121 + for(i=0; i<pTabList->nSrc; i++){
1.2122 + Bitmask m = getMask(&maskSet, pTabList->a[i].iCursor);
1.2123 + assert( (m-1)==toTheLeft );
1.2124 + toTheLeft |= m;
1.2125 + }
1.2126 + }
1.2127 +#endif
1.2128 +
1.2129 + /* Analyze all of the subexpressions. Note that exprAnalyze() might
1.2130 + ** add new virtual terms onto the end of the WHERE clause. We do not
1.2131 + ** want to analyze these virtual terms, so start analyzing at the end
1.2132 + ** and work forward so that the added virtual terms are never processed.
1.2133 + */
1.2134 + exprAnalyzeAll(pTabList, &wc);
1.2135 + if( db->mallocFailed ){
1.2136 + goto whereBeginError;
1.2137 + }
1.2138 +
1.2139 + /* Chose the best index to use for each table in the FROM clause.
1.2140 + **
1.2141 + ** This loop fills in the following fields:
1.2142 + **
1.2143 + ** pWInfo->a[].pIdx The index to use for this level of the loop.
1.2144 + ** pWInfo->a[].flags WHERE_xxx flags associated with pIdx
1.2145 + ** pWInfo->a[].nEq The number of == and IN constraints
1.2146 + ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
1.2147 + ** pWInfo->a[].iTabCur The VDBE cursor for the database table
1.2148 + ** pWInfo->a[].iIdxCur The VDBE cursor for the index
1.2149 + **
1.2150 + ** This loop also figures out the nesting order of tables in the FROM
1.2151 + ** clause.
1.2152 + */
1.2153 + notReady = ~(Bitmask)0;
1.2154 + pTabItem = pTabList->a;
1.2155 + pLevel = pWInfo->a;
1.2156 + andFlags = ~0;
1.2157 + WHERETRACE(("*** Optimizer Start ***\n"));
1.2158 + for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1.2159 + Index *pIdx; /* Index for FROM table at pTabItem */
1.2160 + int flags; /* Flags asssociated with pIdx */
1.2161 + int nEq; /* Number of == or IN constraints */
1.2162 + double cost; /* The cost for pIdx */
1.2163 + int j; /* For looping over FROM tables */
1.2164 + Index *pBest = 0; /* The best index seen so far */
1.2165 + int bestFlags = 0; /* Flags associated with pBest */
1.2166 + int bestNEq = 0; /* nEq associated with pBest */
1.2167 + double lowestCost; /* Cost of the pBest */
1.2168 + int bestJ = 0; /* The value of j */
1.2169 + Bitmask m; /* Bitmask value for j or bestJ */
1.2170 + int once = 0; /* True when first table is seen */
1.2171 + sqlite3_index_info *pIndex; /* Current virtual index */
1.2172 +
1.2173 + lowestCost = SQLITE_BIG_DBL;
1.2174 + for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
1.2175 + int doNotReorder; /* True if this table should not be reordered */
1.2176 +
1.2177 + doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
1.2178 + if( once && doNotReorder ) break;
1.2179 + m = getMask(&maskSet, pTabItem->iCursor);
1.2180 + if( (m & notReady)==0 ){
1.2181 + if( j==iFrom ) iFrom++;
1.2182 + continue;
1.2183 + }
1.2184 + assert( pTabItem->pTab );
1.2185 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.2186 + if( IsVirtual(pTabItem->pTab) ){
1.2187 + sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
1.2188 + cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
1.2189 + ppOrderBy ? *ppOrderBy : 0, i==0,
1.2190 + ppIdxInfo);
1.2191 + flags = WHERE_VIRTUALTABLE;
1.2192 + pIndex = *ppIdxInfo;
1.2193 + if( pIndex && pIndex->orderByConsumed ){
1.2194 + flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
1.2195 + }
1.2196 + pIdx = 0;
1.2197 + nEq = 0;
1.2198 + if( (SQLITE_BIG_DBL/2.0)<cost ){
1.2199 + /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
1.2200 + ** inital value of lowestCost in this loop. If it is, then
1.2201 + ** the (cost<lowestCost) test below will never be true and
1.2202 + ** pLevel->pBestIdx never set.
1.2203 + */
1.2204 + cost = (SQLITE_BIG_DBL/2.0);
1.2205 + }
1.2206 + }else
1.2207 +#endif
1.2208 + {
1.2209 + cost = bestIndex(pParse, &wc, pTabItem, notReady,
1.2210 + (i==0 && ppOrderBy) ? *ppOrderBy : 0,
1.2211 + &pIdx, &flags, &nEq);
1.2212 + pIndex = 0;
1.2213 + }
1.2214 + if( cost<lowestCost ){
1.2215 + once = 1;
1.2216 + lowestCost = cost;
1.2217 + pBest = pIdx;
1.2218 + bestFlags = flags;
1.2219 + bestNEq = nEq;
1.2220 + bestJ = j;
1.2221 + pLevel->pBestIdx = pIndex;
1.2222 + }
1.2223 + if( doNotReorder ) break;
1.2224 + }
1.2225 + WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
1.2226 + pLevel-pWInfo->a));
1.2227 + if( (bestFlags & WHERE_ORDERBY)!=0 ){
1.2228 + *ppOrderBy = 0;
1.2229 + }
1.2230 + andFlags &= bestFlags;
1.2231 + pLevel->flags = bestFlags;
1.2232 + pLevel->pIdx = pBest;
1.2233 + pLevel->nEq = bestNEq;
1.2234 + pLevel->aInLoop = 0;
1.2235 + pLevel->nIn = 0;
1.2236 + if( pBest ){
1.2237 + pLevel->iIdxCur = pParse->nTab++;
1.2238 + }else{
1.2239 + pLevel->iIdxCur = -1;
1.2240 + }
1.2241 + notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
1.2242 + pLevel->iFrom = bestJ;
1.2243 +
1.2244 + /* Check that if the table scanned by this loop iteration had an
1.2245 + ** INDEXED BY clause attached to it, that the named index is being
1.2246 + ** used for the scan. If not, then query compilation has failed.
1.2247 + ** Return an error.
1.2248 + */
1.2249 + pIdx = pTabList->a[bestJ].pIndex;
1.2250 + assert( !pIdx || !pBest || pIdx==pBest );
1.2251 + if( pIdx && pBest!=pIdx ){
1.2252 + sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
1.2253 + goto whereBeginError;
1.2254 + }
1.2255 + }
1.2256 + WHERETRACE(("*** Optimizer Finished ***\n"));
1.2257 +
1.2258 + /* If the total query only selects a single row, then the ORDER BY
1.2259 + ** clause is irrelevant.
1.2260 + */
1.2261 + if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
1.2262 + *ppOrderBy = 0;
1.2263 + }
1.2264 +
1.2265 + /* If the caller is an UPDATE or DELETE statement that is requesting
1.2266 + ** to use a one-pass algorithm, determine if this is appropriate.
1.2267 + ** The one-pass algorithm only works if the WHERE clause constraints
1.2268 + ** the statement to update a single row.
1.2269 + */
1.2270 + assert( (wflags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
1.2271 + if( (wflags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
1.2272 + pWInfo->okOnePass = 1;
1.2273 + pWInfo->a[0].flags &= ~WHERE_IDX_ONLY;
1.2274 + }
1.2275 +
1.2276 + /* Open all tables in the pTabList and any indices selected for
1.2277 + ** searching those tables.
1.2278 + */
1.2279 + sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
1.2280 + for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1.2281 + Table *pTab; /* Table to open */
1.2282 + Index *pIx; /* Index used to access pTab (if any) */
1.2283 + int iDb; /* Index of database containing table/index */
1.2284 + int iIdxCur = pLevel->iIdxCur;
1.2285 +
1.2286 +#ifndef SQLITE_OMIT_EXPLAIN
1.2287 + if( pParse->explain==2 ){
1.2288 + char *zMsg;
1.2289 + struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
1.2290 + zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
1.2291 + if( pItem->zAlias ){
1.2292 + zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
1.2293 + }
1.2294 + if( (pIx = pLevel->pIdx)!=0 ){
1.2295 + zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s", zMsg, pIx->zName);
1.2296 + }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
1.2297 + zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
1.2298 + }
1.2299 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.2300 + else if( pLevel->pBestIdx ){
1.2301 + sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
1.2302 + zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
1.2303 + pBestIdx->idxNum, pBestIdx->idxStr);
1.2304 + }
1.2305 +#endif
1.2306 + if( pLevel->flags & WHERE_ORDERBY ){
1.2307 + zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
1.2308 + }
1.2309 + sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
1.2310 + }
1.2311 +#endif /* SQLITE_OMIT_EXPLAIN */
1.2312 + pTabItem = &pTabList->a[pLevel->iFrom];
1.2313 + pTab = pTabItem->pTab;
1.2314 + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1.2315 + if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
1.2316 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.2317 + if( pLevel->pBestIdx ){
1.2318 + int iCur = pTabItem->iCursor;
1.2319 + sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
1.2320 + (const char*)pTab->pVtab, P4_VTAB);
1.2321 + }else
1.2322 +#endif
1.2323 + if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
1.2324 + int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
1.2325 + sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
1.2326 + if( !pWInfo->okOnePass && pTab->nCol<(sizeof(Bitmask)*8) ){
1.2327 + Bitmask b = pTabItem->colUsed;
1.2328 + int n = 0;
1.2329 + for(; b; b=b>>1, n++){}
1.2330 + sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-2, n);
1.2331 + assert( n<=pTab->nCol );
1.2332 + }
1.2333 + }else{
1.2334 + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1.2335 + }
1.2336 + pLevel->iTabCur = pTabItem->iCursor;
1.2337 + if( (pIx = pLevel->pIdx)!=0 ){
1.2338 + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
1.2339 + assert( pIx->pSchema==pTab->pSchema );
1.2340 + sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIx->nColumn+1);
1.2341 + sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
1.2342 + (char*)pKey, P4_KEYINFO_HANDOFF);
1.2343 + VdbeComment((v, "%s", pIx->zName));
1.2344 + }
1.2345 + sqlite3CodeVerifySchema(pParse, iDb);
1.2346 + }
1.2347 + pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
1.2348 +
1.2349 + /* Generate the code to do the search. Each iteration of the for
1.2350 + ** loop below generates code for a single nested loop of the VM
1.2351 + ** program.
1.2352 + */
1.2353 + notReady = ~(Bitmask)0;
1.2354 + for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1.2355 + int j, k;
1.2356 + int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
1.2357 + Index *pIdx; /* The index we will be using */
1.2358 + int nxt; /* Where to jump to continue with the next IN case */
1.2359 + int iIdxCur; /* The VDBE cursor for the index */
1.2360 + int omitTable; /* True if we use the index only */
1.2361 + int bRev; /* True if we need to scan in reverse order */
1.2362 +
1.2363 + pTabItem = &pTabList->a[pLevel->iFrom];
1.2364 + iCur = pTabItem->iCursor;
1.2365 + pIdx = pLevel->pIdx;
1.2366 + iIdxCur = pLevel->iIdxCur;
1.2367 + bRev = (pLevel->flags & WHERE_REVERSE)!=0;
1.2368 + omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
1.2369 +
1.2370 + /* Create labels for the "break" and "continue" instructions
1.2371 + ** for the current loop. Jump to brk to break out of a loop.
1.2372 + ** Jump to cont to go immediately to the next iteration of the
1.2373 + ** loop.
1.2374 + **
1.2375 + ** When there is an IN operator, we also have a "nxt" label that
1.2376 + ** means to continue with the next IN value combination. When
1.2377 + ** there are no IN operators in the constraints, the "nxt" label
1.2378 + ** is the same as "brk".
1.2379 + */
1.2380 + brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
1.2381 + cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
1.2382 +
1.2383 + /* If this is the right table of a LEFT OUTER JOIN, allocate and
1.2384 + ** initialize a memory cell that records if this table matches any
1.2385 + ** row of the left table of the join.
1.2386 + */
1.2387 + if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
1.2388 + pLevel->iLeftJoin = ++pParse->nMem;
1.2389 + sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
1.2390 + VdbeComment((v, "init LEFT JOIN no-match flag"));
1.2391 + }
1.2392 +
1.2393 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.2394 + if( pLevel->pBestIdx ){
1.2395 + /* Case 0: The table is a virtual-table. Use the VFilter and VNext
1.2396 + ** to access the data.
1.2397 + */
1.2398 + int j;
1.2399 + int iReg; /* P3 Value for OP_VFilter */
1.2400 + sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
1.2401 + int nConstraint = pBestIdx->nConstraint;
1.2402 + struct sqlite3_index_constraint_usage *aUsage =
1.2403 + pBestIdx->aConstraintUsage;
1.2404 + const struct sqlite3_index_constraint *aConstraint =
1.2405 + pBestIdx->aConstraint;
1.2406 +
1.2407 + iReg = sqlite3GetTempRange(pParse, nConstraint+2);
1.2408 + pParse->disableColCache++;
1.2409 + for(j=1; j<=nConstraint; j++){
1.2410 + int k;
1.2411 + for(k=0; k<nConstraint; k++){
1.2412 + if( aUsage[k].argvIndex==j ){
1.2413 + int iTerm = aConstraint[k].iTermOffset;
1.2414 + assert( pParse->disableColCache );
1.2415 + sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight, iReg+j+1);
1.2416 + break;
1.2417 + }
1.2418 + }
1.2419 + if( k==nConstraint ) break;
1.2420 + }
1.2421 + assert( pParse->disableColCache );
1.2422 + pParse->disableColCache--;
1.2423 + sqlite3VdbeAddOp2(v, OP_Integer, pBestIdx->idxNum, iReg);
1.2424 + sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
1.2425 + sqlite3VdbeAddOp4(v, OP_VFilter, iCur, brk, iReg, pBestIdx->idxStr,
1.2426 + pBestIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
1.2427 + sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
1.2428 + pBestIdx->needToFreeIdxStr = 0;
1.2429 + for(j=0; j<nConstraint; j++){
1.2430 + if( aUsage[j].omit ){
1.2431 + int iTerm = aConstraint[j].iTermOffset;
1.2432 + disableTerm(pLevel, &wc.a[iTerm]);
1.2433 + }
1.2434 + }
1.2435 + pLevel->op = OP_VNext;
1.2436 + pLevel->p1 = iCur;
1.2437 + pLevel->p2 = sqlite3VdbeCurrentAddr(v);
1.2438 + }else
1.2439 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
1.2440 +
1.2441 + if( pLevel->flags & WHERE_ROWID_EQ ){
1.2442 + /* Case 1: We can directly reference a single row using an
1.2443 + ** equality comparison against the ROWID field. Or
1.2444 + ** we reference multiple rows using a "rowid IN (...)"
1.2445 + ** construct.
1.2446 + */
1.2447 + int r1;
1.2448 + int rtmp = sqlite3GetTempReg(pParse);
1.2449 + pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1.2450 + assert( pTerm!=0 );
1.2451 + assert( pTerm->pExpr!=0 );
1.2452 + assert( pTerm->leftCursor==iCur );
1.2453 + assert( omitTable==0 );
1.2454 + r1 = codeEqualityTerm(pParse, pTerm, pLevel, rtmp);
1.2455 + nxt = pLevel->nxt;
1.2456 + sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, nxt);
1.2457 + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, nxt, r1);
1.2458 + sqlite3ReleaseTempReg(pParse, rtmp);
1.2459 + VdbeComment((v, "pk"));
1.2460 + pLevel->op = OP_Noop;
1.2461 + }else if( pLevel->flags & WHERE_ROWID_RANGE ){
1.2462 + /* Case 2: We have an inequality comparison against the ROWID field.
1.2463 + */
1.2464 + int testOp = OP_Noop;
1.2465 + int start;
1.2466 + WhereTerm *pStart, *pEnd;
1.2467 +
1.2468 + assert( omitTable==0 );
1.2469 + pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
1.2470 + pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
1.2471 + if( bRev ){
1.2472 + pTerm = pStart;
1.2473 + pStart = pEnd;
1.2474 + pEnd = pTerm;
1.2475 + }
1.2476 + if( pStart ){
1.2477 + Expr *pX;
1.2478 + int r1;
1.2479 + pX = pStart->pExpr;
1.2480 + assert( pX!=0 );
1.2481 + assert( pStart->leftCursor==iCur );
1.2482 +
1.2483 + /* The ForceInt instruction may modify the register that it operates
1.2484 + ** on. For example it may replace a real value with an integer one,
1.2485 + ** or if p3 is true it may increment the register value. For this
1.2486 + ** reason we need to make sure that register r1 is really a newly
1.2487 + ** allocated temporary register, and not part of the column-cache.
1.2488 + ** For this reason we cannot use sqlite3ExprCodeTemp() here.
1.2489 + */
1.2490 + r1 = sqlite3GetTempReg(pParse);
1.2491 + sqlite3ExprCode(pParse, pX->pRight, r1);
1.2492 +
1.2493 + sqlite3VdbeAddOp3(v, OP_ForceInt, r1, brk,
1.2494 + pX->op==TK_LE || pX->op==TK_GT);
1.2495 + sqlite3VdbeAddOp3(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk, r1);
1.2496 + VdbeComment((v, "pk"));
1.2497 + sqlite3ReleaseTempReg(pParse, r1);
1.2498 + disableTerm(pLevel, pStart);
1.2499 + }else{
1.2500 + sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
1.2501 + }
1.2502 + if( pEnd ){
1.2503 + Expr *pX;
1.2504 + pX = pEnd->pExpr;
1.2505 + assert( pX!=0 );
1.2506 + assert( pEnd->leftCursor==iCur );
1.2507 + pLevel->iMem = ++pParse->nMem;
1.2508 + sqlite3ExprCode(pParse, pX->pRight, pLevel->iMem);
1.2509 + if( pX->op==TK_LT || pX->op==TK_GT ){
1.2510 + testOp = bRev ? OP_Le : OP_Ge;
1.2511 + }else{
1.2512 + testOp = bRev ? OP_Lt : OP_Gt;
1.2513 + }
1.2514 + disableTerm(pLevel, pEnd);
1.2515 + }
1.2516 + start = sqlite3VdbeCurrentAddr(v);
1.2517 + pLevel->op = bRev ? OP_Prev : OP_Next;
1.2518 + pLevel->p1 = iCur;
1.2519 + pLevel->p2 = start;
1.2520 + if( testOp!=OP_Noop ){
1.2521 + int r1 = sqlite3GetTempReg(pParse);
1.2522 + sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
1.2523 + /* sqlite3VdbeAddOp2(v, OP_SCopy, pLevel->iMem, 0); */
1.2524 + sqlite3VdbeAddOp3(v, testOp, pLevel->iMem, brk, r1);
1.2525 + sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
1.2526 + sqlite3ReleaseTempReg(pParse, r1);
1.2527 + }
1.2528 + }else if( pLevel->flags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
1.2529 + /* Case 3: A scan using an index.
1.2530 + **
1.2531 + ** The WHERE clause may contain zero or more equality
1.2532 + ** terms ("==" or "IN" operators) that refer to the N
1.2533 + ** left-most columns of the index. It may also contain
1.2534 + ** inequality constraints (>, <, >= or <=) on the indexed
1.2535 + ** column that immediately follows the N equalities. Only
1.2536 + ** the right-most column can be an inequality - the rest must
1.2537 + ** use the "==" and "IN" operators. For example, if the
1.2538 + ** index is on (x,y,z), then the following clauses are all
1.2539 + ** optimized:
1.2540 + **
1.2541 + ** x=5
1.2542 + ** x=5 AND y=10
1.2543 + ** x=5 AND y<10
1.2544 + ** x=5 AND y>5 AND y<10
1.2545 + ** x=5 AND y=5 AND z<=10
1.2546 + **
1.2547 + ** The z<10 term of the following cannot be used, only
1.2548 + ** the x=5 term:
1.2549 + **
1.2550 + ** x=5 AND z<10
1.2551 + **
1.2552 + ** N may be zero if there are inequality constraints.
1.2553 + ** If there are no inequality constraints, then N is at
1.2554 + ** least one.
1.2555 + **
1.2556 + ** This case is also used when there are no WHERE clause
1.2557 + ** constraints but an index is selected anyway, in order
1.2558 + ** to force the output order to conform to an ORDER BY.
1.2559 + */
1.2560 + int aStartOp[] = {
1.2561 + 0,
1.2562 + 0,
1.2563 + OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
1.2564 + OP_Last, /* 3: (!start_constraints && startEq && bRev) */
1.2565 + OP_MoveGt, /* 4: (start_constraints && !startEq && !bRev) */
1.2566 + OP_MoveLt, /* 5: (start_constraints && !startEq && bRev) */
1.2567 + OP_MoveGe, /* 6: (start_constraints && startEq && !bRev) */
1.2568 + OP_MoveLe /* 7: (start_constraints && startEq && bRev) */
1.2569 + };
1.2570 + int aEndOp[] = {
1.2571 + OP_Noop, /* 0: (!end_constraints) */
1.2572 + OP_IdxGE, /* 1: (end_constraints && !bRev) */
1.2573 + OP_IdxLT /* 2: (end_constraints && bRev) */
1.2574 + };
1.2575 + int nEq = pLevel->nEq;
1.2576 + int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
1.2577 + int regBase; /* Base register holding constraint values */
1.2578 + int r1; /* Temp register */
1.2579 + WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
1.2580 + WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
1.2581 + int startEq; /* True if range start uses ==, >= or <= */
1.2582 + int endEq; /* True if range end uses ==, >= or <= */
1.2583 + int start_constraints; /* Start of range is constrained */
1.2584 + int k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
1.2585 + int nConstraint; /* Number of constraint terms */
1.2586 + int op;
1.2587 +
1.2588 + /* Generate code to evaluate all constraint terms using == or IN
1.2589 + ** and store the values of those terms in an array of registers
1.2590 + ** starting at regBase.
1.2591 + */
1.2592 + regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 2);
1.2593 + nxt = pLevel->nxt;
1.2594 +
1.2595 + /* If this loop satisfies a sort order (pOrderBy) request that
1.2596 + ** was passed to this function to implement a "SELECT min(x) ..."
1.2597 + ** query, then the caller will only allow the loop to run for
1.2598 + ** a single iteration. This means that the first row returned
1.2599 + ** should not have a NULL value stored in 'x'. If column 'x' is
1.2600 + ** the first one after the nEq equality constraints in the index,
1.2601 + ** this requires some special handling.
1.2602 + */
1.2603 + if( (wflags&WHERE_ORDERBY_MIN)!=0
1.2604 + && (pLevel->flags&WHERE_ORDERBY)
1.2605 + && (pIdx->nColumn>nEq)
1.2606 + ){
1.2607 + assert( pOrderBy->nExpr==1 );
1.2608 + assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] );
1.2609 + isMinQuery = 1;
1.2610 + }
1.2611 +
1.2612 + /* Find any inequality constraint terms for the start and end
1.2613 + ** of the range.
1.2614 + */
1.2615 + if( pLevel->flags & WHERE_TOP_LIMIT ){
1.2616 + pRangeEnd = findTerm(&wc, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
1.2617 + }
1.2618 + if( pLevel->flags & WHERE_BTM_LIMIT ){
1.2619 + pRangeStart = findTerm(&wc, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
1.2620 + }
1.2621 +
1.2622 + /* If we are doing a reverse order scan on an ascending index, or
1.2623 + ** a forward order scan on a descending index, interchange the
1.2624 + ** start and end terms (pRangeStart and pRangeEnd).
1.2625 + */
1.2626 + if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
1.2627 + SWAP(WhereTerm *, pRangeEnd, pRangeStart);
1.2628 + }
1.2629 +
1.2630 + testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
1.2631 + testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
1.2632 + testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
1.2633 + testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
1.2634 + startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
1.2635 + endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
1.2636 + start_constraints = pRangeStart || nEq>0;
1.2637 +
1.2638 + /* Seek the index cursor to the start of the range. */
1.2639 + nConstraint = nEq;
1.2640 + if( pRangeStart ){
1.2641 + int dcc = pParse->disableColCache;
1.2642 + if( pRangeEnd ){
1.2643 + pParse->disableColCache++;
1.2644 + }
1.2645 + sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
1.2646 + pParse->disableColCache = dcc;
1.2647 + sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
1.2648 + nConstraint++;
1.2649 + }else if( isMinQuery ){
1.2650 + sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
1.2651 + nConstraint++;
1.2652 + startEq = 0;
1.2653 + start_constraints = 1;
1.2654 + }
1.2655 + codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
1.2656 + op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
1.2657 + assert( op!=0 );
1.2658 + testcase( op==OP_Rewind );
1.2659 + testcase( op==OP_Last );
1.2660 + testcase( op==OP_MoveGt );
1.2661 + testcase( op==OP_MoveGe );
1.2662 + testcase( op==OP_MoveLe );
1.2663 + testcase( op==OP_MoveLt );
1.2664 + sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase,
1.2665 + SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
1.2666 +
1.2667 + /* Load the value for the inequality constraint at the end of the
1.2668 + ** range (if any).
1.2669 + */
1.2670 + nConstraint = nEq;
1.2671 + if( pRangeEnd ){
1.2672 + sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
1.2673 + sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
1.2674 + codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
1.2675 + nConstraint++;
1.2676 + }
1.2677 +
1.2678 + /* Top of the loop body */
1.2679 + pLevel->p2 = sqlite3VdbeCurrentAddr(v);
1.2680 +
1.2681 + /* Check if the index cursor is past the end of the range. */
1.2682 + op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
1.2683 + testcase( op==OP_Noop );
1.2684 + testcase( op==OP_IdxGE );
1.2685 + testcase( op==OP_IdxLT );
1.2686 + sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase,
1.2687 + SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
1.2688 + sqlite3VdbeChangeP5(v, endEq!=bRev);
1.2689 +
1.2690 + /* If there are inequality constraints, check that the value
1.2691 + ** of the table column that the inequality contrains is not NULL.
1.2692 + ** If it is, jump to the next iteration of the loop.
1.2693 + */
1.2694 + r1 = sqlite3GetTempReg(pParse);
1.2695 + testcase( pLevel->flags & WHERE_BTM_LIMIT );
1.2696 + testcase( pLevel->flags & WHERE_TOP_LIMIT );
1.2697 + if( pLevel->flags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
1.2698 + sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
1.2699 + sqlite3VdbeAddOp2(v, OP_IsNull, r1, cont);
1.2700 + }
1.2701 +
1.2702 + /* Seek the table cursor, if required */
1.2703 + if( !omitTable ){
1.2704 + sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
1.2705 + sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1); /* Deferred seek */
1.2706 + }
1.2707 + sqlite3ReleaseTempReg(pParse, r1);
1.2708 +
1.2709 + /* Record the instruction used to terminate the loop. Disable
1.2710 + ** WHERE clause terms made redundant by the index range scan.
1.2711 + */
1.2712 + pLevel->op = bRev ? OP_Prev : OP_Next;
1.2713 + pLevel->p1 = iIdxCur;
1.2714 + disableTerm(pLevel, pRangeStart);
1.2715 + disableTerm(pLevel, pRangeEnd);
1.2716 + }else{
1.2717 + /* Case 4: There is no usable index. We must do a complete
1.2718 + ** scan of the entire table.
1.2719 + */
1.2720 + assert( omitTable==0 );
1.2721 + assert( bRev==0 );
1.2722 + pLevel->op = OP_Next;
1.2723 + pLevel->p1 = iCur;
1.2724 + pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, brk);
1.2725 + pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
1.2726 + }
1.2727 + notReady &= ~getMask(&maskSet, iCur);
1.2728 +
1.2729 + /* Insert code to test every subexpression that can be completely
1.2730 + ** computed using the current set of tables.
1.2731 + */
1.2732 + k = 0;
1.2733 + for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
1.2734 + Expr *pE;
1.2735 + testcase( pTerm->flags & TERM_VIRTUAL );
1.2736 + testcase( pTerm->flags & TERM_CODED );
1.2737 + if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1.2738 + if( (pTerm->prereqAll & notReady)!=0 ) continue;
1.2739 + pE = pTerm->pExpr;
1.2740 + assert( pE!=0 );
1.2741 + if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
1.2742 + continue;
1.2743 + }
1.2744 + pParse->disableColCache += k;
1.2745 + sqlite3ExprIfFalse(pParse, pE, cont, SQLITE_JUMPIFNULL);
1.2746 + pParse->disableColCache -= k;
1.2747 + k = 1;
1.2748 + pTerm->flags |= TERM_CODED;
1.2749 + }
1.2750 +
1.2751 + /* For a LEFT OUTER JOIN, generate code that will record the fact that
1.2752 + ** at least one row of the right table has matched the left table.
1.2753 + */
1.2754 + if( pLevel->iLeftJoin ){
1.2755 + pLevel->top = sqlite3VdbeCurrentAddr(v);
1.2756 + sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
1.2757 + VdbeComment((v, "record LEFT JOIN hit"));
1.2758 + sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
1.2759 + sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
1.2760 + for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
1.2761 + testcase( pTerm->flags & TERM_VIRTUAL );
1.2762 + testcase( pTerm->flags & TERM_CODED );
1.2763 + if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1.2764 + if( (pTerm->prereqAll & notReady)!=0 ) continue;
1.2765 + assert( pTerm->pExpr );
1.2766 + sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, SQLITE_JUMPIFNULL);
1.2767 + pTerm->flags |= TERM_CODED;
1.2768 + }
1.2769 + }
1.2770 + }
1.2771 +
1.2772 +#ifdef SQLITE_TEST /* For testing and debugging use only */
1.2773 + /* Record in the query plan information about the current table
1.2774 + ** and the index used to access it (if any). If the table itself
1.2775 + ** is not used, its name is just '{}'. If no index is used
1.2776 + ** the index is listed as "{}". If the primary key is used the
1.2777 + ** index name is '*'.
1.2778 + */
1.2779 + for(i=0; i<pTabList->nSrc; i++){
1.2780 + char *z;
1.2781 + int n;
1.2782 + pLevel = &pWInfo->a[i];
1.2783 + pTabItem = &pTabList->a[pLevel->iFrom];
1.2784 + z = pTabItem->zAlias;
1.2785 + if( z==0 ) z = pTabItem->pTab->zName;
1.2786 + n = strlen(z);
1.2787 + if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
1.2788 + if( pLevel->flags & WHERE_IDX_ONLY ){
1.2789 + memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
1.2790 + nQPlan += 2;
1.2791 + }else{
1.2792 + memcpy(&sqlite3_query_plan[nQPlan], z, n);
1.2793 + nQPlan += n;
1.2794 + }
1.2795 + sqlite3_query_plan[nQPlan++] = ' ';
1.2796 + }
1.2797 + testcase( pLevel->flags & WHERE_ROWID_EQ );
1.2798 + testcase( pLevel->flags & WHERE_ROWID_RANGE );
1.2799 + if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
1.2800 + memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
1.2801 + nQPlan += 2;
1.2802 + }else if( pLevel->pIdx==0 ){
1.2803 + memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
1.2804 + nQPlan += 3;
1.2805 + }else{
1.2806 + n = strlen(pLevel->pIdx->zName);
1.2807 + if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
1.2808 + memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
1.2809 + nQPlan += n;
1.2810 + sqlite3_query_plan[nQPlan++] = ' ';
1.2811 + }
1.2812 + }
1.2813 + }
1.2814 + while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
1.2815 + sqlite3_query_plan[--nQPlan] = 0;
1.2816 + }
1.2817 + sqlite3_query_plan[nQPlan] = 0;
1.2818 + nQPlan = 0;
1.2819 +#endif /* SQLITE_TEST // Testing and debugging use only */
1.2820 +
1.2821 + /* Record the continuation address in the WhereInfo structure. Then
1.2822 + ** clean up and return.
1.2823 + */
1.2824 + pWInfo->iContinue = cont;
1.2825 + whereClauseClear(&wc);
1.2826 + return pWInfo;
1.2827 +
1.2828 + /* Jump here if malloc fails */
1.2829 +whereBeginError:
1.2830 + whereClauseClear(&wc);
1.2831 + whereInfoFree(db, pWInfo);
1.2832 + return 0;
1.2833 +}
1.2834 +
1.2835 +/*
1.2836 +** Generate the end of the WHERE loop. See comments on
1.2837 +** sqlite3WhereBegin() for additional information.
1.2838 +*/
1.2839 +void sqlite3WhereEnd(WhereInfo *pWInfo){
1.2840 + Parse *pParse = pWInfo->pParse;
1.2841 + Vdbe *v = pParse->pVdbe;
1.2842 + int i;
1.2843 + WhereLevel *pLevel;
1.2844 + SrcList *pTabList = pWInfo->pTabList;
1.2845 + sqlite3 *db = pParse->db;
1.2846 +
1.2847 + /* Generate loop termination code.
1.2848 + */
1.2849 + sqlite3ExprClearColumnCache(pParse, -1);
1.2850 + for(i=pTabList->nSrc-1; i>=0; i--){
1.2851 + pLevel = &pWInfo->a[i];
1.2852 + sqlite3VdbeResolveLabel(v, pLevel->cont);
1.2853 + if( pLevel->op!=OP_Noop ){
1.2854 + sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
1.2855 + sqlite3VdbeChangeP5(v, pLevel->p5);
1.2856 + }
1.2857 + if( pLevel->nIn ){
1.2858 + struct InLoop *pIn;
1.2859 + int j;
1.2860 + sqlite3VdbeResolveLabel(v, pLevel->nxt);
1.2861 + for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
1.2862 + sqlite3VdbeJumpHere(v, pIn->topAddr+1);
1.2863 + sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->topAddr);
1.2864 + sqlite3VdbeJumpHere(v, pIn->topAddr-1);
1.2865 + }
1.2866 + sqlite3DbFree(db, pLevel->aInLoop);
1.2867 + }
1.2868 + sqlite3VdbeResolveLabel(v, pLevel->brk);
1.2869 + if( pLevel->iLeftJoin ){
1.2870 + int addr;
1.2871 + addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
1.2872 + sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
1.2873 + if( pLevel->iIdxCur>=0 ){
1.2874 + sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
1.2875 + }
1.2876 + sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->top);
1.2877 + sqlite3VdbeJumpHere(v, addr);
1.2878 + }
1.2879 + }
1.2880 +
1.2881 + /* The "break" point is here, just past the end of the outer loop.
1.2882 + ** Set it.
1.2883 + */
1.2884 + sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
1.2885 +
1.2886 + /* Close all of the cursors that were opened by sqlite3WhereBegin.
1.2887 + */
1.2888 + for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
1.2889 + struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
1.2890 + Table *pTab = pTabItem->pTab;
1.2891 + assert( pTab!=0 );
1.2892 + if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
1.2893 + if( !pWInfo->okOnePass && (pLevel->flags & WHERE_IDX_ONLY)==0 ){
1.2894 + sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
1.2895 + }
1.2896 + if( pLevel->pIdx!=0 ){
1.2897 + sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
1.2898 + }
1.2899 +
1.2900 + /* If this scan uses an index, make code substitutions to read data
1.2901 + ** from the index in preference to the table. Sometimes, this means
1.2902 + ** the table need never be read from. This is a performance boost,
1.2903 + ** as the vdbe level waits until the table is read before actually
1.2904 + ** seeking the table cursor to the record corresponding to the current
1.2905 + ** position in the index.
1.2906 + **
1.2907 + ** Calls to the code generator in between sqlite3WhereBegin and
1.2908 + ** sqlite3WhereEnd will have created code that references the table
1.2909 + ** directly. This loop scans all that code looking for opcodes
1.2910 + ** that reference the table and converts them into opcodes that
1.2911 + ** reference the index.
1.2912 + */
1.2913 + if( pLevel->pIdx ){
1.2914 + int k, j, last;
1.2915 + VdbeOp *pOp;
1.2916 + Index *pIdx = pLevel->pIdx;
1.2917 + int useIndexOnly = pLevel->flags & WHERE_IDX_ONLY;
1.2918 +
1.2919 + assert( pIdx!=0 );
1.2920 + pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
1.2921 + last = sqlite3VdbeCurrentAddr(v);
1.2922 + for(k=pWInfo->iTop; k<last; k++, pOp++){
1.2923 + if( pOp->p1!=pLevel->iTabCur ) continue;
1.2924 + if( pOp->opcode==OP_Column ){
1.2925 + for(j=0; j<pIdx->nColumn; j++){
1.2926 + if( pOp->p2==pIdx->aiColumn[j] ){
1.2927 + pOp->p2 = j;
1.2928 + pOp->p1 = pLevel->iIdxCur;
1.2929 + break;
1.2930 + }
1.2931 + }
1.2932 + assert(!useIndexOnly || j<pIdx->nColumn);
1.2933 + }else if( pOp->opcode==OP_Rowid ){
1.2934 + pOp->p1 = pLevel->iIdxCur;
1.2935 + pOp->opcode = OP_IdxRowid;
1.2936 + }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
1.2937 + pOp->opcode = OP_Noop;
1.2938 + }
1.2939 + }
1.2940 + }
1.2941 + }
1.2942 +
1.2943 + /* Final cleanup
1.2944 + */
1.2945 + whereInfoFree(db, pWInfo);
1.2946 + return;
1.2947 +}