| Index: third_party/sqlite/sqlite-src-3100200/src/where.c
|
| diff --git a/third_party/sqlite/src/src/where.c b/third_party/sqlite/sqlite-src-3100200/src/where.c
|
| similarity index 57%
|
| copy from third_party/sqlite/src/src/where.c
|
| copy to third_party/sqlite/sqlite-src-3100200/src/where.c
|
| index 793b01d1678edeebc90426661e82a05775a6e6a2..e86e26ef1ae8c5805e51a88a7495eb29115538d4 100644
|
| --- a/third_party/sqlite/src/src/where.c
|
| +++ b/third_party/sqlite/sqlite-src-3100200/src/where.c
|
| @@ -19,6 +19,15 @@
|
| #include "sqliteInt.h"
|
| #include "whereInt.h"
|
|
|
| +/* Forward declaration of methods */
|
| +static int whereLoopResize(sqlite3*, WhereLoop*, int);
|
| +
|
| +/* Test variable that can be set to enable WHERE tracing */
|
| +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
|
| +/***/ int sqlite3WhereTrace = 0;
|
| +#endif
|
| +
|
| +
|
| /*
|
| ** Return the estimated number of output rows from a WHERE clause
|
| */
|
| @@ -60,9 +69,11 @@ int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
|
| }
|
|
|
| /*
|
| -** Return TRUE if an UPDATE or DELETE statement can operate directly on
|
| -** the rowids returned by a WHERE clause. Return FALSE if doing an
|
| -** UPDATE or DELETE might change subsequent WHERE clause results.
|
| +** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
|
| +** operate directly on the rowis returned by a WHERE clause. Return
|
| +** ONEPASS_SINGLE (1) if the statement can operation directly because only
|
| +** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
|
| +** optimization can be used on multiple
|
| **
|
| ** If the ONEPASS optimization is used (if this routine returns true)
|
| ** then also write the indices of open cursors used by ONEPASS
|
| @@ -76,7 +87,14 @@ int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
|
| */
|
| int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
|
| memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
|
| - return pWInfo->okOnePass;
|
| +#ifdef WHERETRACE_ENABLED
|
| + if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
|
| + sqlite3DebugPrintf("%s cursors: %d %d\n",
|
| + pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
|
| + aiCur[0], aiCur[1]);
|
| + }
|
| +#endif
|
| + return pWInfo->eOnePass;
|
| }
|
|
|
| /*
|
| @@ -128,152 +146,10 @@ whereOrInsert_done:
|
| }
|
|
|
| /*
|
| -** Initialize a preallocated WhereClause structure.
|
| -*/
|
| -static void whereClauseInit(
|
| - WhereClause *pWC, /* The WhereClause to be initialized */
|
| - WhereInfo *pWInfo /* The WHERE processing context */
|
| -){
|
| - pWC->pWInfo = pWInfo;
|
| - pWC->pOuter = 0;
|
| - pWC->nTerm = 0;
|
| - pWC->nSlot = ArraySize(pWC->aStatic);
|
| - pWC->a = pWC->aStatic;
|
| -}
|
| -
|
| -/* Forward reference */
|
| -static void whereClauseClear(WhereClause*);
|
| -
|
| -/*
|
| -** Deallocate all memory associated with a WhereOrInfo object.
|
| -*/
|
| -static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
|
| - whereClauseClear(&p->wc);
|
| - sqlite3DbFree(db, p);
|
| -}
|
| -
|
| -/*
|
| -** Deallocate all memory associated with a WhereAndInfo object.
|
| -*/
|
| -static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
|
| - whereClauseClear(&p->wc);
|
| - sqlite3DbFree(db, p);
|
| -}
|
| -
|
| -/*
|
| -** Deallocate a WhereClause structure. The WhereClause structure
|
| -** itself is not freed. This routine is the inverse of whereClauseInit().
|
| -*/
|
| -static void whereClauseClear(WhereClause *pWC){
|
| - int i;
|
| - WhereTerm *a;
|
| - sqlite3 *db = pWC->pWInfo->pParse->db;
|
| - for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
|
| - if( a->wtFlags & TERM_DYNAMIC ){
|
| - sqlite3ExprDelete(db, a->pExpr);
|
| - }
|
| - if( a->wtFlags & TERM_ORINFO ){
|
| - whereOrInfoDelete(db, a->u.pOrInfo);
|
| - }else if( a->wtFlags & TERM_ANDINFO ){
|
| - whereAndInfoDelete(db, a->u.pAndInfo);
|
| - }
|
| - }
|
| - if( pWC->a!=pWC->aStatic ){
|
| - sqlite3DbFree(db, pWC->a);
|
| - }
|
| -}
|
| -
|
| -/*
|
| -** Add a single new WhereTerm entry to the WhereClause object pWC.
|
| -** The new WhereTerm object is constructed from Expr p and with wtFlags.
|
| -** The index in pWC->a[] of the new WhereTerm is returned on success.
|
| -** 0 is returned if the new WhereTerm could not be added due to a memory
|
| -** allocation error. The memory allocation failure will be recorded in
|
| -** the db->mallocFailed flag so that higher-level functions can detect it.
|
| -**
|
| -** This routine will increase the size of the pWC->a[] array as necessary.
|
| -**
|
| -** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
|
| -** for freeing the expression p is assumed by the WhereClause object pWC.
|
| -** This is true even if this routine fails to allocate a new WhereTerm.
|
| -**
|
| -** WARNING: This routine might reallocate the space used to store
|
| -** WhereTerms. All pointers to WhereTerms should be invalidated after
|
| -** calling this routine. Such pointers may be reinitialized by referencing
|
| -** the pWC->a[] array.
|
| -*/
|
| -static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
|
| - WhereTerm *pTerm;
|
| - int idx;
|
| - testcase( wtFlags & TERM_VIRTUAL );
|
| - if( pWC->nTerm>=pWC->nSlot ){
|
| - WhereTerm *pOld = pWC->a;
|
| - sqlite3 *db = pWC->pWInfo->pParse->db;
|
| - pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
|
| - if( pWC->a==0 ){
|
| - if( wtFlags & TERM_DYNAMIC ){
|
| - sqlite3ExprDelete(db, p);
|
| - }
|
| - pWC->a = pOld;
|
| - return 0;
|
| - }
|
| - memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
|
| - if( pOld!=pWC->aStatic ){
|
| - sqlite3DbFree(db, pOld);
|
| - }
|
| - pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
|
| - }
|
| - pTerm = &pWC->a[idx = pWC->nTerm++];
|
| - if( p && ExprHasProperty(p, EP_Unlikely) ){
|
| - pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
|
| - }else{
|
| - pTerm->truthProb = 1;
|
| - }
|
| - pTerm->pExpr = sqlite3ExprSkipCollate(p);
|
| - pTerm->wtFlags = wtFlags;
|
| - pTerm->pWC = pWC;
|
| - pTerm->iParent = -1;
|
| - return idx;
|
| -}
|
| -
|
| -/*
|
| -** This routine identifies subexpressions in the WHERE clause where
|
| -** each subexpression is separated by the AND operator or some other
|
| -** operator specified in the op parameter. The WhereClause structure
|
| -** is filled with pointers to subexpressions. For example:
|
| -**
|
| -** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
|
| -** \________/ \_______________/ \________________/
|
| -** slot[0] slot[1] slot[2]
|
| -**
|
| -** The original WHERE clause in pExpr is unaltered. All this routine
|
| -** does is make slot[] entries point to substructure within pExpr.
|
| -**
|
| -** In the previous sentence and in the diagram, "slot[]" refers to
|
| -** the WhereClause.a[] array. The slot[] array grows as needed to contain
|
| -** all terms of the WHERE clause.
|
| -*/
|
| -static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
|
| - pWC->op = op;
|
| - if( pExpr==0 ) return;
|
| - if( pExpr->op!=op ){
|
| - whereClauseInsert(pWC, pExpr, 0);
|
| - }else{
|
| - whereSplit(pWC, pExpr->pLeft, op);
|
| - whereSplit(pWC, pExpr->pRight, op);
|
| - }
|
| -}
|
| -
|
| -/*
|
| -** Initialize a WhereMaskSet object
|
| -*/
|
| -#define initMaskSet(P) (P)->n=0
|
| -
|
| -/*
|
| ** Return the bitmask for the given cursor number. Return 0 if
|
| ** iCursor is not in the set.
|
| */
|
| -static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
|
| +Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
|
| int i;
|
| assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
|
| for(i=0; i<pMaskSet->n; i++){
|
| @@ -298,174 +174,45 @@ static void createMask(WhereMaskSet *pMaskSet, int iCursor){
|
| }
|
|
|
| /*
|
| -** These routines walk (recursively) an expression tree and generate
|
| -** a bitmask indicating which tables are used in that expression
|
| -** tree.
|
| -*/
|
| -static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
|
| -static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
|
| -static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
|
| - Bitmask mask = 0;
|
| - if( p==0 ) return 0;
|
| - if( p->op==TK_COLUMN ){
|
| - mask = getMask(pMaskSet, p->iTable);
|
| - return mask;
|
| - }
|
| - mask = exprTableUsage(pMaskSet, p->pRight);
|
| - mask |= exprTableUsage(pMaskSet, p->pLeft);
|
| - if( ExprHasProperty(p, EP_xIsSelect) ){
|
| - mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
|
| - }else{
|
| - mask |= exprListTableUsage(pMaskSet, p->x.pList);
|
| - }
|
| - return mask;
|
| -}
|
| -static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
|
| - int i;
|
| - Bitmask mask = 0;
|
| - if( pList ){
|
| - for(i=0; i<pList->nExpr; i++){
|
| - mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
|
| - }
|
| - }
|
| - return mask;
|
| -}
|
| -static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
|
| - Bitmask mask = 0;
|
| - while( pS ){
|
| - SrcList *pSrc = pS->pSrc;
|
| - mask |= exprListTableUsage(pMaskSet, pS->pEList);
|
| - mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
|
| - mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
|
| - mask |= exprTableUsage(pMaskSet, pS->pWhere);
|
| - mask |= exprTableUsage(pMaskSet, pS->pHaving);
|
| - if( ALWAYS(pSrc!=0) ){
|
| - int i;
|
| - for(i=0; i<pSrc->nSrc; i++){
|
| - mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
|
| - mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
|
| - }
|
| - }
|
| - pS = pS->pPrior;
|
| - }
|
| - return mask;
|
| -}
|
| -
|
| -/*
|
| -** Return TRUE if the given operator is one of the operators that is
|
| -** allowed for an indexable WHERE clause term. The allowed operators are
|
| -** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
|
| -*/
|
| -static int allowedOp(int op){
|
| - assert( TK_GT>TK_EQ && TK_GT<TK_GE );
|
| - assert( TK_LT>TK_EQ && TK_LT<TK_GE );
|
| - assert( TK_LE>TK_EQ && TK_LE<TK_GE );
|
| - assert( TK_GE==TK_EQ+4 );
|
| - return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
|
| -}
|
| -
|
| -/*
|
| -** Commute a comparison operator. Expressions of the form "X op Y"
|
| -** are converted into "Y op X".
|
| -**
|
| -** If left/right precedence rules come into play when determining the
|
| -** collating sequence, then COLLATE operators are adjusted to ensure
|
| -** that the collating sequence does not change. For example:
|
| -** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
|
| -** the left hand side of a comparison overrides any collation sequence
|
| -** attached to the right. For the same reason the EP_Collate flag
|
| -** is not commuted.
|
| -*/
|
| -static void exprCommute(Parse *pParse, Expr *pExpr){
|
| - u16 expRight = (pExpr->pRight->flags & EP_Collate);
|
| - u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
|
| - assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
|
| - if( expRight==expLeft ){
|
| - /* Either X and Y both have COLLATE operator or neither do */
|
| - if( expRight ){
|
| - /* Both X and Y have COLLATE operators. Make sure X is always
|
| - ** used by clearing the EP_Collate flag from Y. */
|
| - pExpr->pRight->flags &= ~EP_Collate;
|
| - }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
|
| - /* Neither X nor Y have COLLATE operators, but X has a non-default
|
| - ** collating sequence. So add the EP_Collate marker on X to cause
|
| - ** it to be searched first. */
|
| - pExpr->pLeft->flags |= EP_Collate;
|
| - }
|
| - }
|
| - SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
|
| - if( pExpr->op>=TK_GT ){
|
| - assert( TK_LT==TK_GT+2 );
|
| - assert( TK_GE==TK_LE+2 );
|
| - assert( TK_GT>TK_EQ );
|
| - assert( TK_GT<TK_LE );
|
| - assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
|
| - pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
|
| - }
|
| -}
|
| -
|
| -/*
|
| -** Translate from TK_xx operator to WO_xx bitmask.
|
| -*/
|
| -static u16 operatorMask(int op){
|
| - u16 c;
|
| - assert( allowedOp(op) );
|
| - if( op==TK_IN ){
|
| - c = WO_IN;
|
| - }else if( op==TK_ISNULL ){
|
| - c = WO_ISNULL;
|
| - }else{
|
| - assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
|
| - c = (u16)(WO_EQ<<(op-TK_EQ));
|
| - }
|
| - assert( op!=TK_ISNULL || c==WO_ISNULL );
|
| - assert( op!=TK_IN || c==WO_IN );
|
| - assert( op!=TK_EQ || c==WO_EQ );
|
| - assert( op!=TK_LT || c==WO_LT );
|
| - assert( op!=TK_LE || c==WO_LE );
|
| - assert( op!=TK_GT || c==WO_GT );
|
| - assert( op!=TK_GE || c==WO_GE );
|
| - return c;
|
| -}
|
| -
|
| -/*
|
| ** Advance to the next WhereTerm that matches according to the criteria
|
| ** established when the pScan object was initialized by whereScanInit().
|
| ** Return NULL if there are no more matching WhereTerms.
|
| */
|
| static WhereTerm *whereScanNext(WhereScan *pScan){
|
| int iCur; /* The cursor on the LHS of the term */
|
| - int iColumn; /* The column on the LHS of the term. -1 for IPK */
|
| + i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
|
| Expr *pX; /* An expression being tested */
|
| WhereClause *pWC; /* Shorthand for pScan->pWC */
|
| WhereTerm *pTerm; /* The term being tested */
|
| int k = pScan->k; /* Where to start scanning */
|
|
|
| while( pScan->iEquiv<=pScan->nEquiv ){
|
| - iCur = pScan->aEquiv[pScan->iEquiv-2];
|
| - iColumn = pScan->aEquiv[pScan->iEquiv-1];
|
| + iCur = pScan->aiCur[pScan->iEquiv-1];
|
| + iColumn = pScan->aiColumn[pScan->iEquiv-1];
|
| + if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
|
| while( (pWC = pScan->pWC)!=0 ){
|
| for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
|
| if( pTerm->leftCursor==iCur
|
| && pTerm->u.leftColumn==iColumn
|
| - && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
|
| + && (iColumn!=XN_EXPR
|
| + || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
|
| + && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
|
| ){
|
| if( (pTerm->eOperator & WO_EQUIV)!=0
|
| - && pScan->nEquiv<ArraySize(pScan->aEquiv)
|
| + && pScan->nEquiv<ArraySize(pScan->aiCur)
|
| + && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
|
| ){
|
| int j;
|
| - pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
|
| - assert( pX->op==TK_COLUMN );
|
| - for(j=0; j<pScan->nEquiv; j+=2){
|
| - if( pScan->aEquiv[j]==pX->iTable
|
| - && pScan->aEquiv[j+1]==pX->iColumn ){
|
| + for(j=0; j<pScan->nEquiv; j++){
|
| + if( pScan->aiCur[j]==pX->iTable
|
| + && pScan->aiColumn[j]==pX->iColumn ){
|
| break;
|
| }
|
| }
|
| if( j==pScan->nEquiv ){
|
| - pScan->aEquiv[j] = pX->iTable;
|
| - pScan->aEquiv[j+1] = pX->iColumn;
|
| - pScan->nEquiv += 2;
|
| + pScan->aiCur[j] = pX->iTable;
|
| + pScan->aiColumn[j] = pX->iColumn;
|
| + pScan->nEquiv++;
|
| }
|
| }
|
| if( (pTerm->eOperator & pScan->opMask)!=0 ){
|
| @@ -485,11 +232,12 @@ static WhereTerm *whereScanNext(WhereScan *pScan){
|
| continue;
|
| }
|
| }
|
| - if( (pTerm->eOperator & WO_EQ)!=0
|
| + if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
|
| && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
|
| - && pX->iTable==pScan->aEquiv[0]
|
| - && pX->iColumn==pScan->aEquiv[1]
|
| + && pX->iTable==pScan->aiCur[0]
|
| + && pX->iColumn==pScan->aiColumn[0]
|
| ){
|
| + testcase( pTerm->eOperator & WO_IS );
|
| continue;
|
| }
|
| pScan->k = k+1;
|
| @@ -502,7 +250,7 @@ static WhereTerm *whereScanNext(WhereScan *pScan){
|
| }
|
| pScan->pWC = pScan->pOrigWC;
|
| k = 0;
|
| - pScan->iEquiv += 2;
|
| + pScan->iEquiv++;
|
| }
|
| return 0;
|
| }
|
| @@ -531,16 +279,19 @@ static WhereTerm *whereScanInit(
|
| u32 opMask, /* Operator(s) to scan for */
|
| Index *pIdx /* Must be compatible with this index */
|
| ){
|
| - int j;
|
| + int j = 0;
|
|
|
| /* memset(pScan, 0, sizeof(*pScan)); */
|
| pScan->pOrigWC = pWC;
|
| pScan->pWC = pWC;
|
| + pScan->pIdxExpr = 0;
|
| + if( pIdx ){
|
| + j = iColumn;
|
| + iColumn = pIdx->aiColumn[j];
|
| + if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
|
| + }
|
| if( pIdx && iColumn>=0 ){
|
| pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
|
| - for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
|
| - if( NEVER(j>pIdx->nColumn) ) return 0;
|
| - }
|
| pScan->zCollName = pIdx->azColl[j];
|
| }else{
|
| pScan->idxaff = 0;
|
| @@ -548,10 +299,10 @@ static WhereTerm *whereScanInit(
|
| }
|
| pScan->opMask = opMask;
|
| pScan->k = 0;
|
| - pScan->aEquiv[0] = iCur;
|
| - pScan->aEquiv[1] = iColumn;
|
| - pScan->nEquiv = 2;
|
| - pScan->iEquiv = 2;
|
| + pScan->aiCur[0] = iCur;
|
| + pScan->aiColumn[0] = iColumn;
|
| + pScan->nEquiv = 1;
|
| + pScan->iEquiv = 1;
|
| return whereScanNext(pScan);
|
| }
|
|
|
| @@ -561,15 +312,16 @@ static WhereTerm *whereScanInit(
|
| ** the WO_xx operator codes specified by the op parameter.
|
| ** Return a pointer to the term. Return 0 if not found.
|
| **
|
| +** If pIdx!=0 then search for terms matching the iColumn-th column of pIdx
|
| +** rather than the iColumn-th column of table iCur.
|
| +**
|
| ** The term returned might by Y=<expr> if there is another constraint in
|
| ** the WHERE clause that specifies that X=Y. Any such constraints will be
|
| ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
|
| -** aEquiv[] array holds X and all its equivalents, with each SQL variable
|
| -** taking up two slots in aEquiv[]. The first slot is for the cursor number
|
| -** and the second is for the column number. There are 22 slots in aEquiv[]
|
| -** so that means we can look for X plus up to 10 other equivalent values.
|
| -** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
|
| -** and ... and A9=A10 and A10=<expr>.
|
| +** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
|
| +** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
|
| +** other equivalent values. Hence a search for X will return <expr> if X=A1
|
| +** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
|
| **
|
| ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
|
| ** then try for the one with no dependencies on <expr> - in other words where
|
| @@ -578,7 +330,7 @@ static WhereTerm *whereScanInit(
|
| ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
|
| ** exist, try to return a term that does not use WO_EQUIV.
|
| */
|
| -static WhereTerm *findTerm(
|
| +WhereTerm *sqlite3WhereFindTerm(
|
| WhereClause *pWC, /* The WHERE clause to be searched */
|
| int iCur, /* Cursor number of LHS */
|
| int iColumn, /* Column number of LHS */
|
| @@ -591,9 +343,11 @@ static WhereTerm *findTerm(
|
| WhereScan scan;
|
|
|
| p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
|
| + op &= WO_EQ|WO_IS;
|
| while( p ){
|
| if( (p->prereqRight & notReady)==0 ){
|
| - if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
|
| + if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
|
| + testcase( p->eOperator & WO_IS );
|
| return p;
|
| }
|
| if( pResult==0 ) pResult = p;
|
| @@ -603,892 +357,171 @@ static WhereTerm *findTerm(
|
| return pResult;
|
| }
|
|
|
| -/* Forward reference */
|
| -static void exprAnalyze(SrcList*, WhereClause*, int);
|
| -
|
| /*
|
| -** Call exprAnalyze on all terms in a WHERE clause.
|
| +** This function searches pList for an entry that matches the iCol-th column
|
| +** of index pIdx.
|
| +**
|
| +** If such an expression is found, its index in pList->a[] is returned. If
|
| +** no expression is found, -1 is returned.
|
| */
|
| -static void exprAnalyzeAll(
|
| - SrcList *pTabList, /* the FROM clause */
|
| - WhereClause *pWC /* the WHERE clause to be analyzed */
|
| +static int findIndexCol(
|
| + Parse *pParse, /* Parse context */
|
| + ExprList *pList, /* Expression list to search */
|
| + int iBase, /* Cursor for table associated with pIdx */
|
| + Index *pIdx, /* Index to match column of */
|
| + int iCol /* Column of index to match */
|
| ){
|
| int i;
|
| - for(i=pWC->nTerm-1; i>=0; i--){
|
| - exprAnalyze(pTabList, pWC, i);
|
| - }
|
| -}
|
| + const char *zColl = pIdx->azColl[iCol];
|
|
|
| -#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
|
| -/*
|
| -** Check to see if the given expression is a LIKE or GLOB operator that
|
| -** can be optimized using inequality constraints. Return TRUE if it is
|
| -** so and false if not.
|
| -**
|
| -** In order for the operator to be optimizible, the RHS must be a string
|
| -** literal that does not begin with a wildcard.
|
| -*/
|
| -static int isLikeOrGlob(
|
| - Parse *pParse, /* Parsing and code generating context */
|
| - Expr *pExpr, /* Test this expression */
|
| - Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
|
| - int *pisComplete, /* True if the only wildcard is % in the last character */
|
| - int *pnoCase /* True if uppercase is equivalent to lowercase */
|
| -){
|
| - const char *z = 0; /* String on RHS of LIKE operator */
|
| - Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
|
| - ExprList *pList; /* List of operands to the LIKE operator */
|
| - int c; /* One character in z[] */
|
| - int cnt; /* Number of non-wildcard prefix characters */
|
| - char wc[3]; /* Wildcard characters */
|
| - sqlite3 *db = pParse->db; /* Database connection */
|
| - sqlite3_value *pVal = 0;
|
| - int op; /* Opcode of pRight */
|
| -
|
| - if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
|
| - return 0;
|
| - }
|
| -#ifdef SQLITE_EBCDIC
|
| - if( *pnoCase ) return 0;
|
| -#endif
|
| - pList = pExpr->x.pList;
|
| - pLeft = pList->a[1].pExpr;
|
| - if( pLeft->op!=TK_COLUMN
|
| - || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
|
| - || IsVirtual(pLeft->pTab)
|
| - ){
|
| - /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
|
| - ** be the name of an indexed column with TEXT affinity. */
|
| - return 0;
|
| - }
|
| - assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
|
| -
|
| - pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
|
| - op = pRight->op;
|
| - if( op==TK_VARIABLE ){
|
| - Vdbe *pReprepare = pParse->pReprepare;
|
| - int iCol = pRight->iColumn;
|
| - pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
|
| - if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
|
| - z = (char *)sqlite3_value_text(pVal);
|
| - }
|
| - sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
|
| - assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
|
| - }else if( op==TK_STRING ){
|
| - z = pRight->u.zToken;
|
| - }
|
| - if( z ){
|
| - cnt = 0;
|
| - while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
|
| - cnt++;
|
| - }
|
| - if( cnt!=0 && 255!=(u8)z[cnt-1] ){
|
| - Expr *pPrefix;
|
| - *pisComplete = c==wc[0] && z[cnt+1]==0;
|
| - pPrefix = sqlite3Expr(db, TK_STRING, z);
|
| - if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
|
| - *ppPrefix = pPrefix;
|
| - if( op==TK_VARIABLE ){
|
| - Vdbe *v = pParse->pVdbe;
|
| - sqlite3VdbeSetVarmask(v, pRight->iColumn);
|
| - if( *pisComplete && pRight->u.zToken[1] ){
|
| - /* If the rhs of the LIKE expression is a variable, and the current
|
| - ** value of the variable means there is no need to invoke the LIKE
|
| - ** function, then no OP_Variable will be added to the program.
|
| - ** This causes problems for the sqlite3_bind_parameter_name()
|
| - ** API. To work around them, add a dummy OP_Variable here.
|
| - */
|
| - int r1 = sqlite3GetTempReg(pParse);
|
| - sqlite3ExprCodeTarget(pParse, pRight, r1);
|
| - sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
|
| - sqlite3ReleaseTempReg(pParse, r1);
|
| - }
|
| + for(i=0; i<pList->nExpr; i++){
|
| + Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
|
| + if( p->op==TK_COLUMN
|
| + && p->iColumn==pIdx->aiColumn[iCol]
|
| + && p->iTable==iBase
|
| + ){
|
| + CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
|
| + if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
|
| + return i;
|
| }
|
| - }else{
|
| - z = 0;
|
| }
|
| }
|
|
|
| - sqlite3ValueFree(pVal);
|
| - return (z!=0);
|
| + return -1;
|
| }
|
| -#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
|
| -
|
|
|
| -#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| /*
|
| -** Check to see if the given expression is of the form
|
| -**
|
| -** column MATCH expr
|
| -**
|
| -** If it is then return TRUE. If not, return FALSE.
|
| +** Return TRUE if the iCol-th column of index pIdx is NOT NULL
|
| */
|
| -static int isMatchOfColumn(
|
| - Expr *pExpr /* Test this expression */
|
| -){
|
| - ExprList *pList;
|
| -
|
| - if( pExpr->op!=TK_FUNCTION ){
|
| - return 0;
|
| - }
|
| - if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
|
| - return 0;
|
| - }
|
| - pList = pExpr->x.pList;
|
| - if( pList->nExpr!=2 ){
|
| - return 0;
|
| - }
|
| - if( pList->a[1].pExpr->op != TK_COLUMN ){
|
| - return 0;
|
| - }
|
| - return 1;
|
| -}
|
| -#endif /* SQLITE_OMIT_VIRTUALTABLE */
|
| +static int indexColumnNotNull(Index *pIdx, int iCol){
|
| + int j;
|
| + assert( pIdx!=0 );
|
| + assert( iCol>=0 && iCol<pIdx->nColumn );
|
| + j = pIdx->aiColumn[iCol];
|
| + if( j>=0 ){
|
| + return pIdx->pTable->aCol[j].notNull;
|
| + }else if( j==(-1) ){
|
| + return 1;
|
| + }else{
|
| + assert( j==(-2) );
|
| + return 0; /* Assume an indexed expression can always yield a NULL */
|
|
|
| -/*
|
| -** If the pBase expression originated in the ON or USING clause of
|
| -** a join, then transfer the appropriate markings over to derived.
|
| -*/
|
| -static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
|
| - if( pDerived ){
|
| - pDerived->flags |= pBase->flags & EP_FromJoin;
|
| - pDerived->iRightJoinTable = pBase->iRightJoinTable;
|
| }
|
| }
|
|
|
| -#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
|
| /*
|
| -** Analyze a term that consists of two or more OR-connected
|
| -** subterms. So in:
|
| -**
|
| -** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
|
| -** ^^^^^^^^^^^^^^^^^^^^
|
| -**
|
| -** This routine analyzes terms such as the middle term in the above example.
|
| -** A WhereOrTerm object is computed and attached to the term under
|
| -** analysis, regardless of the outcome of the analysis. Hence:
|
| -**
|
| -** WhereTerm.wtFlags |= TERM_ORINFO
|
| -** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
|
| -**
|
| -** The term being analyzed must have two or more of OR-connected subterms.
|
| -** A single subterm might be a set of AND-connected sub-subterms.
|
| -** Examples of terms under analysis:
|
| -**
|
| -** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
|
| -** (B) x=expr1 OR expr2=x OR x=expr3
|
| -** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
|
| -** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
|
| -** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
|
| -**
|
| -** CASE 1:
|
| -**
|
| -** If all subterms are of the form T.C=expr for some single column of C and
|
| -** a single table T (as shown in example B above) then create a new virtual
|
| -** term that is an equivalent IN expression. In other words, if the term
|
| -** being analyzed is:
|
| -**
|
| -** x = expr1 OR expr2 = x OR x = expr3
|
| -**
|
| -** then create a new virtual term like this:
|
| -**
|
| -** x IN (expr1,expr2,expr3)
|
| -**
|
| -** CASE 2:
|
| -**
|
| -** If all subterms are indexable by a single table T, then set
|
| -**
|
| -** WhereTerm.eOperator = WO_OR
|
| -** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
|
| -**
|
| -** A subterm is "indexable" if it is of the form
|
| -** "T.C <op> <expr>" where C is any column of table T and
|
| -** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
|
| -** A subterm is also indexable if it is an AND of two or more
|
| -** subsubterms at least one of which is indexable. Indexable AND
|
| -** subterms have their eOperator set to WO_AND and they have
|
| -** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
|
| -**
|
| -** From another point of view, "indexable" means that the subterm could
|
| -** potentially be used with an index if an appropriate index exists.
|
| -** This analysis does not consider whether or not the index exists; that
|
| -** is decided elsewhere. This analysis only looks at whether subterms
|
| -** appropriate for indexing exist.
|
| -**
|
| -** All examples A through E above satisfy case 2. But if a term
|
| -** also satisfies case 1 (such as B) we know that the optimizer will
|
| -** always prefer case 1, so in that case we pretend that case 2 is not
|
| -** satisfied.
|
| -**
|
| -** It might be the case that multiple tables are indexable. For example,
|
| -** (E) above is indexable on tables P, Q, and R.
|
| -**
|
| -** Terms that satisfy case 2 are candidates for lookup by using
|
| -** separate indices to find rowids for each subterm and composing
|
| -** the union of all rowids using a RowSet object. This is similar
|
| -** to "bitmap indices" in other database engines.
|
| -**
|
| -** OTHERWISE:
|
| +** Return true if the DISTINCT expression-list passed as the third argument
|
| +** is redundant.
|
| **
|
| -** If neither case 1 nor case 2 apply, then leave the eOperator set to
|
| -** zero. This term is not useful for search.
|
| +** A DISTINCT list is redundant if any subset of the columns in the
|
| +** DISTINCT list are collectively unique and individually non-null.
|
| */
|
| -static void exprAnalyzeOrTerm(
|
| - SrcList *pSrc, /* the FROM clause */
|
| - WhereClause *pWC, /* the complete WHERE clause */
|
| - int idxTerm /* Index of the OR-term to be analyzed */
|
| +static int isDistinctRedundant(
|
| + Parse *pParse, /* Parsing context */
|
| + SrcList *pTabList, /* The FROM clause */
|
| + WhereClause *pWC, /* The WHERE clause */
|
| + ExprList *pDistinct /* The result set that needs to be DISTINCT */
|
| ){
|
| - WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
|
| - Parse *pParse = pWInfo->pParse; /* Parser context */
|
| - sqlite3 *db = pParse->db; /* Database connection */
|
| - WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
|
| - Expr *pExpr = pTerm->pExpr; /* The expression of the term */
|
| - int i; /* Loop counters */
|
| - WhereClause *pOrWc; /* Breakup of pTerm into subterms */
|
| - WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
|
| - WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
|
| - Bitmask chngToIN; /* Tables that might satisfy case 1 */
|
| - Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
|
| + Table *pTab;
|
| + Index *pIdx;
|
| + int i;
|
| + int iBase;
|
|
|
| - /*
|
| - ** Break the OR clause into its separate subterms. The subterms are
|
| - ** stored in a WhereClause structure containing within the WhereOrInfo
|
| - ** object that is attached to the original OR clause term.
|
| - */
|
| - assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
|
| - assert( pExpr->op==TK_OR );
|
| - pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
|
| - if( pOrInfo==0 ) return;
|
| - pTerm->wtFlags |= TERM_ORINFO;
|
| - pOrWc = &pOrInfo->wc;
|
| - whereClauseInit(pOrWc, pWInfo);
|
| - whereSplit(pOrWc, pExpr, TK_OR);
|
| - exprAnalyzeAll(pSrc, pOrWc);
|
| - if( db->mallocFailed ) return;
|
| - assert( pOrWc->nTerm>=2 );
|
| + /* If there is more than one table or sub-select in the FROM clause of
|
| + ** this query, then it will not be possible to show that the DISTINCT
|
| + ** clause is redundant. */
|
| + if( pTabList->nSrc!=1 ) return 0;
|
| + iBase = pTabList->a[0].iCursor;
|
| + pTab = pTabList->a[0].pTab;
|
|
|
| - /*
|
| - ** Compute the set of tables that might satisfy cases 1 or 2.
|
| + /* If any of the expressions is an IPK column on table iBase, then return
|
| + ** true. Note: The (p->iTable==iBase) part of this test may be false if the
|
| + ** current SELECT is a correlated sub-query.
|
| */
|
| - indexable = ~(Bitmask)0;
|
| - chngToIN = ~(Bitmask)0;
|
| - for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
|
| - if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
|
| - WhereAndInfo *pAndInfo;
|
| - assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
|
| - chngToIN = 0;
|
| - pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
|
| - if( pAndInfo ){
|
| - WhereClause *pAndWC;
|
| - WhereTerm *pAndTerm;
|
| - int j;
|
| - Bitmask b = 0;
|
| - pOrTerm->u.pAndInfo = pAndInfo;
|
| - pOrTerm->wtFlags |= TERM_ANDINFO;
|
| - pOrTerm->eOperator = WO_AND;
|
| - pAndWC = &pAndInfo->wc;
|
| - whereClauseInit(pAndWC, pWC->pWInfo);
|
| - whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
|
| - exprAnalyzeAll(pSrc, pAndWC);
|
| - pAndWC->pOuter = pWC;
|
| - testcase( db->mallocFailed );
|
| - if( !db->mallocFailed ){
|
| - for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
|
| - assert( pAndTerm->pExpr );
|
| - if( allowedOp(pAndTerm->pExpr->op) ){
|
| - b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
|
| - }
|
| - }
|
| - }
|
| - indexable &= b;
|
| - }
|
| - }else if( pOrTerm->wtFlags & TERM_COPIED ){
|
| - /* Skip this term for now. We revisit it when we process the
|
| - ** corresponding TERM_VIRTUAL term */
|
| - }else{
|
| - Bitmask b;
|
| - b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
|
| - if( pOrTerm->wtFlags & TERM_VIRTUAL ){
|
| - WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
|
| - b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
|
| - }
|
| - indexable &= b;
|
| - if( (pOrTerm->eOperator & WO_EQ)==0 ){
|
| - chngToIN = 0;
|
| - }else{
|
| - chngToIN &= b;
|
| - }
|
| - }
|
| + for(i=0; i<pDistinct->nExpr; i++){
|
| + Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
|
| + if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
|
| }
|
|
|
| - /*
|
| - ** Record the set of tables that satisfy case 2. The set might be
|
| - ** empty.
|
| - */
|
| - pOrInfo->indexable = indexable;
|
| - pTerm->eOperator = indexable==0 ? 0 : WO_OR;
|
| -
|
| - /*
|
| - ** chngToIN holds a set of tables that *might* satisfy case 1. But
|
| - ** we have to do some additional checking to see if case 1 really
|
| - ** is satisfied.
|
| + /* Loop through all indices on the table, checking each to see if it makes
|
| + ** the DISTINCT qualifier redundant. It does so if:
|
| **
|
| - ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
|
| - ** that there is no possibility of transforming the OR clause into an
|
| - ** IN operator because one or more terms in the OR clause contain
|
| - ** something other than == on a column in the single table. The 1-bit
|
| - ** case means that every term of the OR clause is of the form
|
| - ** "table.column=expr" for some single table. The one bit that is set
|
| - ** will correspond to the common table. We still need to check to make
|
| - ** sure the same column is used on all terms. The 2-bit case is when
|
| - ** the all terms are of the form "table1.column=table2.column". It
|
| - ** might be possible to form an IN operator with either table1.column
|
| - ** or table2.column as the LHS if either is common to every term of
|
| - ** the OR clause.
|
| + ** 1. The index is itself UNIQUE, and
|
| + **
|
| + ** 2. All of the columns in the index are either part of the pDistinct
|
| + ** list, or else the WHERE clause contains a term of the form "col=X",
|
| + ** where X is a constant value. The collation sequences of the
|
| + ** comparison and select-list expressions must match those of the index.
|
| **
|
| - ** Note that terms of the form "table.column1=table.column2" (the
|
| - ** same table on both sizes of the ==) cannot be optimized.
|
| + ** 3. All of those index columns for which the WHERE clause does not
|
| + ** contain a "col=X" term are subject to a NOT NULL constraint.
|
| */
|
| - if( chngToIN ){
|
| - int okToChngToIN = 0; /* True if the conversion to IN is valid */
|
| - int iColumn = -1; /* Column index on lhs of IN operator */
|
| - int iCursor = -1; /* Table cursor common to all terms */
|
| - int j = 0; /* Loop counter */
|
| -
|
| - /* Search for a table and column that appears on one side or the
|
| - ** other of the == operator in every subterm. That table and column
|
| - ** will be recorded in iCursor and iColumn. There might not be any
|
| - ** such table and column. Set okToChngToIN if an appropriate table
|
| - ** and column is found but leave okToChngToIN false if not found.
|
| - */
|
| - for(j=0; j<2 && !okToChngToIN; j++){
|
| - pOrTerm = pOrWc->a;
|
| - for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
|
| - assert( pOrTerm->eOperator & WO_EQ );
|
| - pOrTerm->wtFlags &= ~TERM_OR_OK;
|
| - if( pOrTerm->leftCursor==iCursor ){
|
| - /* This is the 2-bit case and we are on the second iteration and
|
| - ** current term is from the first iteration. So skip this term. */
|
| - assert( j==1 );
|
| - continue;
|
| - }
|
| - if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
|
| - /* This term must be of the form t1.a==t2.b where t2 is in the
|
| - ** chngToIN set but t1 is not. This term will be either preceded
|
| - ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
|
| - ** and use its inversion. */
|
| - testcase( pOrTerm->wtFlags & TERM_COPIED );
|
| - testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
|
| - assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
|
| - continue;
|
| - }
|
| - iColumn = pOrTerm->u.leftColumn;
|
| - iCursor = pOrTerm->leftCursor;
|
| - break;
|
| - }
|
| - if( i<0 ){
|
| - /* No candidate table+column was found. This can only occur
|
| - ** on the second iteration */
|
| - assert( j==1 );
|
| - assert( IsPowerOfTwo(chngToIN) );
|
| - assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
|
| - break;
|
| - }
|
| - testcase( j==1 );
|
| -
|
| - /* We have found a candidate table and column. Check to see if that
|
| - ** table and column is common to every term in the OR clause */
|
| - okToChngToIN = 1;
|
| - for(; i>=0 && okToChngToIN; i--, pOrTerm++){
|
| - assert( pOrTerm->eOperator & WO_EQ );
|
| - if( pOrTerm->leftCursor!=iCursor ){
|
| - pOrTerm->wtFlags &= ~TERM_OR_OK;
|
| - }else if( pOrTerm->u.leftColumn!=iColumn ){
|
| - okToChngToIN = 0;
|
| - }else{
|
| - int affLeft, affRight;
|
| - /* If the right-hand side is also a column, then the affinities
|
| - ** of both right and left sides must be such that no type
|
| - ** conversions are required on the right. (Ticket #2249)
|
| - */
|
| - affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
|
| - affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
|
| - if( affRight!=0 && affRight!=affLeft ){
|
| - okToChngToIN = 0;
|
| - }else{
|
| - pOrTerm->wtFlags |= TERM_OR_OK;
|
| - }
|
| - }
|
| + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
| + if( !IsUniqueIndex(pIdx) ) continue;
|
| + for(i=0; i<pIdx->nKeyCol; i++){
|
| + if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
|
| + if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
|
| + if( indexColumnNotNull(pIdx, i)==0 ) break;
|
| }
|
| }
|
| -
|
| - /* At this point, okToChngToIN is true if original pTerm satisfies
|
| - ** case 1. In that case, construct a new virtual term that is
|
| - ** pTerm converted into an IN operator.
|
| - */
|
| - if( okToChngToIN ){
|
| - Expr *pDup; /* A transient duplicate expression */
|
| - ExprList *pList = 0; /* The RHS of the IN operator */
|
| - Expr *pLeft = 0; /* The LHS of the IN operator */
|
| - Expr *pNew; /* The complete IN operator */
|
| -
|
| - for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
|
| - if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
|
| - assert( pOrTerm->eOperator & WO_EQ );
|
| - assert( pOrTerm->leftCursor==iCursor );
|
| - assert( pOrTerm->u.leftColumn==iColumn );
|
| - pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
|
| - pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
|
| - pLeft = pOrTerm->pExpr->pLeft;
|
| - }
|
| - assert( pLeft!=0 );
|
| - pDup = sqlite3ExprDup(db, pLeft, 0);
|
| - pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
|
| - if( pNew ){
|
| - int idxNew;
|
| - transferJoinMarkings(pNew, pExpr);
|
| - assert( !ExprHasProperty(pNew, EP_xIsSelect) );
|
| - pNew->x.pList = pList;
|
| - idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
|
| - testcase( idxNew==0 );
|
| - exprAnalyze(pSrc, pWC, idxNew);
|
| - pTerm = &pWC->a[idxTerm];
|
| - pWC->a[idxNew].iParent = idxTerm;
|
| - pTerm->nChild = 1;
|
| - }else{
|
| - sqlite3ExprListDelete(db, pList);
|
| - }
|
| - pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
|
| + if( i==pIdx->nKeyCol ){
|
| + /* This index implies that the DISTINCT qualifier is redundant. */
|
| + return 1;
|
| }
|
| }
|
| +
|
| + return 0;
|
| }
|
| -#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
|
| +
|
|
|
| /*
|
| -** The input to this routine is an WhereTerm structure with only the
|
| -** "pExpr" field filled in. The job of this routine is to analyze the
|
| -** subexpression and populate all the other fields of the WhereTerm
|
| -** structure.
|
| -**
|
| -** If the expression is of the form "<expr> <op> X" it gets commuted
|
| -** to the standard form of "X <op> <expr>".
|
| -**
|
| -** If the expression is of the form "X <op> Y" where both X and Y are
|
| -** columns, then the original expression is unchanged and a new virtual
|
| -** term of the form "Y <op> X" is added to the WHERE clause and
|
| -** analyzed separately. The original term is marked with TERM_COPIED
|
| -** and the new term is marked with TERM_DYNAMIC (because it's pExpr
|
| -** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
|
| -** is a commuted copy of a prior term.) The original term has nChild=1
|
| -** and the copy has idxParent set to the index of the original term.
|
| +** Estimate the logarithm of the input value to base 2.
|
| */
|
| -static void exprAnalyze(
|
| - SrcList *pSrc, /* the FROM clause */
|
| - WhereClause *pWC, /* the WHERE clause */
|
| - int idxTerm /* Index of the term to be analyzed */
|
| -){
|
| - WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
|
| - WhereTerm *pTerm; /* The term to be analyzed */
|
| - WhereMaskSet *pMaskSet; /* Set of table index masks */
|
| - Expr *pExpr; /* The expression to be analyzed */
|
| - Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
|
| - Bitmask prereqAll; /* Prerequesites of pExpr */
|
| - Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
|
| - Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
|
| - int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
|
| - int noCase = 0; /* LIKE/GLOB distinguishes case */
|
| - int op; /* Top-level operator. pExpr->op */
|
| - Parse *pParse = pWInfo->pParse; /* Parsing context */
|
| - sqlite3 *db = pParse->db; /* Database connection */
|
| -
|
| - if( db->mallocFailed ){
|
| - return;
|
| - }
|
| - pTerm = &pWC->a[idxTerm];
|
| - pMaskSet = &pWInfo->sMaskSet;
|
| - pExpr = pTerm->pExpr;
|
| - assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
|
| - prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
|
| - op = pExpr->op;
|
| - if( op==TK_IN ){
|
| - assert( pExpr->pRight==0 );
|
| - if( ExprHasProperty(pExpr, EP_xIsSelect) ){
|
| - pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
|
| - }else{
|
| - pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
|
| - }
|
| - }else if( op==TK_ISNULL ){
|
| - pTerm->prereqRight = 0;
|
| - }else{
|
| - pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
|
| - }
|
| - prereqAll = exprTableUsage(pMaskSet, pExpr);
|
| - if( ExprHasProperty(pExpr, EP_FromJoin) ){
|
| - Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
|
| - prereqAll |= x;
|
| - extraRight = x-1; /* ON clause terms may not be used with an index
|
| - ** on left table of a LEFT JOIN. Ticket #3015 */
|
| - }
|
| - pTerm->prereqAll = prereqAll;
|
| - pTerm->leftCursor = -1;
|
| - pTerm->iParent = -1;
|
| - pTerm->eOperator = 0;
|
| - if( allowedOp(op) ){
|
| - Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
|
| - Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
|
| - u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
|
| - if( pLeft->op==TK_COLUMN ){
|
| - pTerm->leftCursor = pLeft->iTable;
|
| - pTerm->u.leftColumn = pLeft->iColumn;
|
| - pTerm->eOperator = operatorMask(op) & opMask;
|
| - }
|
| - if( pRight && pRight->op==TK_COLUMN ){
|
| - WhereTerm *pNew;
|
| - Expr *pDup;
|
| - u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
|
| - if( pTerm->leftCursor>=0 ){
|
| - int idxNew;
|
| - pDup = sqlite3ExprDup(db, pExpr, 0);
|
| - if( db->mallocFailed ){
|
| - sqlite3ExprDelete(db, pDup);
|
| - return;
|
| - }
|
| - idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
|
| - if( idxNew==0 ) return;
|
| - pNew = &pWC->a[idxNew];
|
| - pNew->iParent = idxTerm;
|
| - pTerm = &pWC->a[idxTerm];
|
| - pTerm->nChild = 1;
|
| - pTerm->wtFlags |= TERM_COPIED;
|
| - if( pExpr->op==TK_EQ
|
| - && !ExprHasProperty(pExpr, EP_FromJoin)
|
| - && OptimizationEnabled(db, SQLITE_Transitive)
|
| - ){
|
| - pTerm->eOperator |= WO_EQUIV;
|
| - eExtraOp = WO_EQUIV;
|
| - }
|
| - }else{
|
| - pDup = pExpr;
|
| - pNew = pTerm;
|
| - }
|
| - exprCommute(pParse, pDup);
|
| - pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
|
| - pNew->leftCursor = pLeft->iTable;
|
| - pNew->u.leftColumn = pLeft->iColumn;
|
| - testcase( (prereqLeft | extraRight) != prereqLeft );
|
| - pNew->prereqRight = prereqLeft | extraRight;
|
| - pNew->prereqAll = prereqAll;
|
| - pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
|
| - }
|
| - }
|
| -
|
| -#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
|
| - /* If a term is the BETWEEN operator, create two new virtual terms
|
| - ** that define the range that the BETWEEN implements. For example:
|
| - **
|
| - ** a BETWEEN b AND c
|
| - **
|
| - ** is converted into:
|
| - **
|
| - ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
|
| - **
|
| - ** The two new terms are added onto the end of the WhereClause object.
|
| - ** The new terms are "dynamic" and are children of the original BETWEEN
|
| - ** term. That means that if the BETWEEN term is coded, the children are
|
| - ** skipped. Or, if the children are satisfied by an index, the original
|
| - ** BETWEEN term is skipped.
|
| - */
|
| - else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
|
| - ExprList *pList = pExpr->x.pList;
|
| - int i;
|
| - static const u8 ops[] = {TK_GE, TK_LE};
|
| - assert( pList!=0 );
|
| - assert( pList->nExpr==2 );
|
| - for(i=0; i<2; i++){
|
| - Expr *pNewExpr;
|
| - int idxNew;
|
| - pNewExpr = sqlite3PExpr(pParse, ops[i],
|
| - sqlite3ExprDup(db, pExpr->pLeft, 0),
|
| - sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
|
| - transferJoinMarkings(pNewExpr, pExpr);
|
| - idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
|
| - testcase( idxNew==0 );
|
| - exprAnalyze(pSrc, pWC, idxNew);
|
| - pTerm = &pWC->a[idxTerm];
|
| - pWC->a[idxNew].iParent = idxTerm;
|
| - }
|
| - pTerm->nChild = 2;
|
| - }
|
| -#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
|
| -
|
| -#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
|
| - /* Analyze a term that is composed of two or more subterms connected by
|
| - ** an OR operator.
|
| - */
|
| - else if( pExpr->op==TK_OR ){
|
| - assert( pWC->op==TK_AND );
|
| - exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
|
| - pTerm = &pWC->a[idxTerm];
|
| - }
|
| -#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
|
| -
|
| -#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
|
| - /* Add constraints to reduce the search space on a LIKE or GLOB
|
| - ** operator.
|
| - **
|
| - ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
|
| - **
|
| - ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
|
| - **
|
| - ** The last character of the prefix "abc" is incremented to form the
|
| - ** termination condition "abd".
|
| - */
|
| - if( pWC->op==TK_AND
|
| - && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
|
| - ){
|
| - Expr *pLeft; /* LHS of LIKE/GLOB operator */
|
| - Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
|
| - Expr *pNewExpr1;
|
| - Expr *pNewExpr2;
|
| - int idxNew1;
|
| - int idxNew2;
|
| - const char *zCollSeqName; /* Name of collating sequence */
|
| -
|
| - pLeft = pExpr->x.pList->a[1].pExpr;
|
| - pStr2 = sqlite3ExprDup(db, pStr1, 0);
|
| - if( !db->mallocFailed ){
|
| - u8 c, *pC; /* Last character before the first wildcard */
|
| - pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
|
| - c = *pC;
|
| - if( noCase ){
|
| - /* The point is to increment the last character before the first
|
| - ** wildcard. But if we increment '@', that will push it into the
|
| - ** alphabetic range where case conversions will mess up the
|
| - ** inequality. To avoid this, make sure to also run the full
|
| - ** LIKE on all candidate expressions by clearing the isComplete flag
|
| - */
|
| - if( c=='A'-1 ) isComplete = 0;
|
| - c = sqlite3UpperToLower[c];
|
| - }
|
| - *pC = c + 1;
|
| - }
|
| - zCollSeqName = noCase ? "NOCASE" : "BINARY";
|
| - pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
|
| - pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
|
| - sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
|
| - pStr1, 0);
|
| - transferJoinMarkings(pNewExpr1, pExpr);
|
| - idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
|
| - testcase( idxNew1==0 );
|
| - exprAnalyze(pSrc, pWC, idxNew1);
|
| - pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
|
| - pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
|
| - sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
|
| - pStr2, 0);
|
| - transferJoinMarkings(pNewExpr2, pExpr);
|
| - idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
|
| - testcase( idxNew2==0 );
|
| - exprAnalyze(pSrc, pWC, idxNew2);
|
| - pTerm = &pWC->a[idxTerm];
|
| - if( isComplete ){
|
| - pWC->a[idxNew1].iParent = idxTerm;
|
| - pWC->a[idxNew2].iParent = idxTerm;
|
| - pTerm->nChild = 2;
|
| - }
|
| - }
|
| -#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
|
| -
|
| -#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| - /* Add a WO_MATCH auxiliary term to the constraint set if the
|
| - ** current expression is of the form: column MATCH expr.
|
| - ** This information is used by the xBestIndex methods of
|
| - ** virtual tables. The native query optimizer does not attempt
|
| - ** to do anything with MATCH functions.
|
| - */
|
| - if( isMatchOfColumn(pExpr) ){
|
| - int idxNew;
|
| - Expr *pRight, *pLeft;
|
| - WhereTerm *pNewTerm;
|
| - Bitmask prereqColumn, prereqExpr;
|
| -
|
| - pRight = pExpr->x.pList->a[0].pExpr;
|
| - pLeft = pExpr->x.pList->a[1].pExpr;
|
| - prereqExpr = exprTableUsage(pMaskSet, pRight);
|
| - prereqColumn = exprTableUsage(pMaskSet, pLeft);
|
| - if( (prereqExpr & prereqColumn)==0 ){
|
| - Expr *pNewExpr;
|
| - pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
|
| - 0, sqlite3ExprDup(db, pRight, 0), 0);
|
| - idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
|
| - testcase( idxNew==0 );
|
| - pNewTerm = &pWC->a[idxNew];
|
| - pNewTerm->prereqRight = prereqExpr;
|
| - pNewTerm->leftCursor = pLeft->iTable;
|
| - pNewTerm->u.leftColumn = pLeft->iColumn;
|
| - pNewTerm->eOperator = WO_MATCH;
|
| - pNewTerm->iParent = idxTerm;
|
| - pTerm = &pWC->a[idxTerm];
|
| - pTerm->nChild = 1;
|
| - pTerm->wtFlags |= TERM_COPIED;
|
| - pNewTerm->prereqAll = pTerm->prereqAll;
|
| - }
|
| - }
|
| -#endif /* SQLITE_OMIT_VIRTUALTABLE */
|
| -
|
| -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| - /* When sqlite_stat3 histogram data is available an operator of the
|
| - ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
|
| - ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
|
| - ** virtual term of that form.
|
| - **
|
| - ** Note that the virtual term must be tagged with TERM_VNULL. This
|
| - ** TERM_VNULL tag will suppress the not-null check at the beginning
|
| - ** of the loop. Without the TERM_VNULL flag, the not-null check at
|
| - ** the start of the loop will prevent any results from being returned.
|
| - */
|
| - if( pExpr->op==TK_NOTNULL
|
| - && pExpr->pLeft->op==TK_COLUMN
|
| - && pExpr->pLeft->iColumn>=0
|
| - && OptimizationEnabled(db, SQLITE_Stat3)
|
| - ){
|
| - Expr *pNewExpr;
|
| - Expr *pLeft = pExpr->pLeft;
|
| - int idxNew;
|
| - WhereTerm *pNewTerm;
|
| -
|
| - pNewExpr = sqlite3PExpr(pParse, TK_GT,
|
| - sqlite3ExprDup(db, pLeft, 0),
|
| - sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
|
| -
|
| - idxNew = whereClauseInsert(pWC, pNewExpr,
|
| - TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
|
| - if( idxNew ){
|
| - pNewTerm = &pWC->a[idxNew];
|
| - pNewTerm->prereqRight = 0;
|
| - pNewTerm->leftCursor = pLeft->iTable;
|
| - pNewTerm->u.leftColumn = pLeft->iColumn;
|
| - pNewTerm->eOperator = WO_GT;
|
| - pNewTerm->iParent = idxTerm;
|
| - pTerm = &pWC->a[idxTerm];
|
| - pTerm->nChild = 1;
|
| - pTerm->wtFlags |= TERM_COPIED;
|
| - pNewTerm->prereqAll = pTerm->prereqAll;
|
| - }
|
| - }
|
| -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
|
| -
|
| - /* Prevent ON clause terms of a LEFT JOIN from being used to drive
|
| - ** an index for tables to the left of the join.
|
| - */
|
| - pTerm->prereqRight |= extraRight;
|
| +static LogEst estLog(LogEst N){
|
| + return N<=10 ? 0 : sqlite3LogEst(N) - 33;
|
| }
|
|
|
| /*
|
| -** This function searches pList for an entry that matches the iCol-th column
|
| -** of index pIdx.
|
| +** Convert OP_Column opcodes to OP_Copy in previously generated code.
|
| **
|
| -** If such an expression is found, its index in pList->a[] is returned. If
|
| -** no expression is found, -1 is returned.
|
| -*/
|
| -static int findIndexCol(
|
| - Parse *pParse, /* Parse context */
|
| - ExprList *pList, /* Expression list to search */
|
| - int iBase, /* Cursor for table associated with pIdx */
|
| - Index *pIdx, /* Index to match column of */
|
| - int iCol /* Column of index to match */
|
| -){
|
| - int i;
|
| - const char *zColl = pIdx->azColl[iCol];
|
| -
|
| - for(i=0; i<pList->nExpr; i++){
|
| - Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
|
| - if( p->op==TK_COLUMN
|
| - && p->iColumn==pIdx->aiColumn[iCol]
|
| - && p->iTable==iBase
|
| - ){
|
| - CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
|
| - if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
|
| - return i;
|
| - }
|
| - }
|
| - }
|
| -
|
| - return -1;
|
| -}
|
| -
|
| -/*
|
| -** Return true if the DISTINCT expression-list passed as the third argument
|
| -** is redundant.
|
| +** This routine runs over generated VDBE code and translates OP_Column
|
| +** opcodes into OP_Copy when the table is being accessed via co-routine
|
| +** instead of via table lookup.
|
| **
|
| -** A DISTINCT list is redundant if the database contains some subset of
|
| -** columns that are unique and non-null.
|
| +** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
|
| +** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
|
| +** then each OP_Rowid is transformed into an instruction to increment the
|
| +** value stored in its output register.
|
| */
|
| -static int isDistinctRedundant(
|
| - Parse *pParse, /* Parsing context */
|
| - SrcList *pTabList, /* The FROM clause */
|
| - WhereClause *pWC, /* The WHERE clause */
|
| - ExprList *pDistinct /* The result set that needs to be DISTINCT */
|
| +static void translateColumnToCopy(
|
| + Vdbe *v, /* The VDBE containing code to translate */
|
| + int iStart, /* Translate from this opcode to the end */
|
| + int iTabCur, /* OP_Column/OP_Rowid references to this table */
|
| + int iRegister, /* The first column is in this register */
|
| + int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
|
| ){
|
| - Table *pTab;
|
| - Index *pIdx;
|
| - int i;
|
| - int iBase;
|
| -
|
| - /* If there is more than one table or sub-select in the FROM clause of
|
| - ** this query, then it will not be possible to show that the DISTINCT
|
| - ** clause is redundant. */
|
| - if( pTabList->nSrc!=1 ) return 0;
|
| - iBase = pTabList->a[0].iCursor;
|
| - pTab = pTabList->a[0].pTab;
|
| -
|
| - /* If any of the expressions is an IPK column on table iBase, then return
|
| - ** true. Note: The (p->iTable==iBase) part of this test may be false if the
|
| - ** current SELECT is a correlated sub-query.
|
| - */
|
| - for(i=0; i<pDistinct->nExpr; i++){
|
| - Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
|
| - if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
|
| - }
|
| -
|
| - /* Loop through all indices on the table, checking each to see if it makes
|
| - ** the DISTINCT qualifier redundant. It does so if:
|
| - **
|
| - ** 1. The index is itself UNIQUE, and
|
| - **
|
| - ** 2. All of the columns in the index are either part of the pDistinct
|
| - ** list, or else the WHERE clause contains a term of the form "col=X",
|
| - ** where X is a constant value. The collation sequences of the
|
| - ** comparison and select-list expressions must match those of the index.
|
| - **
|
| - ** 3. All of those index columns for which the WHERE clause does not
|
| - ** contain a "col=X" term are subject to a NOT NULL constraint.
|
| - */
|
| - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
| - if( !IsUniqueIndex(pIdx) ) continue;
|
| - for(i=0; i<pIdx->nKeyCol; i++){
|
| - i16 iCol = pIdx->aiColumn[i];
|
| - if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
|
| - int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
|
| - if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
|
| - break;
|
| - }
|
| + VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
|
| + int iEnd = sqlite3VdbeCurrentAddr(v);
|
| + for(; iStart<iEnd; iStart++, pOp++){
|
| + if( pOp->p1!=iTabCur ) continue;
|
| + if( pOp->opcode==OP_Column ){
|
| + pOp->opcode = OP_Copy;
|
| + pOp->p1 = pOp->p2 + iRegister;
|
| + pOp->p2 = pOp->p3;
|
| + pOp->p3 = 0;
|
| + }else if( pOp->opcode==OP_Rowid ){
|
| + if( bIncrRowid ){
|
| + /* Increment the value stored in the P2 operand of the OP_Rowid. */
|
| + pOp->opcode = OP_AddImm;
|
| + pOp->p1 = pOp->p2;
|
| + pOp->p2 = 1;
|
| + }else{
|
| + pOp->opcode = OP_Null;
|
| + pOp->p1 = 0;
|
| + pOp->p3 = 0;
|
| }
|
| }
|
| - if( i==pIdx->nKeyCol ){
|
| - /* This index implies that the DISTINCT qualifier is redundant. */
|
| - return 1;
|
| - }
|
| }
|
| -
|
| - return 0;
|
| -}
|
| -
|
| -
|
| -/*
|
| -** Estimate the logarithm of the input value to base 2.
|
| -*/
|
| -static LogEst estLog(LogEst N){
|
| - return N<=10 ? 0 : sqlite3LogEst(N) - 33;
|
| }
|
|
|
| /*
|
| @@ -1549,11 +582,12 @@ static int termCanDriveIndex(
|
| ){
|
| char aff;
|
| if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
|
| - if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
|
| + if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
|
| if( (pTerm->prereqRight & notReady)!=0 ) return 0;
|
| if( pTerm->u.leftColumn<0 ) return 0;
|
| aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
|
| if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
|
| + testcase( pTerm->pExpr->op==TK_IS );
|
| return 1;
|
| }
|
| #endif
|
| @@ -1590,6 +624,11 @@ static void constructAutomaticIndex(
|
| Bitmask idxCols; /* Bitmap of columns used for indexing */
|
| Bitmask extraCols; /* Bitmap of additional columns */
|
| u8 sentWarning = 0; /* True if a warnning has been issued */
|
| + Expr *pPartial = 0; /* Partial Index Expression */
|
| + int iContinue = 0; /* Jump here to skip excluded rows */
|
| + struct SrcList_item *pTabItem; /* FROM clause term being indexed */
|
| + int addrCounter = 0; /* Address where integer counter is initialized */
|
| + int regBase; /* Array of registers where record is assembled */
|
|
|
| /* Generate code to skip over the creation and initialization of the
|
| ** transient index on 2nd and subsequent iterations of the loop. */
|
| @@ -1605,6 +644,17 @@ static void constructAutomaticIndex(
|
| pLoop = pLevel->pWLoop;
|
| idxCols = 0;
|
| for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
|
| + Expr *pExpr = pTerm->pExpr;
|
| + assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
|
| + || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
|
| + || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
|
| + if( pLoop->prereq==0
|
| + && (pTerm->wtFlags & TERM_VIRTUAL)==0
|
| + && !ExprHasProperty(pExpr, EP_FromJoin)
|
| + && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
|
| + pPartial = sqlite3ExprAnd(pParse->db, pPartial,
|
| + sqlite3ExprDup(pParse->db, pExpr, 0));
|
| + }
|
| if( termCanDriveIndex(pTerm, pSrc, notReady) ){
|
| int iCol = pTerm->u.leftColumn;
|
| Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
|
| @@ -1617,7 +667,9 @@ static void constructAutomaticIndex(
|
| sentWarning = 1;
|
| }
|
| if( (idxCols & cMask)==0 ){
|
| - if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
|
| + if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
|
| + goto end_auto_index_create;
|
| + }
|
| pLoop->aLTerm[nKeyCol++] = pTerm;
|
| idxCols |= cMask;
|
| }
|
| @@ -1637,7 +689,7 @@ static void constructAutomaticIndex(
|
| ** if they go out of sync.
|
| */
|
| extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
|
| - mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
|
| + mxBitCol = MIN(BMS-1,pTable->nCol);
|
| testcase( pTable->nCol==BMS-1 );
|
| testcase( pTable->nCol==BMS-2 );
|
| for(i=0; i<mxBitCol; i++){
|
| @@ -1646,11 +698,10 @@ static void constructAutomaticIndex(
|
| if( pSrc->colUsed & MASKBIT(BMS-1) ){
|
| nKeyCol += pTable->nCol - BMS + 1;
|
| }
|
| - pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
|
|
|
| /* Construct the Index object to describe this index */
|
| pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
|
| - if( pIdx==0 ) return;
|
| + if( pIdx==0 ) goto end_auto_index_create;
|
| pLoop->u.btree.pIndex = pIdx;
|
| pIdx->zName = "auto-index";
|
| pIdx->pTable = pTable;
|
| @@ -1667,7 +718,7 @@ static void constructAutomaticIndex(
|
| idxCols |= cMask;
|
| pIdx->aiColumn[n] = pTerm->u.leftColumn;
|
| pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
|
| - pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
|
| + pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
|
| n++;
|
| }
|
| }
|
| @@ -1679,20 +730,20 @@ static void constructAutomaticIndex(
|
| for(i=0; i<mxBitCol; i++){
|
| if( extraCols & MASKBIT(i) ){
|
| pIdx->aiColumn[n] = i;
|
| - pIdx->azColl[n] = "BINARY";
|
| + pIdx->azColl[n] = sqlite3StrBINARY;
|
| n++;
|
| }
|
| }
|
| if( pSrc->colUsed & MASKBIT(BMS-1) ){
|
| for(i=BMS-1; i<pTable->nCol; i++){
|
| pIdx->aiColumn[n] = i;
|
| - pIdx->azColl[n] = "BINARY";
|
| + pIdx->azColl[n] = sqlite3StrBINARY;
|
| n++;
|
| }
|
| }
|
| assert( n==nKeyCol );
|
| - pIdx->aiColumn[n] = -1;
|
| - pIdx->azColl[n] = "BINARY";
|
| + pIdx->aiColumn[n] = XN_ROWID;
|
| + pIdx->azColl[n] = sqlite3StrBINARY;
|
|
|
| /* Create the automatic index */
|
| assert( pLevel->iIdxCur>=0 );
|
| @@ -1702,18 +753,48 @@ static void constructAutomaticIndex(
|
| VdbeComment((v, "for %s", pTable->zName));
|
|
|
| /* Fill the automatic index with content */
|
| - addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
|
| + sqlite3ExprCachePush(pParse);
|
| + pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
|
| + if( pTabItem->fg.viaCoroutine ){
|
| + int regYield = pTabItem->regReturn;
|
| + addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
|
| + sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
|
| + addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
|
| + VdbeCoverage(v);
|
| + VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
|
| + }else{
|
| + addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
|
| + }
|
| + if( pPartial ){
|
| + iContinue = sqlite3VdbeMakeLabel(v);
|
| + sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
|
| + pLoop->wsFlags |= WHERE_PARTIALIDX;
|
| + }
|
| regRecord = sqlite3GetTempReg(pParse);
|
| - sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
|
| + regBase = sqlite3GenerateIndexKey(
|
| + pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
|
| + );
|
| sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
|
| sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
|
| - sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
|
| + if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
|
| + if( pTabItem->fg.viaCoroutine ){
|
| + sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
|
| + translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1);
|
| + sqlite3VdbeGoto(v, addrTop);
|
| + pTabItem->fg.viaCoroutine = 0;
|
| + }else{
|
| + sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
|
| + }
|
| sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
|
| sqlite3VdbeJumpHere(v, addrTop);
|
| sqlite3ReleaseTempReg(pParse, regRecord);
|
| + sqlite3ExprCachePop(pParse);
|
|
|
| /* Jump here when skipping the initialization */
|
| sqlite3VdbeJumpHere(v, addrInit);
|
| +
|
| +end_auto_index_create:
|
| + sqlite3ExprDelete(pParse->db, pPartial);
|
| }
|
| #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
|
|
|
| @@ -1726,6 +807,7 @@ static void constructAutomaticIndex(
|
| static sqlite3_index_info *allocateIndexInfo(
|
| Parse *pParse,
|
| WhereClause *pWC,
|
| + Bitmask mUnusable, /* Ignore terms with these prereqs */
|
| struct SrcList_item *pSrc,
|
| ExprList *pOrderBy
|
| ){
|
| @@ -1742,12 +824,15 @@ static sqlite3_index_info *allocateIndexInfo(
|
| ** to this virtual table */
|
| for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
|
| if( pTerm->leftCursor != pSrc->iCursor ) continue;
|
| + if( pTerm->prereqRight & mUnusable ) continue;
|
| assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
|
| testcase( pTerm->eOperator & WO_IN );
|
| testcase( pTerm->eOperator & WO_ISNULL );
|
| + testcase( pTerm->eOperator & WO_IS );
|
| testcase( pTerm->eOperator & WO_ALL );
|
| - if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
|
| + if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
|
| if( pTerm->wtFlags & TERM_VNULL ) continue;
|
| + assert( pTerm->u.leftColumn>=(-1) );
|
| nTerm++;
|
| }
|
|
|
| @@ -1795,16 +880,22 @@ static sqlite3_index_info *allocateIndexInfo(
|
| for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
|
| u8 op;
|
| if( pTerm->leftCursor != pSrc->iCursor ) continue;
|
| + if( pTerm->prereqRight & mUnusable ) continue;
|
| assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
|
| testcase( pTerm->eOperator & WO_IN );
|
| + testcase( pTerm->eOperator & WO_IS );
|
| testcase( pTerm->eOperator & WO_ISNULL );
|
| testcase( pTerm->eOperator & WO_ALL );
|
| - if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
|
| + if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
|
| if( pTerm->wtFlags & TERM_VNULL ) continue;
|
| + assert( pTerm->u.leftColumn>=(-1) );
|
| pIdxCons[j].iColumn = pTerm->u.leftColumn;
|
| pIdxCons[j].iTermOffset = i;
|
| op = (u8)pTerm->eOperator & WO_ALL;
|
| if( op==WO_IN ) op = WO_EQ;
|
| + if( op==WO_MATCH ){
|
| + op = pTerm->eMatchOp;
|
| + }
|
| pIdxCons[j].op = op;
|
| /* The direct assignment in the previous line is possible only because
|
| ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
|
| @@ -1873,18 +964,21 @@ static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
|
| }
|
| #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
|
|
|
| -
|
| #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| /*
|
| ** Estimate the location of a particular key among all keys in an
|
| ** index. Store the results in aStat as follows:
|
| **
|
| -** aStat[0] Est. number of rows less than pVal
|
| -** aStat[1] Est. number of rows equal to pVal
|
| +** aStat[0] Est. number of rows less than pRec
|
| +** aStat[1] Est. number of rows equal to pRec
|
| **
|
| -** Return SQLITE_OK on success.
|
| +** Return the index of the sample that is the smallest sample that
|
| +** is greater than or equal to pRec. Note that this index is not an index
|
| +** into the aSample[] array - it is an index into a virtual set of samples
|
| +** based on the contents of aSample[] and the number of fields in record
|
| +** pRec.
|
| */
|
| -static void whereKeyStats(
|
| +static int whereKeyStats(
|
| Parse *pParse, /* Database connection */
|
| Index *pIdx, /* Index to consider domain of */
|
| UnpackedRecord *pRec, /* Vector of values to consider */
|
| @@ -1893,67 +987,158 @@ static void whereKeyStats(
|
| ){
|
| IndexSample *aSample = pIdx->aSample;
|
| int iCol; /* Index of required stats in anEq[] etc. */
|
| + int i; /* Index of first sample >= pRec */
|
| + int iSample; /* Smallest sample larger than or equal to pRec */
|
| int iMin = 0; /* Smallest sample not yet tested */
|
| - int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
|
| int iTest; /* Next sample to test */
|
| int res; /* Result of comparison operation */
|
| + int nField; /* Number of fields in pRec */
|
| + tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
|
|
|
| #ifndef SQLITE_DEBUG
|
| UNUSED_PARAMETER( pParse );
|
| #endif
|
| assert( pRec!=0 );
|
| - iCol = pRec->nField - 1;
|
| assert( pIdx->nSample>0 );
|
| - assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
|
| + assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
|
| +
|
| + /* Do a binary search to find the first sample greater than or equal
|
| + ** to pRec. If pRec contains a single field, the set of samples to search
|
| + ** is simply the aSample[] array. If the samples in aSample[] contain more
|
| + ** than one fields, all fields following the first are ignored.
|
| + **
|
| + ** If pRec contains N fields, where N is more than one, then as well as the
|
| + ** samples in aSample[] (truncated to N fields), the search also has to
|
| + ** consider prefixes of those samples. For example, if the set of samples
|
| + ** in aSample is:
|
| + **
|
| + ** aSample[0] = (a, 5)
|
| + ** aSample[1] = (a, 10)
|
| + ** aSample[2] = (b, 5)
|
| + ** aSample[3] = (c, 100)
|
| + ** aSample[4] = (c, 105)
|
| + **
|
| + ** Then the search space should ideally be the samples above and the
|
| + ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
|
| + ** the code actually searches this set:
|
| + **
|
| + ** 0: (a)
|
| + ** 1: (a, 5)
|
| + ** 2: (a, 10)
|
| + ** 3: (a, 10)
|
| + ** 4: (b)
|
| + ** 5: (b, 5)
|
| + ** 6: (c)
|
| + ** 7: (c, 100)
|
| + ** 8: (c, 105)
|
| + ** 9: (c, 105)
|
| + **
|
| + ** For each sample in the aSample[] array, N samples are present in the
|
| + ** effective sample array. In the above, samples 0 and 1 are based on
|
| + ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
|
| + **
|
| + ** Often, sample i of each block of N effective samples has (i+1) fields.
|
| + ** Except, each sample may be extended to ensure that it is greater than or
|
| + ** equal to the previous sample in the array. For example, in the above,
|
| + ** sample 2 is the first sample of a block of N samples, so at first it
|
| + ** appears that it should be 1 field in size. However, that would make it
|
| + ** smaller than sample 1, so the binary search would not work. As a result,
|
| + ** it is extended to two fields. The duplicates that this creates do not
|
| + ** cause any problems.
|
| + */
|
| + nField = pRec->nField;
|
| + iCol = 0;
|
| + iSample = pIdx->nSample * nField;
|
| do{
|
| - iTest = (iMin+i)/2;
|
| - res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
|
| + int iSamp; /* Index in aSample[] of test sample */
|
| + int n; /* Number of fields in test sample */
|
| +
|
| + iTest = (iMin+iSample)/2;
|
| + iSamp = iTest / nField;
|
| + if( iSamp>0 ){
|
| + /* The proposed effective sample is a prefix of sample aSample[iSamp].
|
| + ** Specifically, the shortest prefix of at least (1 + iTest%nField)
|
| + ** fields that is greater than the previous effective sample. */
|
| + for(n=(iTest % nField) + 1; n<nField; n++){
|
| + if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
|
| + }
|
| + }else{
|
| + n = iTest + 1;
|
| + }
|
| +
|
| + pRec->nField = n;
|
| + res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
|
| if( res<0 ){
|
| + iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
|
| + iMin = iTest+1;
|
| + }else if( res==0 && n<nField ){
|
| + iLower = aSample[iSamp].anLt[n-1];
|
| iMin = iTest+1;
|
| + res = -1;
|
| }else{
|
| - i = iTest;
|
| + iSample = iTest;
|
| + iCol = n-1;
|
| }
|
| - }while( res && iMin<i );
|
| + }while( res && iMin<iSample );
|
| + i = iSample / nField;
|
|
|
| #ifdef SQLITE_DEBUG
|
| /* The following assert statements check that the binary search code
|
| ** above found the right answer. This block serves no purpose other
|
| ** than to invoke the asserts. */
|
| - if( res==0 ){
|
| - /* If (res==0) is true, then sample $i must be equal to pRec */
|
| - assert( i<pIdx->nSample );
|
| - assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
|
| - || pParse->db->mallocFailed );
|
| - }else{
|
| - /* Otherwise, pRec must be smaller than sample $i and larger than
|
| - ** sample ($i-1). */
|
| - assert( i==pIdx->nSample
|
| - || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
|
| - || pParse->db->mallocFailed );
|
| - assert( i==0
|
| - || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
|
| - || pParse->db->mallocFailed );
|
| + if( pParse->db->mallocFailed==0 ){
|
| + if( res==0 ){
|
| + /* If (res==0) is true, then pRec must be equal to sample i. */
|
| + assert( i<pIdx->nSample );
|
| + assert( iCol==nField-1 );
|
| + pRec->nField = nField;
|
| + assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
|
| + || pParse->db->mallocFailed
|
| + );
|
| + }else{
|
| + /* Unless i==pIdx->nSample, indicating that pRec is larger than
|
| + ** all samples in the aSample[] array, pRec must be smaller than the
|
| + ** (iCol+1) field prefix of sample i. */
|
| + assert( i<=pIdx->nSample && i>=0 );
|
| + pRec->nField = iCol+1;
|
| + assert( i==pIdx->nSample
|
| + || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
|
| + || pParse->db->mallocFailed );
|
| +
|
| + /* if i==0 and iCol==0, then record pRec is smaller than all samples
|
| + ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
|
| + ** be greater than or equal to the (iCol) field prefix of sample i.
|
| + ** If (i>0), then pRec must also be greater than sample (i-1). */
|
| + if( iCol>0 ){
|
| + pRec->nField = iCol;
|
| + assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
|
| + || pParse->db->mallocFailed );
|
| + }
|
| + if( i>0 ){
|
| + pRec->nField = nField;
|
| + assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
|
| + || pParse->db->mallocFailed );
|
| + }
|
| + }
|
| }
|
| #endif /* ifdef SQLITE_DEBUG */
|
|
|
| - /* At this point, aSample[i] is the first sample that is greater than
|
| - ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
|
| - ** than pVal. If aSample[i]==pVal, then res==0.
|
| - */
|
| if( res==0 ){
|
| + /* Record pRec is equal to sample i */
|
| + assert( iCol==nField-1 );
|
| aStat[0] = aSample[i].anLt[iCol];
|
| aStat[1] = aSample[i].anEq[iCol];
|
| }else{
|
| - tRowcnt iLower, iUpper, iGap;
|
| - if( i==0 ){
|
| - iLower = 0;
|
| - iUpper = aSample[0].anLt[iCol];
|
| + /* At this point, the (iCol+1) field prefix of aSample[i] is the first
|
| + ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
|
| + ** is larger than all samples in the array. */
|
| + tRowcnt iUpper, iGap;
|
| + if( i>=pIdx->nSample ){
|
| + iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
|
| }else{
|
| - i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
|
| - iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol];
|
| - iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
|
| + iUpper = aSample[i].anLt[iCol];
|
| }
|
| - aStat[1] = pIdx->aAvgEq[iCol];
|
| +
|
| if( iLower>=iUpper ){
|
| iGap = 0;
|
| }else{
|
| @@ -1965,7 +1150,12 @@ static void whereKeyStats(
|
| iGap = iGap/3;
|
| }
|
| aStat[0] = iLower + iGap;
|
| + aStat[1] = pIdx->aAvgEq[iCol];
|
| }
|
| +
|
| + /* Restore the pRec->nField value before returning. */
|
| + pRec->nField = nField;
|
| + return i;
|
| }
|
| #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
|
|
|
| @@ -1992,6 +1182,21 @@ static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
|
| return nRet;
|
| }
|
|
|
| +
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| +/*
|
| +** Return the affinity for a single column of an index.
|
| +*/
|
| +static char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
|
| + assert( iCol>=0 && iCol<pIdx->nColumn );
|
| + if( !pIdx->zColAff ){
|
| + if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
|
| + }
|
| + return pIdx->zColAff[iCol];
|
| +}
|
| +#endif
|
| +
|
| +
|
| #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| /*
|
| ** This function is called to estimate the number of rows visited by a
|
| @@ -2041,8 +1246,7 @@ static int whereRangeSkipScanEst(
|
| int nLower = -1;
|
| int nUpper = p->nSample+1;
|
| int rc = SQLITE_OK;
|
| - int iCol = p->aiColumn[nEq];
|
| - u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
|
| + u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
|
| CollSeq *pColl;
|
|
|
| sqlite3_value *p1 = 0; /* Value extracted from pLower */
|
| @@ -2116,7 +1320,7 @@ static int whereRangeSkipScanEst(
|
| ** If either of the upper or lower bound is not present, then NULL is passed in
|
| ** place of the corresponding WhereTerm.
|
| **
|
| -** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
|
| +** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
|
| ** column subject to the range constraint. Or, equivalently, the number of
|
| ** equality constraints optimized by the proposed index scan. For example,
|
| ** assuming index p is on t1(a, b), and the SQL query is:
|
| @@ -2132,7 +1336,7 @@ static int whereRangeSkipScanEst(
|
| **
|
| ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
|
| ** number of rows that the index scan is expected to visit without
|
| -** considering the range constraints. If nEq is 0, this is the number of
|
| +** considering the range constraints. If nEq is 0, then *pnOut is the number of
|
| ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
|
| ** to account for the range constraints pLower and pUpper.
|
| **
|
| @@ -2156,10 +1360,7 @@ static int whereRangeScanEst(
|
| Index *p = pLoop->u.btree.pIndex;
|
| int nEq = pLoop->u.btree.nEq;
|
|
|
| - if( p->nSample>0
|
| - && nEq<p->nSampleCol
|
| - && OptimizationEnabled(pParse->db, SQLITE_Stat3)
|
| - ){
|
| + if( p->nSample>0 && nEq<p->nSampleCol ){
|
| if( nEq==pBuilder->nRecValid ){
|
| UnpackedRecord *pRec = pBuilder->pRec;
|
| tRowcnt a[2];
|
| @@ -2175,29 +1376,30 @@ static int whereRangeScanEst(
|
| ** is not a simple variable or literal value), the lower bound of the
|
| ** range is $P. Due to a quirk in the way whereKeyStats() works, even
|
| ** if $L is available, whereKeyStats() is called for both ($P) and
|
| - ** ($P:$L) and the larger of the two returned values used.
|
| + ** ($P:$L) and the larger of the two returned values is used.
|
| **
|
| ** Similarly, iUpper is to be set to the estimate of the number of rows
|
| ** less than the upper bound of the range query. Where the upper bound
|
| ** is either ($P) or ($P:$U). Again, even if $U is available, both values
|
| ** of iUpper are requested of whereKeyStats() and the smaller used.
|
| + **
|
| + ** The number of rows between the two bounds is then just iUpper-iLower.
|
| */
|
| - tRowcnt iLower;
|
| - tRowcnt iUpper;
|
| + tRowcnt iLower; /* Rows less than the lower bound */
|
| + tRowcnt iUpper; /* Rows less than the upper bound */
|
| + int iLwrIdx = -2; /* aSample[] for the lower bound */
|
| + int iUprIdx = -1; /* aSample[] for the upper bound */
|
|
|
| if( pRec ){
|
| testcase( pRec->nField!=pBuilder->nRecValid );
|
| pRec->nField = pBuilder->nRecValid;
|
| }
|
| - if( nEq==p->nKeyCol ){
|
| - aff = SQLITE_AFF_INTEGER;
|
| - }else{
|
| - aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
|
| - }
|
| + aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq);
|
| + assert( nEq!=p->nKeyCol || aff==SQLITE_AFF_INTEGER );
|
| /* Determine iLower and iUpper using ($P) only. */
|
| if( nEq==0 ){
|
| iLower = 0;
|
| - iUpper = sqlite3LogEstToInt(p->aiRowLogEst[0]);
|
| + iUpper = p->nRowEst0;
|
| }else{
|
| /* Note: this call could be optimized away - since the same values must
|
| ** have been requested when testing key $P in whereEqualScanEst(). */
|
| @@ -2221,7 +1423,7 @@ static int whereRangeScanEst(
|
| rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
|
| if( rc==SQLITE_OK && bOk ){
|
| tRowcnt iNew;
|
| - whereKeyStats(pParse, p, pRec, 0, a);
|
| + iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
|
| iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
|
| if( iNew>iLower ) iLower = iNew;
|
| nOut--;
|
| @@ -2236,7 +1438,7 @@ static int whereRangeScanEst(
|
| rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
|
| if( rc==SQLITE_OK && bOk ){
|
| tRowcnt iNew;
|
| - whereKeyStats(pParse, p, pRec, 1, a);
|
| + iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
|
| iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
|
| if( iNew<iUpper ) iUpper = iNew;
|
| nOut--;
|
| @@ -2248,6 +1450,11 @@ static int whereRangeScanEst(
|
| if( rc==SQLITE_OK ){
|
| if( iUpper>iLower ){
|
| nNew = sqlite3LogEst(iUpper - iLower);
|
| + /* TUNING: If both iUpper and iLower are derived from the same
|
| + ** sample, then assume they are 4x more selective. This brings
|
| + ** the estimated selectivity more in line with what it would be
|
| + ** if estimated without the use of STAT3/4 tables. */
|
| + if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
|
| }else{
|
| nNew = 10; assert( 10==sqlite3LogEst(2) );
|
| }
|
| @@ -2272,12 +1479,15 @@ static int whereRangeScanEst(
|
| nNew = whereRangeAdjust(pLower, nOut);
|
| nNew = whereRangeAdjust(pUpper, nNew);
|
|
|
| - /* TUNING: If there is both an upper and lower limit, assume the range is
|
| + /* TUNING: If there is both an upper and lower limit and neither limit
|
| + ** has an application-defined likelihood(), assume the range is
|
| ** reduced by an additional 75%. This means that, by default, an open-ended
|
| ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
|
| ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
|
| ** match 1/64 of the index. */
|
| - if( pLower && pUpper ) nNew -= 20;
|
| + if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
|
| + nNew -= 20;
|
| + }
|
|
|
| nOut -= (pLower!=0) + (pUpper!=0);
|
| if( nNew<10 ) nNew = 10;
|
| @@ -2318,1455 +1528,95 @@ static int whereEqualScanEst(
|
| ){
|
| Index *p = pBuilder->pNew->u.btree.pIndex;
|
| int nEq = pBuilder->pNew->u.btree.nEq;
|
| - UnpackedRecord *pRec = pBuilder->pRec;
|
| - u8 aff; /* Column affinity */
|
| - int rc; /* Subfunction return code */
|
| - tRowcnt a[2]; /* Statistics */
|
| - int bOk;
|
| -
|
| - assert( nEq>=1 );
|
| - assert( nEq<=p->nColumn );
|
| - assert( p->aSample!=0 );
|
| - assert( p->nSample>0 );
|
| - assert( pBuilder->nRecValid<nEq );
|
| -
|
| - /* If values are not available for all fields of the index to the left
|
| - ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
|
| - if( pBuilder->nRecValid<(nEq-1) ){
|
| - return SQLITE_NOTFOUND;
|
| - }
|
| -
|
| - /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
|
| - ** below would return the same value. */
|
| - if( nEq>=p->nColumn ){
|
| - *pnRow = 1;
|
| - return SQLITE_OK;
|
| - }
|
| -
|
| - aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
|
| - rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
|
| - pBuilder->pRec = pRec;
|
| - if( rc!=SQLITE_OK ) return rc;
|
| - if( bOk==0 ) return SQLITE_NOTFOUND;
|
| - pBuilder->nRecValid = nEq;
|
| -
|
| - whereKeyStats(pParse, p, pRec, 0, a);
|
| - WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
|
| - *pnRow = a[1];
|
| -
|
| - return rc;
|
| -}
|
| -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
|
| -
|
| -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| -/*
|
| -** Estimate the number of rows that will be returned based on
|
| -** an IN constraint where the right-hand side of the IN operator
|
| -** is a list of values. Example:
|
| -**
|
| -** WHERE x IN (1,2,3,4)
|
| -**
|
| -** Write the estimated row count into *pnRow and return SQLITE_OK.
|
| -** If unable to make an estimate, leave *pnRow unchanged and return
|
| -** non-zero.
|
| -**
|
| -** This routine can fail if it is unable to load a collating sequence
|
| -** required for string comparison, or if unable to allocate memory
|
| -** for a UTF conversion required for comparison. The error is stored
|
| -** in the pParse structure.
|
| -*/
|
| -static int whereInScanEst(
|
| - Parse *pParse, /* Parsing & code generating context */
|
| - WhereLoopBuilder *pBuilder,
|
| - ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
|
| - tRowcnt *pnRow /* Write the revised row estimate here */
|
| -){
|
| - Index *p = pBuilder->pNew->u.btree.pIndex;
|
| - i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
|
| - int nRecValid = pBuilder->nRecValid;
|
| - int rc = SQLITE_OK; /* Subfunction return code */
|
| - tRowcnt nEst; /* Number of rows for a single term */
|
| - tRowcnt nRowEst = 0; /* New estimate of the number of rows */
|
| - int i; /* Loop counter */
|
| -
|
| - assert( p->aSample!=0 );
|
| - for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
|
| - nEst = nRow0;
|
| - rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
|
| - nRowEst += nEst;
|
| - pBuilder->nRecValid = nRecValid;
|
| - }
|
| -
|
| - if( rc==SQLITE_OK ){
|
| - if( nRowEst > nRow0 ) nRowEst = nRow0;
|
| - *pnRow = nRowEst;
|
| - WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
|
| - }
|
| - assert( pBuilder->nRecValid==nRecValid );
|
| - return rc;
|
| -}
|
| -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
|
| -
|
| -/*
|
| -** Disable a term in the WHERE clause. Except, do not disable the term
|
| -** if it controls a LEFT OUTER JOIN and it did not originate in the ON
|
| -** or USING clause of that join.
|
| -**
|
| -** Consider the term t2.z='ok' in the following queries:
|
| -**
|
| -** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
|
| -** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
|
| -** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
|
| -**
|
| -** The t2.z='ok' is disabled in the in (2) because it originates
|
| -** in the ON clause. The term is disabled in (3) because it is not part
|
| -** of a LEFT OUTER JOIN. In (1), the term is not disabled.
|
| -**
|
| -** Disabling a term causes that term to not be tested in the inner loop
|
| -** of the join. Disabling is an optimization. When terms are satisfied
|
| -** by indices, we disable them to prevent redundant tests in the inner
|
| -** loop. We would get the correct results if nothing were ever disabled,
|
| -** but joins might run a little slower. The trick is to disable as much
|
| -** as we can without disabling too much. If we disabled in (1), we'd get
|
| -** the wrong answer. See ticket #813.
|
| -*/
|
| -static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
|
| - if( pTerm
|
| - && (pTerm->wtFlags & TERM_CODED)==0
|
| - && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
|
| - && (pLevel->notReady & pTerm->prereqAll)==0
|
| - ){
|
| - pTerm->wtFlags |= TERM_CODED;
|
| - if( pTerm->iParent>=0 ){
|
| - WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
|
| - if( (--pOther->nChild)==0 ){
|
| - disableTerm(pLevel, pOther);
|
| - }
|
| - }
|
| - }
|
| -}
|
| -
|
| -/*
|
| -** Code an OP_Affinity opcode to apply the column affinity string zAff
|
| -** to the n registers starting at base.
|
| -**
|
| -** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
|
| -** beginning and end of zAff are ignored. If all entries in zAff are
|
| -** SQLITE_AFF_NONE, then no code gets generated.
|
| -**
|
| -** This routine makes its own copy of zAff so that the caller is free
|
| -** to modify zAff after this routine returns.
|
| -*/
|
| -static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
|
| - Vdbe *v = pParse->pVdbe;
|
| - if( zAff==0 ){
|
| - assert( pParse->db->mallocFailed );
|
| - return;
|
| - }
|
| - assert( v!=0 );
|
| -
|
| - /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
|
| - ** and end of the affinity string.
|
| - */
|
| - while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
|
| - n--;
|
| - base++;
|
| - zAff++;
|
| - }
|
| - while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
|
| - n--;
|
| - }
|
| -
|
| - /* Code the OP_Affinity opcode if there is anything left to do. */
|
| - if( n>0 ){
|
| - sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
|
| - sqlite3VdbeChangeP4(v, -1, zAff, n);
|
| - sqlite3ExprCacheAffinityChange(pParse, base, n);
|
| - }
|
| -}
|
| -
|
| -
|
| -/*
|
| -** Generate code for a single equality term of the WHERE clause. An equality
|
| -** term can be either X=expr or X IN (...). pTerm is the term to be
|
| -** coded.
|
| -**
|
| -** The current value for the constraint is left in register iReg.
|
| -**
|
| -** For a constraint of the form X=expr, the expression is evaluated and its
|
| -** result is left on the stack. For constraints of the form X IN (...)
|
| -** this routine sets up a loop that will iterate over all values of X.
|
| -*/
|
| -static int codeEqualityTerm(
|
| - Parse *pParse, /* The parsing context */
|
| - WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
|
| - WhereLevel *pLevel, /* The level of the FROM clause we are working on */
|
| - int iEq, /* Index of the equality term within this level */
|
| - int bRev, /* True for reverse-order IN operations */
|
| - int iTarget /* Attempt to leave results in this register */
|
| -){
|
| - Expr *pX = pTerm->pExpr;
|
| - Vdbe *v = pParse->pVdbe;
|
| - int iReg; /* Register holding results */
|
| -
|
| - assert( iTarget>0 );
|
| - if( pX->op==TK_EQ ){
|
| - iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
|
| - }else if( pX->op==TK_ISNULL ){
|
| - iReg = iTarget;
|
| - sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
|
| -#ifndef SQLITE_OMIT_SUBQUERY
|
| - }else{
|
| - int eType;
|
| - int iTab;
|
| - struct InLoop *pIn;
|
| - WhereLoop *pLoop = pLevel->pWLoop;
|
| -
|
| - if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
|
| - && pLoop->u.btree.pIndex!=0
|
| - && pLoop->u.btree.pIndex->aSortOrder[iEq]
|
| - ){
|
| - testcase( iEq==0 );
|
| - testcase( bRev );
|
| - bRev = !bRev;
|
| - }
|
| - assert( pX->op==TK_IN );
|
| - iReg = iTarget;
|
| - eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
|
| - if( eType==IN_INDEX_INDEX_DESC ){
|
| - testcase( bRev );
|
| - bRev = !bRev;
|
| - }
|
| - iTab = pX->iTable;
|
| - sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
|
| - VdbeCoverageIf(v, bRev);
|
| - VdbeCoverageIf(v, !bRev);
|
| - assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
|
| - pLoop->wsFlags |= WHERE_IN_ABLE;
|
| - if( pLevel->u.in.nIn==0 ){
|
| - pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
|
| - }
|
| - pLevel->u.in.nIn++;
|
| - pLevel->u.in.aInLoop =
|
| - sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
|
| - sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
|
| - pIn = pLevel->u.in.aInLoop;
|
| - if( pIn ){
|
| - pIn += pLevel->u.in.nIn - 1;
|
| - pIn->iCur = iTab;
|
| - if( eType==IN_INDEX_ROWID ){
|
| - pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
|
| - }else{
|
| - pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
|
| - }
|
| - pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
|
| - sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
|
| - }else{
|
| - pLevel->u.in.nIn = 0;
|
| - }
|
| -#endif
|
| - }
|
| - disableTerm(pLevel, pTerm);
|
| - return iReg;
|
| -}
|
| -
|
| -/*
|
| -** Generate code that will evaluate all == and IN constraints for an
|
| -** index scan.
|
| -**
|
| -** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
|
| -** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
|
| -** The index has as many as three equality constraints, but in this
|
| -** example, the third "c" value is an inequality. So only two
|
| -** constraints are coded. This routine will generate code to evaluate
|
| -** a==5 and b IN (1,2,3). The current values for a and b will be stored
|
| -** in consecutive registers and the index of the first register is returned.
|
| -**
|
| -** In the example above nEq==2. But this subroutine works for any value
|
| -** of nEq including 0. If nEq==0, this routine is nearly a no-op.
|
| -** The only thing it does is allocate the pLevel->iMem memory cell and
|
| -** compute the affinity string.
|
| -**
|
| -** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
|
| -** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
|
| -** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
|
| -** occurs after the nEq quality constraints.
|
| -**
|
| -** This routine allocates a range of nEq+nExtraReg memory cells and returns
|
| -** the index of the first memory cell in that range. The code that
|
| -** calls this routine will use that memory range to store keys for
|
| -** start and termination conditions of the loop.
|
| -** key value of the loop. If one or more IN operators appear, then
|
| -** this routine allocates an additional nEq memory cells for internal
|
| -** use.
|
| -**
|
| -** Before returning, *pzAff is set to point to a buffer containing a
|
| -** copy of the column affinity string of the index allocated using
|
| -** sqlite3DbMalloc(). Except, entries in the copy of the string associated
|
| -** with equality constraints that use NONE affinity are set to
|
| -** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
|
| -**
|
| -** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
|
| -** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
|
| -**
|
| -** In the example above, the index on t1(a) has TEXT affinity. But since
|
| -** the right hand side of the equality constraint (t2.b) has NONE affinity,
|
| -** no conversion should be attempted before using a t2.b value as part of
|
| -** a key to search the index. Hence the first byte in the returned affinity
|
| -** string in this example would be set to SQLITE_AFF_NONE.
|
| -*/
|
| -static int codeAllEqualityTerms(
|
| - Parse *pParse, /* Parsing context */
|
| - WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
|
| - int bRev, /* Reverse the order of IN operators */
|
| - int nExtraReg, /* Number of extra registers to allocate */
|
| - char **pzAff /* OUT: Set to point to affinity string */
|
| -){
|
| - u16 nEq; /* The number of == or IN constraints to code */
|
| - u16 nSkip; /* Number of left-most columns to skip */
|
| - Vdbe *v = pParse->pVdbe; /* The vm under construction */
|
| - Index *pIdx; /* The index being used for this loop */
|
| - WhereTerm *pTerm; /* A single constraint term */
|
| - WhereLoop *pLoop; /* The WhereLoop object */
|
| - int j; /* Loop counter */
|
| - int regBase; /* Base register */
|
| - int nReg; /* Number of registers to allocate */
|
| - char *zAff; /* Affinity string to return */
|
| -
|
| - /* This module is only called on query plans that use an index. */
|
| - pLoop = pLevel->pWLoop;
|
| - assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
|
| - nEq = pLoop->u.btree.nEq;
|
| - nSkip = pLoop->u.btree.nSkip;
|
| - pIdx = pLoop->u.btree.pIndex;
|
| - assert( pIdx!=0 );
|
| -
|
| - /* Figure out how many memory cells we will need then allocate them.
|
| - */
|
| - regBase = pParse->nMem + 1;
|
| - nReg = pLoop->u.btree.nEq + nExtraReg;
|
| - pParse->nMem += nReg;
|
| -
|
| - zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
|
| - if( !zAff ){
|
| - pParse->db->mallocFailed = 1;
|
| - }
|
| -
|
| - if( nSkip ){
|
| - int iIdxCur = pLevel->iIdxCur;
|
| - sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
|
| - VdbeCoverageIf(v, bRev==0);
|
| - VdbeCoverageIf(v, bRev!=0);
|
| - VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
|
| - j = sqlite3VdbeAddOp0(v, OP_Goto);
|
| - pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
|
| - iIdxCur, 0, regBase, nSkip);
|
| - VdbeCoverageIf(v, bRev==0);
|
| - VdbeCoverageIf(v, bRev!=0);
|
| - sqlite3VdbeJumpHere(v, j);
|
| - for(j=0; j<nSkip; j++){
|
| - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
|
| - assert( pIdx->aiColumn[j]>=0 );
|
| - VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
|
| - }
|
| - }
|
| -
|
| - /* Evaluate the equality constraints
|
| - */
|
| - assert( zAff==0 || (int)strlen(zAff)>=nEq );
|
| - for(j=nSkip; j<nEq; j++){
|
| - int r1;
|
| - pTerm = pLoop->aLTerm[j];
|
| - assert( pTerm!=0 );
|
| - /* The following testcase is true for indices with redundant columns.
|
| - ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
|
| - testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
|
| - testcase( pTerm->wtFlags & TERM_VIRTUAL );
|
| - r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
|
| - if( r1!=regBase+j ){
|
| - if( nReg==1 ){
|
| - sqlite3ReleaseTempReg(pParse, regBase);
|
| - regBase = r1;
|
| - }else{
|
| - sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
|
| - }
|
| - }
|
| - testcase( pTerm->eOperator & WO_ISNULL );
|
| - testcase( pTerm->eOperator & WO_IN );
|
| - if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
|
| - Expr *pRight = pTerm->pExpr->pRight;
|
| - if( sqlite3ExprCanBeNull(pRight) ){
|
| - sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
|
| - VdbeCoverage(v);
|
| - }
|
| - if( zAff ){
|
| - if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
|
| - zAff[j] = SQLITE_AFF_NONE;
|
| - }
|
| - if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
|
| - zAff[j] = SQLITE_AFF_NONE;
|
| - }
|
| - }
|
| - }
|
| - }
|
| - *pzAff = zAff;
|
| - return regBase;
|
| -}
|
| -
|
| -#ifndef SQLITE_OMIT_EXPLAIN
|
| -/*
|
| -** This routine is a helper for explainIndexRange() below
|
| -**
|
| -** pStr holds the text of an expression that we are building up one term
|
| -** at a time. This routine adds a new term to the end of the expression.
|
| -** Terms are separated by AND so add the "AND" text for second and subsequent
|
| -** terms only.
|
| -*/
|
| -static void explainAppendTerm(
|
| - StrAccum *pStr, /* The text expression being built */
|
| - int iTerm, /* Index of this term. First is zero */
|
| - const char *zColumn, /* Name of the column */
|
| - const char *zOp /* Name of the operator */
|
| -){
|
| - if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
|
| - sqlite3StrAccumAppendAll(pStr, zColumn);
|
| - sqlite3StrAccumAppend(pStr, zOp, 1);
|
| - sqlite3StrAccumAppend(pStr, "?", 1);
|
| -}
|
| -
|
| -/*
|
| -** Argument pLevel describes a strategy for scanning table pTab. This
|
| -** function appends text to pStr that describes the subset of table
|
| -** rows scanned by the strategy in the form of an SQL expression.
|
| -**
|
| -** For example, if the query:
|
| -**
|
| -** SELECT * FROM t1 WHERE a=1 AND b>2;
|
| -**
|
| -** is run and there is an index on (a, b), then this function returns a
|
| -** string similar to:
|
| -**
|
| -** "a=? AND b>?"
|
| -*/
|
| -static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
|
| - Index *pIndex = pLoop->u.btree.pIndex;
|
| - u16 nEq = pLoop->u.btree.nEq;
|
| - u16 nSkip = pLoop->u.btree.nSkip;
|
| - int i, j;
|
| - Column *aCol = pTab->aCol;
|
| - i16 *aiColumn = pIndex->aiColumn;
|
| -
|
| - if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
|
| - sqlite3StrAccumAppend(pStr, " (", 2);
|
| - for(i=0; i<nEq; i++){
|
| - char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
|
| - if( i>=nSkip ){
|
| - explainAppendTerm(pStr, i, z, "=");
|
| - }else{
|
| - if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
|
| - sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
|
| - }
|
| - }
|
| -
|
| - j = i;
|
| - if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
|
| - char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
|
| - explainAppendTerm(pStr, i++, z, ">");
|
| - }
|
| - if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
|
| - char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
|
| - explainAppendTerm(pStr, i, z, "<");
|
| - }
|
| - sqlite3StrAccumAppend(pStr, ")", 1);
|
| -}
|
| -
|
| -/*
|
| -** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
|
| -** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
|
| -** record is added to the output to describe the table scan strategy in
|
| -** pLevel.
|
| -*/
|
| -static void explainOneScan(
|
| - Parse *pParse, /* Parse context */
|
| - SrcList *pTabList, /* Table list this loop refers to */
|
| - WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
|
| - int iLevel, /* Value for "level" column of output */
|
| - int iFrom, /* Value for "from" column of output */
|
| - u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
|
| -){
|
| -#ifndef SQLITE_DEBUG
|
| - if( pParse->explain==2 )
|
| -#endif
|
| - {
|
| - struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
|
| - Vdbe *v = pParse->pVdbe; /* VM being constructed */
|
| - sqlite3 *db = pParse->db; /* Database handle */
|
| - int iId = pParse->iSelectId; /* Select id (left-most output column) */
|
| - int isSearch; /* True for a SEARCH. False for SCAN. */
|
| - WhereLoop *pLoop; /* The controlling WhereLoop object */
|
| - u32 flags; /* Flags that describe this loop */
|
| - char *zMsg; /* Text to add to EQP output */
|
| - StrAccum str; /* EQP output string */
|
| - char zBuf[100]; /* Initial space for EQP output string */
|
| -
|
| - pLoop = pLevel->pWLoop;
|
| - flags = pLoop->wsFlags;
|
| - if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
|
| -
|
| - isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
|
| - || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
|
| - || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
|
| -
|
| - sqlite3StrAccumInit(&str, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
|
| - str.db = db;
|
| - sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
|
| - if( pItem->pSelect ){
|
| - sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
|
| - }else{
|
| - sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
|
| - }
|
| -
|
| - if( pItem->zAlias ){
|
| - sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
|
| - }
|
| - if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
|
| - const char *zFmt = 0;
|
| - Index *pIdx;
|
| -
|
| - assert( pLoop->u.btree.pIndex!=0 );
|
| - pIdx = pLoop->u.btree.pIndex;
|
| - assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
|
| - if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
|
| - if( isSearch ){
|
| - zFmt = "PRIMARY KEY";
|
| - }
|
| - }else if( flags & WHERE_AUTO_INDEX ){
|
| - zFmt = "AUTOMATIC COVERING INDEX";
|
| - }else if( flags & WHERE_IDX_ONLY ){
|
| - zFmt = "COVERING INDEX %s";
|
| - }else{
|
| - zFmt = "INDEX %s";
|
| - }
|
| - if( zFmt ){
|
| - sqlite3StrAccumAppend(&str, " USING ", 7);
|
| - sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
|
| - explainIndexRange(&str, pLoop, pItem->pTab);
|
| - }
|
| - }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
|
| - const char *zRange;
|
| - if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
|
| - zRange = "(rowid=?)";
|
| - }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
|
| - zRange = "(rowid>? AND rowid<?)";
|
| - }else if( flags&WHERE_BTM_LIMIT ){
|
| - zRange = "(rowid>?)";
|
| - }else{
|
| - assert( flags&WHERE_TOP_LIMIT);
|
| - zRange = "(rowid<?)";
|
| - }
|
| - sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
|
| - sqlite3StrAccumAppendAll(&str, zRange);
|
| - }
|
| -#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| - else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
|
| - sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
|
| - pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
|
| - }
|
| -#endif
|
| -#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
|
| - if( pLoop->nOut>=10 ){
|
| - sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
|
| - }else{
|
| - sqlite3StrAccumAppend(&str, " (~1 row)", 9);
|
| - }
|
| -#endif
|
| - zMsg = sqlite3StrAccumFinish(&str);
|
| - sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
|
| - }
|
| -}
|
| -#else
|
| -# define explainOneScan(u,v,w,x,y,z)
|
| -#endif /* SQLITE_OMIT_EXPLAIN */
|
| -
|
| -
|
| -/*
|
| -** Generate code for the start of the iLevel-th loop in the WHERE clause
|
| -** implementation described by pWInfo.
|
| -*/
|
| -static Bitmask codeOneLoopStart(
|
| - WhereInfo *pWInfo, /* Complete information about the WHERE clause */
|
| - int iLevel, /* Which level of pWInfo->a[] should be coded */
|
| - Bitmask notReady /* Which tables are currently available */
|
| -){
|
| - int j, k; /* Loop counters */
|
| - int iCur; /* The VDBE cursor for the table */
|
| - int addrNxt; /* Where to jump to continue with the next IN case */
|
| - int omitTable; /* True if we use the index only */
|
| - int bRev; /* True if we need to scan in reverse order */
|
| - WhereLevel *pLevel; /* The where level to be coded */
|
| - WhereLoop *pLoop; /* The WhereLoop object being coded */
|
| - WhereClause *pWC; /* Decomposition of the entire WHERE clause */
|
| - WhereTerm *pTerm; /* A WHERE clause term */
|
| - Parse *pParse; /* Parsing context */
|
| - sqlite3 *db; /* Database connection */
|
| - Vdbe *v; /* The prepared stmt under constructions */
|
| - struct SrcList_item *pTabItem; /* FROM clause term being coded */
|
| - int addrBrk; /* Jump here to break out of the loop */
|
| - int addrCont; /* Jump here to continue with next cycle */
|
| - int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
|
| - int iReleaseReg = 0; /* Temp register to free before returning */
|
| -
|
| - pParse = pWInfo->pParse;
|
| - v = pParse->pVdbe;
|
| - pWC = &pWInfo->sWC;
|
| - db = pParse->db;
|
| - pLevel = &pWInfo->a[iLevel];
|
| - pLoop = pLevel->pWLoop;
|
| - pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
|
| - iCur = pTabItem->iCursor;
|
| - pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
|
| - bRev = (pWInfo->revMask>>iLevel)&1;
|
| - omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
|
| - && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
|
| - VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
|
| -
|
| - /* Create labels for the "break" and "continue" instructions
|
| - ** for the current loop. Jump to addrBrk to break out of a loop.
|
| - ** Jump to cont to go immediately to the next iteration of the
|
| - ** loop.
|
| - **
|
| - ** When there is an IN operator, we also have a "addrNxt" label that
|
| - ** means to continue with the next IN value combination. When
|
| - ** there are no IN operators in the constraints, the "addrNxt" label
|
| - ** is the same as "addrBrk".
|
| - */
|
| - addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
|
| - addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
|
| -
|
| - /* If this is the right table of a LEFT OUTER JOIN, allocate and
|
| - ** initialize a memory cell that records if this table matches any
|
| - ** row of the left table of the join.
|
| - */
|
| - if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
|
| - pLevel->iLeftJoin = ++pParse->nMem;
|
| - sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
|
| - VdbeComment((v, "init LEFT JOIN no-match flag"));
|
| - }
|
| -
|
| - /* Special case of a FROM clause subquery implemented as a co-routine */
|
| - if( pTabItem->viaCoroutine ){
|
| - int regYield = pTabItem->regReturn;
|
| - sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
|
| - pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
|
| - VdbeCoverage(v);
|
| - VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
|
| - pLevel->op = OP_Goto;
|
| - }else
|
| -
|
| -#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| - if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
|
| - /* Case 1: The table is a virtual-table. Use the VFilter and VNext
|
| - ** to access the data.
|
| - */
|
| - int iReg; /* P3 Value for OP_VFilter */
|
| - int addrNotFound;
|
| - int nConstraint = pLoop->nLTerm;
|
| -
|
| - sqlite3ExprCachePush(pParse);
|
| - iReg = sqlite3GetTempRange(pParse, nConstraint+2);
|
| - addrNotFound = pLevel->addrBrk;
|
| - for(j=0; j<nConstraint; j++){
|
| - int iTarget = iReg+j+2;
|
| - pTerm = pLoop->aLTerm[j];
|
| - if( pTerm==0 ) continue;
|
| - if( pTerm->eOperator & WO_IN ){
|
| - codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
|
| - addrNotFound = pLevel->addrNxt;
|
| - }else{
|
| - sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
|
| - }
|
| - }
|
| - sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
|
| - sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
|
| - sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
|
| - pLoop->u.vtab.idxStr,
|
| - pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
|
| - VdbeCoverage(v);
|
| - pLoop->u.vtab.needFree = 0;
|
| - for(j=0; j<nConstraint && j<16; j++){
|
| - if( (pLoop->u.vtab.omitMask>>j)&1 ){
|
| - disableTerm(pLevel, pLoop->aLTerm[j]);
|
| - }
|
| - }
|
| - pLevel->op = OP_VNext;
|
| - pLevel->p1 = iCur;
|
| - pLevel->p2 = sqlite3VdbeCurrentAddr(v);
|
| - sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
|
| - sqlite3ExprCachePop(pParse);
|
| - }else
|
| -#endif /* SQLITE_OMIT_VIRTUALTABLE */
|
| -
|
| - if( (pLoop->wsFlags & WHERE_IPK)!=0
|
| - && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
|
| - ){
|
| - /* Case 2: We can directly reference a single row using an
|
| - ** equality comparison against the ROWID field. Or
|
| - ** we reference multiple rows using a "rowid IN (...)"
|
| - ** construct.
|
| - */
|
| - assert( pLoop->u.btree.nEq==1 );
|
| - pTerm = pLoop->aLTerm[0];
|
| - assert( pTerm!=0 );
|
| - assert( pTerm->pExpr!=0 );
|
| - assert( omitTable==0 );
|
| - testcase( pTerm->wtFlags & TERM_VIRTUAL );
|
| - iReleaseReg = ++pParse->nMem;
|
| - iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
|
| - if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
|
| - addrNxt = pLevel->addrNxt;
|
| - sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
|
| - sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
|
| - VdbeCoverage(v);
|
| - sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
|
| - sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
|
| - VdbeComment((v, "pk"));
|
| - pLevel->op = OP_Noop;
|
| - }else if( (pLoop->wsFlags & WHERE_IPK)!=0
|
| - && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
|
| - ){
|
| - /* Case 3: We have an inequality comparison against the ROWID field.
|
| - */
|
| - int testOp = OP_Noop;
|
| - int start;
|
| - int memEndValue = 0;
|
| - WhereTerm *pStart, *pEnd;
|
| -
|
| - assert( omitTable==0 );
|
| - j = 0;
|
| - pStart = pEnd = 0;
|
| - if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
|
| - if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
|
| - assert( pStart!=0 || pEnd!=0 );
|
| - if( bRev ){
|
| - pTerm = pStart;
|
| - pStart = pEnd;
|
| - pEnd = pTerm;
|
| - }
|
| - if( pStart ){
|
| - Expr *pX; /* The expression that defines the start bound */
|
| - int r1, rTemp; /* Registers for holding the start boundary */
|
| -
|
| - /* The following constant maps TK_xx codes into corresponding
|
| - ** seek opcodes. It depends on a particular ordering of TK_xx
|
| - */
|
| - const u8 aMoveOp[] = {
|
| - /* TK_GT */ OP_SeekGT,
|
| - /* TK_LE */ OP_SeekLE,
|
| - /* TK_LT */ OP_SeekLT,
|
| - /* TK_GE */ OP_SeekGE
|
| - };
|
| - assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
|
| - assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
|
| - assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
|
| -
|
| - assert( (pStart->wtFlags & TERM_VNULL)==0 );
|
| - testcase( pStart->wtFlags & TERM_VIRTUAL );
|
| - pX = pStart->pExpr;
|
| - assert( pX!=0 );
|
| - testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
|
| - r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
|
| - sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
|
| - VdbeComment((v, "pk"));
|
| - VdbeCoverageIf(v, pX->op==TK_GT);
|
| - VdbeCoverageIf(v, pX->op==TK_LE);
|
| - VdbeCoverageIf(v, pX->op==TK_LT);
|
| - VdbeCoverageIf(v, pX->op==TK_GE);
|
| - sqlite3ExprCacheAffinityChange(pParse, r1, 1);
|
| - sqlite3ReleaseTempReg(pParse, rTemp);
|
| - disableTerm(pLevel, pStart);
|
| - }else{
|
| - sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
|
| - VdbeCoverageIf(v, bRev==0);
|
| - VdbeCoverageIf(v, bRev!=0);
|
| - }
|
| - if( pEnd ){
|
| - Expr *pX;
|
| - pX = pEnd->pExpr;
|
| - assert( pX!=0 );
|
| - assert( (pEnd->wtFlags & TERM_VNULL)==0 );
|
| - testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
|
| - testcase( pEnd->wtFlags & TERM_VIRTUAL );
|
| - memEndValue = ++pParse->nMem;
|
| - sqlite3ExprCode(pParse, pX->pRight, memEndValue);
|
| - if( pX->op==TK_LT || pX->op==TK_GT ){
|
| - testOp = bRev ? OP_Le : OP_Ge;
|
| - }else{
|
| - testOp = bRev ? OP_Lt : OP_Gt;
|
| - }
|
| - disableTerm(pLevel, pEnd);
|
| - }
|
| - start = sqlite3VdbeCurrentAddr(v);
|
| - pLevel->op = bRev ? OP_Prev : OP_Next;
|
| - pLevel->p1 = iCur;
|
| - pLevel->p2 = start;
|
| - assert( pLevel->p5==0 );
|
| - if( testOp!=OP_Noop ){
|
| - iRowidReg = ++pParse->nMem;
|
| - sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
|
| - sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
|
| - sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
|
| - VdbeCoverageIf(v, testOp==OP_Le);
|
| - VdbeCoverageIf(v, testOp==OP_Lt);
|
| - VdbeCoverageIf(v, testOp==OP_Ge);
|
| - VdbeCoverageIf(v, testOp==OP_Gt);
|
| - sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
|
| - }
|
| - }else if( pLoop->wsFlags & WHERE_INDEXED ){
|
| - /* Case 4: A scan using an index.
|
| - **
|
| - ** The WHERE clause may contain zero or more equality
|
| - ** terms ("==" or "IN" operators) that refer to the N
|
| - ** left-most columns of the index. It may also contain
|
| - ** inequality constraints (>, <, >= or <=) on the indexed
|
| - ** column that immediately follows the N equalities. Only
|
| - ** the right-most column can be an inequality - the rest must
|
| - ** use the "==" and "IN" operators. For example, if the
|
| - ** index is on (x,y,z), then the following clauses are all
|
| - ** optimized:
|
| - **
|
| - ** x=5
|
| - ** x=5 AND y=10
|
| - ** x=5 AND y<10
|
| - ** x=5 AND y>5 AND y<10
|
| - ** x=5 AND y=5 AND z<=10
|
| - **
|
| - ** The z<10 term of the following cannot be used, only
|
| - ** the x=5 term:
|
| - **
|
| - ** x=5 AND z<10
|
| - **
|
| - ** N may be zero if there are inequality constraints.
|
| - ** If there are no inequality constraints, then N is at
|
| - ** least one.
|
| - **
|
| - ** This case is also used when there are no WHERE clause
|
| - ** constraints but an index is selected anyway, in order
|
| - ** to force the output order to conform to an ORDER BY.
|
| - */
|
| - static const u8 aStartOp[] = {
|
| - 0,
|
| - 0,
|
| - OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
|
| - OP_Last, /* 3: (!start_constraints && startEq && bRev) */
|
| - OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
|
| - OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
|
| - OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
|
| - OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
|
| - };
|
| - static const u8 aEndOp[] = {
|
| - OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
|
| - OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
|
| - OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
|
| - OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
|
| - };
|
| - u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
|
| - int regBase; /* Base register holding constraint values */
|
| - WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
|
| - WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
|
| - int startEq; /* True if range start uses ==, >= or <= */
|
| - int endEq; /* True if range end uses ==, >= or <= */
|
| - int start_constraints; /* Start of range is constrained */
|
| - int nConstraint; /* Number of constraint terms */
|
| - Index *pIdx; /* The index we will be using */
|
| - int iIdxCur; /* The VDBE cursor for the index */
|
| - int nExtraReg = 0; /* Number of extra registers needed */
|
| - int op; /* Instruction opcode */
|
| - char *zStartAff; /* Affinity for start of range constraint */
|
| - char cEndAff = 0; /* Affinity for end of range constraint */
|
| - u8 bSeekPastNull = 0; /* True to seek past initial nulls */
|
| - u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
|
| -
|
| - pIdx = pLoop->u.btree.pIndex;
|
| - iIdxCur = pLevel->iIdxCur;
|
| - assert( nEq>=pLoop->u.btree.nSkip );
|
| -
|
| - /* If this loop satisfies a sort order (pOrderBy) request that
|
| - ** was passed to this function to implement a "SELECT min(x) ..."
|
| - ** query, then the caller will only allow the loop to run for
|
| - ** a single iteration. This means that the first row returned
|
| - ** should not have a NULL value stored in 'x'. If column 'x' is
|
| - ** the first one after the nEq equality constraints in the index,
|
| - ** this requires some special handling.
|
| - */
|
| - assert( pWInfo->pOrderBy==0
|
| - || pWInfo->pOrderBy->nExpr==1
|
| - || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
|
| - if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
|
| - && pWInfo->nOBSat>0
|
| - && (pIdx->nKeyCol>nEq)
|
| - ){
|
| - assert( pLoop->u.btree.nSkip==0 );
|
| - bSeekPastNull = 1;
|
| - nExtraReg = 1;
|
| - }
|
| -
|
| - /* Find any inequality constraint terms for the start and end
|
| - ** of the range.
|
| - */
|
| - j = nEq;
|
| - if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
|
| - pRangeStart = pLoop->aLTerm[j++];
|
| - nExtraReg = 1;
|
| - }
|
| - if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
|
| - pRangeEnd = pLoop->aLTerm[j++];
|
| - nExtraReg = 1;
|
| - if( pRangeStart==0
|
| - && (j = pIdx->aiColumn[nEq])>=0
|
| - && pIdx->pTable->aCol[j].notNull==0
|
| - ){
|
| - bSeekPastNull = 1;
|
| - }
|
| - }
|
| - assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
|
| -
|
| - /* Generate code to evaluate all constraint terms using == or IN
|
| - ** and store the values of those terms in an array of registers
|
| - ** starting at regBase.
|
| - */
|
| - regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
|
| - assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
|
| - if( zStartAff ) cEndAff = zStartAff[nEq];
|
| - addrNxt = pLevel->addrNxt;
|
| -
|
| - /* If we are doing a reverse order scan on an ascending index, or
|
| - ** a forward order scan on a descending index, interchange the
|
| - ** start and end terms (pRangeStart and pRangeEnd).
|
| - */
|
| - if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
|
| - || (bRev && pIdx->nKeyCol==nEq)
|
| - ){
|
| - SWAP(WhereTerm *, pRangeEnd, pRangeStart);
|
| - SWAP(u8, bSeekPastNull, bStopAtNull);
|
| - }
|
| -
|
| - testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
|
| - testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
|
| - testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
|
| - testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
|
| - startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
|
| - endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
|
| - start_constraints = pRangeStart || nEq>0;
|
| -
|
| - /* Seek the index cursor to the start of the range. */
|
| - nConstraint = nEq;
|
| - if( pRangeStart ){
|
| - Expr *pRight = pRangeStart->pExpr->pRight;
|
| - sqlite3ExprCode(pParse, pRight, regBase+nEq);
|
| - if( (pRangeStart->wtFlags & TERM_VNULL)==0
|
| - && sqlite3ExprCanBeNull(pRight)
|
| - ){
|
| - sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
|
| - VdbeCoverage(v);
|
| - }
|
| - if( zStartAff ){
|
| - if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
|
| - /* Since the comparison is to be performed with no conversions
|
| - ** applied to the operands, set the affinity to apply to pRight to
|
| - ** SQLITE_AFF_NONE. */
|
| - zStartAff[nEq] = SQLITE_AFF_NONE;
|
| - }
|
| - if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
|
| - zStartAff[nEq] = SQLITE_AFF_NONE;
|
| - }
|
| - }
|
| - nConstraint++;
|
| - testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
|
| - }else if( bSeekPastNull ){
|
| - sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
|
| - nConstraint++;
|
| - startEq = 0;
|
| - start_constraints = 1;
|
| - }
|
| - codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
|
| - op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
|
| - assert( op!=0 );
|
| - sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
|
| - VdbeCoverage(v);
|
| - VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
|
| - VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
|
| - VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
|
| - VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
|
| - VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
|
| - VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
|
| -
|
| - /* Load the value for the inequality constraint at the end of the
|
| - ** range (if any).
|
| - */
|
| - nConstraint = nEq;
|
| - if( pRangeEnd ){
|
| - Expr *pRight = pRangeEnd->pExpr->pRight;
|
| - sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
|
| - sqlite3ExprCode(pParse, pRight, regBase+nEq);
|
| - if( (pRangeEnd->wtFlags & TERM_VNULL)==0
|
| - && sqlite3ExprCanBeNull(pRight)
|
| - ){
|
| - sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
|
| - VdbeCoverage(v);
|
| - }
|
| - if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
|
| - && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
|
| - ){
|
| - codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
|
| - }
|
| - nConstraint++;
|
| - testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
|
| - }else if( bStopAtNull ){
|
| - sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
|
| - endEq = 0;
|
| - nConstraint++;
|
| - }
|
| - sqlite3DbFree(db, zStartAff);
|
| -
|
| - /* Top of the loop body */
|
| - pLevel->p2 = sqlite3VdbeCurrentAddr(v);
|
| -
|
| - /* Check if the index cursor is past the end of the range. */
|
| - if( nConstraint ){
|
| - op = aEndOp[bRev*2 + endEq];
|
| - sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
|
| - testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
|
| - testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
|
| - testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
|
| - testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
|
| - }
|
| -
|
| - /* Seek the table cursor, if required */
|
| - disableTerm(pLevel, pRangeStart);
|
| - disableTerm(pLevel, pRangeEnd);
|
| - if( omitTable ){
|
| - /* pIdx is a covering index. No need to access the main table. */
|
| - }else if( HasRowid(pIdx->pTable) ){
|
| - iRowidReg = ++pParse->nMem;
|
| - sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
|
| - sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
|
| - sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
|
| - }else if( iCur!=iIdxCur ){
|
| - Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
|
| - iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
|
| - for(j=0; j<pPk->nKeyCol; j++){
|
| - k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
|
| - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
|
| - }
|
| - sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
|
| - iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
|
| - }
|
| -
|
| - /* Record the instruction used to terminate the loop. Disable
|
| - ** WHERE clause terms made redundant by the index range scan.
|
| - */
|
| - if( pLoop->wsFlags & WHERE_ONEROW ){
|
| - pLevel->op = OP_Noop;
|
| - }else if( bRev ){
|
| - pLevel->op = OP_Prev;
|
| - }else{
|
| - pLevel->op = OP_Next;
|
| - }
|
| - pLevel->p1 = iIdxCur;
|
| - pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
|
| - if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
|
| - pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
|
| - }else{
|
| - assert( pLevel->p5==0 );
|
| - }
|
| - }else
|
| -
|
| -#ifndef SQLITE_OMIT_OR_OPTIMIZATION
|
| - if( pLoop->wsFlags & WHERE_MULTI_OR ){
|
| - /* Case 5: Two or more separately indexed terms connected by OR
|
| - **
|
| - ** Example:
|
| - **
|
| - ** CREATE TABLE t1(a,b,c,d);
|
| - ** CREATE INDEX i1 ON t1(a);
|
| - ** CREATE INDEX i2 ON t1(b);
|
| - ** CREATE INDEX i3 ON t1(c);
|
| - **
|
| - ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
|
| - **
|
| - ** In the example, there are three indexed terms connected by OR.
|
| - ** The top of the loop looks like this:
|
| - **
|
| - ** Null 1 # Zero the rowset in reg 1
|
| - **
|
| - ** Then, for each indexed term, the following. The arguments to
|
| - ** RowSetTest are such that the rowid of the current row is inserted
|
| - ** into the RowSet. If it is already present, control skips the
|
| - ** Gosub opcode and jumps straight to the code generated by WhereEnd().
|
| - **
|
| - ** sqlite3WhereBegin(<term>)
|
| - ** RowSetTest # Insert rowid into rowset
|
| - ** Gosub 2 A
|
| - ** sqlite3WhereEnd()
|
| - **
|
| - ** Following the above, code to terminate the loop. Label A, the target
|
| - ** of the Gosub above, jumps to the instruction right after the Goto.
|
| - **
|
| - ** Null 1 # Zero the rowset in reg 1
|
| - ** Goto B # The loop is finished.
|
| - **
|
| - ** A: <loop body> # Return data, whatever.
|
| - **
|
| - ** Return 2 # Jump back to the Gosub
|
| - **
|
| - ** B: <after the loop>
|
| - **
|
| - ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
|
| - ** use an ephemeral index instead of a RowSet to record the primary
|
| - ** keys of the rows we have already seen.
|
| - **
|
| - */
|
| - WhereClause *pOrWc; /* The OR-clause broken out into subterms */
|
| - SrcList *pOrTab; /* Shortened table list or OR-clause generation */
|
| - Index *pCov = 0; /* Potential covering index (or NULL) */
|
| - int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
|
| -
|
| - int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
|
| - int regRowset = 0; /* Register for RowSet object */
|
| - int regRowid = 0; /* Register holding rowid */
|
| - int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
|
| - int iRetInit; /* Address of regReturn init */
|
| - int untestedTerms = 0; /* Some terms not completely tested */
|
| - int ii; /* Loop counter */
|
| - u16 wctrlFlags; /* Flags for sub-WHERE clause */
|
| - Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
|
| - Table *pTab = pTabItem->pTab;
|
| -
|
| - pTerm = pLoop->aLTerm[0];
|
| - assert( pTerm!=0 );
|
| - assert( pTerm->eOperator & WO_OR );
|
| - assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
|
| - pOrWc = &pTerm->u.pOrInfo->wc;
|
| - pLevel->op = OP_Return;
|
| - pLevel->p1 = regReturn;
|
| -
|
| - /* Set up a new SrcList in pOrTab containing the table being scanned
|
| - ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
|
| - ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
|
| - */
|
| - if( pWInfo->nLevel>1 ){
|
| - int nNotReady; /* The number of notReady tables */
|
| - struct SrcList_item *origSrc; /* Original list of tables */
|
| - nNotReady = pWInfo->nLevel - iLevel - 1;
|
| - pOrTab = sqlite3StackAllocRaw(db,
|
| - sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
|
| - if( pOrTab==0 ) return notReady;
|
| - pOrTab->nAlloc = (u8)(nNotReady + 1);
|
| - pOrTab->nSrc = pOrTab->nAlloc;
|
| - memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
|
| - origSrc = pWInfo->pTabList->a;
|
| - for(k=1; k<=nNotReady; k++){
|
| - memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
|
| - }
|
| - }else{
|
| - pOrTab = pWInfo->pTabList;
|
| - }
|
| -
|
| - /* Initialize the rowset register to contain NULL. An SQL NULL is
|
| - ** equivalent to an empty rowset. Or, create an ephemeral index
|
| - ** capable of holding primary keys in the case of a WITHOUT ROWID.
|
| - **
|
| - ** Also initialize regReturn to contain the address of the instruction
|
| - ** immediately following the OP_Return at the bottom of the loop. This
|
| - ** is required in a few obscure LEFT JOIN cases where control jumps
|
| - ** over the top of the loop into the body of it. In this case the
|
| - ** correct response for the end-of-loop code (the OP_Return) is to
|
| - ** fall through to the next instruction, just as an OP_Next does if
|
| - ** called on an uninitialized cursor.
|
| - */
|
| - if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
|
| - if( HasRowid(pTab) ){
|
| - regRowset = ++pParse->nMem;
|
| - sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
|
| - }else{
|
| - Index *pPk = sqlite3PrimaryKeyIndex(pTab);
|
| - regRowset = pParse->nTab++;
|
| - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
|
| - sqlite3VdbeSetP4KeyInfo(pParse, pPk);
|
| - }
|
| - regRowid = ++pParse->nMem;
|
| - }
|
| - iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
|
| -
|
| - /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
|
| - ** Then for every term xN, evaluate as the subexpression: xN AND z
|
| - ** That way, terms in y that are factored into the disjunction will
|
| - ** be picked up by the recursive calls to sqlite3WhereBegin() below.
|
| - **
|
| - ** Actually, each subexpression is converted to "xN AND w" where w is
|
| - ** the "interesting" terms of z - terms that did not originate in the
|
| - ** ON or USING clause of a LEFT JOIN, and terms that are usable as
|
| - ** indices.
|
| - **
|
| - ** This optimization also only applies if the (x1 OR x2 OR ...) term
|
| - ** is not contained in the ON clause of a LEFT JOIN.
|
| - ** See ticket http://www.sqlite.org/src/info/f2369304e4
|
| - */
|
| - if( pWC->nTerm>1 ){
|
| - int iTerm;
|
| - for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
|
| - Expr *pExpr = pWC->a[iTerm].pExpr;
|
| - if( &pWC->a[iTerm] == pTerm ) continue;
|
| - if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
|
| - testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
|
| - testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
|
| - if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
|
| - if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
|
| - pExpr = sqlite3ExprDup(db, pExpr, 0);
|
| - pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
|
| - }
|
| - if( pAndExpr ){
|
| - pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
|
| - }
|
| - }
|
| + UnpackedRecord *pRec = pBuilder->pRec;
|
| + u8 aff; /* Column affinity */
|
| + int rc; /* Subfunction return code */
|
| + tRowcnt a[2]; /* Statistics */
|
| + int bOk;
|
|
|
| - /* Run a separate WHERE clause for each term of the OR clause. After
|
| - ** eliminating duplicates from other WHERE clauses, the action for each
|
| - ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
|
| - */
|
| - wctrlFlags = WHERE_OMIT_OPEN_CLOSE
|
| - | WHERE_FORCE_TABLE
|
| - | WHERE_ONETABLE_ONLY;
|
| - for(ii=0; ii<pOrWc->nTerm; ii++){
|
| - WhereTerm *pOrTerm = &pOrWc->a[ii];
|
| - if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
|
| - WhereInfo *pSubWInfo; /* Info for single OR-term scan */
|
| - Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
|
| - int j1 = 0; /* Address of jump operation */
|
| - if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
|
| - pAndExpr->pLeft = pOrExpr;
|
| - pOrExpr = pAndExpr;
|
| - }
|
| - /* Loop through table entries that match term pOrTerm. */
|
| - WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
|
| - pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
|
| - wctrlFlags, iCovCur);
|
| - assert( pSubWInfo || pParse->nErr || db->mallocFailed );
|
| - if( pSubWInfo ){
|
| - WhereLoop *pSubLoop;
|
| - explainOneScan(
|
| - pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
|
| - );
|
| - /* This is the sub-WHERE clause body. First skip over
|
| - ** duplicate rows from prior sub-WHERE clauses, and record the
|
| - ** rowid (or PRIMARY KEY) for the current row so that the same
|
| - ** row will be skipped in subsequent sub-WHERE clauses.
|
| - */
|
| - if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
|
| - int r;
|
| - int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
|
| - if( HasRowid(pTab) ){
|
| - r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
|
| - j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
|
| - VdbeCoverage(v);
|
| - }else{
|
| - Index *pPk = sqlite3PrimaryKeyIndex(pTab);
|
| - int nPk = pPk->nKeyCol;
|
| - int iPk;
|
| -
|
| - /* Read the PK into an array of temp registers. */
|
| - r = sqlite3GetTempRange(pParse, nPk);
|
| - for(iPk=0; iPk<nPk; iPk++){
|
| - int iCol = pPk->aiColumn[iPk];
|
| - sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
|
| - }
|
| + assert( nEq>=1 );
|
| + assert( nEq<=p->nColumn );
|
| + assert( p->aSample!=0 );
|
| + assert( p->nSample>0 );
|
| + assert( pBuilder->nRecValid<nEq );
|
|
|
| - /* Check if the temp table already contains this key. If so,
|
| - ** the row has already been included in the result set and
|
| - ** can be ignored (by jumping past the Gosub below). Otherwise,
|
| - ** insert the key into the temp table and proceed with processing
|
| - ** the row.
|
| - **
|
| - ** Use some of the same optimizations as OP_RowSetTest: If iSet
|
| - ** is zero, assume that the key cannot already be present in
|
| - ** the temp table. And if iSet is -1, assume that there is no
|
| - ** need to insert the key into the temp table, as it will never
|
| - ** be tested for. */
|
| - if( iSet ){
|
| - j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
|
| - VdbeCoverage(v);
|
| - }
|
| - if( iSet>=0 ){
|
| - sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
|
| - sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
|
| - if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
|
| - }
|
| + /* If values are not available for all fields of the index to the left
|
| + ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
|
| + if( pBuilder->nRecValid<(nEq-1) ){
|
| + return SQLITE_NOTFOUND;
|
| + }
|
|
|
| - /* Release the array of temp registers */
|
| - sqlite3ReleaseTempRange(pParse, r, nPk);
|
| - }
|
| - }
|
| + /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
|
| + ** below would return the same value. */
|
| + if( nEq>=p->nColumn ){
|
| + *pnRow = 1;
|
| + return SQLITE_OK;
|
| + }
|
|
|
| - /* Invoke the main loop body as a subroutine */
|
| - sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
|
| -
|
| - /* Jump here (skipping the main loop body subroutine) if the
|
| - ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
|
| - if( j1 ) sqlite3VdbeJumpHere(v, j1);
|
| -
|
| - /* The pSubWInfo->untestedTerms flag means that this OR term
|
| - ** contained one or more AND term from a notReady table. The
|
| - ** terms from the notReady table could not be tested and will
|
| - ** need to be tested later.
|
| - */
|
| - if( pSubWInfo->untestedTerms ) untestedTerms = 1;
|
| -
|
| - /* If all of the OR-connected terms are optimized using the same
|
| - ** index, and the index is opened using the same cursor number
|
| - ** by each call to sqlite3WhereBegin() made by this loop, it may
|
| - ** be possible to use that index as a covering index.
|
| - **
|
| - ** If the call to sqlite3WhereBegin() above resulted in a scan that
|
| - ** uses an index, and this is either the first OR-connected term
|
| - ** processed or the index is the same as that used by all previous
|
| - ** terms, set pCov to the candidate covering index. Otherwise, set
|
| - ** pCov to NULL to indicate that no candidate covering index will
|
| - ** be available.
|
| - */
|
| - pSubLoop = pSubWInfo->a[0].pWLoop;
|
| - assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
|
| - if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
|
| - && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
|
| - && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
|
| - ){
|
| - assert( pSubWInfo->a[0].iIdxCur==iCovCur );
|
| - pCov = pSubLoop->u.btree.pIndex;
|
| - wctrlFlags |= WHERE_REOPEN_IDX;
|
| - }else{
|
| - pCov = 0;
|
| - }
|
| + aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq-1);
|
| + rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
|
| + pBuilder->pRec = pRec;
|
| + if( rc!=SQLITE_OK ) return rc;
|
| + if( bOk==0 ) return SQLITE_NOTFOUND;
|
| + pBuilder->nRecValid = nEq;
|
|
|
| - /* Finish the loop through table entries that match term pOrTerm. */
|
| - sqlite3WhereEnd(pSubWInfo);
|
| - }
|
| - }
|
| - }
|
| - pLevel->u.pCovidx = pCov;
|
| - if( pCov ) pLevel->iIdxCur = iCovCur;
|
| - if( pAndExpr ){
|
| - pAndExpr->pLeft = 0;
|
| - sqlite3ExprDelete(db, pAndExpr);
|
| - }
|
| - sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
|
| - sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
|
| - sqlite3VdbeResolveLabel(v, iLoopBody);
|
| -
|
| - if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
|
| - if( !untestedTerms ) disableTerm(pLevel, pTerm);
|
| - }else
|
| -#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
|
| -
|
| - {
|
| - /* Case 6: There is no usable index. We must do a complete
|
| - ** scan of the entire table.
|
| - */
|
| - static const u8 aStep[] = { OP_Next, OP_Prev };
|
| - static const u8 aStart[] = { OP_Rewind, OP_Last };
|
| - assert( bRev==0 || bRev==1 );
|
| - if( pTabItem->isRecursive ){
|
| - /* Tables marked isRecursive have only a single row that is stored in
|
| - ** a pseudo-cursor. No need to Rewind or Next such cursors. */
|
| - pLevel->op = OP_Noop;
|
| - }else{
|
| - pLevel->op = aStep[bRev];
|
| - pLevel->p1 = iCur;
|
| - pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
|
| - VdbeCoverageIf(v, bRev==0);
|
| - VdbeCoverageIf(v, bRev!=0);
|
| - pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
|
| - }
|
| - }
|
| + whereKeyStats(pParse, p, pRec, 0, a);
|
| + WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
|
| + *pnRow = a[1];
|
| +
|
| + return rc;
|
| +}
|
| +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
|
|
|
| - /* Insert code to test every subexpression that can be completely
|
| - ** computed using the current set of tables.
|
| - */
|
| - for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
|
| - Expr *pE;
|
| - testcase( pTerm->wtFlags & TERM_VIRTUAL );
|
| - testcase( pTerm->wtFlags & TERM_CODED );
|
| - if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
|
| - if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
|
| - testcase( pWInfo->untestedTerms==0
|
| - && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
|
| - pWInfo->untestedTerms = 1;
|
| - continue;
|
| - }
|
| - pE = pTerm->pExpr;
|
| - assert( pE!=0 );
|
| - if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
|
| - continue;
|
| - }
|
| - sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
|
| - pTerm->wtFlags |= TERM_CODED;
|
| - }
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| +/*
|
| +** Estimate the number of rows that will be returned based on
|
| +** an IN constraint where the right-hand side of the IN operator
|
| +** is a list of values. Example:
|
| +**
|
| +** WHERE x IN (1,2,3,4)
|
| +**
|
| +** Write the estimated row count into *pnRow and return SQLITE_OK.
|
| +** If unable to make an estimate, leave *pnRow unchanged and return
|
| +** non-zero.
|
| +**
|
| +** This routine can fail if it is unable to load a collating sequence
|
| +** required for string comparison, or if unable to allocate memory
|
| +** for a UTF conversion required for comparison. The error is stored
|
| +** in the pParse structure.
|
| +*/
|
| +static int whereInScanEst(
|
| + Parse *pParse, /* Parsing & code generating context */
|
| + WhereLoopBuilder *pBuilder,
|
| + ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
|
| + tRowcnt *pnRow /* Write the revised row estimate here */
|
| +){
|
| + Index *p = pBuilder->pNew->u.btree.pIndex;
|
| + i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
|
| + int nRecValid = pBuilder->nRecValid;
|
| + int rc = SQLITE_OK; /* Subfunction return code */
|
| + tRowcnt nEst; /* Number of rows for a single term */
|
| + tRowcnt nRowEst = 0; /* New estimate of the number of rows */
|
| + int i; /* Loop counter */
|
|
|
| - /* Insert code to test for implied constraints based on transitivity
|
| - ** of the "==" operator.
|
| - **
|
| - ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
|
| - ** and we are coding the t1 loop and the t2 loop has not yet coded,
|
| - ** then we cannot use the "t1.a=t2.b" constraint, but we can code
|
| - ** the implied "t1.a=123" constraint.
|
| - */
|
| - for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
|
| - Expr *pE, *pEAlt;
|
| - WhereTerm *pAlt;
|
| - if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
|
| - if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
|
| - if( pTerm->leftCursor!=iCur ) continue;
|
| - if( pLevel->iLeftJoin ) continue;
|
| - pE = pTerm->pExpr;
|
| - assert( !ExprHasProperty(pE, EP_FromJoin) );
|
| - assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
|
| - pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
|
| - if( pAlt==0 ) continue;
|
| - if( pAlt->wtFlags & (TERM_CODED) ) continue;
|
| - testcase( pAlt->eOperator & WO_EQ );
|
| - testcase( pAlt->eOperator & WO_IN );
|
| - VdbeModuleComment((v, "begin transitive constraint"));
|
| - pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
|
| - if( pEAlt ){
|
| - *pEAlt = *pAlt->pExpr;
|
| - pEAlt->pLeft = pE->pLeft;
|
| - sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
|
| - sqlite3StackFree(db, pEAlt);
|
| - }
|
| + assert( p->aSample!=0 );
|
| + for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
|
| + nEst = nRow0;
|
| + rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
|
| + nRowEst += nEst;
|
| + pBuilder->nRecValid = nRecValid;
|
| }
|
|
|
| - /* For a LEFT OUTER JOIN, generate code that will record the fact that
|
| - ** at least one row of the right table has matched the left table.
|
| - */
|
| - if( pLevel->iLeftJoin ){
|
| - pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
|
| - sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
|
| - VdbeComment((v, "record LEFT JOIN hit"));
|
| - sqlite3ExprCacheClear(pParse);
|
| - for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
|
| - testcase( pTerm->wtFlags & TERM_VIRTUAL );
|
| - testcase( pTerm->wtFlags & TERM_CODED );
|
| - if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
|
| - if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
|
| - assert( pWInfo->untestedTerms );
|
| - continue;
|
| - }
|
| - assert( pTerm->pExpr );
|
| - sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
|
| - pTerm->wtFlags |= TERM_CODED;
|
| - }
|
| + if( rc==SQLITE_OK ){
|
| + if( nRowEst > nRow0 ) nRowEst = nRow0;
|
| + *pnRow = nRowEst;
|
| + WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
|
| }
|
| -
|
| - return pLevel->notReady;
|
| + assert( pBuilder->nRecValid==nRecValid );
|
| + return rc;
|
| }
|
| +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
|
| +
|
|
|
| #ifdef WHERETRACE_ENABLED
|
| /*
|
| @@ -3781,9 +1631,10 @@ static void whereTermPrint(WhereTerm *pTerm, int iTerm){
|
| if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
|
| if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
|
| if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
|
| - sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n",
|
| - iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
|
| - pTerm->eOperator);
|
| + sqlite3DebugPrintf(
|
| + "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n",
|
| + iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
|
| + pTerm->eOperator, pTerm->wtFlags);
|
| sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
|
| }
|
| }
|
| @@ -3826,7 +1677,7 @@ static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
|
| sqlite3_free(z);
|
| }
|
| if( p->wsFlags & WHERE_SKIPSCAN ){
|
| - sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->u.btree.nSkip);
|
| + sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
|
| }else{
|
| sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
|
| }
|
| @@ -3862,7 +1713,6 @@ static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
|
| p->u.vtab.idxStr = 0;
|
| }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
|
| sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
|
| - sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
|
| sqlite3DbFree(db, p->u.btree.pIndex);
|
| p->u.btree.pIndex = 0;
|
| }
|
| @@ -3926,7 +1776,14 @@ static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
|
| */
|
| static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
|
| if( ALWAYS(pWInfo) ){
|
| - whereClauseClear(&pWInfo->sWC);
|
| + int i;
|
| + for(i=0; i<pWInfo->nLevel; i++){
|
| + WhereLevel *pLevel = &pWInfo->a[i];
|
| + if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
|
| + sqlite3DbFree(db, pLevel->u.in.aInLoop);
|
| + }
|
| + }
|
| + sqlite3WhereClauseClear(&pWInfo->sWC);
|
| while( pWInfo->pLoops ){
|
| WhereLoop *p = pWInfo->pLoops;
|
| pWInfo->pLoops = p->pNextLoop;
|
| @@ -3937,10 +1794,11 @@ static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
|
| }
|
|
|
| /*
|
| -** Return TRUE if both of the following are true:
|
| +** Return TRUE if all of the following are true:
|
| **
|
| ** (1) X has the same or lower cost that Y
|
| ** (2) X is a proper subset of Y
|
| +** (3) X skips at least as many columns as Y
|
| **
|
| ** By "proper subset" we mean that X uses fewer WHERE clause terms
|
| ** than Y and that every WHERE clause term used by X is also used
|
| @@ -3948,19 +1806,25 @@ static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
|
| **
|
| ** If X is a proper subset of Y then Y is a better choice and ought
|
| ** to have a lower cost. This routine returns TRUE when that cost
|
| -** relationship is inverted and needs to be adjusted.
|
| +** relationship is inverted and needs to be adjusted. The third rule
|
| +** was added because if X uses skip-scan less than Y it still might
|
| +** deserve a lower cost even if it is a proper subset of Y.
|
| */
|
| static int whereLoopCheaperProperSubset(
|
| const WhereLoop *pX, /* First WhereLoop to compare */
|
| const WhereLoop *pY /* Compare against this WhereLoop */
|
| ){
|
| int i, j;
|
| - if( pX->nLTerm >= pY->nLTerm ) return 0; /* X is not a subset of Y */
|
| + if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
|
| + return 0; /* X is not a subset of Y */
|
| + }
|
| + if( pY->nSkip > pX->nSkip ) return 0;
|
| if( pX->rRun >= pY->rRun ){
|
| if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
|
| if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
|
| }
|
| for(i=pX->nLTerm-1; i>=0; i--){
|
| + if( pX->aLTerm[i]==0 ) continue;
|
| for(j=pY->nLTerm-1; j>=0; j--){
|
| if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
|
| }
|
| @@ -3982,33 +1846,24 @@ static int whereLoopCheaperProperSubset(
|
| ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
|
| ** WHERE clause terms than Y and that every WHERE clause term used by X is
|
| ** also used by Y.
|
| -**
|
| -** This adjustment is omitted for SKIPSCAN loops. In a SKIPSCAN loop, the
|
| -** WhereLoop.nLTerm field is not an accurate measure of the number of WHERE
|
| -** clause terms covered, since some of the first nLTerm entries in aLTerm[]
|
| -** will be NULL (because they are skipped). That makes it more difficult
|
| -** to compare the loops. We could add extra code to do the comparison, and
|
| -** perhaps we will someday. But SKIPSCAN is sufficiently uncommon, and this
|
| -** adjustment is sufficient minor, that it is very difficult to construct
|
| -** a test case where the extra code would improve the query plan. Better
|
| -** to avoid the added complexity and just omit cost adjustments to SKIPSCAN
|
| -** loops.
|
| */
|
| static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
|
| if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
|
| - if( (pTemplate->wsFlags & WHERE_SKIPSCAN)!=0 ) return;
|
| for(; p; p=p->pNextLoop){
|
| if( p->iTab!=pTemplate->iTab ) continue;
|
| if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
|
| - if( (p->wsFlags & WHERE_SKIPSCAN)!=0 ) continue;
|
| if( whereLoopCheaperProperSubset(p, pTemplate) ){
|
| /* Adjust pTemplate cost downward so that it is cheaper than its
|
| - ** subset p */
|
| + ** subset p. */
|
| + WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
|
| + pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
|
| pTemplate->rRun = p->rRun;
|
| pTemplate->nOut = p->nOut - 1;
|
| }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
|
| /* Adjust pTemplate cost upward so that it is costlier than p since
|
| ** pTemplate is a proper subset of p */
|
| + WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
|
| + pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
|
| pTemplate->rRun = p->rRun;
|
| pTemplate->nOut = p->nOut + 1;
|
| }
|
| @@ -4053,8 +1908,9 @@ static WhereLoop **whereLoopFindLesser(
|
|
|
| /* Any loop using an appliation-defined index (or PRIMARY KEY or
|
| ** UNIQUE constraint) with one or more == constraints is better
|
| - ** than an automatic index. */
|
| + ** than an automatic index. Unless it is a skip-scan. */
|
| if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
|
| + && (pTemplate->nSkip)==0
|
| && (pTemplate->wsFlags & WHERE_INDEXED)!=0
|
| && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
|
| && (p->prereq & pTemplate->prereq)==pTemplate->prereq
|
| @@ -4124,18 +1980,20 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
|
| ** and prereqs.
|
| */
|
| if( pBuilder->pOrSet!=0 ){
|
| + if( pTemplate->nLTerm ){
|
| #if WHERETRACE_ENABLED
|
| - u16 n = pBuilder->pOrSet->n;
|
| - int x =
|
| + u16 n = pBuilder->pOrSet->n;
|
| + int x =
|
| #endif
|
| - whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
|
| + whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
|
| pTemplate->nOut);
|
| #if WHERETRACE_ENABLED /* 0x8 */
|
| - if( sqlite3WhereTrace & 0x8 ){
|
| - sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
|
| - whereLoopPrint(pTemplate, pBuilder->pWC);
|
| - }
|
| + if( sqlite3WhereTrace & 0x8 ){
|
| + sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
|
| + whereLoopPrint(pTemplate, pBuilder->pWC);
|
| + }
|
| #endif
|
| + }
|
| return SQLITE_OK;
|
| }
|
|
|
| @@ -4213,10 +2071,30 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
|
| ** Adjust the WhereLoop.nOut value downward to account for terms of the
|
| ** WHERE clause that reference the loop but which are not used by an
|
| ** index.
|
| -**
|
| -** In the current implementation, the first extra WHERE clause term reduces
|
| -** the number of output rows by a factor of 10 and each additional term
|
| -** reduces the number of output rows by sqrt(2).
|
| +*
|
| +** For every WHERE clause term that is not used by the index
|
| +** and which has a truth probability assigned by one of the likelihood(),
|
| +** likely(), or unlikely() SQL functions, reduce the estimated number
|
| +** of output rows by the probability specified.
|
| +**
|
| +** TUNING: For every WHERE clause term that is not used by the index
|
| +** and which does not have an assigned truth probability, heuristics
|
| +** described below are used to try to estimate the truth probability.
|
| +** TODO --> Perhaps this is something that could be improved by better
|
| +** table statistics.
|
| +**
|
| +** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
|
| +** value corresponds to -1 in LogEst notation, so this means decrement
|
| +** the WhereLoop.nOut field for every such WHERE clause term.
|
| +**
|
| +** Heuristic 2: If there exists one or more WHERE clause terms of the
|
| +** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
|
| +** final output row estimate is no greater than 1/4 of the total number
|
| +** of rows in the table. In other words, assume that x==EXPR will filter
|
| +** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
|
| +** "x" column is boolean or else -1 or 0 or 1 is a common default value
|
| +** on the "x" column and so in that case only cap the output row estimate
|
| +** at 1/2 instead of 1/4.
|
| */
|
| static void whereLoopOutputAdjust(
|
| WhereClause *pWC, /* The WHERE clause */
|
| @@ -4225,9 +2103,10 @@ static void whereLoopOutputAdjust(
|
| ){
|
| WhereTerm *pTerm, *pX;
|
| Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
|
| - int i, j;
|
| - int nEq = 0; /* Number of = constraints not within likely()/unlikely() */
|
| + int i, j, k;
|
| + LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
|
|
|
| + assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
|
| for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
|
| if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
|
| if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
|
| @@ -4240,20 +2119,27 @@ static void whereLoopOutputAdjust(
|
| }
|
| if( j<0 ){
|
| if( pTerm->truthProb<=0 ){
|
| + /* If a truth probability is specified using the likelihood() hints,
|
| + ** then use the probability provided by the application. */
|
| pLoop->nOut += pTerm->truthProb;
|
| }else{
|
| + /* In the absence of explicit truth probabilities, use heuristics to
|
| + ** guess a reasonable truth probability. */
|
| pLoop->nOut--;
|
| - if( pTerm->eOperator&WO_EQ ) nEq++;
|
| + if( pTerm->eOperator&(WO_EQ|WO_IS) ){
|
| + Expr *pRight = pTerm->pExpr->pRight;
|
| + testcase( pTerm->pExpr->op==TK_IS );
|
| + if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
|
| + k = 10;
|
| + }else{
|
| + k = 20;
|
| + }
|
| + if( iReduce<k ) iReduce = k;
|
| + }
|
| }
|
| }
|
| }
|
| - /* TUNING: If there is at least one equality constraint in the WHERE
|
| - ** clause that does not have a likelihood() explicitly assigned to it
|
| - ** then do not let the estimated number of output rows exceed half
|
| - ** the number of rows in the table. */
|
| - if( nEq && pLoop->nOut>nRow-10 ){
|
| - pLoop->nOut = nRow - 10;
|
| - }
|
| + if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
|
| }
|
|
|
| /*
|
| @@ -4294,10 +2180,9 @@ static int whereLoopAddBtreeIndex(
|
| Bitmask saved_prereq; /* Original value of pNew->prereq */
|
| u16 saved_nLTerm; /* Original value of pNew->nLTerm */
|
| u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
|
| - u16 saved_nSkip; /* Original value of pNew->u.btree.nSkip */
|
| + u16 saved_nSkip; /* Original value of pNew->nSkip */
|
| u32 saved_wsFlags; /* Original value of pNew->wsFlags */
|
| LogEst saved_nOut; /* Original value of pNew->nOut */
|
| - int iCol; /* Index of the column in the table */
|
| int rc = SQLITE_OK; /* Return code */
|
| LogEst rSize; /* Number of rows in the table */
|
| LogEst rLogSize; /* Logarithm of table size */
|
| @@ -4310,65 +2195,26 @@ static int whereLoopAddBtreeIndex(
|
| assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
|
| if( pNew->wsFlags & WHERE_BTM_LIMIT ){
|
| opMask = WO_LT|WO_LE;
|
| - }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
|
| + }else if( /*pProbe->tnum<=0 ||*/ (pSrc->fg.jointype & JT_LEFT)!=0 ){
|
| opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
|
| }else{
|
| - opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
|
| + opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
|
| }
|
| if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
|
|
|
| assert( pNew->u.btree.nEq<pProbe->nColumn );
|
| - iCol = pProbe->aiColumn[pNew->u.btree.nEq];
|
|
|
| - pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
|
| - opMask, pProbe);
|
| saved_nEq = pNew->u.btree.nEq;
|
| - saved_nSkip = pNew->u.btree.nSkip;
|
| + saved_nSkip = pNew->nSkip;
|
| saved_nLTerm = pNew->nLTerm;
|
| saved_wsFlags = pNew->wsFlags;
|
| saved_prereq = pNew->prereq;
|
| saved_nOut = pNew->nOut;
|
| + pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
|
| + opMask, pProbe);
|
| pNew->rSetup = 0;
|
| rSize = pProbe->aiRowLogEst[0];
|
| rLogSize = estLog(rSize);
|
| -
|
| - /* Consider using a skip-scan if there are no WHERE clause constraints
|
| - ** available for the left-most terms of the index, and if the average
|
| - ** number of repeats in the left-most terms is at least 18.
|
| - **
|
| - ** The magic number 18 is selected on the basis that scanning 17 rows
|
| - ** is almost always quicker than an index seek (even though if the index
|
| - ** contains fewer than 2^17 rows we assume otherwise in other parts of
|
| - ** the code). And, even if it is not, it should not be too much slower.
|
| - ** On the other hand, the extra seeks could end up being significantly
|
| - ** more expensive. */
|
| - assert( 42==sqlite3LogEst(18) );
|
| - if( saved_nEq==saved_nSkip
|
| - && saved_nEq+1<pProbe->nKeyCol
|
| - && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
|
| - && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
|
| - ){
|
| - LogEst nIter;
|
| - pNew->u.btree.nEq++;
|
| - pNew->u.btree.nSkip++;
|
| - pNew->aLTerm[pNew->nLTerm++] = 0;
|
| - pNew->wsFlags |= WHERE_SKIPSCAN;
|
| - nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
|
| - if( pTerm ){
|
| - /* TUNING: When estimating skip-scan for a term that is also indexable,
|
| - ** multiply the cost of the skip-scan by 2.0, to make it a little less
|
| - ** desirable than the regular index lookup. */
|
| - nIter += 10; assert( 10==sqlite3LogEst(2) );
|
| - }
|
| - pNew->nOut -= nIter;
|
| - /* TUNING: Because uncertainties in the estimates for skip-scan queries,
|
| - ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
|
| - nIter += 5;
|
| - whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
|
| - pNew->nOut = saved_nOut;
|
| - pNew->u.btree.nEq = saved_nEq;
|
| - pNew->u.btree.nSkip = saved_nSkip;
|
| - }
|
| for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
|
| u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
|
| LogEst rCostIdx;
|
| @@ -4378,12 +2224,16 @@ static int whereLoopAddBtreeIndex(
|
| int nRecValid = pBuilder->nRecValid;
|
| #endif
|
| if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
|
| - && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
|
| + && indexColumnNotNull(pProbe, saved_nEq)
|
| ){
|
| continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
|
| }
|
| if( pTerm->prereqRight & pNew->maskSelf ) continue;
|
|
|
| + /* Do not allow the upper bound of a LIKE optimization range constraint
|
| + ** to mix with a lower range bound from some other source */
|
| + if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
|
| +
|
| pNew->wsFlags = saved_wsFlags;
|
| pNew->u.btree.nEq = saved_nEq;
|
| pNew->nLTerm = saved_nLTerm;
|
| @@ -4410,10 +2260,14 @@ static int whereLoopAddBtreeIndex(
|
| assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
|
| ** changes "x IN (?)" into "x=?". */
|
|
|
| - }else if( eOp & (WO_EQ) ){
|
| + }else if( eOp & (WO_EQ|WO_IS) ){
|
| + int iCol = pProbe->aiColumn[saved_nEq];
|
| pNew->wsFlags |= WHERE_COLUMN_EQ;
|
| - if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
|
| - if( iCol>=0 && !IsUniqueIndex(pProbe) ){
|
| + assert( saved_nEq==pNew->u.btree.nEq );
|
| + if( iCol==XN_ROWID
|
| + || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
|
| + ){
|
| + if( iCol>=0 && pProbe->uniqNotNull==0 ){
|
| pNew->wsFlags |= WHERE_UNQ_WANTED;
|
| }else{
|
| pNew->wsFlags |= WHERE_ONEROW;
|
| @@ -4427,6 +2281,17 @@ static int whereLoopAddBtreeIndex(
|
| pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
|
| pBtm = pTerm;
|
| pTop = 0;
|
| + if( pTerm->wtFlags & TERM_LIKEOPT ){
|
| + /* Range contraints that come from the LIKE optimization are
|
| + ** always used in pairs. */
|
| + pTop = &pTerm[1];
|
| + assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
|
| + assert( pTop->wtFlags & TERM_LIKEOPT );
|
| + assert( pTop->eOperator==WO_LT );
|
| + if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
|
| + pNew->aLTerm[pNew->nLTerm++] = pTop;
|
| + pNew->wsFlags |= WHERE_TOP_LIMIT;
|
| + }
|
| }else{
|
| assert( eOp & (WO_LT|WO_LE) );
|
| testcase( eOp & WO_LT );
|
| @@ -4449,10 +2314,10 @@ static int whereLoopAddBtreeIndex(
|
| whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
|
| }else{
|
| int nEq = ++pNew->u.btree.nEq;
|
| - assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
|
| + assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
|
|
|
| assert( pNew->nOut==saved_nOut );
|
| - if( pTerm->truthProb<=0 && iCol>=0 ){
|
| + if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
|
| assert( (eOp & WO_IN) || nIn==0 );
|
| testcase( eOp & WO_IN );
|
| pNew->nOut += pTerm->truthProb;
|
| @@ -4463,12 +2328,12 @@ static int whereLoopAddBtreeIndex(
|
| if( nInMul==0
|
| && pProbe->nSample
|
| && pNew->u.btree.nEq<=pProbe->nSampleCol
|
| - && OptimizationEnabled(db, SQLITE_Stat3)
|
| && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
|
| ){
|
| Expr *pExpr = pTerm->pExpr;
|
| - if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
|
| + if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
|
| testcase( eOp & WO_EQ );
|
| + testcase( eOp & WO_IS );
|
| testcase( eOp & WO_ISNULL );
|
| rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
|
| }else{
|
| @@ -4531,10 +2396,45 @@ static int whereLoopAddBtreeIndex(
|
| }
|
| pNew->prereq = saved_prereq;
|
| pNew->u.btree.nEq = saved_nEq;
|
| - pNew->u.btree.nSkip = saved_nSkip;
|
| + pNew->nSkip = saved_nSkip;
|
| pNew->wsFlags = saved_wsFlags;
|
| pNew->nOut = saved_nOut;
|
| pNew->nLTerm = saved_nLTerm;
|
| +
|
| + /* Consider using a skip-scan if there are no WHERE clause constraints
|
| + ** available for the left-most terms of the index, and if the average
|
| + ** number of repeats in the left-most terms is at least 18.
|
| + **
|
| + ** The magic number 18 is selected on the basis that scanning 17 rows
|
| + ** is almost always quicker than an index seek (even though if the index
|
| + ** contains fewer than 2^17 rows we assume otherwise in other parts of
|
| + ** the code). And, even if it is not, it should not be too much slower.
|
| + ** On the other hand, the extra seeks could end up being significantly
|
| + ** more expensive. */
|
| + assert( 42==sqlite3LogEst(18) );
|
| + if( saved_nEq==saved_nSkip
|
| + && saved_nEq+1<pProbe->nKeyCol
|
| + && pProbe->noSkipScan==0
|
| + && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
|
| + && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
|
| + ){
|
| + LogEst nIter;
|
| + pNew->u.btree.nEq++;
|
| + pNew->nSkip++;
|
| + pNew->aLTerm[pNew->nLTerm++] = 0;
|
| + pNew->wsFlags |= WHERE_SKIPSCAN;
|
| + nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
|
| + pNew->nOut -= nIter;
|
| + /* TUNING: Because uncertainties in the estimates for skip-scan queries,
|
| + ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
|
| + nIter += 5;
|
| + whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
|
| + pNew->nOut = saved_nOut;
|
| + pNew->u.btree.nEq = saved_nEq;
|
| + pNew->nSkip = saved_nSkip;
|
| + pNew->wsFlags = saved_wsFlags;
|
| + }
|
| +
|
| return rc;
|
| }
|
|
|
| @@ -4552,18 +2452,25 @@ static int indexMightHelpWithOrderBy(
|
| int iCursor
|
| ){
|
| ExprList *pOB;
|
| + ExprList *aColExpr;
|
| int ii, jj;
|
|
|
| if( pIndex->bUnordered ) return 0;
|
| if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
|
| for(ii=0; ii<pOB->nExpr; ii++){
|
| Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
|
| - if( pExpr->op!=TK_COLUMN ) return 0;
|
| - if( pExpr->iTable==iCursor ){
|
| + if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
|
| if( pExpr->iColumn<0 ) return 1;
|
| for(jj=0; jj<pIndex->nKeyCol; jj++){
|
| if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
|
| }
|
| + }else if( (aColExpr = pIndex->aColExpr)!=0 ){
|
| + for(jj=0; jj<pIndex->nKeyCol; jj++){
|
| + if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
|
| + if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
|
| + return 1;
|
| + }
|
| + }
|
| }
|
| }
|
| return 0;
|
| @@ -4593,8 +2500,17 @@ static Bitmask columnsInIndex(Index *pIdx){
|
| static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
|
| int i;
|
| WhereTerm *pTerm;
|
| + while( pWhere->op==TK_AND ){
|
| + if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
|
| + pWhere = pWhere->pRight;
|
| + }
|
| for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
|
| - if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
|
| + Expr *pExpr = pTerm->pExpr;
|
| + if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
|
| + && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
|
| + ){
|
| + return 1;
|
| + }
|
| }
|
| return 0;
|
| }
|
| @@ -4663,9 +2579,9 @@ static int whereLoopAddBtree(
|
| pWC = pBuilder->pWC;
|
| assert( !IsVirtual(pSrc->pTab) );
|
|
|
| - if( pSrc->pIndex ){
|
| + if( pSrc->pIBIndex ){
|
| /* An INDEXED BY clause specifies a particular index to use */
|
| - pProbe = pSrc->pIndex;
|
| + pProbe = pSrc->pIBIndex;
|
| }else if( !HasRowid(pTab) ){
|
| pProbe = pTab->pIndex;
|
| }else{
|
| @@ -4685,7 +2601,7 @@ static int whereLoopAddBtree(
|
| aiRowEstPk[0] = pTab->nRowLogEst;
|
| aiRowEstPk[1] = 0;
|
| pFirst = pSrc->pTab->pIndex;
|
| - if( pSrc->notIndexed==0 ){
|
| + if( pSrc->fg.notIndexed==0 ){
|
| /* The real indices of the table are only considered if the
|
| ** NOT INDEXED qualifier is omitted from the FROM clause */
|
| sPk.pNext = pFirst;
|
| @@ -4697,14 +2613,14 @@ static int whereLoopAddBtree(
|
|
|
| #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
|
| /* Automatic indexes */
|
| - if( !pBuilder->pOrSet
|
| + if( !pBuilder->pOrSet /* Not part of an OR optimization */
|
| + && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
|
| && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
|
| - && pSrc->pIndex==0
|
| - && !pSrc->viaCoroutine
|
| - && !pSrc->notIndexed
|
| - && HasRowid(pTab)
|
| - && !pSrc->isCorrelated
|
| - && !pSrc->isRecursive
|
| + && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
|
| + && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
|
| + && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
|
| + && !pSrc->fg.isCorrelated /* Not a correlated subquery */
|
| + && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
|
| ){
|
| /* Generate auto-index WhereLoops */
|
| WhereTerm *pTerm;
|
| @@ -4713,7 +2629,7 @@ static int whereLoopAddBtree(
|
| if( pTerm->prereqRight & pNew->maskSelf ) continue;
|
| if( termCanDriveIndex(pTerm, pSrc, 0) ){
|
| pNew->u.btree.nEq = 1;
|
| - pNew->u.btree.nSkip = 0;
|
| + pNew->nSkip = 0;
|
| pNew->u.btree.pIndex = 0;
|
| pNew->nLTerm = 1;
|
| pNew->aLTerm[0] = pTerm;
|
| @@ -4754,7 +2670,7 @@ static int whereLoopAddBtree(
|
| }
|
| rSize = pProbe->aiRowLogEst[0];
|
| pNew->u.btree.nEq = 0;
|
| - pNew->u.btree.nSkip = 0;
|
| + pNew->nSkip = 0;
|
| pNew->nLTerm = 0;
|
| pNew->iSortIdx = 0;
|
| pNew->rSetup = 0;
|
| @@ -4825,7 +2741,7 @@ static int whereLoopAddBtree(
|
|
|
| /* If there was an INDEXED BY clause, then only that one index is
|
| ** considered. */
|
| - if( pSrc->pIndex ) break;
|
| + if( pSrc->pIBIndex ) break;
|
| }
|
| return rc;
|
| }
|
| @@ -4834,10 +2750,32 @@ static int whereLoopAddBtree(
|
| /*
|
| ** Add all WhereLoop objects for a table of the join identified by
|
| ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
|
| +**
|
| +** If there are no LEFT or CROSS JOIN joins in the query, both mExtra and
|
| +** mUnusable are set to 0. Otherwise, mExtra is a mask of all FROM clause
|
| +** entries that occur before the virtual table in the FROM clause and are
|
| +** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
|
| +** mUnusable mask contains all FROM clause entries that occur after the
|
| +** virtual table and are separated from it by at least one LEFT or
|
| +** CROSS JOIN.
|
| +**
|
| +** For example, if the query were:
|
| +**
|
| +** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
|
| +**
|
| +** then mExtra corresponds to (t1, t2) and mUnusable to (t5, t6).
|
| +**
|
| +** All the tables in mExtra must be scanned before the current virtual
|
| +** table. So any terms for which all prerequisites are satisfied by
|
| +** mExtra may be specified as "usable" in all calls to xBestIndex.
|
| +** Conversely, all tables in mUnusable must be scanned after the current
|
| +** virtual table, so any terms for which the prerequisites overlap with
|
| +** mUnusable should always be configured as "not-usable" for xBestIndex.
|
| */
|
| static int whereLoopAddVirtual(
|
| WhereLoopBuilder *pBuilder, /* WHERE clause information */
|
| - Bitmask mExtra
|
| + Bitmask mExtra, /* Tables that must be scanned before this one */
|
| + Bitmask mUnusable /* Tables that must be scanned after this one */
|
| ){
|
| WhereInfo *pWInfo; /* WHERE analysis context */
|
| Parse *pParse; /* The parsing context */
|
| @@ -4858,6 +2796,7 @@ static int whereLoopAddVirtual(
|
| WhereLoop *pNew;
|
| int rc = SQLITE_OK;
|
|
|
| + assert( (mExtra & mUnusable)==0 );
|
| pWInfo = pBuilder->pWInfo;
|
| pParse = pWInfo->pParse;
|
| db = pParse->db;
|
| @@ -4866,7 +2805,7 @@ static int whereLoopAddVirtual(
|
| pSrc = &pWInfo->pTabList->a[pNew->iTab];
|
| pTab = pSrc->pTab;
|
| assert( IsVirtual(pTab) );
|
| - pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
|
| + pIdxInfo = allocateIndexInfo(pParse, pWC, mUnusable, pSrc,pBuilder->pOrderBy);
|
| if( pIdxInfo==0 ) return SQLITE_NOMEM;
|
| pNew->prereq = 0;
|
| pNew->rSetup = 0;
|
| @@ -4896,7 +2835,7 @@ static int whereLoopAddVirtual(
|
| if( (pTerm->eOperator & WO_IN)!=0 ){
|
| seenIn = 1;
|
| }
|
| - if( pTerm->prereqRight!=0 ){
|
| + if( (pTerm->prereqRight & ~mExtra)!=0 ){
|
| seenVar = 1;
|
| }else if( (pTerm->eOperator & WO_IN)==0 ){
|
| pIdxCons->usable = 1;
|
| @@ -4904,7 +2843,7 @@ static int whereLoopAddVirtual(
|
| break;
|
| case 1: /* Constants with IN operators */
|
| assert( seenIn );
|
| - pIdxCons->usable = (pTerm->prereqRight==0);
|
| + pIdxCons->usable = (pTerm->prereqRight & ~mExtra)==0;
|
| break;
|
| case 2: /* Variables without IN */
|
| assert( seenVar );
|
| @@ -4924,6 +2863,8 @@ static int whereLoopAddVirtual(
|
| pIdxInfo->orderByConsumed = 0;
|
| pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
|
| pIdxInfo->estimatedRows = 25;
|
| + pIdxInfo->idxFlags = 0;
|
| + pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
|
| rc = vtabBestIndex(pParse, pTab, pIdxInfo);
|
| if( rc ) goto whereLoopAddVtab_exit;
|
| pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
|
| @@ -4969,6 +2910,7 @@ static int whereLoopAddVirtual(
|
| ** (2) Multiple outputs from a single IN value will not merge
|
| ** together. */
|
| pIdxInfo->orderByConsumed = 0;
|
| + pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
|
| }
|
| }
|
| }
|
| @@ -4984,6 +2926,14 @@ static int whereLoopAddVirtual(
|
| pNew->rSetup = 0;
|
| pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
|
| pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
|
| +
|
| + /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
|
| + ** that the scan will visit at most one row. Clear it otherwise. */
|
| + if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
|
| + pNew->wsFlags |= WHERE_ONEROW;
|
| + }else{
|
| + pNew->wsFlags &= ~WHERE_ONEROW;
|
| + }
|
| whereLoopInsert(pBuilder, pNew);
|
| if( pNew->u.vtab.needFree ){
|
| sqlite3_free(pNew->u.vtab.idxStr);
|
| @@ -5003,7 +2953,11 @@ whereLoopAddVtab_exit:
|
| ** Add WhereLoop entries to handle OR terms. This works for either
|
| ** btrees or virtual tables.
|
| */
|
| -static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
|
| +static int whereLoopAddOr(
|
| + WhereLoopBuilder *pBuilder,
|
| + Bitmask mExtra,
|
| + Bitmask mUnusable
|
| +){
|
| WhereInfo *pWInfo = pBuilder->pWInfo;
|
| WhereClause *pWC;
|
| WhereLoop *pNew;
|
| @@ -5062,14 +3016,14 @@ static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
|
| #endif
|
| #ifndef SQLITE_OMIT_VIRTUALTABLE
|
| if( IsVirtual(pItem->pTab) ){
|
| - rc = whereLoopAddVirtual(&sSubBuild, mExtra);
|
| + rc = whereLoopAddVirtual(&sSubBuild, mExtra, mUnusable);
|
| }else
|
| #endif
|
| {
|
| rc = whereLoopAddBtree(&sSubBuild, mExtra);
|
| }
|
| if( rc==SQLITE_OK ){
|
| - rc = whereLoopAddOr(&sSubBuild, mExtra);
|
| + rc = whereLoopAddOr(&sSubBuild, mExtra, mUnusable);
|
| }
|
| assert( rc==SQLITE_OK || sCur.n==0 );
|
| if( sCur.n==0 ){
|
| @@ -5131,33 +3085,43 @@ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
|
| int iTab;
|
| SrcList *pTabList = pWInfo->pTabList;
|
| struct SrcList_item *pItem;
|
| + struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
|
| sqlite3 *db = pWInfo->pParse->db;
|
| - int nTabList = pWInfo->nLevel;
|
| int rc = SQLITE_OK;
|
| - u8 priorJoinType = 0;
|
| WhereLoop *pNew;
|
| + u8 priorJointype = 0;
|
|
|
| /* Loop over the tables in the join, from left to right */
|
| pNew = pBuilder->pNew;
|
| whereLoopInit(pNew);
|
| - for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
|
| + for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
|
| + Bitmask mUnusable = 0;
|
| pNew->iTab = iTab;
|
| - pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
|
| - if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
|
| + pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
|
| + if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
|
| + /* This condition is true when pItem is the FROM clause term on the
|
| + ** right-hand-side of a LEFT or CROSS JOIN. */
|
| mExtra = mPrior;
|
| }
|
| - priorJoinType = pItem->jointype;
|
| + priorJointype = pItem->fg.jointype;
|
| if( IsVirtual(pItem->pTab) ){
|
| - rc = whereLoopAddVirtual(pBuilder, mExtra);
|
| + struct SrcList_item *p;
|
| + for(p=&pItem[1]; p<pEnd; p++){
|
| + if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
|
| + mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
|
| + }
|
| + }
|
| + rc = whereLoopAddVirtual(pBuilder, mExtra, mUnusable);
|
| }else{
|
| rc = whereLoopAddBtree(pBuilder, mExtra);
|
| }
|
| if( rc==SQLITE_OK ){
|
| - rc = whereLoopAddOr(pBuilder, mExtra);
|
| + rc = whereLoopAddOr(pBuilder, mExtra, mUnusable);
|
| }
|
| mPrior |= pNew->maskSelf;
|
| if( rc || db->mallocFailed ) break;
|
| }
|
| +
|
| whereLoopClear(db, pNew);
|
| return rc;
|
| }
|
| @@ -5263,10 +3227,10 @@ static i8 wherePathSatisfiesOrderBy(
|
| pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
|
| if( pOBExpr->op!=TK_COLUMN ) continue;
|
| if( pOBExpr->iTable!=iCur ) continue;
|
| - pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
|
| - ~ready, WO_EQ|WO_ISNULL, 0);
|
| + pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
|
| + ~ready, WO_EQ|WO_ISNULL|WO_IS, 0);
|
| if( pTerm==0 ) continue;
|
| - if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
|
| + if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
|
| const char *z1, *z2;
|
| pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
|
| if( !pColl ) pColl = db->pDfltColl;
|
| @@ -5275,6 +3239,7 @@ static i8 wherePathSatisfiesOrderBy(
|
| if( !pColl ) pColl = db->pDfltColl;
|
| z2 = pColl->zName;
|
| if( sqlite3StrICmp(z1, z2)!=0 ) continue;
|
| + testcase( pTerm->pExpr->op==TK_IS );
|
| }
|
| obSat |= MASKBIT(i);
|
| }
|
| @@ -5290,7 +3255,8 @@ static i8 wherePathSatisfiesOrderBy(
|
| nKeyCol = pIndex->nKeyCol;
|
| nColumn = pIndex->nColumn;
|
| assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
|
| - assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
|
| + assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
|
| + || !HasRowid(pIndex->pTable));
|
| isOrderDistinct = IsUniqueIndex(pIndex);
|
| }
|
|
|
| @@ -5304,8 +3270,8 @@ static i8 wherePathSatisfiesOrderBy(
|
|
|
| /* Skip over == and IS NULL terms */
|
| if( j<pLoop->u.btree.nEq
|
| - && pLoop->u.btree.nSkip==0
|
| - && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
|
| + && pLoop->nSkip==0
|
| + && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0
|
| ){
|
| if( i & WO_ISNULL ){
|
| testcase( isOrderDistinct );
|
| @@ -5322,7 +3288,7 @@ static i8 wherePathSatisfiesOrderBy(
|
| revIdx = pIndex->aSortOrder[j];
|
| if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
|
| }else{
|
| - iColumn = -1;
|
| + iColumn = XN_ROWID;
|
| revIdx = 0;
|
| }
|
|
|
| @@ -5348,9 +3314,15 @@ static i8 wherePathSatisfiesOrderBy(
|
| testcase( wctrlFlags & WHERE_GROUPBY );
|
| testcase( wctrlFlags & WHERE_DISTINCTBY );
|
| if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
|
| - if( pOBExpr->op!=TK_COLUMN ) continue;
|
| - if( pOBExpr->iTable!=iCur ) continue;
|
| - if( pOBExpr->iColumn!=iColumn ) continue;
|
| + if( iColumn>=(-1) ){
|
| + if( pOBExpr->op!=TK_COLUMN ) continue;
|
| + if( pOBExpr->iTable!=iCur ) continue;
|
| + if( pOBExpr->iColumn!=iColumn ) continue;
|
| + }else{
|
| + if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
|
| + continue;
|
| + }
|
| + }
|
| if( iColumn>=0 ){
|
| pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
|
| if( !pColl ) pColl = db->pDfltColl;
|
| @@ -5399,7 +3371,7 @@ static i8 wherePathSatisfiesOrderBy(
|
| Bitmask mTerm;
|
| if( MASKBIT(i) & obSat ) continue;
|
| p = pOrderBy->a[i].pExpr;
|
| - mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
|
| + mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
|
| if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
|
| if( (mTerm&~orderDistinctMask)==0 ){
|
| obSat |= MASKBIT(i);
|
| @@ -5581,10 +3553,10 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
|
|
|
| /* Seed the search with a single WherePath containing zero WhereLoops.
|
| **
|
| - ** TUNING: Do not let the number of iterations go above 25. If the cost
|
| - ** of computing an automatic index is not paid back within the first 25
|
| + ** TUNING: Do not let the number of iterations go above 28. If the cost
|
| + ** of computing an automatic index is not paid back within the first 28
|
| ** rows, then do not use the automatic index. */
|
| - aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
|
| + aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
|
| nFrom = 1;
|
| assert( aFrom[0].isOrdered==0 );
|
| if( nOrderBy ){
|
| @@ -5758,7 +3730,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
|
| }
|
|
|
| #ifdef WHERETRACE_ENABLED /* >=2 */
|
| - if( sqlite3WhereTrace>=2 ){
|
| + if( sqlite3WhereTrace & 0x02 ){
|
| sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
|
| for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
|
| sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
|
| @@ -5822,7 +3794,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
|
| pWInfo->revMask = pFrom->revLoop;
|
| }
|
| if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
|
| - && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
|
| + && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
|
| ){
|
| Bitmask revMask = 0;
|
| int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
|
| @@ -5872,14 +3844,15 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){
|
| pItem = pWInfo->pTabList->a;
|
| pTab = pItem->pTab;
|
| if( IsVirtual(pTab) ) return 0;
|
| - if( pItem->zIndex ) return 0;
|
| + if( pItem->fg.isIndexedBy ) return 0;
|
| iCur = pItem->iCursor;
|
| pWC = &pWInfo->sWC;
|
| pLoop = pBuilder->pNew;
|
| pLoop->wsFlags = 0;
|
| - pLoop->u.btree.nSkip = 0;
|
| - pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
|
| + pLoop->nSkip = 0;
|
| + pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
|
| if( pTerm ){
|
| + testcase( pTerm->eOperator & WO_IS );
|
| pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
|
| pLoop->aLTerm[0] = pTerm;
|
| pLoop->nLTerm = 1;
|
| @@ -5888,15 +3861,17 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){
|
| pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
|
| }else{
|
| for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
| + int opMask;
|
| assert( pLoop->aLTermSpace==pLoop->aLTerm );
|
| - assert( ArraySize(pLoop->aLTermSpace)==4 );
|
| if( !IsUniqueIndex(pIdx)
|
| || pIdx->pPartIdxWhere!=0
|
| || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
|
| ) continue;
|
| + opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
|
| for(j=0; j<pIdx->nKeyCol; j++){
|
| - pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
|
| + pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
|
| if( pTerm==0 ) break;
|
| + testcase( pTerm->eOperator & WO_IS );
|
| pLoop->aLTerm[j] = pTerm;
|
| }
|
| if( j!=pIdx->nKeyCol ) continue;
|
| @@ -5915,7 +3890,7 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){
|
| if( pLoop->wsFlags ){
|
| pLoop->nOut = (LogEst)1;
|
| pWInfo->a[0].pWLoop = pLoop;
|
| - pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
|
| + pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
|
| pWInfo->a[0].iTabCur = iCur;
|
| pWInfo->nRowOut = 1;
|
| if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
|
| @@ -6039,7 +4014,12 @@ WhereInfo *sqlite3WhereBegin(
|
| int ii; /* Loop counter */
|
| sqlite3 *db; /* Database connection */
|
| int rc; /* Return code */
|
| + u8 bFordelete = 0;
|
|
|
| + assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
|
| + (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
|
| + && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
|
| + ));
|
|
|
| /* Variable initialization */
|
| db = pParse->db;
|
| @@ -6095,6 +4075,7 @@ WhereInfo *sqlite3WhereBegin(
|
| pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
|
| pWInfo->wctrlFlags = wctrlFlags;
|
| pWInfo->savedNQueryLoop = pParse->nQueryLoop;
|
| + assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
|
| pMaskSet = &pWInfo->sMaskSet;
|
| sWLB.pWInfo = pWInfo;
|
| sWLB.pWC = &pWInfo->sWC;
|
| @@ -6109,8 +4090,8 @@ WhereInfo *sqlite3WhereBegin(
|
| ** subexpression is separated by an AND operator.
|
| */
|
| initMaskSet(pMaskSet);
|
| - whereClauseInit(&pWInfo->sWC, pWInfo);
|
| - whereSplit(&pWInfo->sWC, pWhere, TK_AND);
|
| + sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
|
| + sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
|
|
|
| /* Special case: a WHERE clause that is constant. Evaluate the
|
| ** expression and either jump over all of the code or fall thru.
|
| @@ -6134,14 +4115,12 @@ WhereInfo *sqlite3WhereBegin(
|
|
|
| /* Assign a bit from the bitmask to every term in the FROM clause.
|
| **
|
| - ** When assigning bitmask values to FROM clause cursors, it must be
|
| - ** the case that if X is the bitmask for the N-th FROM clause term then
|
| - ** the bitmask for all FROM clause terms to the left of the N-th term
|
| - ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
|
| - ** its Expr.iRightJoinTable value to find the bitmask of the right table
|
| - ** of the join. Subtracting one from the right table bitmask gives a
|
| - ** bitmask for all tables to the left of the join. Knowing the bitmask
|
| - ** for all tables to the left of a left join is important. Ticket #3015.
|
| + ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
|
| + **
|
| + ** The rule of the previous sentence ensures thta if X is the bitmask for
|
| + ** a table T, then X-1 is the bitmask for all other tables to the left of T.
|
| + ** Knowing the bitmask for all tables to the left of a left join is
|
| + ** important. Ticket #3015.
|
| **
|
| ** Note that bitmasks are created for all pTabList->nSrc tables in
|
| ** pTabList, not just the first nTabList tables. nTabList is normally
|
| @@ -6150,27 +4129,18 @@ WhereInfo *sqlite3WhereBegin(
|
| */
|
| for(ii=0; ii<pTabList->nSrc; ii++){
|
| createMask(pMaskSet, pTabList->a[ii].iCursor);
|
| + sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
|
| }
|
| -#ifndef NDEBUG
|
| - {
|
| - Bitmask toTheLeft = 0;
|
| - for(ii=0; ii<pTabList->nSrc; ii++){
|
| - Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
|
| - assert( (m-1)==toTheLeft );
|
| - toTheLeft |= m;
|
| - }
|
| +#ifdef SQLITE_DEBUG
|
| + for(ii=0; ii<pTabList->nSrc; ii++){
|
| + Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
|
| + assert( m==MASKBIT(ii) );
|
| }
|
| #endif
|
|
|
| - /* Analyze all of the subexpressions. Note that exprAnalyze() might
|
| - ** add new virtual terms onto the end of the WHERE clause. We do not
|
| - ** want to analyze these virtual terms, so start analyzing at the end
|
| - ** and work forward so that the added virtual terms are never processed.
|
| - */
|
| - exprAnalyzeAll(pTabList, &pWInfo->sWC);
|
| - if( db->mallocFailed ){
|
| - goto whereBeginError;
|
| - }
|
| + /* Analyze all of the subexpressions. */
|
| + sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
|
| + if( db->mallocFailed ) goto whereBeginError;
|
|
|
| if( wctrlFlags & WHERE_WANT_DISTINCT ){
|
| if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
|
| @@ -6184,10 +4154,10 @@ WhereInfo *sqlite3WhereBegin(
|
| }
|
|
|
| /* Construct the WhereLoop objects */
|
| - WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
|
| + WHERETRACE(0xffff,("*** Optimizer Start *** (wctrlFlags: 0x%x)\n",
|
| + wctrlFlags));
|
| #if defined(WHERETRACE_ENABLED)
|
| - /* Display all terms of the WHERE clause */
|
| - if( sqlite3WhereTrace & 0x100 ){
|
| + if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
|
| int i;
|
| for(i=0; i<sWLB.pWC->nTerm; i++){
|
| whereTermPrint(&sWLB.pWC->a[i], i);
|
| @@ -6199,13 +4169,12 @@ WhereInfo *sqlite3WhereBegin(
|
| rc = whereLoopAddAll(&sWLB);
|
| if( rc ) goto whereBeginError;
|
|
|
| - /* Display all of the WhereLoop objects if wheretrace is enabled */
|
| -#ifdef WHERETRACE_ENABLED /* !=0 */
|
| - if( sqlite3WhereTrace ){
|
| +#ifdef WHERETRACE_ENABLED
|
| + if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
|
| WhereLoop *p;
|
| int i;
|
| - static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
|
| - "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
|
| + static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
|
| + "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
|
| for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
|
| p->cId = zLabel[i%sizeof(zLabel)];
|
| whereLoopPrint(p, sWLB.pWC);
|
| @@ -6226,9 +4195,8 @@ WhereInfo *sqlite3WhereBegin(
|
| if( pParse->nErr || NEVER(db->mallocFailed) ){
|
| goto whereBeginError;
|
| }
|
| -#ifdef WHERETRACE_ENABLED /* !=0 */
|
| +#ifdef WHERETRACE_ENABLED
|
| if( sqlite3WhereTrace ){
|
| - int ii;
|
| sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
|
| if( pWInfo->nOBSat>0 ){
|
| sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
|
| @@ -6258,12 +4226,14 @@ WhereInfo *sqlite3WhereBegin(
|
| && pResultSet!=0
|
| && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
|
| ){
|
| - Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
|
| - if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
|
| + Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
|
| + if( sWLB.pOrderBy ){
|
| + tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
|
| + }
|
| while( pWInfo->nLevel>=2 ){
|
| WhereTerm *pTerm, *pEnd;
|
| pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
|
| - if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
|
| + if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
|
| if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
|
| && (pLoop->wsFlags & WHERE_ONEROW)==0
|
| ){
|
| @@ -6290,21 +4260,28 @@ WhereInfo *sqlite3WhereBegin(
|
| /* If the caller is an UPDATE or DELETE statement that is requesting
|
| ** to use a one-pass algorithm, determine if this is appropriate.
|
| ** The one-pass algorithm only works if the WHERE clause constrains
|
| - ** the statement to update a single row.
|
| + ** the statement to update or delete a single row.
|
| */
|
| assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
|
| - if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
|
| - && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
|
| - pWInfo->okOnePass = 1;
|
| - if( HasRowid(pTabList->a[0].pTab) ){
|
| - pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
|
| + if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
|
| + int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
|
| + int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
|
| + if( bOnerow || ( (wctrlFlags & WHERE_ONEPASS_MULTIROW)
|
| + && 0==(wsFlags & WHERE_VIRTUALTABLE)
|
| + )){
|
| + pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
|
| + if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
|
| + if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
|
| + bFordelete = OPFLAG_FORDELETE;
|
| + }
|
| + pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
|
| + }
|
| }
|
| }
|
|
|
| /* Open all tables in the pTabList and any indices selected for
|
| ** searching those tables.
|
| */
|
| - notReady = ~(Bitmask)0;
|
| for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
|
| Table *pTab; /* Table to open */
|
| int iDb; /* Index of database containing table/index */
|
| @@ -6329,15 +4306,15 @@ WhereInfo *sqlite3WhereBegin(
|
| if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
|
| && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
|
| int op = OP_OpenRead;
|
| - if( pWInfo->okOnePass ){
|
| + if( pWInfo->eOnePass!=ONEPASS_OFF ){
|
| op = OP_OpenWrite;
|
| pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
|
| };
|
| sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
|
| assert( pTabItem->iCursor==pLevel->iTabCur );
|
| - testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
|
| - testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
|
| - if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
|
| + testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
|
| + testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
|
| + if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
|
| Bitmask b = pTabItem->colUsed;
|
| int n = 0;
|
| for(; b; b=b>>1, n++){}
|
| @@ -6345,6 +4322,18 @@ WhereInfo *sqlite3WhereBegin(
|
| SQLITE_INT_TO_PTR(n), P4_INT32);
|
| assert( n<=pTab->nCol );
|
| }
|
| +#ifdef SQLITE_ENABLE_CURSOR_HINTS
|
| + if( pLoop->u.btree.pIndex!=0 ){
|
| + sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
|
| + }else
|
| +#endif
|
| + {
|
| + sqlite3VdbeChangeP5(v, bFordelete);
|
| + }
|
| +#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
|
| + sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
|
| + (const u8*)&pTabItem->colUsed, P4_INT64);
|
| +#endif
|
| }else{
|
| sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
|
| }
|
| @@ -6361,7 +4350,7 @@ WhereInfo *sqlite3WhereBegin(
|
| ** WITHOUT ROWID table. No need for a separate index */
|
| iIndexCur = pLevel->iTabCur;
|
| op = 0;
|
| - }else if( pWInfo->okOnePass ){
|
| + }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
|
| Index *pJ = pTabItem->pTab->pIndex;
|
| iIndexCur = iIdxCur;
|
| assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
|
| @@ -6383,11 +4372,31 @@ WhereInfo *sqlite3WhereBegin(
|
| if( op ){
|
| sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
|
| sqlite3VdbeSetP4KeyInfo(pParse, pIx);
|
| + if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
|
| + && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
|
| + && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
|
| + ){
|
| + sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
|
| + }
|
| VdbeComment((v, "%s", pIx->zName));
|
| +#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
|
| + {
|
| + u64 colUsed = 0;
|
| + int ii, jj;
|
| + for(ii=0; ii<pIx->nColumn; ii++){
|
| + jj = pIx->aiColumn[ii];
|
| + if( jj<0 ) continue;
|
| + if( jj>63 ) jj = 63;
|
| + if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
|
| + colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
|
| + }
|
| + sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
|
| + (u8*)&colUsed, P4_INT64);
|
| + }
|
| +#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
|
| }
|
| }
|
| if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
|
| - notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
|
| }
|
| pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
|
| if( db->mallocFailed ) goto whereBeginError;
|
| @@ -6398,7 +4407,10 @@ WhereInfo *sqlite3WhereBegin(
|
| */
|
| notReady = ~(Bitmask)0;
|
| for(ii=0; ii<nTabList; ii++){
|
| + int addrExplain;
|
| + int wsFlags;
|
| pLevel = &pWInfo->a[ii];
|
| + wsFlags = pLevel->pWLoop->wsFlags;
|
| #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
|
| if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
|
| constructAutomaticIndex(pParse, &pWInfo->sWC,
|
| @@ -6406,10 +4418,15 @@ WhereInfo *sqlite3WhereBegin(
|
| if( db->mallocFailed ) goto whereBeginError;
|
| }
|
| #endif
|
| - explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
|
| + addrExplain = sqlite3WhereExplainOneScan(
|
| + pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
|
| + );
|
| pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
|
| - notReady = codeOneLoopStart(pWInfo, ii, notReady);
|
| + notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
|
| pWInfo->iContinue = pLevel->addrCont;
|
| + if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
|
| + sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
|
| + }
|
| }
|
|
|
| /* Done. */
|
| @@ -6467,15 +4484,26 @@ void sqlite3WhereEnd(WhereInfo *pWInfo){
|
| VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
|
| sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
|
| }
|
| - sqlite3DbFree(db, pLevel->u.in.aInLoop);
|
| }
|
| sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
|
| if( pLevel->addrSkip ){
|
| - sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
|
| + sqlite3VdbeGoto(v, pLevel->addrSkip);
|
| VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
|
| sqlite3VdbeJumpHere(v, pLevel->addrSkip);
|
| sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
|
| }
|
| +#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
|
| + if( pLevel->addrLikeRep ){
|
| + int op;
|
| + if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
|
| + op = OP_DecrJumpZero;
|
| + }else{
|
| + op = OP_JumpZeroIncr;
|
| + }
|
| + sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
|
| + VdbeCoverage(v);
|
| + }
|
| +#endif
|
| if( pLevel->iLeftJoin ){
|
| addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
|
| assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
|
| @@ -6489,7 +4517,7 @@ void sqlite3WhereEnd(WhereInfo *pWInfo){
|
| if( pLevel->op==OP_Return ){
|
| sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
|
| }else{
|
| - sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
|
| + sqlite3VdbeGoto(v, pLevel->addrFirst);
|
| }
|
| sqlite3VdbeJumpHere(v, addr);
|
| }
|
| @@ -6513,26 +4541,12 @@ void sqlite3WhereEnd(WhereInfo *pWInfo){
|
| pLoop = pLevel->pWLoop;
|
|
|
| /* For a co-routine, change all OP_Column references to the table of
|
| - ** the co-routine into OP_SCopy of result contained in a register.
|
| + ** the co-routine into OP_Copy of result contained in a register.
|
| ** OP_Rowid becomes OP_Null.
|
| */
|
| - if( pTabItem->viaCoroutine && !db->mallocFailed ){
|
| - last = sqlite3VdbeCurrentAddr(v);
|
| - k = pLevel->addrBody;
|
| - pOp = sqlite3VdbeGetOp(v, k);
|
| - for(; k<last; k++, pOp++){
|
| - if( pOp->p1!=pLevel->iTabCur ) continue;
|
| - if( pOp->opcode==OP_Column ){
|
| - pOp->opcode = OP_Copy;
|
| - pOp->p1 = pOp->p2 + pTabItem->regResult;
|
| - pOp->p2 = pOp->p3;
|
| - pOp->p3 = 0;
|
| - }else if( pOp->opcode==OP_Rowid ){
|
| - pOp->opcode = OP_Null;
|
| - pOp->p1 = 0;
|
| - pOp->p3 = 0;
|
| - }
|
| - }
|
| + if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
|
| + translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
|
| + pTabItem->regResult, 0);
|
| continue;
|
| }
|
|
|
| @@ -6546,7 +4560,7 @@ void sqlite3WhereEnd(WhereInfo *pWInfo){
|
| && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
|
| ){
|
| int ws = pLoop->wsFlags;
|
| - if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
|
| + if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
|
| sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
|
| }
|
| if( (ws & WHERE_INDEXED)!=0
|
| @@ -6573,7 +4587,10 @@ void sqlite3WhereEnd(WhereInfo *pWInfo){
|
| }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
|
| pIdx = pLevel->u.pCovidx;
|
| }
|
| - if( pIdx && !db->mallocFailed ){
|
| + if( pIdx
|
| + && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
|
| + && !db->mallocFailed
|
| + ){
|
| last = sqlite3VdbeCurrentAddr(v);
|
| k = pLevel->addrBody;
|
| pOp = sqlite3VdbeGetOp(v, k);
|
| @@ -6585,6 +4602,7 @@ void sqlite3WhereEnd(WhereInfo *pWInfo){
|
| if( !HasRowid(pTab) ){
|
| Index *pPk = sqlite3PrimaryKeyIndex(pTab);
|
| x = pPk->aiColumn[x];
|
| + assert( x>=0 );
|
| }
|
| x = sqlite3ColumnOfIndex(pIdx, x);
|
| if( x>=0 ){
|
|
|