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