⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 where.c

📁 sqlite最新源码
💻 C
📖 第 1 页 / 共 5 页
字号:
/*** 2001 September 15**** The author disclaims copyright to this source code.  In place of** a legal notice, here is a blessing:****    May you do good and not evil.**    May you find forgiveness for yourself and forgive others.**    May you share freely, never taking more than you give.***************************************************************************** This module contains C code that generates VDBE code used to process** the WHERE clause of SQL statements.  This module is responsible for** generating the code that loops through a table looking for applicable** rows.  Indices are selected and used to speed the search when doing** so is applicable.  Because this module is responsible for selecting** indices, you might also think of this module as the "query optimizer".**** $Id: where.c,v 1.368 2009/02/04 03:59:25 shane Exp $*/#include "sqliteInt.h"/*** Trace output macros*/#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)int sqlite3WhereTrace = 0;#endif#if 0# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X#else# define WHERETRACE(X)#endif/* Forward reference*/typedef struct WhereClause WhereClause;typedef struct WhereMaskSet WhereMaskSet;typedef struct WhereOrInfo WhereOrInfo;typedef struct WhereAndInfo WhereAndInfo;typedef struct WhereCost WhereCost;/*** The query generator uses an array of instances of this structure to** help it analyze the subexpressions of the WHERE clause.  Each WHERE** clause subexpression is separated from the others by AND operators.** (Note: the same data structure is also reused to hold a group of terms** separated by OR operators.  But at the top-level, everything is AND** separated.)**** All WhereTerms are collected into a single WhereClause structure.  ** The following identity holds:****        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm**** When a term is of the form:****              X <op> <expr>**** where X is a column name and <op> is one of certain operators,** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the** cursor number and column number for X.  WhereTerm.eOperator records** the <op> using a bitmask encoding defined by WO_xxx below.  The** use of a bitmask encoding for the operator allows us to search** quickly for terms that match any of several different operators.**** A WhereTerm might also be two or more subterms connected by OR:****         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....**** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR** and the WhereTerm.u.pOrInfo field points to auxiliary information that** is collected about the**** If a term in the WHERE clause does not match either of the two previous** categories, then eOperator==0.  The WhereTerm.pExpr field is still set** to the original subexpression content and wtFlags is set up appropriately** but no other fields in the WhereTerm object are meaningful.**** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,** but they do so indirectly.  A single WhereMaskSet structure translates** cursor number into bits and the translated bit is stored in the prereq** fields.  The translation is used in order to maximize the number of** bits that will fit in a Bitmask.  The VDBE cursor numbers might be** spread out over the non-negative integers.  For example, the cursor** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet** translates these sparse cursor numbers into consecutive integers** beginning with 0 in order to make the best possible use of the available** bits in the Bitmask.  So, in the example above, the cursor numbers** would be mapped into integers 0 through 7.**** The number of terms in a join is limited by the number of bits** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite** is only able to process joins with 64 or fewer tables.*/typedef struct WhereTerm WhereTerm;struct WhereTerm {  Expr *pExpr;            /* Pointer to the subexpression that is this term */  int iParent;            /* Disable pWC->a[iParent] when this term disabled */  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */  union {    int leftColumn;         /* Column number of X in "X <op> <expr>" */    WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */    WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */  } u;  u16 eOperator;          /* A WO_xx value describing <op> */  u8 wtFlags;             /* TERM_xxx bit flags.  See below */  u8 nChild;              /* Number of children that must disable us */  WhereClause *pWC;       /* The clause this term is part of */  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */};/*** Allowed values of WhereTerm.wtFlags*/#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */#define TERM_CODED      0x04   /* This term is already coded */#define TERM_COPIED     0x08   /* Has a child */#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */#define TERM_OR_OK      0x40   /* Used during OR-clause processing *//*** An instance of the following structure holds all information about a** WHERE clause.  Mostly this is a container for one or more WhereTerms.*/struct WhereClause {  Parse *pParse;           /* The parser context */  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */  u8 op;                   /* Split operator.  TK_AND or TK_OR */  int nTerm;               /* Number of terms */  int nSlot;               /* Number of entries in a[] */  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */  WhereTerm aStatic[4];    /* Initial static space for a[] */};/*** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to** a dynamically allocated instance of the following structure.*/struct WhereOrInfo {  WhereClause wc;          /* Decomposition into subterms */  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */};/*** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to** a dynamically allocated instance of the following structure.*/struct WhereAndInfo {  WhereClause wc;          /* The subexpression broken out */};/*** An instance of the following structure keeps track of a mapping** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.**** The VDBE cursor numbers are small integers contained in ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE ** clause, the cursor numbers might not begin with 0 and they might** contain gaps in the numbering sequence.  But we want to make maximum** use of the bits in our bitmasks.  This structure provides a mapping** from the sparse cursor numbers into consecutive integers beginning** with 0.**** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.**** For example, if the WHERE clause expression used these VDBE** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure** would map those cursor numbers into bits 0 through 5.**** Note that the mapping is not necessarily ordered.  In the example** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,** 57->5, 73->4.  Or one of 719 other combinations might be used. It** does not really matter.  What is important is that sparse cursor** numbers all get mapped into bit numbers that begin with 0 and contain** no gaps.*/struct WhereMaskSet {  int n;                        /* Number of assigned cursor values */  int ix[BMS];                  /* Cursor assigned to each bit */};/*** A WhereCost object records a lookup strategy and the estimated** cost of pursuing that strategy.*/struct WhereCost {  WherePlan plan;    /* The lookup strategy */  double rCost;      /* Overall cost of pursuing this search strategy */  double nRow;       /* Estimated number of output rows */};/*** Bitmasks for the operators that indices are able to exploit.  An** OR-ed combination of these values can be used when searching for** terms in the where clause.*/#define WO_IN     0x001#define WO_EQ     0x002#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))#define WO_MATCH  0x040#define WO_ISNULL 0x080#define WO_OR     0x100       /* Two or more OR-connected terms */#define WO_AND    0x200       /* Two or more AND-connected terms */#define WO_ALL    0xfff       /* Mask of all possible WO_* values */#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values *//*** Value for wsFlags returned by bestIndex() and stored in** WhereLevel.wsFlags.  These flags determine which search** strategies are appropriate.**** The least significant 12 bits is reserved as a mask for WO_ values above.** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.** But if the table is the right table of a left join, WhereLevel.wsFlags** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as** the "op" parameter to findTerm when we are resolving equality constraints.** ISNULL constraints will then not be used on the right table of a left** join.  Tickets #2177 and #2189.*/#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) */#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */#define WHERE_INDEXED      0x00070000  /* Anything that uses an index */#define WHERE_IN_ABLE      0x00071000  /* Able to support an IN operator */#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */#define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */#define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */#define WHERE_REVERSE      0x02000000  /* Scan in reverse order */#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices *//*** Initialize a preallocated WhereClause structure.*/static void whereClauseInit(  WhereClause *pWC,        /* The WhereClause to be initialized */  Parse *pParse,           /* The parsing context */  WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */){  pWC->pParse = pParse;  pWC->pMaskSet = pMaskSet;  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->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;  if( pWC->nTerm>=pWC->nSlot ){    WhereTerm *pOld = pWC->a;    sqlite3 *db = pWC->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++];  pTerm->pExpr = 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:**

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -