ds@1952: /* ds@1952: ** 2001 September 15 ds@1952: ** ds@1952: ** The author disclaims copyright to this source code. In place of ds@1952: ** a legal notice, here is a blessing: ds@1952: ** ds@1952: ** May you do good and not evil. ds@1952: ** May you find forgiveness for yourself and forgive others. ds@1952: ** May you share freely, never taking more than you give. ds@1952: ** ds@1952: ************************************************************************* ds@1952: ** This module contains C code that generates VDBE code used to process ds@1952: ** the WHERE clause of SQL statements. This module is reponsible for ds@1952: ** generating the code that loops through a table looking for applicable ds@1952: ** rows. Indices are selected and used to speed the search when doing ds@1952: ** so is applicable. Because this module is responsible for selecting ds@1952: ** indices, you might also think of this module as the "query optimizer". ds@1952: ** ds@1952: ** $Id$ ds@1952: */ ds@1952: #include "sqliteInt.h" ds@1952: ds@1952: /* ds@1952: ** The number of bits in a Bitmask. "BMS" means "BitMask Size". ds@1952: */ ds@1952: #define BMS (sizeof(Bitmask)*8) ds@1952: ds@1952: /* ds@1952: ** Trace output macros ds@1952: */ ds@1952: #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) ds@1952: int sqlite3_where_trace = 0; ds@1952: # define WHERETRACE(X) if(sqlite3_where_trace) sqlite3DebugPrintf X ds@1952: #else ds@1952: # define WHERETRACE(X) ds@1952: #endif ds@1952: ds@1952: /* Forward reference ds@1952: */ ds@1952: typedef struct WhereClause WhereClause; ds@1952: typedef struct ExprMaskSet ExprMaskSet; ds@1952: ds@1952: /* ds@1952: ** The query generator uses an array of instances of this structure to ds@1952: ** help it analyze the subexpressions of the WHERE clause. Each WHERE ds@1952: ** clause subexpression is separated from the others by an AND operator. ds@1952: ** ds@1952: ** All WhereTerms are collected into a single WhereClause structure. ds@1952: ** The following identity holds: ds@1952: ** ds@1952: ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm ds@1952: ** ds@1952: ** When a term is of the form: ds@1952: ** ds@1952: ** X ds@1952: ** ds@1952: ** where X is a column name and is one of certain operators, ds@1952: ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the ds@1952: ** cursor number and column number for X. WhereTerm.operator records ds@1952: ** the using a bitmask encoding defined by WO_xxx below. The ds@1952: ** use of a bitmask encoding for the operator allows us to search ds@1952: ** quickly for terms that match any of several different operators. ds@1952: ** ds@1952: ** prereqRight and prereqAll record sets of cursor numbers, ds@1952: ** but they do so indirectly. A single ExprMaskSet structure translates ds@1952: ** cursor number into bits and the translated bit is stored in the prereq ds@1952: ** fields. The translation is used in order to maximize the number of ds@1952: ** bits that will fit in a Bitmask. The VDBE cursor numbers might be ds@1952: ** spread out over the non-negative integers. For example, the cursor ds@1952: ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The ExprMaskSet ds@1952: ** translates these sparse cursor numbers into consecutive integers ds@1952: ** beginning with 0 in order to make the best possible use of the available ds@1952: ** bits in the Bitmask. So, in the example above, the cursor numbers ds@1952: ** would be mapped into integers 0 through 7. ds@1952: */ ds@1952: typedef struct WhereTerm WhereTerm; ds@1952: struct WhereTerm { ds@1952: Expr *pExpr; /* Pointer to the subexpression */ ds@1952: i16 iParent; /* Disable pWC->a[iParent] when this term disabled */ ds@1952: i16 leftCursor; /* Cursor number of X in "X " */ ds@1952: i16 leftColumn; /* Column number of X in "X " */ ds@1952: u16 eOperator; /* A WO_xx value describing */ ds@1952: u8 flags; /* Bit flags. See below */ ds@1952: u8 nChild; /* Number of children that must disable us */ ds@1952: WhereClause *pWC; /* The clause this term is part of */ ds@1952: Bitmask prereqRight; /* Bitmask of tables used by pRight */ ds@1952: Bitmask prereqAll; /* Bitmask of tables referenced by p */ ds@1952: }; ds@1952: ds@1952: /* ds@1952: ** Allowed values of WhereTerm.flags ds@1952: */ ds@1952: #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(pExpr) */ ds@1952: #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */ ds@1952: #define TERM_CODED 0x04 /* This term is already coded */ ds@1952: #define TERM_COPIED 0x08 /* Has a child */ ds@1952: #define TERM_OR_OK 0x10 /* Used during OR-clause processing */ ds@1952: ds@1952: /* ds@1952: ** An instance of the following structure holds all information about a ds@1952: ** WHERE clause. Mostly this is a container for one or more WhereTerms. ds@1952: */ ds@1952: struct WhereClause { ds@1952: Parse *pParse; /* The parser context */ ds@1952: ExprMaskSet *pMaskSet; /* Mapping of table indices to bitmasks */ ds@1952: int nTerm; /* Number of terms */ ds@1952: int nSlot; /* Number of entries in a[] */ ds@1952: WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */ ds@1952: WhereTerm aStatic[10]; /* Initial static space for a[] */ ds@1952: }; ds@1952: ds@1952: /* ds@1952: ** An instance of the following structure keeps track of a mapping ds@1952: ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm. ds@1952: ** ds@1952: ** The VDBE cursor numbers are small integers contained in ds@1952: ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE ds@1952: ** clause, the cursor numbers might not begin with 0 and they might ds@1952: ** contain gaps in the numbering sequence. But we want to make maximum ds@1952: ** use of the bits in our bitmasks. This structure provides a mapping ds@1952: ** from the sparse cursor numbers into consecutive integers beginning ds@1952: ** with 0. ds@1952: ** ds@1952: ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask ds@1952: ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<3, 5->1, 8->2, 29->0, ds@1952: ** 57->5, 73->4. Or one of 719 other combinations might be used. It ds@1952: ** does not really matter. What is important is that sparse cursor ds@1952: ** numbers all get mapped into bit numbers that begin with 0 and contain ds@1952: ** no gaps. ds@1952: */ ds@1952: struct ExprMaskSet { ds@1952: int n; /* Number of assigned cursor values */ ds@1952: int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */ ds@1952: }; ds@1952: ds@1952: ds@1952: /* ds@1952: ** Bitmasks for the operators that indices are able to exploit. An ds@1952: ** OR-ed combination of these values can be used when searching for ds@1952: ** terms in the where clause. ds@1952: */ ds@1952: #define WO_IN 1 ds@1952: #define WO_EQ 2 ds@1952: #define WO_LT (WO_EQ<<(TK_LT-TK_EQ)) ds@1952: #define WO_LE (WO_EQ<<(TK_LE-TK_EQ)) ds@1952: #define WO_GT (WO_EQ<<(TK_GT-TK_EQ)) ds@1952: #define WO_GE (WO_EQ<<(TK_GE-TK_EQ)) ds@1952: #define WO_MATCH 64 ds@1952: #define WO_ISNULL 128 ds@1952: ds@1952: /* ds@1952: ** Value for flags returned by bestIndex(). ds@1952: ** ds@1952: ** The least significant byte is reserved as a mask for WO_ values above. ds@1952: ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL. ds@1952: ** But if the table is the right table of a left join, WhereLevel.flags ds@1952: ** is set to WO_IN|WO_EQ. The WhereLevel.flags field can then be used as ds@1952: ** the "op" parameter to findTerm when we are resolving equality constraints. ds@1952: ** ISNULL constraints will then not be used on the right table of a left ds@1952: ** join. Tickets #2177 and #2189. ds@1952: */ ds@1952: #define WHERE_ROWID_EQ 0x000100 /* rowid=EXPR or rowid IN (...) */ ds@1952: #define WHERE_ROWID_RANGE 0x000200 /* rowidEXPR */ ds@1952: #define WHERE_COLUMN_EQ 0x001000 /* x=EXPR or x IN (...) */ ds@1952: #define WHERE_COLUMN_RANGE 0x002000 /* xEXPR */ ds@1952: #define WHERE_COLUMN_IN 0x004000 /* x IN (...) */ ds@1952: #define WHERE_TOP_LIMIT 0x010000 /* xEXPR or x>=EXPR constraint */ ds@1952: #define WHERE_IDX_ONLY 0x080000 /* Use index only - omit table */ ds@1952: #define WHERE_ORDERBY 0x100000 /* Output will appear in correct order */ ds@1952: #define WHERE_REVERSE 0x200000 /* Scan in reverse order */ ds@1952: #define WHERE_UNIQUE 0x400000 /* Selects no more than one row */ ds@1952: #define WHERE_VIRTUALTABLE 0x800000 /* Use virtual-table processing */ ds@1952: ds@1952: /* ds@1952: ** Initialize a preallocated WhereClause structure. ds@1952: */ ds@1952: static void whereClauseInit( ds@1952: WhereClause *pWC, /* The WhereClause to be initialized */ ds@1952: Parse *pParse, /* The parsing context */ ds@1952: ExprMaskSet *pMaskSet /* Mapping from table indices to bitmasks */ ds@1952: ){ ds@1952: pWC->pParse = pParse; ds@1952: pWC->pMaskSet = pMaskSet; ds@1952: pWC->nTerm = 0; ds@1952: pWC->nSlot = ArraySize(pWC->aStatic); ds@1952: pWC->a = pWC->aStatic; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Deallocate a WhereClause structure. The WhereClause structure ds@1952: ** itself is not freed. This routine is the inverse of whereClauseInit(). ds@1952: */ ds@1952: static void whereClauseClear(WhereClause *pWC){ ds@1952: int i; ds@1952: WhereTerm *a; ds@1952: for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){ ds@1952: if( a->flags & TERM_DYNAMIC ){ ds@1952: sqlite3ExprDelete(a->pExpr); ds@1952: } ds@1952: } ds@1952: if( pWC->a!=pWC->aStatic ){ ds@1952: sqlite3_free(pWC->a); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Add a new entries to the WhereClause structure. Increase the allocated ds@1952: ** space as necessary. ds@1952: ** ds@1952: ** If the flags argument includes TERM_DYNAMIC, then responsibility ds@1952: ** for freeing the expression p is assumed by the WhereClause object. ds@1952: ** ds@1952: ** WARNING: This routine might reallocate the space used to store ds@1952: ** WhereTerms. All pointers to WhereTerms should be invalided after ds@1952: ** calling this routine. Such pointers may be reinitialized by referencing ds@1952: ** the pWC->a[] array. ds@1952: */ ds@1952: static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){ ds@1952: WhereTerm *pTerm; ds@1952: int idx; ds@1952: if( pWC->nTerm>=pWC->nSlot ){ ds@1952: WhereTerm *pOld = pWC->a; ds@1952: pWC->a = sqlite3_malloc( sizeof(pWC->a[0])*pWC->nSlot*2 ); ds@1952: if( pWC->a==0 ){ ds@1952: pWC->pParse->db->mallocFailed = 1; ds@1952: if( flags & TERM_DYNAMIC ){ ds@1952: sqlite3ExprDelete(p); ds@1952: } ds@1952: return 0; ds@1952: } ds@1952: memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); ds@1952: if( pOld!=pWC->aStatic ){ ds@1952: sqlite3_free(pOld); ds@1952: } ds@1952: pWC->nSlot *= 2; ds@1952: } ds@1952: pTerm = &pWC->a[idx = pWC->nTerm]; ds@1952: pWC->nTerm++; ds@1952: pTerm->pExpr = p; ds@1952: pTerm->flags = flags; ds@1952: pTerm->pWC = pWC; ds@1952: pTerm->iParent = -1; ds@1952: return idx; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine identifies subexpressions in the WHERE clause where ds@1952: ** each subexpression is separated by the AND operator or some other ds@1952: ** operator specified in the op parameter. The WhereClause structure ds@1952: ** is filled with pointers to subexpressions. For example: ds@1952: ** ds@1952: ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22) ds@1952: ** \________/ \_______________/ \________________/ ds@1952: ** slot[0] slot[1] slot[2] ds@1952: ** ds@1952: ** The original WHERE clause in pExpr is unaltered. All this routine ds@1952: ** does is make slot[] entries point to substructure within pExpr. ds@1952: ** ds@1952: ** In the previous sentence and in the diagram, "slot[]" refers to ds@1952: ** the WhereClause.a[] array. This array grows as needed to contain ds@1952: ** all terms of the WHERE clause. ds@1952: */ ds@1952: static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){ ds@1952: if( pExpr==0 ) return; ds@1952: if( pExpr->op!=op ){ ds@1952: whereClauseInsert(pWC, pExpr, 0); ds@1952: }else{ ds@1952: whereSplit(pWC, pExpr->pLeft, op); ds@1952: whereSplit(pWC, pExpr->pRight, op); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Initialize an expression mask set ds@1952: */ ds@1952: #define initMaskSet(P) memset(P, 0, sizeof(*P)) ds@1952: ds@1952: /* ds@1952: ** Return the bitmask for the given cursor number. Return 0 if ds@1952: ** iCursor is not in the set. ds@1952: */ ds@1952: static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){ ds@1952: int i; ds@1952: for(i=0; in; i++){ ds@1952: if( pMaskSet->ix[i]==iCursor ){ ds@1952: return ((Bitmask)1)<ix[] ds@1952: ** array will never overflow. ds@1952: */ ds@1952: static void createMask(ExprMaskSet *pMaskSet, int iCursor){ ds@1952: assert( pMaskSet->n < ArraySize(pMaskSet->ix) ); ds@1952: pMaskSet->ix[pMaskSet->n++] = iCursor; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine walks (recursively) an expression tree and generates ds@1952: ** a bitmask indicating which tables are used in that expression ds@1952: ** tree. ds@1952: ** ds@1952: ** In order for this routine to work, the calling function must have ds@1952: ** previously invoked sqlite3ExprResolveNames() on the expression. See ds@1952: ** the header comment on that routine for additional information. ds@1952: ** The sqlite3ExprResolveNames() routines looks for column names and ds@1952: ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to ds@1952: ** the VDBE cursor number of the table. This routine just has to ds@1952: ** translate the cursor numbers into bitmask values and OR all ds@1952: ** the bitmasks together. ds@1952: */ ds@1952: static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*); ds@1952: static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*); ds@1952: static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){ ds@1952: Bitmask mask = 0; ds@1952: if( p==0 ) return 0; ds@1952: if( p->op==TK_COLUMN ){ ds@1952: mask = getMask(pMaskSet, p->iTable); ds@1952: return mask; ds@1952: } ds@1952: mask = exprTableUsage(pMaskSet, p->pRight); ds@1952: mask |= exprTableUsage(pMaskSet, p->pLeft); ds@1952: mask |= exprListTableUsage(pMaskSet, p->pList); ds@1952: mask |= exprSelectTableUsage(pMaskSet, p->pSelect); ds@1952: return mask; ds@1952: } ds@1952: static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){ ds@1952: int i; ds@1952: Bitmask mask = 0; ds@1952: if( pList ){ ds@1952: for(i=0; inExpr; i++){ ds@1952: mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr); ds@1952: } ds@1952: } ds@1952: return mask; ds@1952: } ds@1952: static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){ ds@1952: Bitmask mask = 0; ds@1952: while( pS ){ ds@1952: mask |= exprListTableUsage(pMaskSet, pS->pEList); ds@1952: mask |= exprListTableUsage(pMaskSet, pS->pGroupBy); ds@1952: mask |= exprListTableUsage(pMaskSet, pS->pOrderBy); ds@1952: mask |= exprTableUsage(pMaskSet, pS->pWhere); ds@1952: mask |= exprTableUsage(pMaskSet, pS->pHaving); ds@1952: pS = pS->pPrior; ds@1952: } ds@1952: return mask; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return TRUE if the given operator is one of the operators that is ds@1952: ** allowed for an indexable WHERE clause term. The allowed operators are ds@1952: ** "=", "<", ">", "<=", ">=", and "IN". ds@1952: */ ds@1952: static int allowedOp(int op){ ds@1952: assert( TK_GT>TK_EQ && TK_GTTK_EQ && TK_LTTK_EQ && TK_LE=TK_EQ && op<=TK_GE) || op==TK_ISNULL; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Swap two objects of type T. ds@1952: */ ds@1952: #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;} ds@1952: ds@1952: /* ds@1952: ** Commute a comparision operator. Expressions of the form "X op Y" ds@1952: ** are converted into "Y op X". ds@1952: ** ds@1952: ** If a collation sequence is associated with either the left or right ds@1952: ** side of the comparison, it remains associated with the same side after ds@1952: ** the commutation. So "Y collate NOCASE op X" becomes ds@1952: ** "X collate NOCASE op Y". This is because any collation sequence on ds@1952: ** the left hand side of a comparison overrides any collation sequence ds@1952: ** attached to the right. For the same reason the EP_ExpCollate flag ds@1952: ** is not commuted. ds@1952: */ ds@1952: static void exprCommute(Expr *pExpr){ ds@1952: u16 expRight = (pExpr->pRight->flags & EP_ExpCollate); ds@1952: u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate); ds@1952: assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN ); ds@1952: SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl); ds@1952: pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft; ds@1952: pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight; ds@1952: SWAP(Expr*,pExpr->pRight,pExpr->pLeft); ds@1952: if( pExpr->op>=TK_GT ){ ds@1952: assert( TK_LT==TK_GT+2 ); ds@1952: assert( TK_GE==TK_LE+2 ); ds@1952: assert( TK_GT>TK_EQ ); ds@1952: assert( TK_GTop>=TK_GT && pExpr->op<=TK_GE ); ds@1952: pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT; ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Translate from TK_xx operator to WO_xx bitmask. ds@1952: */ ds@1952: static int operatorMask(int op){ ds@1952: int c; ds@1952: assert( allowedOp(op) ); ds@1952: if( op==TK_IN ){ ds@1952: c = WO_IN; ds@1952: }else if( op==TK_ISNULL ){ ds@1952: c = WO_ISNULL; ds@1952: }else{ ds@1952: c = WO_EQ<<(op-TK_EQ); ds@1952: } ds@1952: assert( op!=TK_ISNULL || c==WO_ISNULL ); ds@1952: assert( op!=TK_IN || c==WO_IN ); ds@1952: assert( op!=TK_EQ || c==WO_EQ ); ds@1952: assert( op!=TK_LT || c==WO_LT ); ds@1952: assert( op!=TK_LE || c==WO_LE ); ds@1952: assert( op!=TK_GT || c==WO_GT ); ds@1952: assert( op!=TK_GE || c==WO_GE ); ds@1952: return c; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Search for a term in the WHERE clause that is of the form "X " ds@1952: ** where X is a reference to the iColumn of table iCur and is one of ds@1952: ** the WO_xx operator codes specified by the op parameter. ds@1952: ** Return a pointer to the term. Return 0 if not found. ds@1952: */ ds@1952: static WhereTerm *findTerm( ds@1952: WhereClause *pWC, /* The WHERE clause to be searched */ ds@1952: int iCur, /* Cursor number of LHS */ ds@1952: int iColumn, /* Column number of LHS */ ds@1952: Bitmask notReady, /* RHS must not overlap with this mask */ ds@1952: u16 op, /* Mask of WO_xx values describing operator */ ds@1952: Index *pIdx /* Must be compatible with this index, if not NULL */ ds@1952: ){ ds@1952: WhereTerm *pTerm; ds@1952: int k; ds@1952: for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){ ds@1952: if( pTerm->leftCursor==iCur ds@1952: && (pTerm->prereqRight & notReady)==0 ds@1952: && pTerm->leftColumn==iColumn ds@1952: && (pTerm->eOperator & op)!=0 ds@1952: ){ ds@1952: if( iCur>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){ ds@1952: Expr *pX = pTerm->pExpr; ds@1952: CollSeq *pColl; ds@1952: char idxaff; ds@1952: int j; ds@1952: Parse *pParse = pWC->pParse; ds@1952: ds@1952: idxaff = pIdx->pTable->aCol[iColumn].affinity; ds@1952: if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue; ds@1952: ds@1952: /* Figure out the collation sequence required from an index for ds@1952: ** it to be useful for optimising expression pX. Store this ds@1952: ** value in variable pColl. ds@1952: */ ds@1952: assert(pX->pLeft); ds@1952: pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); ds@1952: if( !pColl ){ ds@1952: pColl = pParse->db->pDfltColl; ds@1952: } ds@1952: ds@1952: for(j=0; jnColumn && pIdx->aiColumn[j]!=iColumn; j++){} ds@1952: assert( jnColumn ); ds@1952: if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue; ds@1952: } ds@1952: return pTerm; ds@1952: } ds@1952: } ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* Forward reference */ ds@1952: static void exprAnalyze(SrcList*, WhereClause*, int); ds@1952: ds@1952: /* ds@1952: ** Call exprAnalyze on all terms in a WHERE clause. ds@1952: ** ds@1952: ** ds@1952: */ ds@1952: static void exprAnalyzeAll( ds@1952: SrcList *pTabList, /* the FROM clause */ ds@1952: WhereClause *pWC /* the WHERE clause to be analyzed */ ds@1952: ){ ds@1952: int i; ds@1952: for(i=pWC->nTerm-1; i>=0; i--){ ds@1952: exprAnalyze(pTabList, pWC, i); ds@1952: } ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION ds@1952: /* ds@1952: ** Check to see if the given expression is a LIKE or GLOB operator that ds@1952: ** can be optimized using inequality constraints. Return TRUE if it is ds@1952: ** so and false if not. ds@1952: ** ds@1952: ** In order for the operator to be optimizible, the RHS must be a string ds@1952: ** literal that does not begin with a wildcard. ds@1952: */ ds@1952: static int isLikeOrGlob( ds@1952: sqlite3 *db, /* The database */ ds@1952: Expr *pExpr, /* Test this expression */ ds@1952: int *pnPattern, /* Number of non-wildcard prefix characters */ ds@1952: int *pisComplete /* True if the only wildcard is % in the last character */ ds@1952: ){ ds@1952: const char *z; ds@1952: Expr *pRight, *pLeft; ds@1952: ExprList *pList; ds@1952: int c, cnt; ds@1952: int noCase; ds@1952: char wc[3]; ds@1952: CollSeq *pColl; ds@1952: ds@1952: if( !sqlite3IsLikeFunction(db, pExpr, &noCase, wc) ){ ds@1952: return 0; ds@1952: } ds@1952: pList = pExpr->pList; ds@1952: pRight = pList->a[0].pExpr; ds@1952: if( pRight->op!=TK_STRING ){ ds@1952: return 0; ds@1952: } ds@1952: pLeft = pList->a[1].pExpr; ds@1952: if( pLeft->op!=TK_COLUMN ){ ds@1952: return 0; ds@1952: } ds@1952: pColl = pLeft->pColl; ds@1952: if( pColl==0 ){ ds@1952: /* TODO: Coverage testing doesn't get this case. Is it actually possible ds@1952: ** for an expression of type TK_COLUMN to not have an assigned collation ds@1952: ** sequence at this point? ds@1952: */ ds@1952: pColl = db->pDfltColl; ds@1952: } ds@1952: if( (pColl->type!=SQLITE_COLL_BINARY || noCase) && ds@1952: (pColl->type!=SQLITE_COLL_NOCASE || !noCase) ){ ds@1952: return 0; ds@1952: } ds@1952: sqlite3DequoteExpr(db, pRight); ds@1952: z = (char *)pRight->token.z; ds@1952: for(cnt=0; (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2]; cnt++){} ds@1952: if( cnt==0 || 255==(u8)z[cnt] ){ ds@1952: return 0; ds@1952: } ds@1952: *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0; ds@1952: *pnPattern = cnt; ds@1952: return 1; ds@1952: } ds@1952: #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ ds@1952: ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: /* ds@1952: ** Check to see if the given expression is of the form ds@1952: ** ds@1952: ** column MATCH expr ds@1952: ** ds@1952: ** If it is then return TRUE. If not, return FALSE. ds@1952: */ ds@1952: static int isMatchOfColumn( ds@1952: Expr *pExpr /* Test this expression */ ds@1952: ){ ds@1952: ExprList *pList; ds@1952: ds@1952: if( pExpr->op!=TK_FUNCTION ){ ds@1952: return 0; ds@1952: } ds@1952: if( pExpr->token.n!=5 || ds@1952: sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){ ds@1952: return 0; ds@1952: } ds@1952: pList = pExpr->pList; ds@1952: if( pList->nExpr!=2 ){ ds@1952: return 0; ds@1952: } ds@1952: if( pList->a[1].pExpr->op != TK_COLUMN ){ ds@1952: return 0; ds@1952: } ds@1952: return 1; ds@1952: } ds@1952: #endif /* SQLITE_OMIT_VIRTUALTABLE */ ds@1952: ds@1952: /* ds@1952: ** If the pBase expression originated in the ON or USING clause of ds@1952: ** a join, then transfer the appropriate markings over to derived. ds@1952: */ ds@1952: static void transferJoinMarkings(Expr *pDerived, Expr *pBase){ ds@1952: pDerived->flags |= pBase->flags & EP_FromJoin; ds@1952: pDerived->iRightJoinTable = pBase->iRightJoinTable; ds@1952: } ds@1952: ds@1952: #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) ds@1952: /* ds@1952: ** Return TRUE if the given term of an OR clause can be converted ds@1952: ** into an IN clause. The iCursor and iColumn define the left-hand ds@1952: ** side of the IN clause. ds@1952: ** ds@1952: ** The context is that we have multiple OR-connected equality terms ds@1952: ** like this: ds@1952: ** ds@1952: ** a= OR a= OR b= OR ... ds@1952: ** ds@1952: ** The pOrTerm input to this routine corresponds to a single term of ds@1952: ** this OR clause. In order for the term to be a condidate for ds@1952: ** conversion to an IN operator, the following must be true: ds@1952: ** ds@1952: ** * The left-hand side of the term must be the column which ds@1952: ** is identified by iCursor and iColumn. ds@1952: ** ds@1952: ** * If the right-hand side is also a column, then the affinities ds@1952: ** of both right and left sides must be such that no type ds@1952: ** conversions are required on the right. (Ticket #2249) ds@1952: ** ds@1952: ** If both of these conditions are true, then return true. Otherwise ds@1952: ** return false. ds@1952: */ ds@1952: static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){ ds@1952: int affLeft, affRight; ds@1952: assert( pOrTerm->eOperator==WO_EQ ); ds@1952: if( pOrTerm->leftCursor!=iCursor ){ ds@1952: return 0; ds@1952: } ds@1952: if( pOrTerm->leftColumn!=iColumn ){ ds@1952: return 0; ds@1952: } ds@1952: affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight); ds@1952: if( affRight==0 ){ ds@1952: return 1; ds@1952: } ds@1952: affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft); ds@1952: if( affRight!=affLeft ){ ds@1952: return 0; ds@1952: } ds@1952: return 1; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return true if the given term of an OR clause can be ignored during ds@1952: ** a check to make sure all OR terms are candidates for optimization. ds@1952: ** In other words, return true if a call to the orTermIsOptCandidate() ds@1952: ** above returned false but it is not necessary to disqualify the ds@1952: ** optimization. ds@1952: ** ds@1952: ** Suppose the original OR phrase was this: ds@1952: ** ds@1952: ** a=4 OR a=11 OR a=b ds@1952: ** ds@1952: ** During analysis, the third term gets flipped around and duplicate ds@1952: ** so that we are left with this: ds@1952: ** ds@1952: ** a=4 OR a=11 OR a=b OR b=a ds@1952: ** ds@1952: ** Since the last two terms are duplicates, only one of them ds@1952: ** has to qualify in order for the whole phrase to qualify. When ds@1952: ** this routine is called, we know that pOrTerm did not qualify. ds@1952: ** This routine merely checks to see if pOrTerm has a duplicate that ds@1952: ** might qualify. If there is a duplicate that has not yet been ds@1952: ** disqualified, then return true. If there are no duplicates, or ds@1952: ** the duplicate has also been disqualifed, return false. ds@1952: */ ds@1952: static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){ ds@1952: if( pOrTerm->flags & TERM_COPIED ){ ds@1952: /* This is the original term. The duplicate is to the left had ds@1952: ** has not yet been analyzed and thus has not yet been disqualified. */ ds@1952: return 1; ds@1952: } ds@1952: if( (pOrTerm->flags & TERM_VIRTUAL)!=0 ds@1952: && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){ ds@1952: /* This is a duplicate term. The original qualified so this one ds@1952: ** does not have to. */ ds@1952: return 1; ds@1952: } ds@1952: /* This is either a singleton term or else it is a duplicate for ds@1952: ** which the original did not qualify. Either way we are done for. */ ds@1952: return 0; ds@1952: } ds@1952: #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */ ds@1952: ds@1952: /* ds@1952: ** The input to this routine is an WhereTerm structure with only the ds@1952: ** "pExpr" field filled in. The job of this routine is to analyze the ds@1952: ** subexpression and populate all the other fields of the WhereTerm ds@1952: ** structure. ds@1952: ** ds@1952: ** If the expression is of the form " X" it gets commuted ds@1952: ** to the standard form of "X ". If the expression is of ds@1952: ** the form "X Y" where both X and Y are columns, then the original ds@1952: ** expression is unchanged and a new virtual expression of the form ds@1952: ** "Y X" is added to the WHERE clause and analyzed separately. ds@1952: */ ds@1952: static void exprAnalyze( ds@1952: SrcList *pSrc, /* the FROM clause */ ds@1952: WhereClause *pWC, /* the WHERE clause */ ds@1952: int idxTerm /* Index of the term to be analyzed */ ds@1952: ){ ds@1952: WhereTerm *pTerm = &pWC->a[idxTerm]; ds@1952: ExprMaskSet *pMaskSet = pWC->pMaskSet; ds@1952: Expr *pExpr = pTerm->pExpr; ds@1952: Bitmask prereqLeft; ds@1952: Bitmask prereqAll; ds@1952: int nPattern; ds@1952: int isComplete; ds@1952: int op; ds@1952: Parse *pParse = pWC->pParse; ds@1952: sqlite3 *db = pParse->db; ds@1952: ds@1952: if( db->mallocFailed ) return; ds@1952: prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft); ds@1952: op = pExpr->op; ds@1952: if( op==TK_IN ){ ds@1952: assert( pExpr->pRight==0 ); ds@1952: pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList) ds@1952: | exprSelectTableUsage(pMaskSet, pExpr->pSelect); ds@1952: }else if( op==TK_ISNULL ){ ds@1952: pTerm->prereqRight = 0; ds@1952: }else{ ds@1952: pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight); ds@1952: } ds@1952: prereqAll = exprTableUsage(pMaskSet, pExpr); ds@1952: if( ExprHasProperty(pExpr, EP_FromJoin) ){ ds@1952: prereqAll |= getMask(pMaskSet, pExpr->iRightJoinTable); ds@1952: } ds@1952: pTerm->prereqAll = prereqAll; ds@1952: pTerm->leftCursor = -1; ds@1952: pTerm->iParent = -1; ds@1952: pTerm->eOperator = 0; ds@1952: if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){ ds@1952: Expr *pLeft = pExpr->pLeft; ds@1952: Expr *pRight = pExpr->pRight; ds@1952: if( pLeft->op==TK_COLUMN ){ ds@1952: pTerm->leftCursor = pLeft->iTable; ds@1952: pTerm->leftColumn = pLeft->iColumn; ds@1952: pTerm->eOperator = operatorMask(op); ds@1952: } ds@1952: if( pRight && pRight->op==TK_COLUMN ){ ds@1952: WhereTerm *pNew; ds@1952: Expr *pDup; ds@1952: if( pTerm->leftCursor>=0 ){ ds@1952: int idxNew; ds@1952: pDup = sqlite3ExprDup(db, pExpr); ds@1952: if( db->mallocFailed ){ ds@1952: sqlite3ExprDelete(pDup); ds@1952: return; ds@1952: } ds@1952: idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); ds@1952: if( idxNew==0 ) return; ds@1952: pNew = &pWC->a[idxNew]; ds@1952: pNew->iParent = idxTerm; ds@1952: pTerm = &pWC->a[idxTerm]; ds@1952: pTerm->nChild = 1; ds@1952: pTerm->flags |= TERM_COPIED; ds@1952: }else{ ds@1952: pDup = pExpr; ds@1952: pNew = pTerm; ds@1952: } ds@1952: exprCommute(pDup); ds@1952: pLeft = pDup->pLeft; ds@1952: pNew->leftCursor = pLeft->iTable; ds@1952: pNew->leftColumn = pLeft->iColumn; ds@1952: pNew->prereqRight = prereqLeft; ds@1952: pNew->prereqAll = prereqAll; ds@1952: pNew->eOperator = operatorMask(pDup->op); ds@1952: } ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION ds@1952: /* If a term is the BETWEEN operator, create two new virtual terms ds@1952: ** that define the range that the BETWEEN implements. ds@1952: */ ds@1952: else if( pExpr->op==TK_BETWEEN ){ ds@1952: ExprList *pList = pExpr->pList; ds@1952: int i; ds@1952: static const u8 ops[] = {TK_GE, TK_LE}; ds@1952: assert( pList!=0 ); ds@1952: assert( pList->nExpr==2 ); ds@1952: for(i=0; i<2; i++){ ds@1952: Expr *pNewExpr; ds@1952: int idxNew; ds@1952: pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft), ds@1952: sqlite3ExprDup(db, pList->a[i].pExpr), 0); ds@1952: idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); ds@1952: exprAnalyze(pSrc, pWC, idxNew); ds@1952: pTerm = &pWC->a[idxTerm]; ds@1952: pWC->a[idxNew].iParent = idxTerm; ds@1952: } ds@1952: pTerm->nChild = 2; ds@1952: } ds@1952: #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */ ds@1952: ds@1952: #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) ds@1952: /* Attempt to convert OR-connected terms into an IN operator so that ds@1952: ** they can make use of indices. Example: ds@1952: ** ds@1952: ** x = expr1 OR expr2 = x OR x = expr3 ds@1952: ** ds@1952: ** is converted into ds@1952: ** ds@1952: ** x IN (expr1,expr2,expr3) ds@1952: ** ds@1952: ** This optimization must be omitted if OMIT_SUBQUERY is defined because ds@1952: ** the compiler for the the IN operator is part of sub-queries. ds@1952: */ ds@1952: else if( pExpr->op==TK_OR ){ ds@1952: int ok; ds@1952: int i, j; ds@1952: int iColumn, iCursor; ds@1952: WhereClause sOr; ds@1952: WhereTerm *pOrTerm; ds@1952: ds@1952: assert( (pTerm->flags & TERM_DYNAMIC)==0 ); ds@1952: whereClauseInit(&sOr, pWC->pParse, pMaskSet); ds@1952: whereSplit(&sOr, pExpr, TK_OR); ds@1952: exprAnalyzeAll(pSrc, &sOr); ds@1952: assert( sOr.nTerm>=2 ); ds@1952: j = 0; ds@1952: do{ ds@1952: assert( j=0; ds@1952: for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){ ds@1952: if( pOrTerm->eOperator!=WO_EQ ){ ds@1952: goto or_not_possible; ds@1952: } ds@1952: if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){ ds@1952: pOrTerm->flags |= TERM_OR_OK; ds@1952: }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){ ds@1952: pOrTerm->flags &= ~TERM_OR_OK; ds@1952: }else{ ds@1952: ok = 0; ds@1952: } ds@1952: } ds@1952: }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 ); ds@1952: if( ok ){ ds@1952: ExprList *pList = 0; ds@1952: Expr *pNew, *pDup; ds@1952: Expr *pLeft = 0; ds@1952: for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){ ds@1952: if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue; ds@1952: pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight); ds@1952: pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0); ds@1952: pLeft = pOrTerm->pExpr->pLeft; ds@1952: } ds@1952: assert( pLeft!=0 ); ds@1952: pDup = sqlite3ExprDup(db, pLeft); ds@1952: pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0); ds@1952: if( pNew ){ ds@1952: int idxNew; ds@1952: transferJoinMarkings(pNew, pExpr); ds@1952: pNew->pList = pList; ds@1952: idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); ds@1952: exprAnalyze(pSrc, pWC, idxNew); ds@1952: pTerm = &pWC->a[idxTerm]; ds@1952: pWC->a[idxNew].iParent = idxTerm; ds@1952: pTerm->nChild = 1; ds@1952: }else{ ds@1952: sqlite3ExprListDelete(pList); ds@1952: } ds@1952: } ds@1952: or_not_possible: ds@1952: whereClauseClear(&sOr); ds@1952: } ds@1952: #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ ds@1952: ds@1952: #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION ds@1952: /* Add constraints to reduce the search space on a LIKE or GLOB ds@1952: ** operator. ds@1952: */ ds@1952: if( isLikeOrGlob(db, pExpr, &nPattern, &isComplete) ){ ds@1952: Expr *pLeft, *pRight; ds@1952: Expr *pStr1, *pStr2; ds@1952: Expr *pNewExpr1, *pNewExpr2; ds@1952: int idxNew1, idxNew2; ds@1952: ds@1952: pLeft = pExpr->pList->a[1].pExpr; ds@1952: pRight = pExpr->pList->a[0].pExpr; ds@1952: pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0); ds@1952: if( pStr1 ){ ds@1952: sqlite3TokenCopy(db, &pStr1->token, &pRight->token); ds@1952: pStr1->token.n = nPattern; ds@1952: pStr1->flags = EP_Dequoted; ds@1952: } ds@1952: pStr2 = sqlite3ExprDup(db, pStr1); ds@1952: if( pStr2 ){ ds@1952: assert( pStr2->token.dyn ); ds@1952: ++*(u8*)&pStr2->token.z[nPattern-1]; ds@1952: } ds@1952: pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0); ds@1952: idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC); ds@1952: exprAnalyze(pSrc, pWC, idxNew1); ds@1952: pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0); ds@1952: idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC); ds@1952: exprAnalyze(pSrc, pWC, idxNew2); ds@1952: pTerm = &pWC->a[idxTerm]; ds@1952: if( isComplete ){ ds@1952: pWC->a[idxNew1].iParent = idxTerm; ds@1952: pWC->a[idxNew2].iParent = idxTerm; ds@1952: pTerm->nChild = 2; ds@1952: } ds@1952: } ds@1952: #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: /* Add a WO_MATCH auxiliary term to the constraint set if the ds@1952: ** current expression is of the form: column MATCH expr. ds@1952: ** This information is used by the xBestIndex methods of ds@1952: ** virtual tables. The native query optimizer does not attempt ds@1952: ** to do anything with MATCH functions. ds@1952: */ ds@1952: if( isMatchOfColumn(pExpr) ){ ds@1952: int idxNew; ds@1952: Expr *pRight, *pLeft; ds@1952: WhereTerm *pNewTerm; ds@1952: Bitmask prereqColumn, prereqExpr; ds@1952: ds@1952: pRight = pExpr->pList->a[0].pExpr; ds@1952: pLeft = pExpr->pList->a[1].pExpr; ds@1952: prereqExpr = exprTableUsage(pMaskSet, pRight); ds@1952: prereqColumn = exprTableUsage(pMaskSet, pLeft); ds@1952: if( (prereqExpr & prereqColumn)==0 ){ ds@1952: Expr *pNewExpr; ds@1952: pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0); ds@1952: idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); ds@1952: pNewTerm = &pWC->a[idxNew]; ds@1952: pNewTerm->prereqRight = prereqExpr; ds@1952: pNewTerm->leftCursor = pLeft->iTable; ds@1952: pNewTerm->leftColumn = pLeft->iColumn; ds@1952: pNewTerm->eOperator = WO_MATCH; ds@1952: pNewTerm->iParent = idxTerm; ds@1952: pTerm = &pWC->a[idxTerm]; ds@1952: pTerm->nChild = 1; ds@1952: pTerm->flags |= TERM_COPIED; ds@1952: pNewTerm->prereqAll = pTerm->prereqAll; ds@1952: } ds@1952: } ds@1952: #endif /* SQLITE_OMIT_VIRTUALTABLE */ ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return TRUE if any of the expressions in pList->a[iFirst...] contain ds@1952: ** a reference to any table other than the iBase table. ds@1952: */ ds@1952: static int referencesOtherTables( ds@1952: ExprList *pList, /* Search expressions in ths list */ ds@1952: ExprMaskSet *pMaskSet, /* Mapping from tables to bitmaps */ ds@1952: int iFirst, /* Be searching with the iFirst-th expression */ ds@1952: int iBase /* Ignore references to this table */ ds@1952: ){ ds@1952: Bitmask allowed = ~getMask(pMaskSet, iBase); ds@1952: while( iFirstnExpr ){ ds@1952: if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){ ds@1952: return 1; ds@1952: } ds@1952: } ds@1952: return 0; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** This routine decides if pIdx can be used to satisfy the ORDER BY ds@1952: ** clause. If it can, it returns 1. If pIdx cannot satisfy the ds@1952: ** ORDER BY clause, this routine returns 0. ds@1952: ** ds@1952: ** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the ds@1952: ** left-most table in the FROM clause of that same SELECT statement and ds@1952: ** the table has a cursor number of "base". pIdx is an index on pTab. ds@1952: ** ds@1952: ** nEqCol is the number of columns of pIdx that are used as equality ds@1952: ** constraints. Any of these columns may be missing from the ORDER BY ds@1952: ** clause and the match can still be a success. ds@1952: ** ds@1952: ** All terms of the ORDER BY that match against the index must be either ds@1952: ** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE ds@1952: ** index do not need to satisfy this constraint.) The *pbRev value is ds@1952: ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if ds@1952: ** the ORDER BY clause is all ASC. ds@1952: */ ds@1952: static int isSortingIndex( ds@1952: Parse *pParse, /* Parsing context */ ds@1952: ExprMaskSet *pMaskSet, /* Mapping from table indices to bitmaps */ ds@1952: Index *pIdx, /* The index we are testing */ ds@1952: int base, /* Cursor number for the table to be sorted */ ds@1952: ExprList *pOrderBy, /* The ORDER BY clause */ ds@1952: int nEqCol, /* Number of index columns with == constraints */ ds@1952: int *pbRev /* Set to 1 if ORDER BY is DESC */ ds@1952: ){ ds@1952: int i, j; /* Loop counters */ ds@1952: int sortOrder = 0; /* XOR of index and ORDER BY sort direction */ ds@1952: int nTerm; /* Number of ORDER BY terms */ ds@1952: struct ExprList_item *pTerm; /* A term of the ORDER BY clause */ ds@1952: sqlite3 *db = pParse->db; ds@1952: ds@1952: assert( pOrderBy!=0 ); ds@1952: nTerm = pOrderBy->nExpr; ds@1952: assert( nTerm>0 ); ds@1952: ds@1952: /* Match terms of the ORDER BY clause against columns of ds@1952: ** the index. ds@1952: ** ds@1952: ** Note that indices have pIdx->nColumn regular columns plus ds@1952: ** one additional column containing the rowid. The rowid column ds@1952: ** of the index is also allowed to match against the ORDER BY ds@1952: ** clause. ds@1952: */ ds@1952: for(i=j=0, pTerm=pOrderBy->a; jnColumn; i++){ ds@1952: Expr *pExpr; /* The expression of the ORDER BY pTerm */ ds@1952: CollSeq *pColl; /* The collating sequence of pExpr */ ds@1952: int termSortOrder; /* Sort order for this term */ ds@1952: int iColumn; /* The i-th column of the index. -1 for rowid */ ds@1952: int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */ ds@1952: const char *zColl; /* Name of the collating sequence for i-th index term */ ds@1952: ds@1952: pExpr = pTerm->pExpr; ds@1952: if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){ ds@1952: /* Can not use an index sort on anything that is not a column in the ds@1952: ** left-most table of the FROM clause */ ds@1952: break; ds@1952: } ds@1952: pColl = sqlite3ExprCollSeq(pParse, pExpr); ds@1952: if( !pColl ){ ds@1952: pColl = db->pDfltColl; ds@1952: } ds@1952: if( inColumn ){ ds@1952: iColumn = pIdx->aiColumn[i]; ds@1952: if( iColumn==pIdx->pTable->iPKey ){ ds@1952: iColumn = -1; ds@1952: } ds@1952: iSortOrder = pIdx->aSortOrder[i]; ds@1952: zColl = pIdx->azColl[i]; ds@1952: }else{ ds@1952: iColumn = -1; ds@1952: iSortOrder = 0; ds@1952: zColl = pColl->zName; ds@1952: } ds@1952: if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){ ds@1952: /* Term j of the ORDER BY clause does not match column i of the index */ ds@1952: if( iaSortOrder!=0 ); ds@1952: assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 ); ds@1952: assert( iSortOrder==0 || iSortOrder==1 ); ds@1952: termSortOrder = iSortOrder ^ pTerm->sortOrder; ds@1952: if( i>nEqCol ){ ds@1952: if( termSortOrder!=sortOrder ){ ds@1952: /* Indices can only be used if all ORDER BY terms past the ds@1952: ** equality constraints are all either DESC or ASC. */ ds@1952: return 0; ds@1952: } ds@1952: }else{ ds@1952: sortOrder = termSortOrder; ds@1952: } ds@1952: j++; ds@1952: pTerm++; ds@1952: if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){ ds@1952: /* If the indexed column is the primary key and everything matches ds@1952: ** so far and none of the ORDER BY terms to the right reference other ds@1952: ** tables in the join, then we are assured that the index can be used ds@1952: ** to sort because the primary key is unique and so none of the other ds@1952: ** columns will make any difference ds@1952: */ ds@1952: j = nTerm; ds@1952: } ds@1952: } ds@1952: ds@1952: *pbRev = sortOrder!=0; ds@1952: if( j>=nTerm ){ ds@1952: /* All terms of the ORDER BY clause are covered by this index so ds@1952: ** this index can be used for sorting. */ ds@1952: return 1; ds@1952: } ds@1952: if( pIdx->onError!=OE_None && i==pIdx->nColumn ds@1952: && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){ ds@1952: /* All terms of this index match some prefix of the ORDER BY clause ds@1952: ** and the index is UNIQUE and no terms on the tail of the ORDER BY ds@1952: ** clause reference other tables in a join. If this is all true then ds@1952: ** the order by clause is superfluous. */ ds@1952: return 1; ds@1952: } ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied ds@1952: ** by sorting in order of ROWID. Return true if so and set *pbRev to be ds@1952: ** true for reverse ROWID and false for forward ROWID order. ds@1952: */ ds@1952: static int sortableByRowid( ds@1952: int base, /* Cursor number for table to be sorted */ ds@1952: ExprList *pOrderBy, /* The ORDER BY clause */ ds@1952: ExprMaskSet *pMaskSet, /* Mapping from tables to bitmaps */ ds@1952: int *pbRev /* Set to 1 if ORDER BY is DESC */ ds@1952: ){ ds@1952: Expr *p; ds@1952: ds@1952: assert( pOrderBy!=0 ); ds@1952: assert( pOrderBy->nExpr>0 ); ds@1952: p = pOrderBy->a[0].pExpr; ds@1952: if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1 ds@1952: && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){ ds@1952: *pbRev = pOrderBy->a[0].sortOrder; ds@1952: return 1; ds@1952: } ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Prepare a crude estimate of the logarithm of the input value. ds@1952: ** The results need not be exact. This is only used for estimating ds@1952: ** the total cost of performing operatings with O(logN) or O(NlogN) ds@1952: ** complexity. Because N is just a guess, it is no great tragedy if ds@1952: ** logN is a little off. ds@1952: */ ds@1952: static double estLog(double N){ ds@1952: double logN = 1; ds@1952: double x = 10; ds@1952: while( N>x ){ ds@1952: logN += 1; ds@1952: x *= 10; ds@1952: } ds@1952: return logN; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Two routines for printing the content of an sqlite3_index_info ds@1952: ** structure. Used for testing and debugging only. If neither ds@1952: ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines ds@1952: ** are no-ops. ds@1952: */ ds@1952: #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG) ds@1952: static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ ds@1952: int i; ds@1952: if( !sqlite3_where_trace ) return; ds@1952: for(i=0; inConstraint; i++){ ds@1952: sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n", ds@1952: i, ds@1952: p->aConstraint[i].iColumn, ds@1952: p->aConstraint[i].iTermOffset, ds@1952: p->aConstraint[i].op, ds@1952: p->aConstraint[i].usable); ds@1952: } ds@1952: for(i=0; inOrderBy; i++){ ds@1952: sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n", ds@1952: i, ds@1952: p->aOrderBy[i].iColumn, ds@1952: p->aOrderBy[i].desc); ds@1952: } ds@1952: } ds@1952: static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){ ds@1952: int i; ds@1952: if( !sqlite3_where_trace ) return; ds@1952: for(i=0; inConstraint; i++){ ds@1952: sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", ds@1952: i, ds@1952: p->aConstraintUsage[i].argvIndex, ds@1952: p->aConstraintUsage[i].omit); ds@1952: } ds@1952: sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum); ds@1952: sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); ds@1952: sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); ds@1952: sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); ds@1952: } ds@1952: #else ds@1952: #define TRACE_IDX_INPUTS(A) ds@1952: #define TRACE_IDX_OUTPUTS(A) ds@1952: #endif ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: /* ds@1952: ** Compute the best index for a virtual table. ds@1952: ** ds@1952: ** The best index is computed by the xBestIndex method of the virtual ds@1952: ** table module. This routine is really just a wrapper that sets up ds@1952: ** the sqlite3_index_info structure that is used to communicate with ds@1952: ** xBestIndex. ds@1952: ** ds@1952: ** In a join, this routine might be called multiple times for the ds@1952: ** same virtual table. The sqlite3_index_info structure is created ds@1952: ** and initialized on the first invocation and reused on all subsequent ds@1952: ** invocations. The sqlite3_index_info structure is also used when ds@1952: ** code is generated to access the virtual table. The whereInfoDelete() ds@1952: ** routine takes care of freeing the sqlite3_index_info structure after ds@1952: ** everybody has finished with it. ds@1952: */ ds@1952: static double bestVirtualIndex( ds@1952: Parse *pParse, /* The parsing context */ ds@1952: WhereClause *pWC, /* The WHERE clause */ ds@1952: struct SrcList_item *pSrc, /* The FROM clause term to search */ ds@1952: Bitmask notReady, /* Mask of cursors that are not available */ ds@1952: ExprList *pOrderBy, /* The order by clause */ ds@1952: int orderByUsable, /* True if we can potential sort */ ds@1952: sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */ ds@1952: ){ ds@1952: Table *pTab = pSrc->pTab; ds@1952: sqlite3_index_info *pIdxInfo; ds@1952: struct sqlite3_index_constraint *pIdxCons; ds@1952: struct sqlite3_index_orderby *pIdxOrderBy; ds@1952: struct sqlite3_index_constraint_usage *pUsage; ds@1952: WhereTerm *pTerm; ds@1952: int i, j; ds@1952: int nOrderBy; ds@1952: int rc; ds@1952: ds@1952: /* If the sqlite3_index_info structure has not been previously ds@1952: ** allocated and initialized for this virtual table, then allocate ds@1952: ** and initialize it now ds@1952: */ ds@1952: pIdxInfo = *ppIdxInfo; ds@1952: if( pIdxInfo==0 ){ ds@1952: WhereTerm *pTerm; ds@1952: int nTerm; ds@1952: WHERETRACE(("Recomputing index info for %s...\n", pTab->zName)); ds@1952: ds@1952: /* Count the number of possible WHERE clause constraints referring ds@1952: ** to this virtual table */ ds@1952: for(i=nTerm=0, pTerm=pWC->a; inTerm; i++, pTerm++){ ds@1952: if( pTerm->leftCursor != pSrc->iCursor ) continue; ds@1952: if( pTerm->eOperator==WO_IN ) continue; ds@1952: nTerm++; ds@1952: } ds@1952: ds@1952: /* If the ORDER BY clause contains only columns in the current ds@1952: ** virtual table then allocate space for the aOrderBy part of ds@1952: ** the sqlite3_index_info structure. ds@1952: */ ds@1952: nOrderBy = 0; ds@1952: if( pOrderBy ){ ds@1952: for(i=0; inExpr; i++){ ds@1952: Expr *pExpr = pOrderBy->a[i].pExpr; ds@1952: if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break; ds@1952: } ds@1952: if( i==pOrderBy->nExpr ){ ds@1952: nOrderBy = pOrderBy->nExpr; ds@1952: } ds@1952: } ds@1952: ds@1952: /* Allocate the sqlite3_index_info structure ds@1952: */ ds@1952: pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) ds@1952: + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm ds@1952: + sizeof(*pIdxOrderBy)*nOrderBy ); ds@1952: if( pIdxInfo==0 ){ ds@1952: sqlite3ErrorMsg(pParse, "out of memory"); ds@1952: return 0.0; ds@1952: } ds@1952: *ppIdxInfo = pIdxInfo; ds@1952: ds@1952: /* Initialize the structure. The sqlite3_index_info structure contains ds@1952: ** many fields that are declared "const" to prevent xBestIndex from ds@1952: ** changing them. We have to do some funky casting in order to ds@1952: ** initialize those fields. ds@1952: */ ds@1952: pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1]; ds@1952: pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm]; ds@1952: pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; ds@1952: *(int*)&pIdxInfo->nConstraint = nTerm; ds@1952: *(int*)&pIdxInfo->nOrderBy = nOrderBy; ds@1952: *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons; ds@1952: *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy; ds@1952: *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage = ds@1952: pUsage; ds@1952: ds@1952: for(i=j=0, pTerm=pWC->a; inTerm; i++, pTerm++){ ds@1952: if( pTerm->leftCursor != pSrc->iCursor ) continue; ds@1952: if( pTerm->eOperator==WO_IN ) continue; ds@1952: pIdxCons[j].iColumn = pTerm->leftColumn; ds@1952: pIdxCons[j].iTermOffset = i; ds@1952: pIdxCons[j].op = pTerm->eOperator; ds@1952: /* The direct assignment in the previous line is possible only because ds@1952: ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The ds@1952: ** following asserts verify this fact. */ ds@1952: assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); ds@1952: assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); ds@1952: assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); ds@1952: assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); ds@1952: assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); ds@1952: assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH ); ds@1952: assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) ); ds@1952: j++; ds@1952: } ds@1952: for(i=0; ia[i].pExpr; ds@1952: pIdxOrderBy[i].iColumn = pExpr->iColumn; ds@1952: pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder; ds@1952: } ds@1952: } ds@1952: ds@1952: /* At this point, the sqlite3_index_info structure that pIdxInfo points ds@1952: ** to will have been initialized, either during the current invocation or ds@1952: ** during some prior invocation. Now we just have to customize the ds@1952: ** details of pIdxInfo for the current invocation and pass it to ds@1952: ** xBestIndex. ds@1952: */ ds@1952: ds@1952: /* The module name must be defined. Also, by this point there must ds@1952: ** be a pointer to an sqlite3_vtab structure. Otherwise ds@1952: ** sqlite3ViewGetColumnNames() would have picked up the error. ds@1952: */ ds@1952: assert( pTab->azModuleArg && pTab->azModuleArg[0] ); ds@1952: assert( pTab->pVtab ); ds@1952: #if 0 ds@1952: if( pTab->pVtab==0 ){ ds@1952: sqlite3ErrorMsg(pParse, "undefined module %s for table %s", ds@1952: pTab->azModuleArg[0], pTab->zName); ds@1952: return 0.0; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Set the aConstraint[].usable fields and initialize all ds@1952: ** output variables to zero. ds@1952: ** ds@1952: ** aConstraint[].usable is true for constraints where the right-hand ds@1952: ** side contains only references to tables to the left of the current ds@1952: ** table. In other words, if the constraint is of the form: ds@1952: ** ds@1952: ** column = expr ds@1952: ** ds@1952: ** and we are evaluating a join, then the constraint on column is ds@1952: ** only valid if all tables referenced in expr occur to the left ds@1952: ** of the table containing column. ds@1952: ** ds@1952: ** The aConstraints[] array contains entries for all constraints ds@1952: ** on the current table. That way we only have to compute it once ds@1952: ** even though we might try to pick the best index multiple times. ds@1952: ** For each attempt at picking an index, the order of tables in the ds@1952: ** join might be different so we have to recompute the usable flag ds@1952: ** each time. ds@1952: */ ds@1952: pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; ds@1952: pUsage = pIdxInfo->aConstraintUsage; ds@1952: for(i=0; inConstraint; i++, pIdxCons++){ ds@1952: j = pIdxCons->iTermOffset; ds@1952: pTerm = &pWC->a[j]; ds@1952: pIdxCons->usable = (pTerm->prereqRight & notReady)==0; ds@1952: } ds@1952: memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint); ds@1952: if( pIdxInfo->needToFreeIdxStr ){ ds@1952: sqlite3_free(pIdxInfo->idxStr); ds@1952: } ds@1952: pIdxInfo->idxStr = 0; ds@1952: pIdxInfo->idxNum = 0; ds@1952: pIdxInfo->needToFreeIdxStr = 0; ds@1952: pIdxInfo->orderByConsumed = 0; ds@1952: pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0; ds@1952: nOrderBy = pIdxInfo->nOrderBy; ds@1952: if( pIdxInfo->nOrderBy && !orderByUsable ){ ds@1952: *(int*)&pIdxInfo->nOrderBy = 0; ds@1952: } ds@1952: ds@1952: sqlite3SafetyOff(pParse->db); ds@1952: WHERETRACE(("xBestIndex for %s\n", pTab->zName)); ds@1952: TRACE_IDX_INPUTS(pIdxInfo); ds@1952: rc = pTab->pVtab->pModule->xBestIndex(pTab->pVtab, pIdxInfo); ds@1952: TRACE_IDX_OUTPUTS(pIdxInfo); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: if( rc==SQLITE_NOMEM ){ ds@1952: pParse->db->mallocFailed = 1; ds@1952: }else { ds@1952: sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); ds@1952: } ds@1952: sqlite3SafetyOn(pParse->db); ds@1952: }else{ ds@1952: rc = sqlite3SafetyOn(pParse->db); ds@1952: } ds@1952: *(int*)&pIdxInfo->nOrderBy = nOrderBy; ds@1952: ds@1952: return pIdxInfo->estimatedCost; ds@1952: } ds@1952: #endif /* SQLITE_OMIT_VIRTUALTABLE */ ds@1952: ds@1952: /* ds@1952: ** Find the best index for accessing a particular table. Return a pointer ds@1952: ** to the index, flags that describe how the index should be used, the ds@1952: ** number of equality constraints, and the "cost" for this index. ds@1952: ** ds@1952: ** The lowest cost index wins. The cost is an estimate of the amount of ds@1952: ** CPU and disk I/O need to process the request using the selected index. ds@1952: ** Factors that influence cost include: ds@1952: ** ds@1952: ** * The estimated number of rows that will be retrieved. (The ds@1952: ** fewer the better.) ds@1952: ** ds@1952: ** * Whether or not sorting must occur. ds@1952: ** ds@1952: ** * Whether or not there must be separate lookups in the ds@1952: ** index and in the main table. ds@1952: ** ds@1952: */ ds@1952: static double bestIndex( ds@1952: Parse *pParse, /* The parsing context */ ds@1952: WhereClause *pWC, /* The WHERE clause */ ds@1952: struct SrcList_item *pSrc, /* The FROM clause term to search */ ds@1952: Bitmask notReady, /* Mask of cursors that are not available */ ds@1952: ExprList *pOrderBy, /* The order by clause */ ds@1952: Index **ppIndex, /* Make *ppIndex point to the best index */ ds@1952: int *pFlags, /* Put flags describing this choice in *pFlags */ ds@1952: int *pnEq /* Put the number of == or IN constraints here */ ds@1952: ){ ds@1952: WhereTerm *pTerm; ds@1952: Index *bestIdx = 0; /* Index that gives the lowest cost */ ds@1952: double lowestCost; /* The cost of using bestIdx */ ds@1952: int bestFlags = 0; /* Flags associated with bestIdx */ ds@1952: int bestNEq = 0; /* Best value for nEq */ ds@1952: int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */ ds@1952: Index *pProbe; /* An index we are evaluating */ ds@1952: int rev; /* True to scan in reverse order */ ds@1952: int flags; /* Flags associated with pProbe */ ds@1952: int nEq; /* Number of == or IN constraints */ ds@1952: int eqTermMask; /* Mask of valid equality operators */ ds@1952: double cost; /* Cost of using pProbe */ ds@1952: ds@1952: WHERETRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady)); ds@1952: lowestCost = SQLITE_BIG_DBL; ds@1952: pProbe = pSrc->pTab->pIndex; ds@1952: ds@1952: /* If the table has no indices and there are no terms in the where ds@1952: ** clause that refer to the ROWID, then we will never be able to do ds@1952: ** anything other than a full table scan on this table. We might as ds@1952: ** well put it first in the join order. That way, perhaps it can be ds@1952: ** referenced by other tables in the join. ds@1952: */ ds@1952: if( pProbe==0 && ds@1952: findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 && ds@1952: (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){ ds@1952: *pFlags = 0; ds@1952: *ppIndex = 0; ds@1952: *pnEq = 0; ds@1952: return 0.0; ds@1952: } ds@1952: ds@1952: /* Check for a rowid=EXPR or rowid IN (...) constraints ds@1952: */ ds@1952: pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0); ds@1952: if( pTerm ){ ds@1952: Expr *pExpr; ds@1952: *ppIndex = 0; ds@1952: bestFlags = WHERE_ROWID_EQ; ds@1952: if( pTerm->eOperator & WO_EQ ){ ds@1952: /* Rowid== is always the best pick. Look no further. Because only ds@1952: ** a single row is generated, output is always in sorted order */ ds@1952: *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE; ds@1952: *pnEq = 1; ds@1952: WHERETRACE(("... best is rowid\n")); ds@1952: return 0.0; ds@1952: }else if( (pExpr = pTerm->pExpr)->pList!=0 ){ ds@1952: /* Rowid IN (LIST): cost is NlogN where N is the number of list ds@1952: ** elements. */ ds@1952: lowestCost = pExpr->pList->nExpr; ds@1952: lowestCost *= estLog(lowestCost); ds@1952: }else{ ds@1952: /* Rowid IN (SELECT): cost is NlogN where N is the number of rows ds@1952: ** in the result of the inner select. We have no way to estimate ds@1952: ** that value so make a wild guess. */ ds@1952: lowestCost = 200; ds@1952: } ds@1952: WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost)); ds@1952: } ds@1952: ds@1952: /* Estimate the cost of a table scan. If we do not know how many ds@1952: ** entries are in the table, use 1 million as a guess. ds@1952: */ ds@1952: cost = pProbe ? pProbe->aiRowEst[0] : 1000000; ds@1952: WHERETRACE(("... table scan base cost: %.9g\n", cost)); ds@1952: flags = WHERE_ROWID_RANGE; ds@1952: ds@1952: /* Check for constraints on a range of rowids in a table scan. ds@1952: */ ds@1952: pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0); ds@1952: if( pTerm ){ ds@1952: if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){ ds@1952: flags |= WHERE_TOP_LIMIT; ds@1952: cost /= 3; /* Guess that rowidEXPR eliminates two-thirds of rows */ ds@1952: } ds@1952: WHERETRACE(("... rowid range reduces cost to %.9g\n", cost)); ds@1952: }else{ ds@1952: flags = 0; ds@1952: } ds@1952: ds@1952: /* If the table scan does not satisfy the ORDER BY clause, increase ds@1952: ** the cost by NlogN to cover the expense of sorting. */ ds@1952: if( pOrderBy ){ ds@1952: if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){ ds@1952: flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE; ds@1952: if( rev ){ ds@1952: flags |= WHERE_REVERSE; ds@1952: } ds@1952: }else{ ds@1952: cost += cost*estLog(cost); ds@1952: WHERETRACE(("... sorting increases cost to %.9g\n", cost)); ds@1952: } ds@1952: } ds@1952: if( costjointype & JT_LEFT)!=0 ){ ds@1952: eqTermMask = WO_EQ|WO_IN; ds@1952: }else{ ds@1952: eqTermMask = WO_EQ|WO_IN|WO_ISNULL; ds@1952: } ds@1952: ds@1952: /* Look at each index. ds@1952: */ ds@1952: for(; pProbe; pProbe=pProbe->pNext){ ds@1952: int i; /* Loop counter */ ds@1952: double inMultiplier = 1; ds@1952: ds@1952: WHERETRACE(("... index %s:\n", pProbe->zName)); ds@1952: ds@1952: /* Count the number of columns in the index that are satisfied ds@1952: ** by x=EXPR constraints or x IN (...) constraints. ds@1952: */ ds@1952: flags = 0; ds@1952: for(i=0; inColumn; i++){ ds@1952: int j = pProbe->aiColumn[i]; ds@1952: pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe); ds@1952: if( pTerm==0 ) break; ds@1952: flags |= WHERE_COLUMN_EQ; ds@1952: if( pTerm->eOperator & WO_IN ){ ds@1952: Expr *pExpr = pTerm->pExpr; ds@1952: flags |= WHERE_COLUMN_IN; ds@1952: if( pExpr->pSelect!=0 ){ ds@1952: inMultiplier *= 25; ds@1952: }else if( pExpr->pList!=0 ){ ds@1952: inMultiplier *= pExpr->pList->nExpr + 1; ds@1952: } ds@1952: } ds@1952: } ds@1952: cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier); ds@1952: nEq = i; ds@1952: if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0 ds@1952: && nEq==pProbe->nColumn ){ ds@1952: flags |= WHERE_UNIQUE; ds@1952: } ds@1952: WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost)); ds@1952: ds@1952: /* Look for range constraints ds@1952: */ ds@1952: if( nEqnColumn ){ ds@1952: int j = pProbe->aiColumn[nEq]; ds@1952: pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe); ds@1952: if( pTerm ){ ds@1952: flags |= WHERE_COLUMN_RANGE; ds@1952: if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){ ds@1952: flags |= WHERE_TOP_LIMIT; ds@1952: cost /= 3; ds@1952: } ds@1952: if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){ ds@1952: flags |= WHERE_BTM_LIMIT; ds@1952: cost /= 3; ds@1952: } ds@1952: WHERETRACE(("...... range reduces cost to %.9g\n", cost)); ds@1952: } ds@1952: } ds@1952: ds@1952: /* Add the additional cost of sorting if that is a factor. ds@1952: */ ds@1952: if( pOrderBy ){ ds@1952: if( (flags & WHERE_COLUMN_IN)==0 && ds@1952: isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){ ds@1952: if( flags==0 ){ ds@1952: flags = WHERE_COLUMN_RANGE; ds@1952: } ds@1952: flags |= WHERE_ORDERBY; ds@1952: if( rev ){ ds@1952: flags |= WHERE_REVERSE; ds@1952: } ds@1952: }else{ ds@1952: cost += cost*estLog(cost); ds@1952: WHERETRACE(("...... orderby increases cost to %.9g\n", cost)); ds@1952: } ds@1952: } ds@1952: ds@1952: /* Check to see if we can get away with using just the index without ds@1952: ** ever reading the table. If that is the case, then halve the ds@1952: ** cost of this index. ds@1952: */ ds@1952: if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){ ds@1952: Bitmask m = pSrc->colUsed; ds@1952: int j; ds@1952: for(j=0; jnColumn; j++){ ds@1952: int x = pProbe->aiColumn[j]; ds@1952: if( xzName : "(none)", lowestCost, bestFlags, bestNEq)); ds@1952: *pFlags = bestFlags | eqTermMask; ds@1952: *pnEq = bestNEq; ds@1952: return lowestCost; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Disable a term in the WHERE clause. Except, do not disable the term ds@1952: ** if it controls a LEFT OUTER JOIN and it did not originate in the ON ds@1952: ** or USING clause of that join. ds@1952: ** ds@1952: ** Consider the term t2.z='ok' in the following queries: ds@1952: ** ds@1952: ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' ds@1952: ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' ds@1952: ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' ds@1952: ** ds@1952: ** The t2.z='ok' is disabled in the in (2) because it originates ds@1952: ** in the ON clause. The term is disabled in (3) because it is not part ds@1952: ** of a LEFT OUTER JOIN. In (1), the term is not disabled. ds@1952: ** ds@1952: ** Disabling a term causes that term to not be tested in the inner loop ds@1952: ** of the join. Disabling is an optimization. When terms are satisfied ds@1952: ** by indices, we disable them to prevent redundant tests in the inner ds@1952: ** loop. We would get the correct results if nothing were ever disabled, ds@1952: ** but joins might run a little slower. The trick is to disable as much ds@1952: ** as we can without disabling too much. If we disabled in (1), we'd get ds@1952: ** the wrong answer. See ticket #813. ds@1952: */ ds@1952: static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ ds@1952: if( pTerm ds@1952: && (pTerm->flags & TERM_CODED)==0 ds@1952: && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) ds@1952: ){ ds@1952: pTerm->flags |= TERM_CODED; ds@1952: if( pTerm->iParent>=0 ){ ds@1952: WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent]; ds@1952: if( (--pOther->nChild)==0 ){ ds@1952: disableTerm(pLevel, pOther); ds@1952: } ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Generate code that builds a probe for an index. ds@1952: ** ds@1952: ** There should be nColumn values on the stack. The index ds@1952: ** to be probed is pIdx. Pop the values from the stack and ds@1952: ** replace them all with a single record that is the index ds@1952: ** problem. ds@1952: */ ds@1952: static void buildIndexProbe( ds@1952: Vdbe *v, /* Generate code into this VM */ ds@1952: int nColumn, /* The number of columns to check for NULL */ ds@1952: Index *pIdx /* Index that we will be searching */ ds@1952: ){ ds@1952: sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); ds@1952: sqlite3IndexAffinityStr(v, pIdx); ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Generate code for a single equality term of the WHERE clause. An equality ds@1952: ** term can be either X=expr or X IN (...). pTerm is the term to be ds@1952: ** coded. ds@1952: ** ds@1952: ** The current value for the constraint is left on the top of the stack. ds@1952: ** ds@1952: ** For a constraint of the form X=expr, the expression is evaluated and its ds@1952: ** result is left on the stack. For constraints of the form X IN (...) ds@1952: ** this routine sets up a loop that will iterate over all values of X. ds@1952: */ ds@1952: static void codeEqualityTerm( ds@1952: Parse *pParse, /* The parsing context */ ds@1952: WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ ds@1952: WhereLevel *pLevel /* When level of the FROM clause we are working on */ ds@1952: ){ ds@1952: Expr *pX = pTerm->pExpr; ds@1952: Vdbe *v = pParse->pVdbe; ds@1952: if( pX->op==TK_EQ ){ ds@1952: sqlite3ExprCode(pParse, pX->pRight); ds@1952: }else if( pX->op==TK_ISNULL ){ ds@1952: sqlite3VdbeAddOp(v, OP_Null, 0, 0); ds@1952: #ifndef SQLITE_OMIT_SUBQUERY ds@1952: }else{ ds@1952: int iTab; ds@1952: struct InLoop *pIn; ds@1952: ds@1952: assert( pX->op==TK_IN ); ds@1952: sqlite3CodeSubselect(pParse, pX); ds@1952: iTab = pX->iTable; ds@1952: sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0); ds@1952: VdbeComment((v, "# %.*s", pX->span.n, pX->span.z)); ds@1952: if( pLevel->nIn==0 ){ ds@1952: pLevel->nxt = sqlite3VdbeMakeLabel(v); ds@1952: } ds@1952: pLevel->nIn++; ds@1952: pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop, ds@1952: sizeof(pLevel->aInLoop[0])*pLevel->nIn); ds@1952: pIn = pLevel->aInLoop; ds@1952: if( pIn ){ ds@1952: pIn += pLevel->nIn - 1; ds@1952: pIn->iCur = iTab; ds@1952: pIn->topAddr = sqlite3VdbeAddOp(v, OP_Column, iTab, 0); ds@1952: sqlite3VdbeAddOp(v, OP_IsNull, -1, 0); ds@1952: }else{ ds@1952: pLevel->nIn = 0; ds@1952: } ds@1952: #endif ds@1952: } ds@1952: disableTerm(pLevel, pTerm); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Generate code that will evaluate all == and IN constraints for an ds@1952: ** index. The values for all constraints are left on the stack. ds@1952: ** ds@1952: ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). ds@1952: ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 ds@1952: ** The index has as many as three equality constraints, but in this ds@1952: ** example, the third "c" value is an inequality. So only two ds@1952: ** constraints are coded. This routine will generate code to evaluate ds@1952: ** a==5 and b IN (1,2,3). The current values for a and b will be left ds@1952: ** on the stack - a is the deepest and b the shallowest. ds@1952: ** ds@1952: ** In the example above nEq==2. But this subroutine works for any value ds@1952: ** of nEq including 0. If nEq==0, this routine is nearly a no-op. ds@1952: ** The only thing it does is allocate the pLevel->iMem memory cell. ds@1952: ** ds@1952: ** This routine always allocates at least one memory cell and puts ds@1952: ** the address of that memory cell in pLevel->iMem. The code that ds@1952: ** calls this routine will use pLevel->iMem to store the termination ds@1952: ** key value of the loop. If one or more IN operators appear, then ds@1952: ** this routine allocates an additional nEq memory cells for internal ds@1952: ** use. ds@1952: */ ds@1952: static void codeAllEqualityTerms( ds@1952: Parse *pParse, /* Parsing context */ ds@1952: WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ ds@1952: WhereClause *pWC, /* The WHERE clause */ ds@1952: Bitmask notReady /* Which parts of FROM have not yet been coded */ ds@1952: ){ ds@1952: int nEq = pLevel->nEq; /* The number of == or IN constraints to code */ ds@1952: int termsInMem = 0; /* If true, store value in mem[] cells */ ds@1952: Vdbe *v = pParse->pVdbe; /* The virtual machine under construction */ ds@1952: Index *pIdx = pLevel->pIdx; /* The index being used for this loop */ ds@1952: int iCur = pLevel->iTabCur; /* The cursor of the table */ ds@1952: WhereTerm *pTerm; /* A single constraint term */ ds@1952: int j; /* Loop counter */ ds@1952: ds@1952: /* Figure out how many memory cells we will need then allocate them. ds@1952: ** We always need at least one used to store the loop terminator ds@1952: ** value. If there are IN operators we'll need one for each == or ds@1952: ** IN constraint. ds@1952: */ ds@1952: pLevel->iMem = pParse->nMem++; ds@1952: if( pLevel->flags & WHERE_COLUMN_IN ){ ds@1952: pParse->nMem += pLevel->nEq; ds@1952: termsInMem = 1; ds@1952: } ds@1952: ds@1952: /* Evaluate the equality constraints ds@1952: */ ds@1952: assert( pIdx->nColumn>=nEq ); ds@1952: for(j=0; jaiColumn[j]; ds@1952: pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx); ds@1952: if( pTerm==0 ) break; ds@1952: assert( (pTerm->flags & TERM_CODED)==0 ); ds@1952: codeEqualityTerm(pParse, pTerm, pLevel); ds@1952: if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){ ds@1952: sqlite3VdbeAddOp(v, OP_IsNull, termsInMem ? -1 : -(j+1), pLevel->brk); ds@1952: } ds@1952: if( termsInMem ){ ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1); ds@1952: } ds@1952: } ds@1952: ds@1952: /* Make sure all the constraint values are on the top of the stack ds@1952: */ ds@1952: if( termsInMem ){ ds@1952: for(j=0; jiMem+j+1, 0); ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: #if defined(SQLITE_TEST) ds@1952: /* ds@1952: ** The following variable holds a text description of query plan generated ds@1952: ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin ds@1952: ** overwrites the previous. This information is used for testing and ds@1952: ** analysis only. ds@1952: */ ds@1952: char sqlite3_query_plan[BMS*2*40]; /* Text of the join */ ds@1952: static int nQPlan = 0; /* Next free slow in _query_plan[] */ ds@1952: ds@1952: #endif /* SQLITE_TEST */ ds@1952: ds@1952: ds@1952: /* ds@1952: ** Free a WhereInfo structure ds@1952: */ ds@1952: static void whereInfoFree(WhereInfo *pWInfo){ ds@1952: if( pWInfo ){ ds@1952: int i; ds@1952: for(i=0; inLevel; i++){ ds@1952: sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo; ds@1952: if( pInfo ){ ds@1952: if( pInfo->needToFreeIdxStr ){ ds@1952: /* Coverage: Don't think this can be reached. By the time this ds@1952: ** function is called, the index-strings have been passed ds@1952: ** to the vdbe layer for deletion. ds@1952: */ ds@1952: sqlite3_free(pInfo->idxStr); ds@1952: } ds@1952: sqlite3_free(pInfo); ds@1952: } ds@1952: } ds@1952: sqlite3_free(pWInfo); ds@1952: } ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Generate the beginning of the loop used for WHERE clause processing. ds@1952: ** The return value is a pointer to an opaque structure that contains ds@1952: ** information needed to terminate the loop. Later, the calling routine ds@1952: ** should invoke sqlite3WhereEnd() with the return value of this function ds@1952: ** in order to complete the WHERE clause processing. ds@1952: ** ds@1952: ** If an error occurs, this routine returns NULL. ds@1952: ** ds@1952: ** The basic idea is to do a nested loop, one loop for each table in ds@1952: ** the FROM clause of a select. (INSERT and UPDATE statements are the ds@1952: ** same as a SELECT with only a single table in the FROM clause.) For ds@1952: ** example, if the SQL is this: ds@1952: ** ds@1952: ** SELECT * FROM t1, t2, t3 WHERE ...; ds@1952: ** ds@1952: ** Then the code generated is conceptually like the following: ds@1952: ** ds@1952: ** foreach row1 in t1 do \ Code generated ds@1952: ** foreach row2 in t2 do |-- by sqlite3WhereBegin() ds@1952: ** foreach row3 in t3 do / ds@1952: ** ... ds@1952: ** end \ Code generated ds@1952: ** end |-- by sqlite3WhereEnd() ds@1952: ** end / ds@1952: ** ds@1952: ** Note that the loops might not be nested in the order in which they ds@1952: ** appear in the FROM clause if a different order is better able to make ds@1952: ** use of indices. Note also that when the IN operator appears in ds@1952: ** the WHERE clause, it might result in additional nested loops for ds@1952: ** scanning through all values on the right-hand side of the IN. ds@1952: ** ds@1952: ** There are Btree cursors associated with each table. t1 uses cursor ds@1952: ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor. ds@1952: ** And so forth. This routine generates code to open those VDBE cursors ds@1952: ** and sqlite3WhereEnd() generates the code to close them. ds@1952: ** ds@1952: ** The code that sqlite3WhereBegin() generates leaves the cursors named ds@1952: ** in pTabList pointing at their appropriate entries. The [...] code ds@1952: ** can use OP_Column and OP_Rowid opcodes on these cursors to extract ds@1952: ** data from the various tables of the loop. ds@1952: ** ds@1952: ** If the WHERE clause is empty, the foreach loops must each scan their ds@1952: ** entire tables. Thus a three-way join is an O(N^3) operation. But if ds@1952: ** the tables have indices and there are terms in the WHERE clause that ds@1952: ** refer to those indices, a complete table scan can be avoided and the ds@1952: ** code will run much faster. Most of the work of this routine is checking ds@1952: ** to see if there are indices that can be used to speed up the loop. ds@1952: ** ds@1952: ** Terms of the WHERE clause are also used to limit which rows actually ds@1952: ** make it to the "..." in the middle of the loop. After each "foreach", ds@1952: ** terms of the WHERE clause that use only terms in that loop and outer ds@1952: ** loops are evaluated and if false a jump is made around all subsequent ds@1952: ** inner loops (or around the "..." if the test occurs within the inner- ds@1952: ** most loop) ds@1952: ** ds@1952: ** OUTER JOINS ds@1952: ** ds@1952: ** An outer join of tables t1 and t2 is conceptally coded as follows: ds@1952: ** ds@1952: ** foreach row1 in t1 do ds@1952: ** flag = 0 ds@1952: ** foreach row2 in t2 do ds@1952: ** start: ds@1952: ** ... ds@1952: ** flag = 1 ds@1952: ** end ds@1952: ** if flag==0 then ds@1952: ** move the row2 cursor to a null row ds@1952: ** goto start ds@1952: ** fi ds@1952: ** end ds@1952: ** ds@1952: ** ORDER BY CLAUSE PROCESSING ds@1952: ** ds@1952: ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement, ds@1952: ** if there is one. If there is no ORDER BY clause or if this routine ds@1952: ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL. ds@1952: ** ds@1952: ** If an index can be used so that the natural output order of the table ds@1952: ** scan is correct for the ORDER BY clause, then that index is used and ds@1952: ** *ppOrderBy is set to NULL. This is an optimization that prevents an ds@1952: ** unnecessary sort of the result set if an index appropriate for the ds@1952: ** ORDER BY clause already exists. ds@1952: ** ds@1952: ** If the where clause loops cannot be arranged to provide the correct ds@1952: ** output order, then the *ppOrderBy is unchanged. ds@1952: */ ds@1952: WhereInfo *sqlite3WhereBegin( ds@1952: Parse *pParse, /* The parser context */ ds@1952: SrcList *pTabList, /* A list of all tables to be scanned */ ds@1952: Expr *pWhere, /* The WHERE clause */ ds@1952: ExprList **ppOrderBy /* An ORDER BY clause, or NULL */ ds@1952: ){ ds@1952: int i; /* Loop counter */ ds@1952: WhereInfo *pWInfo; /* Will become the return value of this function */ ds@1952: Vdbe *v = pParse->pVdbe; /* The virtual database engine */ ds@1952: int brk, cont = 0; /* Addresses used during code generation */ ds@1952: Bitmask notReady; /* Cursors that are not yet positioned */ ds@1952: WhereTerm *pTerm; /* A single term in the WHERE clause */ ds@1952: ExprMaskSet maskSet; /* The expression mask set */ ds@1952: WhereClause wc; /* The WHERE clause is divided into these terms */ ds@1952: struct SrcList_item *pTabItem; /* A single entry from pTabList */ ds@1952: WhereLevel *pLevel; /* A single level in the pWInfo list */ ds@1952: int iFrom; /* First unused FROM clause element */ ds@1952: int andFlags; /* AND-ed combination of all wc.a[].flags */ ds@1952: sqlite3 *db; /* Database connection */ ds@1952: ds@1952: /* The number of tables in the FROM clause is limited by the number of ds@1952: ** bits in a Bitmask ds@1952: */ ds@1952: if( pTabList->nSrc>BMS ){ ds@1952: sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* Split the WHERE clause into separate subexpressions where each ds@1952: ** subexpression is separated by an AND operator. ds@1952: */ ds@1952: initMaskSet(&maskSet); ds@1952: whereClauseInit(&wc, pParse, &maskSet); ds@1952: whereSplit(&wc, pWhere, TK_AND); ds@1952: ds@1952: /* Allocate and initialize the WhereInfo structure that will become the ds@1952: ** return value. ds@1952: */ ds@1952: db = pParse->db; ds@1952: pWInfo = sqlite3DbMallocZero(db, ds@1952: sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel)); ds@1952: if( db->mallocFailed ){ ds@1952: goto whereBeginNoMem; ds@1952: } ds@1952: pWInfo->nLevel = pTabList->nSrc; ds@1952: pWInfo->pParse = pParse; ds@1952: pWInfo->pTabList = pTabList; ds@1952: pWInfo->iBreak = sqlite3VdbeMakeLabel(v); ds@1952: ds@1952: /* Special case: a WHERE clause that is constant. Evaluate the ds@1952: ** expression and either jump over all of the code or fall thru. ds@1952: */ ds@1952: if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){ ds@1952: sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1); ds@1952: pWhere = 0; ds@1952: } ds@1952: ds@1952: /* Analyze all of the subexpressions. Note that exprAnalyze() might ds@1952: ** add new virtual terms onto the end of the WHERE clause. We do not ds@1952: ** want to analyze these virtual terms, so start analyzing at the end ds@1952: ** and work forward so that the added virtual terms are never processed. ds@1952: */ ds@1952: for(i=0; inSrc; i++){ ds@1952: createMask(&maskSet, pTabList->a[i].iCursor); ds@1952: } ds@1952: exprAnalyzeAll(pTabList, &wc); ds@1952: if( db->mallocFailed ){ ds@1952: goto whereBeginNoMem; ds@1952: } ds@1952: ds@1952: /* Chose the best index to use for each table in the FROM clause. ds@1952: ** ds@1952: ** This loop fills in the following fields: ds@1952: ** ds@1952: ** pWInfo->a[].pIdx The index to use for this level of the loop. ds@1952: ** pWInfo->a[].flags WHERE_xxx flags associated with pIdx ds@1952: ** pWInfo->a[].nEq The number of == and IN constraints ds@1952: ** pWInfo->a[].iFrom When term of the FROM clause is being coded ds@1952: ** pWInfo->a[].iTabCur The VDBE cursor for the database table ds@1952: ** pWInfo->a[].iIdxCur The VDBE cursor for the index ds@1952: ** ds@1952: ** This loop also figures out the nesting order of tables in the FROM ds@1952: ** clause. ds@1952: */ ds@1952: notReady = ~(Bitmask)0; ds@1952: pTabItem = pTabList->a; ds@1952: pLevel = pWInfo->a; ds@1952: andFlags = ~0; ds@1952: WHERETRACE(("*** Optimizer Start ***\n")); ds@1952: for(i=iFrom=0, pLevel=pWInfo->a; inSrc; i++, pLevel++){ ds@1952: Index *pIdx; /* Index for FROM table at pTabItem */ ds@1952: int flags; /* Flags asssociated with pIdx */ ds@1952: int nEq; /* Number of == or IN constraints */ ds@1952: double cost; /* The cost for pIdx */ ds@1952: int j; /* For looping over FROM tables */ ds@1952: Index *pBest = 0; /* The best index seen so far */ ds@1952: int bestFlags = 0; /* Flags associated with pBest */ ds@1952: int bestNEq = 0; /* nEq associated with pBest */ ds@1952: double lowestCost; /* Cost of the pBest */ ds@1952: int bestJ = 0; /* The value of j */ ds@1952: Bitmask m; /* Bitmask value for j or bestJ */ ds@1952: int once = 0; /* True when first table is seen */ ds@1952: sqlite3_index_info *pIndex; /* Current virtual index */ ds@1952: ds@1952: lowestCost = SQLITE_BIG_DBL; ds@1952: for(j=iFrom, pTabItem=&pTabList->a[j]; jnSrc; j++, pTabItem++){ ds@1952: int doNotReorder; /* True if this table should not be reordered */ ds@1952: ds@1952: doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0; ds@1952: if( once && doNotReorder ) break; ds@1952: m = getMask(&maskSet, pTabItem->iCursor); ds@1952: if( (m & notReady)==0 ){ ds@1952: if( j==iFrom ) iFrom++; ds@1952: continue; ds@1952: } ds@1952: assert( pTabItem->pTab ); ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: if( IsVirtual(pTabItem->pTab) ){ ds@1952: sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo; ds@1952: cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady, ds@1952: ppOrderBy ? *ppOrderBy : 0, i==0, ds@1952: ppIdxInfo); ds@1952: flags = WHERE_VIRTUALTABLE; ds@1952: pIndex = *ppIdxInfo; ds@1952: if( pIndex && pIndex->orderByConsumed ){ ds@1952: flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY; ds@1952: } ds@1952: pIdx = 0; ds@1952: nEq = 0; ds@1952: if( (SQLITE_BIG_DBL/2.0)pBestIdx never set. ds@1952: */ ds@1952: cost = (SQLITE_BIG_DBL/2.0); ds@1952: } ds@1952: }else ds@1952: #endif ds@1952: { ds@1952: cost = bestIndex(pParse, &wc, pTabItem, notReady, ds@1952: (i==0 && ppOrderBy) ? *ppOrderBy : 0, ds@1952: &pIdx, &flags, &nEq); ds@1952: pIndex = 0; ds@1952: } ds@1952: if( costpBestIdx = pIndex; ds@1952: } ds@1952: if( doNotReorder ) break; ds@1952: } ds@1952: WHERETRACE(("*** Optimizer choose table %d for loop %d\n", bestJ, ds@1952: pLevel-pWInfo->a)); ds@1952: if( (bestFlags & WHERE_ORDERBY)!=0 ){ ds@1952: *ppOrderBy = 0; ds@1952: } ds@1952: andFlags &= bestFlags; ds@1952: pLevel->flags = bestFlags; ds@1952: pLevel->pIdx = pBest; ds@1952: pLevel->nEq = bestNEq; ds@1952: pLevel->aInLoop = 0; ds@1952: pLevel->nIn = 0; ds@1952: if( pBest ){ ds@1952: pLevel->iIdxCur = pParse->nTab++; ds@1952: }else{ ds@1952: pLevel->iIdxCur = -1; ds@1952: } ds@1952: notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor); ds@1952: pLevel->iFrom = bestJ; ds@1952: } ds@1952: WHERETRACE(("*** Optimizer Finished ***\n")); ds@1952: ds@1952: /* If the total query only selects a single row, then the ORDER BY ds@1952: ** clause is irrelevant. ds@1952: */ ds@1952: if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){ ds@1952: *ppOrderBy = 0; ds@1952: } ds@1952: ds@1952: /* Open all tables in the pTabList and any indices selected for ds@1952: ** searching those tables. ds@1952: */ ds@1952: sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */ ds@1952: for(i=0, pLevel=pWInfo->a; inSrc; i++, pLevel++){ ds@1952: Table *pTab; /* Table to open */ ds@1952: Index *pIx; /* Index used to access pTab (if any) */ ds@1952: int iDb; /* Index of database containing table/index */ ds@1952: int iIdxCur = pLevel->iIdxCur; ds@1952: ds@1952: #ifndef SQLITE_OMIT_EXPLAIN ds@1952: if( pParse->explain==2 ){ ds@1952: char *zMsg; ds@1952: struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; ds@1952: zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName); ds@1952: if( pItem->zAlias ){ ds@1952: zMsg = sqlite3MPrintf(db, "%z AS %s", zMsg, pItem->zAlias); ds@1952: } ds@1952: if( (pIx = pLevel->pIdx)!=0 ){ ds@1952: zMsg = sqlite3MPrintf(db, "%z WITH INDEX %s", zMsg, pIx->zName); ds@1952: }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){ ds@1952: zMsg = sqlite3MPrintf(db, "%z USING PRIMARY KEY", zMsg); ds@1952: } ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: else if( pLevel->pBestIdx ){ ds@1952: sqlite3_index_info *pBestIdx = pLevel->pBestIdx; ds@1952: zMsg = sqlite3MPrintf(db, "%z VIRTUAL TABLE INDEX %d:%s", zMsg, ds@1952: pBestIdx->idxNum, pBestIdx->idxStr); ds@1952: } ds@1952: #endif ds@1952: if( pLevel->flags & WHERE_ORDERBY ){ ds@1952: zMsg = sqlite3MPrintf(db, "%z ORDER BY", zMsg); ds@1952: } ds@1952: sqlite3VdbeOp3(v, OP_Explain, i, pLevel->iFrom, zMsg, P3_DYNAMIC); ds@1952: } ds@1952: #endif /* SQLITE_OMIT_EXPLAIN */ ds@1952: pTabItem = &pTabList->a[pLevel->iFrom]; ds@1952: pTab = pTabItem->pTab; ds@1952: iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); ds@1952: if( pTab->isEphem || pTab->pSelect ) continue; ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: if( pLevel->pBestIdx ){ ds@1952: int iCur = pTabItem->iCursor; ds@1952: sqlite3VdbeOp3(v, OP_VOpen, iCur, 0, (const char*)pTab->pVtab, P3_VTAB); ds@1952: }else ds@1952: #endif ds@1952: if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){ ds@1952: sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, OP_OpenRead); ds@1952: if( pTab->nCol<(sizeof(Bitmask)*8) ){ ds@1952: Bitmask b = pTabItem->colUsed; ds@1952: int n = 0; ds@1952: for(; b; b=b>>1, n++){} ds@1952: sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-1, n); ds@1952: assert( n<=pTab->nCol ); ds@1952: } ds@1952: }else{ ds@1952: sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); ds@1952: } ds@1952: pLevel->iTabCur = pTabItem->iCursor; ds@1952: if( (pIx = pLevel->pIdx)!=0 ){ ds@1952: KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx); ds@1952: assert( pIx->pSchema==pTab->pSchema ); ds@1952: sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); ds@1952: VdbeComment((v, "# %s", pIx->zName)); ds@1952: sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum, ds@1952: (char*)pKey, P3_KEYINFO_HANDOFF); ds@1952: } ds@1952: if( (pLevel->flags & (WHERE_IDX_ONLY|WHERE_COLUMN_RANGE))!=0 ){ ds@1952: /* Only call OP_SetNumColumns on the index if we might later use ds@1952: ** OP_Column on the index. */ ds@1952: sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1); ds@1952: } ds@1952: sqlite3CodeVerifySchema(pParse, iDb); ds@1952: } ds@1952: pWInfo->iTop = sqlite3VdbeCurrentAddr(v); ds@1952: ds@1952: /* Generate the code to do the search. Each iteration of the for ds@1952: ** loop below generates code for a single nested loop of the VM ds@1952: ** program. ds@1952: */ ds@1952: notReady = ~(Bitmask)0; ds@1952: for(i=0, pLevel=pWInfo->a; inSrc; i++, pLevel++){ ds@1952: int j; ds@1952: int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */ ds@1952: Index *pIdx; /* The index we will be using */ ds@1952: int nxt; /* Where to jump to continue with the next IN case */ ds@1952: int iIdxCur; /* The VDBE cursor for the index */ ds@1952: int omitTable; /* True if we use the index only */ ds@1952: int bRev; /* True if we need to scan in reverse order */ ds@1952: ds@1952: pTabItem = &pTabList->a[pLevel->iFrom]; ds@1952: iCur = pTabItem->iCursor; ds@1952: pIdx = pLevel->pIdx; ds@1952: iIdxCur = pLevel->iIdxCur; ds@1952: bRev = (pLevel->flags & WHERE_REVERSE)!=0; ds@1952: omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0; ds@1952: ds@1952: /* Create labels for the "break" and "continue" instructions ds@1952: ** for the current loop. Jump to brk to break out of a loop. ds@1952: ** Jump to cont to go immediately to the next iteration of the ds@1952: ** loop. ds@1952: ** ds@1952: ** When there is an IN operator, we also have a "nxt" label that ds@1952: ** means to continue with the next IN value combination. When ds@1952: ** there are no IN operators in the constraints, the "nxt" label ds@1952: ** is the same as "brk". ds@1952: */ ds@1952: brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v); ds@1952: cont = pLevel->cont = sqlite3VdbeMakeLabel(v); ds@1952: ds@1952: /* If this is the right table of a LEFT OUTER JOIN, allocate and ds@1952: ** initialize a memory cell that records if this table matches any ds@1952: ** row of the left table of the join. ds@1952: */ ds@1952: if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){ ds@1952: if( !pParse->nMem ) pParse->nMem++; ds@1952: pLevel->iLeftJoin = pParse->nMem++; ds@1952: sqlite3VdbeAddOp(v, OP_MemInt, 0, pLevel->iLeftJoin); ds@1952: VdbeComment((v, "# init LEFT JOIN no-match flag")); ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIRTUALTABLE ds@1952: if( pLevel->pBestIdx ){ ds@1952: /* Case 0: The table is a virtual-table. Use the VFilter and VNext ds@1952: ** to access the data. ds@1952: */ ds@1952: int j; ds@1952: sqlite3_index_info *pBestIdx = pLevel->pBestIdx; ds@1952: int nConstraint = pBestIdx->nConstraint; ds@1952: struct sqlite3_index_constraint_usage *aUsage = ds@1952: pBestIdx->aConstraintUsage; ds@1952: const struct sqlite3_index_constraint *aConstraint = ds@1952: pBestIdx->aConstraint; ds@1952: ds@1952: for(j=1; j<=nConstraint; j++){ ds@1952: int k; ds@1952: for(k=0; kpRight); ds@1952: break; ds@1952: } ds@1952: } ds@1952: if( k==nConstraint ) break; ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_Integer, j-1, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Integer, pBestIdx->idxNum, 0); ds@1952: sqlite3VdbeOp3(v, OP_VFilter, iCur, brk, pBestIdx->idxStr, ds@1952: pBestIdx->needToFreeIdxStr ? P3_MPRINTF : P3_STATIC); ds@1952: pBestIdx->needToFreeIdxStr = 0; ds@1952: for(j=0; jnConstraint; j++){ ds@1952: if( aUsage[j].omit ){ ds@1952: int iTerm = aConstraint[j].iTermOffset; ds@1952: disableTerm(pLevel, &wc.a[iTerm]); ds@1952: } ds@1952: } ds@1952: pLevel->op = OP_VNext; ds@1952: pLevel->p1 = iCur; ds@1952: pLevel->p2 = sqlite3VdbeCurrentAddr(v); ds@1952: }else ds@1952: #endif /* SQLITE_OMIT_VIRTUALTABLE */ ds@1952: ds@1952: if( pLevel->flags & WHERE_ROWID_EQ ){ ds@1952: /* Case 1: We can directly reference a single row using an ds@1952: ** equality comparison against the ROWID field. Or ds@1952: ** we reference multiple rows using a "rowid IN (...)" ds@1952: ** construct. ds@1952: */ ds@1952: pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0); ds@1952: assert( pTerm!=0 ); ds@1952: assert( pTerm->pExpr!=0 ); ds@1952: assert( pTerm->leftCursor==iCur ); ds@1952: assert( omitTable==0 ); ds@1952: codeEqualityTerm(pParse, pTerm, pLevel); ds@1952: nxt = pLevel->nxt; ds@1952: sqlite3VdbeAddOp(v, OP_MustBeInt, 1, nxt); ds@1952: sqlite3VdbeAddOp(v, OP_NotExists, iCur, nxt); ds@1952: VdbeComment((v, "pk")); ds@1952: pLevel->op = OP_Noop; ds@1952: }else if( pLevel->flags & WHERE_ROWID_RANGE ){ ds@1952: /* Case 2: We have an inequality comparison against the ROWID field. ds@1952: */ ds@1952: int testOp = OP_Noop; ds@1952: int start; ds@1952: WhereTerm *pStart, *pEnd; ds@1952: ds@1952: assert( omitTable==0 ); ds@1952: pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0); ds@1952: pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0); ds@1952: if( bRev ){ ds@1952: pTerm = pStart; ds@1952: pStart = pEnd; ds@1952: pEnd = pTerm; ds@1952: } ds@1952: if( pStart ){ ds@1952: Expr *pX; ds@1952: pX = pStart->pExpr; ds@1952: assert( pX!=0 ); ds@1952: assert( pStart->leftCursor==iCur ); ds@1952: sqlite3ExprCode(pParse, pX->pRight); ds@1952: sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk); ds@1952: sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk); ds@1952: VdbeComment((v, "pk")); ds@1952: disableTerm(pLevel, pStart); ds@1952: }else{ ds@1952: sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk); ds@1952: } ds@1952: if( pEnd ){ ds@1952: Expr *pX; ds@1952: pX = pEnd->pExpr; ds@1952: assert( pX!=0 ); ds@1952: assert( pEnd->leftCursor==iCur ); ds@1952: sqlite3ExprCode(pParse, pX->pRight); ds@1952: pLevel->iMem = pParse->nMem++; ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1); ds@1952: if( pX->op==TK_LT || pX->op==TK_GT ){ ds@1952: testOp = bRev ? OP_Le : OP_Ge; ds@1952: }else{ ds@1952: testOp = bRev ? OP_Lt : OP_Gt; ds@1952: } ds@1952: disableTerm(pLevel, pEnd); ds@1952: } ds@1952: start = sqlite3VdbeCurrentAddr(v); ds@1952: pLevel->op = bRev ? OP_Prev : OP_Next; ds@1952: pLevel->p1 = iCur; ds@1952: pLevel->p2 = start; ds@1952: if( testOp!=OP_Noop ){ ds@1952: sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0); ds@1952: sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0); ds@1952: sqlite3VdbeAddOp(v, testOp, SQLITE_AFF_NUMERIC|0x100, brk); ds@1952: } ds@1952: }else if( pLevel->flags & WHERE_COLUMN_RANGE ){ ds@1952: /* Case 3: The WHERE clause term that refers to the right-most ds@1952: ** column of the index is an inequality. For example, if ds@1952: ** the index is on (x,y,z) and the WHERE clause is of the ds@1952: ** form "x=5 AND y<10" then this case is used. Only the ds@1952: ** right-most column can be an inequality - the rest must ds@1952: ** use the "==" and "IN" operators. ds@1952: ** ds@1952: ** This case is also used when there are no WHERE clause ds@1952: ** constraints but an index is selected anyway, in order ds@1952: ** to force the output order to conform to an ORDER BY. ds@1952: */ ds@1952: int start; ds@1952: int nEq = pLevel->nEq; ds@1952: int topEq=0; /* True if top limit uses ==. False is strictly < */ ds@1952: int btmEq=0; /* True if btm limit uses ==. False if strictly > */ ds@1952: int topOp, btmOp; /* Operators for the top and bottom search bounds */ ds@1952: int testOp; ds@1952: int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0; ds@1952: int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0; ds@1952: ds@1952: /* Generate code to evaluate all constraint terms using == or IN ds@1952: ** and level the values of those terms on the stack. ds@1952: */ ds@1952: codeAllEqualityTerms(pParse, pLevel, &wc, notReady); ds@1952: ds@1952: /* Duplicate the equality term values because they will all be ds@1952: ** used twice: once to make the termination key and once to make the ds@1952: ** start key. ds@1952: */ ds@1952: for(j=0; j or >= ds@1952: ** operator and the top bound is a < or <= operator. For a descending ds@1952: ** index the operators are reversed. ds@1952: */ ds@1952: if( pIdx->aSortOrder[nEq]==SQLITE_SO_ASC ){ ds@1952: topOp = WO_LT|WO_LE; ds@1952: btmOp = WO_GT|WO_GE; ds@1952: }else{ ds@1952: topOp = WO_GT|WO_GE; ds@1952: btmOp = WO_LT|WO_LE; ds@1952: SWAP(int, topLimit, btmLimit); ds@1952: } ds@1952: ds@1952: /* Generate the termination key. This is the key value that ds@1952: ** will end the search. There is no termination key if there ds@1952: ** are no equality terms and no "X<..." term. ds@1952: ** ds@1952: ** 2002-Dec-04: On a reverse-order scan, the so-called "termination" ds@1952: ** key computed here really ends up being the start key. ds@1952: */ ds@1952: nxt = pLevel->nxt; ds@1952: if( topLimit ){ ds@1952: Expr *pX; ds@1952: int k = pIdx->aiColumn[j]; ds@1952: pTerm = findTerm(&wc, iCur, k, notReady, topOp, pIdx); ds@1952: assert( pTerm!=0 ); ds@1952: pX = pTerm->pExpr; ds@1952: assert( (pTerm->flags & TERM_CODED)==0 ); ds@1952: sqlite3ExprCode(pParse, pX->pRight); ds@1952: sqlite3VdbeAddOp(v, OP_IsNull, -(nEq*2+1), nxt); ds@1952: topEq = pTerm->eOperator & (WO_LE|WO_GE); ds@1952: disableTerm(pLevel, pTerm); ds@1952: testOp = OP_IdxGE; ds@1952: }else{ ds@1952: testOp = nEq>0 ? OP_IdxGE : OP_Noop; ds@1952: topEq = 1; ds@1952: } ds@1952: if( testOp!=OP_Noop ){ ds@1952: int nCol = nEq + topLimit; ds@1952: pLevel->iMem = pParse->nMem++; ds@1952: buildIndexProbe(v, nCol, pIdx); ds@1952: if( bRev ){ ds@1952: int op = topEq ? OP_MoveLe : OP_MoveLt; ds@1952: sqlite3VdbeAddOp(v, op, iIdxCur, nxt); ds@1952: }else{ ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1); ds@1952: } ds@1952: }else if( bRev ){ ds@1952: sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk); ds@1952: } ds@1952: ds@1952: /* Generate the start key. This is the key that defines the lower ds@1952: ** bound on the search. There is no start key if there are no ds@1952: ** equality terms and if there is no "X>..." term. In ds@1952: ** that case, generate a "Rewind" instruction in place of the ds@1952: ** start key search. ds@1952: ** ds@1952: ** 2002-Dec-04: In the case of a reverse-order search, the so-called ds@1952: ** "start" key really ends up being used as the termination key. ds@1952: */ ds@1952: if( btmLimit ){ ds@1952: Expr *pX; ds@1952: int k = pIdx->aiColumn[j]; ds@1952: pTerm = findTerm(&wc, iCur, k, notReady, btmOp, pIdx); ds@1952: assert( pTerm!=0 ); ds@1952: pX = pTerm->pExpr; ds@1952: assert( (pTerm->flags & TERM_CODED)==0 ); ds@1952: sqlite3ExprCode(pParse, pX->pRight); ds@1952: sqlite3VdbeAddOp(v, OP_IsNull, -(nEq+1), nxt); ds@1952: btmEq = pTerm->eOperator & (WO_LE|WO_GE); ds@1952: disableTerm(pLevel, pTerm); ds@1952: }else{ ds@1952: btmEq = 1; ds@1952: } ds@1952: if( nEq>0 || btmLimit ){ ds@1952: int nCol = nEq + btmLimit; ds@1952: buildIndexProbe(v, nCol, pIdx); ds@1952: if( bRev ){ ds@1952: pLevel->iMem = pParse->nMem++; ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1); ds@1952: testOp = OP_IdxLT; ds@1952: }else{ ds@1952: int op = btmEq ? OP_MoveGe : OP_MoveGt; ds@1952: sqlite3VdbeAddOp(v, op, iIdxCur, nxt); ds@1952: } ds@1952: }else if( bRev ){ ds@1952: testOp = OP_Noop; ds@1952: }else{ ds@1952: sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk); ds@1952: } ds@1952: ds@1952: /* Generate the the top of the loop. If there is a termination ds@1952: ** key we have to test for that key and abort at the top of the ds@1952: ** loop. ds@1952: */ ds@1952: start = sqlite3VdbeCurrentAddr(v); ds@1952: if( testOp!=OP_Noop ){ ds@1952: sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0); ds@1952: sqlite3VdbeAddOp(v, testOp, iIdxCur, nxt); ds@1952: if( (topEq && !bRev) || (!btmEq && bRev) ){ ds@1952: sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC); ds@1952: } ds@1952: } ds@1952: if( topLimit | btmLimit ){ ds@1952: sqlite3VdbeAddOp(v, OP_Column, iIdxCur, nEq); ds@1952: sqlite3VdbeAddOp(v, OP_IsNull, 1, cont); ds@1952: } ds@1952: if( !omitTable ){ ds@1952: sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0); ds@1952: sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0); ds@1952: } ds@1952: ds@1952: /* Record the instruction used to terminate the loop. ds@1952: */ ds@1952: pLevel->op = bRev ? OP_Prev : OP_Next; ds@1952: pLevel->p1 = iIdxCur; ds@1952: pLevel->p2 = start; ds@1952: }else if( pLevel->flags & WHERE_COLUMN_EQ ){ ds@1952: /* Case 4: There is an index and all terms of the WHERE clause that ds@1952: ** refer to the index using the "==" or "IN" operators. ds@1952: */ ds@1952: int start; ds@1952: int nEq = pLevel->nEq; ds@1952: ds@1952: /* Generate code to evaluate all constraint terms using == or IN ds@1952: ** and leave the values of those terms on the stack. ds@1952: */ ds@1952: codeAllEqualityTerms(pParse, pLevel, &wc, notReady); ds@1952: nxt = pLevel->nxt; ds@1952: ds@1952: /* Generate a single key that will be used to both start and terminate ds@1952: ** the search ds@1952: */ ds@1952: buildIndexProbe(v, nEq, pIdx); ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0); ds@1952: ds@1952: /* Generate code (1) to move to the first matching element of the table. ds@1952: ** Then generate code (2) that jumps to "nxt" after the cursor is past ds@1952: ** the last matching element of the table. The code (1) is executed ds@1952: ** once to initialize the search, the code (2) is executed before each ds@1952: ** iteration of the scan to see if the scan has finished. */ ds@1952: if( bRev ){ ds@1952: /* Scan in reverse order */ ds@1952: sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, nxt); ds@1952: start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0); ds@1952: sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, nxt); ds@1952: pLevel->op = OP_Prev; ds@1952: }else{ ds@1952: /* Scan in the forward order */ ds@1952: sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, nxt); ds@1952: start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0); ds@1952: sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, nxt, "+", P3_STATIC); ds@1952: pLevel->op = OP_Next; ds@1952: } ds@1952: if( !omitTable ){ ds@1952: sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0); ds@1952: sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0); ds@1952: } ds@1952: pLevel->p1 = iIdxCur; ds@1952: pLevel->p2 = start; ds@1952: }else{ ds@1952: /* Case 5: There is no usable index. We must do a complete ds@1952: ** scan of the entire table. ds@1952: */ ds@1952: assert( omitTable==0 ); ds@1952: assert( bRev==0 ); ds@1952: pLevel->op = OP_Next; ds@1952: pLevel->p1 = iCur; ds@1952: pLevel->p2 = 1 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, brk); ds@1952: } ds@1952: notReady &= ~getMask(&maskSet, iCur); ds@1952: ds@1952: /* Insert code to test every subexpression that can be completely ds@1952: ** computed using the current set of tables. ds@1952: */ ds@1952: for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){ ds@1952: Expr *pE; ds@1952: if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue; ds@1952: if( (pTerm->prereqAll & notReady)!=0 ) continue; ds@1952: pE = pTerm->pExpr; ds@1952: assert( pE!=0 ); ds@1952: if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ ds@1952: continue; ds@1952: } ds@1952: sqlite3ExprIfFalse(pParse, pE, cont, 1); ds@1952: pTerm->flags |= TERM_CODED; ds@1952: } ds@1952: ds@1952: /* For a LEFT OUTER JOIN, generate code that will record the fact that ds@1952: ** at least one row of the right table has matched the left table. ds@1952: */ ds@1952: if( pLevel->iLeftJoin ){ ds@1952: pLevel->top = sqlite3VdbeCurrentAddr(v); ds@1952: sqlite3VdbeAddOp(v, OP_MemInt, 1, pLevel->iLeftJoin); ds@1952: VdbeComment((v, "# record LEFT JOIN hit")); ds@1952: for(pTerm=wc.a, j=0; jflags & (TERM_VIRTUAL|TERM_CODED) ) continue; ds@1952: if( (pTerm->prereqAll & notReady)!=0 ) continue; ds@1952: assert( pTerm->pExpr ); ds@1952: sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1); ds@1952: pTerm->flags |= TERM_CODED; ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: #ifdef SQLITE_TEST /* For testing and debugging use only */ ds@1952: /* Record in the query plan information about the current table ds@1952: ** and the index used to access it (if any). If the table itself ds@1952: ** is not used, its name is just '{}'. If no index is used ds@1952: ** the index is listed as "{}". If the primary key is used the ds@1952: ** index name is '*'. ds@1952: */ ds@1952: for(i=0; inSrc; i++){ ds@1952: char *z; ds@1952: int n; ds@1952: pLevel = &pWInfo->a[i]; ds@1952: pTabItem = &pTabList->a[pLevel->iFrom]; ds@1952: z = pTabItem->zAlias; ds@1952: if( z==0 ) z = pTabItem->pTab->zName; ds@1952: n = strlen(z); ds@1952: if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){ ds@1952: if( pLevel->flags & WHERE_IDX_ONLY ){ ds@1952: memcpy(&sqlite3_query_plan[nQPlan], "{}", 2); ds@1952: nQPlan += 2; ds@1952: }else{ ds@1952: memcpy(&sqlite3_query_plan[nQPlan], z, n); ds@1952: nQPlan += n; ds@1952: } ds@1952: sqlite3_query_plan[nQPlan++] = ' '; ds@1952: } ds@1952: if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){ ds@1952: memcpy(&sqlite3_query_plan[nQPlan], "* ", 2); ds@1952: nQPlan += 2; ds@1952: }else if( pLevel->pIdx==0 ){ ds@1952: memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3); ds@1952: nQPlan += 3; ds@1952: }else{ ds@1952: n = strlen(pLevel->pIdx->zName); ds@1952: if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){ ds@1952: memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n); ds@1952: nQPlan += n; ds@1952: sqlite3_query_plan[nQPlan++] = ' '; ds@1952: } ds@1952: } ds@1952: } ds@1952: while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){ ds@1952: sqlite3_query_plan[--nQPlan] = 0; ds@1952: } ds@1952: sqlite3_query_plan[nQPlan] = 0; ds@1952: nQPlan = 0; ds@1952: #endif /* SQLITE_TEST // Testing and debugging use only */ ds@1952: ds@1952: /* Record the continuation address in the WhereInfo structure. Then ds@1952: ** clean up and return. ds@1952: */ ds@1952: pWInfo->iContinue = cont; ds@1952: whereClauseClear(&wc); ds@1952: return pWInfo; ds@1952: ds@1952: /* Jump here if malloc fails */ ds@1952: whereBeginNoMem: ds@1952: whereClauseClear(&wc); ds@1952: whereInfoFree(pWInfo); ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Generate the end of the WHERE loop. See comments on ds@1952: ** sqlite3WhereBegin() for additional information. ds@1952: */ ds@1952: void sqlite3WhereEnd(WhereInfo *pWInfo){ ds@1952: Vdbe *v = pWInfo->pParse->pVdbe; ds@1952: int i; ds@1952: WhereLevel *pLevel; ds@1952: SrcList *pTabList = pWInfo->pTabList; ds@1952: ds@1952: /* Generate loop termination code. ds@1952: */ ds@1952: for(i=pTabList->nSrc-1; i>=0; i--){ ds@1952: pLevel = &pWInfo->a[i]; ds@1952: sqlite3VdbeResolveLabel(v, pLevel->cont); ds@1952: if( pLevel->op!=OP_Noop ){ ds@1952: sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2); ds@1952: } ds@1952: if( pLevel->nIn ){ ds@1952: struct InLoop *pIn; ds@1952: int j; ds@1952: sqlite3VdbeResolveLabel(v, pLevel->nxt); ds@1952: for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){ ds@1952: sqlite3VdbeJumpHere(v, pIn->topAddr+1); ds@1952: sqlite3VdbeAddOp(v, OP_Next, pIn->iCur, pIn->topAddr); ds@1952: sqlite3VdbeJumpHere(v, pIn->topAddr-1); ds@1952: } ds@1952: sqlite3_free(pLevel->aInLoop); ds@1952: } ds@1952: sqlite3VdbeResolveLabel(v, pLevel->brk); ds@1952: if( pLevel->iLeftJoin ){ ds@1952: int addr; ds@1952: addr = sqlite3VdbeAddOp(v, OP_IfMemPos, pLevel->iLeftJoin, 0); ds@1952: sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0); ds@1952: if( pLevel->iIdxCur>=0 ){ ds@1952: sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0); ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top); ds@1952: sqlite3VdbeJumpHere(v, addr); ds@1952: } ds@1952: } ds@1952: ds@1952: /* The "break" point is here, just past the end of the outer loop. ds@1952: ** Set it. ds@1952: */ ds@1952: sqlite3VdbeResolveLabel(v, pWInfo->iBreak); ds@1952: ds@1952: /* Close all of the cursors that were opened by sqlite3WhereBegin. ds@1952: */ ds@1952: for(i=0, pLevel=pWInfo->a; inSrc; i++, pLevel++){ ds@1952: struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; ds@1952: Table *pTab = pTabItem->pTab; ds@1952: assert( pTab!=0 ); ds@1952: if( pTab->isEphem || pTab->pSelect ) continue; ds@1952: if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){ ds@1952: sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0); ds@1952: } ds@1952: if( pLevel->pIdx!=0 ){ ds@1952: sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0); ds@1952: } ds@1952: ds@1952: /* Make cursor substitutions for cases where we want to use ds@1952: ** just the index and never reference the table. ds@1952: ** ds@1952: ** Calls to the code generator in between sqlite3WhereBegin and ds@1952: ** sqlite3WhereEnd will have created code that references the table ds@1952: ** directly. This loop scans all that code looking for opcodes ds@1952: ** that reference the table and converts them into opcodes that ds@1952: ** reference the index. ds@1952: */ ds@1952: if( pLevel->flags & WHERE_IDX_ONLY ){ ds@1952: int k, j, last; ds@1952: VdbeOp *pOp; ds@1952: Index *pIdx = pLevel->pIdx; ds@1952: ds@1952: assert( pIdx!=0 ); ds@1952: pOp = sqlite3VdbeGetOp(v, pWInfo->iTop); ds@1952: last = sqlite3VdbeCurrentAddr(v); ds@1952: for(k=pWInfo->iTop; kp1!=pLevel->iTabCur ) continue; ds@1952: if( pOp->opcode==OP_Column ){ ds@1952: pOp->p1 = pLevel->iIdxCur; ds@1952: for(j=0; jnColumn; j++){ ds@1952: if( pOp->p2==pIdx->aiColumn[j] ){ ds@1952: pOp->p2 = j; ds@1952: break; ds@1952: } ds@1952: } ds@1952: }else if( pOp->opcode==OP_Rowid ){ ds@1952: pOp->p1 = pLevel->iIdxCur; ds@1952: pOp->opcode = OP_IdxRowid; ds@1952: }else if( pOp->opcode==OP_NullRow ){ ds@1952: pOp->opcode = OP_Noop; ds@1952: } ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: /* Final cleanup ds@1952: */ ds@1952: whereInfoFree(pWInfo); ds@1952: return; ds@1952: }