Index: third_party/sqlite/amalgamation/sqlite3.06.c |
diff --git a/third_party/sqlite/amalgamation/sqlite3.06.c b/third_party/sqlite/amalgamation/sqlite3.06.c |
new file mode 100644 |
index 0000000000000000000000000000000000000000..5d9075f549a293b83adb28b0da50758394688579 |
--- /dev/null |
+++ b/third_party/sqlite/amalgamation/sqlite3.06.c |
@@ -0,0 +1,18528 @@ |
+/************** Begin file wherecode.c ***************************************/ |
+/* |
+** 2015-06-06 |
+** |
+** 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 file was split off from where.c on 2015-06-06 in order to reduce the |
+** size of where.c and make it easier to edit. This file contains the routines |
+** that actually generate the bulk of the WHERE loop code. The original where.c |
+** file retains the code that does query planning and analysis. |
+*/ |
+/* #include "sqliteInt.h" */ |
+/************** Include whereInt.h in the middle of wherecode.c **************/ |
+/************** Begin file whereInt.h ****************************************/ |
+/* |
+** 2013-11-12 |
+** |
+** 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 file contains structure and macro definitions for the query |
+** planner logic in "where.c". These definitions are broken out into |
+** a separate source file for easier editing. |
+*/ |
+ |
+/* |
+** Trace output macros |
+*/ |
+#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) |
+/***/ int sqlite3WhereTrace; |
+#endif |
+#if defined(SQLITE_DEBUG) \ |
+ && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE)) |
+# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X |
+# define WHERETRACE_ENABLED 1 |
+#else |
+# define WHERETRACE(K,X) |
+#endif |
+ |
+/* Forward references |
+*/ |
+typedef struct WhereClause WhereClause; |
+typedef struct WhereMaskSet WhereMaskSet; |
+typedef struct WhereOrInfo WhereOrInfo; |
+typedef struct WhereAndInfo WhereAndInfo; |
+typedef struct WhereLevel WhereLevel; |
+typedef struct WhereLoop WhereLoop; |
+typedef struct WherePath WherePath; |
+typedef struct WhereTerm WhereTerm; |
+typedef struct WhereLoopBuilder WhereLoopBuilder; |
+typedef struct WhereScan WhereScan; |
+typedef struct WhereOrCost WhereOrCost; |
+typedef struct WhereOrSet WhereOrSet; |
+ |
+/* |
+** This object contains information needed to implement a single nested |
+** loop in WHERE clause. |
+** |
+** Contrast this object with WhereLoop. This object describes the |
+** implementation of the loop. WhereLoop describes the algorithm. |
+** This object contains a pointer to the WhereLoop algorithm as one of |
+** its elements. |
+** |
+** The WhereInfo object contains a single instance of this object for |
+** each term in the FROM clause (which is to say, for each of the |
+** nested loops as implemented). The order of WhereLevel objects determines |
+** the loop nested order, with WhereInfo.a[0] being the outer loop and |
+** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop. |
+*/ |
+struct WhereLevel { |
+ int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */ |
+ int iTabCur; /* The VDBE cursor used to access the table */ |
+ int iIdxCur; /* The VDBE cursor used to access pIdx */ |
+ int addrBrk; /* Jump here to break out of the loop */ |
+ int addrNxt; /* Jump here to start the next IN combination */ |
+ int addrSkip; /* Jump here for next iteration of skip-scan */ |
+ int addrCont; /* Jump here to continue with the next loop cycle */ |
+ int addrFirst; /* First instruction of interior of the loop */ |
+ int addrBody; /* Beginning of the body of this loop */ |
+#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS |
+ u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */ |
+ int addrLikeRep; /* LIKE range processing address */ |
+#endif |
+ u8 iFrom; /* Which entry in the FROM clause */ |
+ u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */ |
+ int p1, p2; /* Operands of the opcode used to ends the loop */ |
+ union { /* Information that depends on pWLoop->wsFlags */ |
+ struct { |
+ int nIn; /* Number of entries in aInLoop[] */ |
+ struct InLoop { |
+ int iCur; /* The VDBE cursor used by this IN operator */ |
+ int addrInTop; /* Top of the IN loop */ |
+ u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */ |
+ } *aInLoop; /* Information about each nested IN operator */ |
+ } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */ |
+ Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */ |
+ } u; |
+ struct WhereLoop *pWLoop; /* The selected WhereLoop object */ |
+ Bitmask notReady; /* FROM entries not usable at this level */ |
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS |
+ int addrVisit; /* Address at which row is visited */ |
+#endif |
+}; |
+ |
+/* |
+** Each instance of this object represents an algorithm for evaluating one |
+** term of a join. Every term of the FROM clause will have at least |
+** one corresponding WhereLoop object (unless INDEXED BY constraints |
+** prevent a query solution - which is an error) and many terms of the |
+** FROM clause will have multiple WhereLoop objects, each describing a |
+** potential way of implementing that FROM-clause term, together with |
+** dependencies and cost estimates for using the chosen algorithm. |
+** |
+** Query planning consists of building up a collection of these WhereLoop |
+** objects, then computing a particular sequence of WhereLoop objects, with |
+** one WhereLoop object per FROM clause term, that satisfy all dependencies |
+** and that minimize the overall cost. |
+*/ |
+struct WhereLoop { |
+ Bitmask prereq; /* Bitmask of other loops that must run first */ |
+ Bitmask maskSelf; /* Bitmask identifying table iTab */ |
+#ifdef SQLITE_DEBUG |
+ char cId; /* Symbolic ID of this loop for debugging use */ |
+#endif |
+ u8 iTab; /* Position in FROM clause of table for this loop */ |
+ u8 iSortIdx; /* Sorting index number. 0==None */ |
+ LogEst rSetup; /* One-time setup cost (ex: create transient index) */ |
+ LogEst rRun; /* Cost of running each loop */ |
+ LogEst nOut; /* Estimated number of output rows */ |
+ union { |
+ struct { /* Information for internal btree tables */ |
+ u16 nEq; /* Number of equality constraints */ |
+ u16 nBtm; /* Size of BTM vector */ |
+ u16 nTop; /* Size of TOP vector */ |
+ Index *pIndex; /* Index used, or NULL */ |
+ } btree; |
+ struct { /* Information for virtual tables */ |
+ int idxNum; /* Index number */ |
+ u8 needFree; /* True if sqlite3_free(idxStr) is needed */ |
+ i8 isOrdered; /* True if satisfies ORDER BY */ |
+ u16 omitMask; /* Terms that may be omitted */ |
+ char *idxStr; /* Index identifier string */ |
+ } vtab; |
+ } u; |
+ u32 wsFlags; /* WHERE_* flags describing the plan */ |
+ u16 nLTerm; /* Number of entries in aLTerm[] */ |
+ u16 nSkip; /* Number of NULL aLTerm[] entries */ |
+ /**** whereLoopXfer() copies fields above ***********************/ |
+# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot) |
+ u16 nLSlot; /* Number of slots allocated for aLTerm[] */ |
+ WhereTerm **aLTerm; /* WhereTerms used */ |
+ WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */ |
+ WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */ |
+}; |
+ |
+/* This object holds the prerequisites and the cost of running a |
+** subquery on one operand of an OR operator in the WHERE clause. |
+** See WhereOrSet for additional information |
+*/ |
+struct WhereOrCost { |
+ Bitmask prereq; /* Prerequisites */ |
+ LogEst rRun; /* Cost of running this subquery */ |
+ LogEst nOut; /* Number of outputs for this subquery */ |
+}; |
+ |
+/* The WhereOrSet object holds a set of possible WhereOrCosts that |
+** correspond to the subquery(s) of OR-clause processing. Only the |
+** best N_OR_COST elements are retained. |
+*/ |
+#define N_OR_COST 3 |
+struct WhereOrSet { |
+ u16 n; /* Number of valid a[] entries */ |
+ WhereOrCost a[N_OR_COST]; /* Set of best costs */ |
+}; |
+ |
+/* |
+** Each instance of this object holds a sequence of WhereLoop objects |
+** that implement some or all of a query plan. |
+** |
+** Think of each WhereLoop object as a node in a graph with arcs |
+** showing dependencies and costs for travelling between nodes. (That is |
+** not a completely accurate description because WhereLoop costs are a |
+** vector, not a scalar, and because dependencies are many-to-one, not |
+** one-to-one as are graph nodes. But it is a useful visualization aid.) |
+** Then a WherePath object is a path through the graph that visits some |
+** or all of the WhereLoop objects once. |
+** |
+** The "solver" works by creating the N best WherePath objects of length |
+** 1. Then using those as a basis to compute the N best WherePath objects |
+** of length 2. And so forth until the length of WherePaths equals the |
+** number of nodes in the FROM clause. The best (lowest cost) WherePath |
+** at the end is the chosen query plan. |
+*/ |
+struct WherePath { |
+ Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */ |
+ Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */ |
+ LogEst nRow; /* Estimated number of rows generated by this path */ |
+ LogEst rCost; /* Total cost of this path */ |
+ LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */ |
+ i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */ |
+ WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */ |
+}; |
+ |
+/* |
+** 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, |
+** usually, or sometimes subexpressions separated by OR. |
+** |
+** 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 has the TERM_ORINFO bit set and eOperator==WO_OR |
+** and the WhereTerm.u.pOrInfo field points to auxiliary information that |
+** is collected about the OR clause. |
+** |
+** 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. |
+*/ |
+struct WhereTerm { |
+ Expr *pExpr; /* Pointer to the subexpression that is this term */ |
+ WhereClause *pWC; /* The clause this term is part of */ |
+ LogEst truthProb; /* Probability of truth for this expression */ |
+ u16 wtFlags; /* TERM_xxx bit flags. See below */ |
+ u16 eOperator; /* A WO_xx value describing <op> */ |
+ u8 nChild; /* Number of children that must disable us */ |
+ u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */ |
+ int iParent; /* Disable pWC->a[iParent] when this term disabled */ |
+ int leftCursor; /* Cursor number of X in "X <op> <expr>" */ |
+ int iField; /* Field in (?,?,?) IN (SELECT...) vector */ |
+ union { |
+ int leftColumn; /* Column number of X in "X <op> <expr>" */ |
+ WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */ |
+ WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */ |
+ } u; |
+ 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 */ |
+#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
+# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */ |
+#else |
+# define TERM_VNULL 0x00 /* Disabled if not using stat3 */ |
+#endif |
+#define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */ |
+#define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */ |
+#define TERM_LIKE 0x400 /* The original LIKE operator */ |
+#define TERM_IS 0x800 /* Term.pExpr is an IS operator */ |
+ |
+/* |
+** An instance of the WhereScan object is used as an iterator for locating |
+** terms in the WHERE clause that are useful to the query planner. |
+*/ |
+struct WhereScan { |
+ WhereClause *pOrigWC; /* Original, innermost WhereClause */ |
+ WhereClause *pWC; /* WhereClause currently being scanned */ |
+ const char *zCollName; /* Required collating sequence, if not NULL */ |
+ Expr *pIdxExpr; /* Search for this index expression */ |
+ char idxaff; /* Must match this affinity, if zCollName!=NULL */ |
+ unsigned char nEquiv; /* Number of entries in aEquiv[] */ |
+ unsigned char iEquiv; /* Next unused slot in aEquiv[] */ |
+ u32 opMask; /* Acceptable operators */ |
+ int k; /* Resume scanning at this->pWC->a[this->k] */ |
+ int aiCur[11]; /* Cursors in the equivalence class */ |
+ i16 aiColumn[11]; /* Corresponding column number in the eq-class */ |
+}; |
+ |
+/* |
+** An instance of the following structure holds all information about a |
+** WHERE clause. Mostly this is a container for one or more WhereTerms. |
+** |
+** Explanation of pOuter: For a WHERE clause of the form |
+** |
+** a AND ((b AND c) OR (d AND e)) AND f |
+** |
+** There are separate WhereClause objects for the whole clause and for |
+** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the |
+** subclauses points to the WhereClause object for the whole clause. |
+*/ |
+struct WhereClause { |
+ WhereInfo *pWInfo; /* WHERE clause processing context */ |
+ WhereClause *pOuter; /* Outer conjunction */ |
+ 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 */ |
+#if defined(SQLITE_SMALL_STACK) |
+ WhereTerm aStatic[1]; /* Initial static space for a[] */ |
+#else |
+ WhereTerm aStatic[8]; /* Initial static space for a[] */ |
+#endif |
+}; |
+ |
+/* |
+** 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 */ |
+}; |
+ |
+/* |
+** Initialize a WhereMaskSet object |
+*/ |
+#define initMaskSet(P) (P)->n=0 |
+ |
+/* |
+** This object is a convenience wrapper holding all information needed |
+** to construct WhereLoop objects for a particular query. |
+*/ |
+struct WhereLoopBuilder { |
+ WhereInfo *pWInfo; /* Information about this WHERE */ |
+ WhereClause *pWC; /* WHERE clause terms */ |
+ ExprList *pOrderBy; /* ORDER BY clause */ |
+ WhereLoop *pNew; /* Template WhereLoop */ |
+ WhereOrSet *pOrSet; /* Record best loops here, if not NULL */ |
+#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
+ UnpackedRecord *pRec; /* Probe for stat4 (if required) */ |
+ int nRecValid; /* Number of valid fields currently in pRec */ |
+#endif |
+}; |
+ |
+/* |
+** The WHERE clause processing routine has two halves. The |
+** first part does the start of the WHERE loop and the second |
+** half does the tail of the WHERE loop. An instance of |
+** this structure is returned by the first half and passed |
+** into the second half to give some continuity. |
+** |
+** An instance of this object holds the complete state of the query |
+** planner. |
+*/ |
+struct WhereInfo { |
+ Parse *pParse; /* Parsing and code generating context */ |
+ SrcList *pTabList; /* List of tables in the join */ |
+ ExprList *pOrderBy; /* The ORDER BY clause or NULL */ |
+ ExprList *pDistinctSet; /* DISTINCT over all these values */ |
+ LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */ |
+ int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */ |
+ int iContinue; /* Jump here to continue with next record */ |
+ int iBreak; /* Jump here to break out of the loop */ |
+ int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */ |
+ u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */ |
+ u8 nLevel; /* Number of nested loop */ |
+ i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */ |
+ u8 sorted; /* True if really sorted (not just grouped) */ |
+ u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */ |
+ u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */ |
+ u8 eDistinct; /* One of the WHERE_DISTINCT_* values */ |
+ u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */ |
+ int iTop; /* The very beginning of the WHERE loop */ |
+ WhereLoop *pLoops; /* List of all WhereLoop objects */ |
+ Bitmask revMask; /* Mask of ORDER BY terms that need reversing */ |
+ LogEst nRowOut; /* Estimated number of output rows */ |
+ WhereClause sWC; /* Decomposition of the WHERE clause */ |
+ WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */ |
+ WhereLevel a[1]; /* Information about each nest loop in WHERE */ |
+}; |
+ |
+/* |
+** Private interfaces - callable only by other where.c routines. |
+** |
+** where.c: |
+*/ |
+SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int); |
+#ifdef WHERETRACE_ENABLED |
+SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC); |
+#endif |
+SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm( |
+ WhereClause *pWC, /* The WHERE clause to be searched */ |
+ int iCur, /* Cursor number of LHS */ |
+ int iColumn, /* Column number of LHS */ |
+ Bitmask notReady, /* RHS must not overlap with this mask */ |
+ u32 op, /* Mask of WO_xx values describing operator */ |
+ Index *pIdx /* Must be compatible with this index, if not NULL */ |
+); |
+ |
+/* wherecode.c: */ |
+#ifndef SQLITE_OMIT_EXPLAIN |
+SQLITE_PRIVATE int sqlite3WhereExplainOneScan( |
+ 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() */ |
+); |
+#else |
+# define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0 |
+#endif /* SQLITE_OMIT_EXPLAIN */ |
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS |
+SQLITE_PRIVATE void sqlite3WhereAddScanStatus( |
+ Vdbe *v, /* Vdbe to add scanstatus entry to */ |
+ SrcList *pSrclist, /* FROM clause pLvl reads data from */ |
+ WhereLevel *pLvl, /* Level to add scanstatus() entry for */ |
+ int addrExplain /* Address of OP_Explain (or 0) */ |
+); |
+#else |
+# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d) |
+#endif |
+SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( |
+ 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 */ |
+); |
+ |
+/* whereexpr.c: */ |
+SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*); |
+SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*); |
+SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8); |
+SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*); |
+SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*); |
+SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*); |
+SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*); |
+ |
+ |
+ |
+ |
+ |
+/* |
+** Bitmasks for the operators on WhereTerm objects. These are all |
+** operators that are of interest to the query planner. An |
+** OR-ed combination of these values can be used when searching for |
+** particular WhereTerms within a WhereClause. |
+** |
+** Value constraints: |
+** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ |
+** WO_LT == SQLITE_INDEX_CONSTRAINT_LT |
+** WO_LE == SQLITE_INDEX_CONSTRAINT_LE |
+** WO_GT == SQLITE_INDEX_CONSTRAINT_GT |
+** WO_GE == SQLITE_INDEX_CONSTRAINT_GE |
+** WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH |
+*/ |
+#define WO_IN 0x0001 |
+#define WO_EQ 0x0002 |
+#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 0x0040 |
+#define WO_IS 0x0080 |
+#define WO_ISNULL 0x0100 |
+#define WO_OR 0x0200 /* Two or more OR-connected terms */ |
+#define WO_AND 0x0400 /* Two or more AND-connected terms */ |
+#define WO_EQUIV 0x0800 /* Of the form A==B, both columns */ |
+#define WO_NOOP 0x1000 /* This term does not restrict search space */ |
+ |
+#define WO_ALL 0x1fff /* Mask of all possible WO_* values */ |
+#define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */ |
+ |
+/* |
+** These are definitions of bits in the WhereLoop.wsFlags field. |
+** The particular combination of bits in each WhereLoop help to |
+** determine the algorithm that WhereLoop represents. |
+*/ |
+#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */ |
+#define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */ |
+#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */ |
+#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */ |
+#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */ |
+#define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */ |
+#define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */ |
+#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */ |
+#define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */ |
+#define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */ |
+#define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */ |
+#define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */ |
+#define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */ |
+#define WHERE_ONEROW 0x00001000 /* Selects no more than one row */ |
+#define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */ |
+#define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */ |
+#define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */ |
+#define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/ |
+#define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */ |
+ |
+/************** End of whereInt.h ********************************************/ |
+/************** Continuing where we left off in wherecode.c ******************/ |
+ |
+#ifndef SQLITE_OMIT_EXPLAIN |
+ |
+/* |
+** Return the name of the i-th column of the pIdx index. |
+*/ |
+static const char *explainIndexColumnName(Index *pIdx, int i){ |
+ i = pIdx->aiColumn[i]; |
+ if( i==XN_EXPR ) return "<expr>"; |
+ if( i==XN_ROWID ) return "rowid"; |
+ return pIdx->pTable->aCol[i].zName; |
+} |
+ |
+/* |
+** 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 */ |
+ Index *pIdx, /* Index to read column names from */ |
+ int nTerm, /* Number of terms */ |
+ int iTerm, /* Zero-based index of first term. */ |
+ int bAnd, /* Non-zero to append " AND " */ |
+ const char *zOp /* Name of the operator */ |
+){ |
+ int i; |
+ |
+ assert( nTerm>=1 ); |
+ if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5); |
+ |
+ if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1); |
+ for(i=0; i<nTerm; i++){ |
+ if( i ) sqlite3StrAccumAppend(pStr, ",", 1); |
+ sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i)); |
+ } |
+ if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1); |
+ |
+ sqlite3StrAccumAppend(pStr, zOp, 1); |
+ |
+ if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1); |
+ for(i=0; i<nTerm; i++){ |
+ if( i ) sqlite3StrAccumAppend(pStr, ",", 1); |
+ sqlite3StrAccumAppend(pStr, "?", 1); |
+ } |
+ if( nTerm>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){ |
+ Index *pIndex = pLoop->u.btree.pIndex; |
+ u16 nEq = pLoop->u.btree.nEq; |
+ u16 nSkip = pLoop->nSkip; |
+ int i, j; |
+ |
+ if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return; |
+ sqlite3StrAccumAppend(pStr, " (", 2); |
+ for(i=0; i<nEq; i++){ |
+ const char *z = explainIndexColumnName(pIndex, i); |
+ if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5); |
+ sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z); |
+ } |
+ |
+ j = i; |
+ if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ |
+ explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">"); |
+ i = 1; |
+ } |
+ if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ |
+ explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<"); |
+ } |
+ sqlite3StrAccumAppend(pStr, ")", 1); |
+} |
+ |
+/* |
+** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN |
+** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was |
+** defined at compile-time. If it is not a no-op, a single OP_Explain opcode |
+** is added to the output to describe the table scan strategy in pLevel. |
+** |
+** If an OP_Explain opcode is added to the VM, its address is returned. |
+** Otherwise, if no OP_Explain is coded, zero is returned. |
+*/ |
+SQLITE_PRIVATE int sqlite3WhereExplainOneScan( |
+ 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() */ |
+){ |
+ int ret = 0; |
+#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS) |
+ 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_OR_SUBCLAUSE) ) return 0; |
+ |
+ 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, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); |
+ sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN"); |
+ if( pItem->pSelect ){ |
+ sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId); |
+ }else{ |
+ sqlite3XPrintf(&str, " TABLE %s", pItem->zName); |
+ } |
+ |
+ if( pItem->zAlias ){ |
+ sqlite3XPrintf(&str, " 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_PARTIALIDX ){ |
+ zFmt = "AUTOMATIC PARTIAL COVERING INDEX"; |
+ }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, zFmt, pIdx->zName); |
+ explainIndexRange(&str, pLoop); |
+ } |
+ }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ |
+ const char *zRangeOp; |
+ if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ |
+ zRangeOp = "="; |
+ }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ |
+ zRangeOp = ">? AND rowid<"; |
+ }else if( flags&WHERE_BTM_LIMIT ){ |
+ zRangeOp = ">"; |
+ }else{ |
+ assert( flags&WHERE_TOP_LIMIT); |
+ zRangeOp = "<"; |
+ } |
+ sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); |
+ } |
+#ifndef SQLITE_OMIT_VIRTUALTABLE |
+ else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ |
+ sqlite3XPrintf(&str, " 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, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut)); |
+ }else{ |
+ sqlite3StrAccumAppend(&str, " (~1 row)", 9); |
+ } |
+#endif |
+ zMsg = sqlite3StrAccumFinish(&str); |
+ ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC); |
+ } |
+ return ret; |
+} |
+#endif /* SQLITE_OMIT_EXPLAIN */ |
+ |
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS |
+/* |
+** Configure the VM passed as the first argument with an |
+** sqlite3_stmt_scanstatus() entry corresponding to the scan used to |
+** implement level pLvl. Argument pSrclist is a pointer to the FROM |
+** clause that the scan reads data from. |
+** |
+** If argument addrExplain is not 0, it must be the address of an |
+** OP_Explain instruction that describes the same loop. |
+*/ |
+SQLITE_PRIVATE void sqlite3WhereAddScanStatus( |
+ Vdbe *v, /* Vdbe to add scanstatus entry to */ |
+ SrcList *pSrclist, /* FROM clause pLvl reads data from */ |
+ WhereLevel *pLvl, /* Level to add scanstatus() entry for */ |
+ int addrExplain /* Address of OP_Explain (or 0) */ |
+){ |
+ const char *zObj = 0; |
+ WhereLoop *pLoop = pLvl->pWLoop; |
+ if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){ |
+ zObj = pLoop->u.btree.pIndex->zName; |
+ }else{ |
+ zObj = pSrclist->a[pLvl->iFrom].zName; |
+ } |
+ sqlite3VdbeScanStatus( |
+ v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj |
+ ); |
+} |
+#endif |
+ |
+ |
+/* |
+** 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. |
+** |
+** If all the children of a term are disabled, then that term is also |
+** automatically disabled. In this way, terms get disabled if derived |
+** virtual terms are tested first. For example: |
+** |
+** x GLOB 'abc*' AND x>='abc' AND x<'acd' |
+** \___________/ \______/ \_____/ |
+** parent child1 child2 |
+** |
+** Only the parent term was in the original WHERE clause. The child1 |
+** and child2 terms were added by the LIKE optimization. If both of |
+** the virtual child terms are valid, then testing of the parent can be |
+** skipped. |
+** |
+** Usually the parent term is marked as TERM_CODED. But if the parent |
+** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead. |
+** The TERM_LIKECOND marking indicates that the term should be coded inside |
+** a conditional such that is only evaluated on the second pass of a |
+** LIKE-optimization loop, when scanning BLOBs instead of strings. |
+*/ |
+static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ |
+ int nLoop = 0; |
+ while( ALWAYS(pTerm!=0) |
+ && (pTerm->wtFlags & TERM_CODED)==0 |
+ && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) |
+ && (pLevel->notReady & pTerm->prereqAll)==0 |
+ ){ |
+ if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){ |
+ pTerm->wtFlags |= TERM_LIKECOND; |
+ }else{ |
+ pTerm->wtFlags |= TERM_CODED; |
+ } |
+ if( pTerm->iParent<0 ) break; |
+ pTerm = &pTerm->pWC->a[pTerm->iParent]; |
+ pTerm->nChild--; |
+ if( pTerm->nChild!=0 ) break; |
+ nLoop++; |
+ } |
+} |
+ |
+/* |
+** Code an OP_Affinity opcode to apply the column affinity string zAff |
+** to the n registers starting at base. |
+** |
+** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the |
+** beginning and end of zAff are ignored. If all entries in zAff are |
+** SQLITE_AFF_BLOB, 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_BLOB entries at the beginning |
+ ** and end of the affinity string. |
+ */ |
+ while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){ |
+ n--; |
+ base++; |
+ zAff++; |
+ } |
+ while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){ |
+ n--; |
+ } |
+ |
+ /* Code the OP_Affinity opcode if there is anything left to do. */ |
+ if( n>0 ){ |
+ sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n); |
+ sqlite3ExprCacheAffinityChange(pParse, base, n); |
+ } |
+} |
+ |
+/* |
+** Expression pRight, which is the RHS of a comparison operation, is |
+** either a vector of n elements or, if n==1, a scalar expression. |
+** Before the comparison operation, affinity zAff is to be applied |
+** to the pRight values. This function modifies characters within the |
+** affinity string to SQLITE_AFF_BLOB if either: |
+** |
+** * the comparison will be performed with no affinity, or |
+** * the affinity change in zAff is guaranteed not to change the value. |
+*/ |
+static void updateRangeAffinityStr( |
+ Expr *pRight, /* RHS of comparison */ |
+ int n, /* Number of vector elements in comparison */ |
+ char *zAff /* Affinity string to modify */ |
+){ |
+ int i; |
+ for(i=0; i<n; i++){ |
+ Expr *p = sqlite3VectorFieldSubexpr(pRight, i); |
+ if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB |
+ || sqlite3ExprNeedsNoAffinityChange(p, zAff[i]) |
+ ){ |
+ zAff[i] = SQLITE_AFF_BLOB; |
+ } |
+ } |
+} |
+ |
+/* |
+** 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 a register, the index |
+** of which is returned. An attempt is made store the result in iTarget but |
+** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the |
+** constraint is a TK_EQ or TK_IS, then the current value might be left in |
+** some other register and it is the caller's responsibility to compensate. |
+** |
+** For a constraint of the form X=expr, the expression is evaluated in |
+** straight-line code. 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( pLevel->pWLoop->aLTerm[iEq]==pTerm ); |
+ assert( iTarget>0 ); |
+ if( pX->op==TK_EQ || pX->op==TK_IS ){ |
+ 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 = IN_INDEX_NOOP; |
+ int iTab; |
+ struct InLoop *pIn; |
+ WhereLoop *pLoop = pLevel->pWLoop; |
+ int i; |
+ int nEq = 0; |
+ int *aiMap = 0; |
+ |
+ 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; |
+ |
+ for(i=0; i<iEq; i++){ |
+ if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){ |
+ disableTerm(pLevel, pTerm); |
+ return iTarget; |
+ } |
+ } |
+ for(i=iEq;i<pLoop->nLTerm; i++){ |
+ if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++; |
+ } |
+ |
+ if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){ |
+ eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0); |
+ }else{ |
+ Select *pSelect = pX->x.pSelect; |
+ sqlite3 *db = pParse->db; |
+ u16 savedDbOptFlags = db->dbOptFlags; |
+ ExprList *pOrigRhs = pSelect->pEList; |
+ ExprList *pOrigLhs = pX->pLeft->x.pList; |
+ ExprList *pRhs = 0; /* New Select.pEList for RHS */ |
+ ExprList *pLhs = 0; /* New pX->pLeft vector */ |
+ |
+ for(i=iEq;i<pLoop->nLTerm; i++){ |
+ if( pLoop->aLTerm[i]->pExpr==pX ){ |
+ int iField = pLoop->aLTerm[i]->iField - 1; |
+ Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0); |
+ Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0); |
+ |
+ pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs); |
+ pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs); |
+ } |
+ } |
+ if( !db->mallocFailed ){ |
+ Expr *pLeft = pX->pLeft; |
+ |
+ if( pSelect->pOrderBy ){ |
+ /* If the SELECT statement has an ORDER BY clause, zero the |
+ ** iOrderByCol variables. These are set to non-zero when an |
+ ** ORDER BY term exactly matches one of the terms of the |
+ ** result-set. Since the result-set of the SELECT statement may |
+ ** have been modified or reordered, these variables are no longer |
+ ** set correctly. Since setting them is just an optimization, |
+ ** it's easiest just to zero them here. */ |
+ ExprList *pOrderBy = pSelect->pOrderBy; |
+ for(i=0; i<pOrderBy->nExpr; i++){ |
+ pOrderBy->a[i].u.x.iOrderByCol = 0; |
+ } |
+ } |
+ |
+ /* Take care here not to generate a TK_VECTOR containing only a |
+ ** single value. Since the parser never creates such a vector, some |
+ ** of the subroutines do not handle this case. */ |
+ if( pLhs->nExpr==1 ){ |
+ pX->pLeft = pLhs->a[0].pExpr; |
+ }else{ |
+ pLeft->x.pList = pLhs; |
+ aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq); |
+ testcase( aiMap==0 ); |
+ } |
+ pSelect->pEList = pRhs; |
+ db->dbOptFlags |= SQLITE_QueryFlattener; |
+ eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap); |
+ db->dbOptFlags = savedDbOptFlags; |
+ testcase( aiMap!=0 && aiMap[0]!=0 ); |
+ pSelect->pEList = pOrigRhs; |
+ pLeft->x.pList = pOrigLhs; |
+ pX->pLeft = pLeft; |
+ } |
+ sqlite3ExprListDelete(pParse->db, pLhs); |
+ sqlite3ExprListDelete(pParse->db, pRhs); |
+ } |
+ |
+ 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); |
+ } |
+ |
+ i = pLevel->u.in.nIn; |
+ pLevel->u.in.nIn += nEq; |
+ 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 ){ |
+ int iMap = 0; /* Index in aiMap[] */ |
+ pIn += i; |
+ for(i=iEq;i<pLoop->nLTerm; i++){ |
+ if( pLoop->aLTerm[i]->pExpr==pX ){ |
+ int iOut = iReg + i - iEq; |
+ if( eType==IN_INDEX_ROWID ){ |
+ testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */ |
+ pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut); |
+ }else{ |
+ int iCol = aiMap ? aiMap[iMap++] : 0; |
+ pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut); |
+ } |
+ sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v); |
+ if( i==iEq ){ |
+ pIn->iCur = iTab; |
+ pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen; |
+ }else{ |
+ pIn->eEndLoopOp = OP_Noop; |
+ } |
+ pIn++; |
+ } |
+ } |
+ }else{ |
+ pLevel->u.in.nIn = 0; |
+ } |
+ sqlite3DbFree(pParse->db, aiMap); |
+#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 BLOB or NONE affinity are set to |
+** SQLITE_AFF_BLOB. 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 BLOB/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_BLOB. |
+*/ |
+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->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(pParse->db,pIdx)); |
+ assert( zAff!=0 || pParse->db->mallocFailed ); |
+ |
+ 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); |
+ testcase( pIdx->aiColumn[j]==XN_EXPR ); |
+ VdbeComment((v, "%s", explainIndexColumnName(pIdx, j))); |
+ } |
+ } |
+ |
+ /* 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); |
+ } |
+ } |
+ if( pTerm->eOperator & WO_IN ){ |
+ if( pTerm->pExpr->flags & EP_xIsSelect ){ |
+ /* No affinity ever needs to be (or should be) applied to a value |
+ ** from the RHS of an "? IN (SELECT ...)" expression. The |
+ ** sqlite3FindInIndex() routine has already ensured that the |
+ ** affinity of the comparison has been applied to the value. */ |
+ if( zAff ) zAff[j] = SQLITE_AFF_BLOB; |
+ } |
+ }else if( (pTerm->eOperator & WO_ISNULL)==0 ){ |
+ Expr *pRight = pTerm->pExpr->pRight; |
+ if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){ |
+ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); |
+ VdbeCoverage(v); |
+ } |
+ if( zAff ){ |
+ if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ |
+ zAff[j] = SQLITE_AFF_BLOB; |
+ } |
+ if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ |
+ zAff[j] = SQLITE_AFF_BLOB; |
+ } |
+ } |
+ } |
+ } |
+ *pzAff = zAff; |
+ return regBase; |
+} |
+ |
+#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS |
+/* |
+** If the most recently coded instruction is a constant range constraint |
+** (a string literal) that originated from the LIKE optimization, then |
+** set P3 and P5 on the OP_String opcode so that the string will be cast |
+** to a BLOB at appropriate times. |
+** |
+** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range |
+** expression: "x>='ABC' AND x<'abd'". But this requires that the range |
+** scan loop run twice, once for strings and a second time for BLOBs. |
+** The OP_String opcodes on the second pass convert the upper and lower |
+** bound string constants to blobs. This routine makes the necessary changes |
+** to the OP_String opcodes for that to happen. |
+** |
+** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then |
+** only the one pass through the string space is required, so this routine |
+** becomes a no-op. |
+*/ |
+static void whereLikeOptimizationStringFixup( |
+ Vdbe *v, /* prepared statement under construction */ |
+ WhereLevel *pLevel, /* The loop that contains the LIKE operator */ |
+ WhereTerm *pTerm /* The upper or lower bound just coded */ |
+){ |
+ if( pTerm->wtFlags & TERM_LIKEOPT ){ |
+ VdbeOp *pOp; |
+ assert( pLevel->iLikeRepCntr>0 ); |
+ pOp = sqlite3VdbeGetOp(v, -1); |
+ assert( pOp!=0 ); |
+ assert( pOp->opcode==OP_String8 |
+ || pTerm->pWC->pWInfo->pParse->db->mallocFailed ); |
+ pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */ |
+ pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */ |
+ } |
+} |
+#else |
+# define whereLikeOptimizationStringFixup(A,B,C) |
+#endif |
+ |
+#ifdef SQLITE_ENABLE_CURSOR_HINTS |
+/* |
+** Information is passed from codeCursorHint() down to individual nodes of |
+** the expression tree (by sqlite3WalkExpr()) using an instance of this |
+** structure. |
+*/ |
+struct CCurHint { |
+ int iTabCur; /* Cursor for the main table */ |
+ int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */ |
+ Index *pIdx; /* The index used to access the table */ |
+}; |
+ |
+/* |
+** This function is called for every node of an expression that is a candidate |
+** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference |
+** the table CCurHint.iTabCur, verify that the same column can be |
+** accessed through the index. If it cannot, then set pWalker->eCode to 1. |
+*/ |
+static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){ |
+ struct CCurHint *pHint = pWalker->u.pCCurHint; |
+ assert( pHint->pIdx!=0 ); |
+ if( pExpr->op==TK_COLUMN |
+ && pExpr->iTable==pHint->iTabCur |
+ && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0 |
+ ){ |
+ pWalker->eCode = 1; |
+ } |
+ return WRC_Continue; |
+} |
+ |
+/* |
+** Test whether or not expression pExpr, which was part of a WHERE clause, |
+** should be included in the cursor-hint for a table that is on the rhs |
+** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the |
+** expression is not suitable. |
+** |
+** An expression is unsuitable if it might evaluate to non NULL even if |
+** a TK_COLUMN node that does affect the value of the expression is set |
+** to NULL. For example: |
+** |
+** col IS NULL |
+** col IS NOT NULL |
+** coalesce(col, 1) |
+** CASE WHEN col THEN 0 ELSE 1 END |
+*/ |
+static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){ |
+ if( pExpr->op==TK_IS |
+ || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT |
+ || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE |
+ ){ |
+ pWalker->eCode = 1; |
+ }else if( pExpr->op==TK_FUNCTION ){ |
+ int d1; |
+ char d2[3]; |
+ if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){ |
+ pWalker->eCode = 1; |
+ } |
+ } |
+ |
+ return WRC_Continue; |
+} |
+ |
+ |
+/* |
+** This function is called on every node of an expression tree used as an |
+** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN |
+** that accesses any table other than the one identified by |
+** CCurHint.iTabCur, then do the following: |
+** |
+** 1) allocate a register and code an OP_Column instruction to read |
+** the specified column into the new register, and |
+** |
+** 2) transform the expression node to a TK_REGISTER node that reads |
+** from the newly populated register. |
+** |
+** Also, if the node is a TK_COLUMN that does access the table idenified |
+** by pCCurHint.iTabCur, and an index is being used (which we will |
+** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into |
+** an access of the index rather than the original table. |
+*/ |
+static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){ |
+ int rc = WRC_Continue; |
+ struct CCurHint *pHint = pWalker->u.pCCurHint; |
+ if( pExpr->op==TK_COLUMN ){ |
+ if( pExpr->iTable!=pHint->iTabCur ){ |
+ Vdbe *v = pWalker->pParse->pVdbe; |
+ int reg = ++pWalker->pParse->nMem; /* Register for column value */ |
+ sqlite3ExprCodeGetColumnOfTable( |
+ v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg |
+ ); |
+ pExpr->op = TK_REGISTER; |
+ pExpr->iTable = reg; |
+ }else if( pHint->pIdx!=0 ){ |
+ pExpr->iTable = pHint->iIdxCur; |
+ pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn); |
+ assert( pExpr->iColumn>=0 ); |
+ } |
+ }else if( pExpr->op==TK_AGG_FUNCTION ){ |
+ /* An aggregate function in the WHERE clause of a query means this must |
+ ** be a correlated sub-query, and expression pExpr is an aggregate from |
+ ** the parent context. Do not walk the function arguments in this case. |
+ ** |
+ ** todo: It should be possible to replace this node with a TK_REGISTER |
+ ** expression, as the result of the expression must be stored in a |
+ ** register at this point. The same holds for TK_AGG_COLUMN nodes. */ |
+ rc = WRC_Prune; |
+ } |
+ return rc; |
+} |
+ |
+/* |
+** Insert an OP_CursorHint instruction if it is appropriate to do so. |
+*/ |
+static void codeCursorHint( |
+ struct SrcList_item *pTabItem, /* FROM clause item */ |
+ WhereInfo *pWInfo, /* The where clause */ |
+ WhereLevel *pLevel, /* Which loop to provide hints for */ |
+ WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */ |
+){ |
+ Parse *pParse = pWInfo->pParse; |
+ sqlite3 *db = pParse->db; |
+ Vdbe *v = pParse->pVdbe; |
+ Expr *pExpr = 0; |
+ WhereLoop *pLoop = pLevel->pWLoop; |
+ int iCur; |
+ WhereClause *pWC; |
+ WhereTerm *pTerm; |
+ int i, j; |
+ struct CCurHint sHint; |
+ Walker sWalker; |
+ |
+ if( OptimizationDisabled(db, SQLITE_CursorHints) ) return; |
+ iCur = pLevel->iTabCur; |
+ assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor ); |
+ sHint.iTabCur = iCur; |
+ sHint.iIdxCur = pLevel->iIdxCur; |
+ sHint.pIdx = pLoop->u.btree.pIndex; |
+ memset(&sWalker, 0, sizeof(sWalker)); |
+ sWalker.pParse = pParse; |
+ sWalker.u.pCCurHint = &sHint; |
+ pWC = &pWInfo->sWC; |
+ for(i=0; i<pWC->nTerm; i++){ |
+ pTerm = &pWC->a[i]; |
+ if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; |
+ if( pTerm->prereqAll & pLevel->notReady ) continue; |
+ |
+ /* Any terms specified as part of the ON(...) clause for any LEFT |
+ ** JOIN for which the current table is not the rhs are omitted |
+ ** from the cursor-hint. |
+ ** |
+ ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms |
+ ** that were specified as part of the WHERE clause must be excluded. |
+ ** This is to address the following: |
+ ** |
+ ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL; |
+ ** |
+ ** Say there is a single row in t2 that matches (t1.a=t2.b), but its |
+ ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is |
+ ** pushed down to the cursor, this row is filtered out, causing |
+ ** SQLite to synthesize a row of NULL values. Which does match the |
+ ** WHERE clause, and so the query returns a row. Which is incorrect. |
+ ** |
+ ** For the same reason, WHERE terms such as: |
+ ** |
+ ** WHERE 1 = (t2.c IS NULL) |
+ ** |
+ ** are also excluded. See codeCursorHintIsOrFunction() for details. |
+ */ |
+ if( pTabItem->fg.jointype & JT_LEFT ){ |
+ Expr *pExpr = pTerm->pExpr; |
+ if( !ExprHasProperty(pExpr, EP_FromJoin) |
+ || pExpr->iRightJoinTable!=pTabItem->iCursor |
+ ){ |
+ sWalker.eCode = 0; |
+ sWalker.xExprCallback = codeCursorHintIsOrFunction; |
+ sqlite3WalkExpr(&sWalker, pTerm->pExpr); |
+ if( sWalker.eCode ) continue; |
+ } |
+ }else{ |
+ if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue; |
+ } |
+ |
+ /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize |
+ ** the cursor. These terms are not needed as hints for a pure range |
+ ** scan (that has no == terms) so omit them. */ |
+ if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){ |
+ for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){} |
+ if( j<pLoop->nLTerm ) continue; |
+ } |
+ |
+ /* No subqueries or non-deterministic functions allowed */ |
+ if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue; |
+ |
+ /* For an index scan, make sure referenced columns are actually in |
+ ** the index. */ |
+ if( sHint.pIdx!=0 ){ |
+ sWalker.eCode = 0; |
+ sWalker.xExprCallback = codeCursorHintCheckExpr; |
+ sqlite3WalkExpr(&sWalker, pTerm->pExpr); |
+ if( sWalker.eCode ) continue; |
+ } |
+ |
+ /* If we survive all prior tests, that means this term is worth hinting */ |
+ pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0)); |
+ } |
+ if( pExpr!=0 ){ |
+ sWalker.xExprCallback = codeCursorHintFixExpr; |
+ sqlite3WalkExpr(&sWalker, pExpr); |
+ sqlite3VdbeAddOp4(v, OP_CursorHint, |
+ (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0, |
+ (const char*)pExpr, P4_EXPR); |
+ } |
+} |
+#else |
+# define codeCursorHint(A,B,C,D) /* No-op */ |
+#endif /* SQLITE_ENABLE_CURSOR_HINTS */ |
+ |
+/* |
+** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains |
+** a rowid value just read from cursor iIdxCur, open on index pIdx. This |
+** function generates code to do a deferred seek of cursor iCur to the |
+** rowid stored in register iRowid. |
+** |
+** Normally, this is just: |
+** |
+** OP_Seek $iCur $iRowid |
+** |
+** However, if the scan currently being coded is a branch of an OR-loop and |
+** the statement currently being coded is a SELECT, then P3 of the OP_Seek |
+** is set to iIdxCur and P4 is set to point to an array of integers |
+** containing one entry for each column of the table cursor iCur is open |
+** on. For each table column, if the column is the i'th column of the |
+** index, then the corresponding array entry is set to (i+1). If the column |
+** does not appear in the index at all, the array entry is set to 0. |
+*/ |
+static void codeDeferredSeek( |
+ WhereInfo *pWInfo, /* Where clause context */ |
+ Index *pIdx, /* Index scan is using */ |
+ int iCur, /* Cursor for IPK b-tree */ |
+ int iIdxCur /* Index cursor */ |
+){ |
+ Parse *pParse = pWInfo->pParse; /* Parse context */ |
+ Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */ |
+ |
+ assert( iIdxCur>0 ); |
+ assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 ); |
+ |
+ sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur); |
+ if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) |
+ && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask) |
+ ){ |
+ int i; |
+ Table *pTab = pIdx->pTable; |
+ int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1)); |
+ if( ai ){ |
+ ai[0] = pTab->nCol; |
+ for(i=0; i<pIdx->nColumn-1; i++){ |
+ assert( pIdx->aiColumn[i]<pTab->nCol ); |
+ if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1; |
+ } |
+ sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY); |
+ } |
+ } |
+} |
+ |
+/* |
+** If the expression passed as the second argument is a vector, generate |
+** code to write the first nReg elements of the vector into an array |
+** of registers starting with iReg. |
+** |
+** If the expression is not a vector, then nReg must be passed 1. In |
+** this case, generate code to evaluate the expression and leave the |
+** result in register iReg. |
+*/ |
+static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ |
+ assert( nReg>0 ); |
+ if( sqlite3ExprIsVector(p) ){ |
+#ifndef SQLITE_OMIT_SUBQUERY |
+ if( (p->flags & EP_xIsSelect) ){ |
+ Vdbe *v = pParse->pVdbe; |
+ int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0); |
+ sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1); |
+ }else |
+#endif |
+ { |
+ int i; |
+ ExprList *pList = p->x.pList; |
+ assert( nReg<=pList->nExpr ); |
+ for(i=0; i<nReg; i++){ |
+ sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i); |
+ } |
+ } |
+ }else{ |
+ assert( nReg==1 ); |
+ sqlite3ExprCode(pParse, p, iReg); |
+ } |
+} |
+ |
+/* |
+** Generate code for the start of the iLevel-th loop in the WHERE clause |
+** implementation described by pWInfo. |
+*/ |
+SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( |
+ 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 & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); |
+ bRev = (pWInfo->revMask>>iLevel)&1; |
+ omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 |
+ && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==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].fg.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->fg.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; |
+ int iIn; /* Counter for IN constraints */ |
+ |
+ 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( NEVER(pTerm==0) ) continue; |
+ if( pTerm->eOperator & WO_IN ){ |
+ codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); |
+ addrNotFound = pLevel->addrNxt; |
+ }else{ |
+ Expr *pRight = pTerm->pExpr->pRight; |
+ codeExprOrVector(pParse, pRight, iTarget, 1); |
+ } |
+ } |
+ 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_DYNAMIC : P4_STATIC); |
+ VdbeCoverage(v); |
+ pLoop->u.vtab.needFree = 0; |
+ pLevel->p1 = iCur; |
+ pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext; |
+ pLevel->p2 = sqlite3VdbeCurrentAddr(v); |
+ iIn = pLevel->u.in.nIn; |
+ for(j=nConstraint-1; j>=0; j--){ |
+ pTerm = pLoop->aLTerm[j]; |
+ if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){ |
+ disableTerm(pLevel, pTerm); |
+ }else if( (pTerm->eOperator & WO_IN)!=0 ){ |
+ Expr *pCompare; /* The comparison operator */ |
+ Expr *pRight; /* RHS of the comparison */ |
+ VdbeOp *pOp; /* Opcode to access the value of the IN constraint */ |
+ |
+ /* Reload the constraint value into reg[iReg+j+2]. The same value |
+ ** was loaded into the same register prior to the OP_VFilter, but |
+ ** the xFilter implementation might have changed the datatype or |
+ ** encoding of the value in the register, so it *must* be reloaded. */ |
+ assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed ); |
+ if( !db->mallocFailed ){ |
+ assert( iIn>0 ); |
+ pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop); |
+ assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid ); |
+ assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 ); |
+ assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 ); |
+ testcase( pOp->opcode==OP_Rowid ); |
+ sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3); |
+ } |
+ |
+ /* Generate code that will continue to the next row if |
+ ** the IN constraint is not satisfied */ |
+ pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0); |
+ assert( pCompare!=0 || db->mallocFailed ); |
+ if( pCompare ){ |
+ pCompare->pLeft = pTerm->pExpr->pLeft; |
+ pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0); |
+ if( pRight ){ |
+ pRight->iTable = iReg+j+2; |
+ sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0); |
+ } |
+ pCompare->pLeft = 0; |
+ sqlite3ExprDelete(db, pCompare); |
+ } |
+ } |
+ } |
+ /* These registers need to be preserved in case there is an IN operator |
+ ** loop. So we could deallocate the registers here (and potentially |
+ ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems |
+ ** simpler and safer to simply not reuse the registers. |
+ ** |
+ ** 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; |
+ sqlite3VdbeAddOp3(v, OP_SeekRowid, 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; |
+ } |
+ codeCursorHint(pTabItem, pWInfo, pLevel, pEnd); |
+ if( pStart ){ |
+ Expr *pX; /* The expression that defines the start bound */ |
+ int r1, rTemp; /* Registers for holding the start boundary */ |
+ int op; /* Cursor seek operation */ |
+ |
+ /* 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 */ |
+ if( sqlite3ExprIsVector(pX->pRight) ){ |
+ r1 = rTemp = sqlite3GetTempReg(pParse); |
+ codeExprOrVector(pParse, pX->pRight, r1, 1); |
+ op = aMoveOp[(pX->op - TK_GT) | 0x0001]; |
+ }else{ |
+ r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); |
+ disableTerm(pLevel, pStart); |
+ op = aMoveOp[(pX->op - TK_GT)]; |
+ } |
+ sqlite3VdbeAddOp3(v, op, 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); |
+ }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; |
+ codeExprOrVector(pParse, pX->pRight, memEndValue, 1); |
+ if( 0==sqlite3ExprIsVector(pX->pRight) |
+ && (pX->op==TK_LT || pX->op==TK_GT) |
+ ){ |
+ testOp = bRev ? OP_Le : OP_Ge; |
+ }else{ |
+ testOp = bRev ? OP_Lt : OP_Gt; |
+ } |
+ if( 0==sqlite3ExprIsVector(pX->pRight) ){ |
+ 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 */ |
+ u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */ |
+ u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */ |
+ 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 *zEndAff = 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->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->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 = MAX(nExtraReg, pLoop->u.btree.nBtm); |
+ /* Like optimization range constraints always occur in pairs */ |
+ assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || |
+ (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 ); |
+ } |
+ if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ |
+ pRangeEnd = pLoop->aLTerm[j++]; |
+ nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop); |
+#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS |
+ if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){ |
+ assert( pRangeStart!=0 ); /* LIKE opt constraints */ |
+ assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */ |
+ pLevel->iLikeRepCntr = (u32)++pParse->nMem; |
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr); |
+ VdbeComment((v, "LIKE loop counter")); |
+ pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v); |
+ /* iLikeRepCntr actually stores 2x the counter register number. The |
+ ** bottom bit indicates whether the search order is ASC or DESC. */ |
+ testcase( bRev ); |
+ testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC ); |
+ assert( (bRev & ~1)==0 ); |
+ pLevel->iLikeRepCntr <<=1; |
+ pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC); |
+ } |
+#endif |
+ if( pRangeStart==0 ){ |
+ j = pIdx->aiColumn[nEq]; |
+ if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){ |
+ bSeekPastNull = 1; |
+ } |
+ } |
+ } |
+ assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); |
+ |
+ /* 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); |
+ SWAP(u8, nBtm, nTop); |
+ } |
+ |
+ /* 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. |
+ */ |
+ codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd); |
+ regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); |
+ assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); |
+ if( zStartAff && nTop ){ |
+ zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]); |
+ } |
+ addrNxt = pLevel->addrNxt; |
+ |
+ 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; |
+ codeExprOrVector(pParse, pRight, regBase+nEq, nBtm); |
+ whereLikeOptimizationStringFixup(v, pLevel, pRangeStart); |
+ if( (pRangeStart->wtFlags & TERM_VNULL)==0 |
+ && sqlite3ExprCanBeNull(pRight) |
+ ){ |
+ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); |
+ VdbeCoverage(v); |
+ } |
+ if( zStartAff ){ |
+ updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]); |
+ } |
+ nConstraint += nBtm; |
+ testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); |
+ if( sqlite3ExprIsVector(pRight)==0 ){ |
+ disableTerm(pLevel, pRangeStart); |
+ }else{ |
+ startEq = 1; |
+ } |
+ bSeekPastNull = 0; |
+ }else if( bSeekPastNull ){ |
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); |
+ nConstraint++; |
+ startEq = 0; |
+ start_constraints = 1; |
+ } |
+ codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); |
+ if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){ |
+ /* The skip-scan logic inside the call to codeAllEqualityConstraints() |
+ ** above has already left the cursor sitting on the correct row, |
+ ** so no further seeking is needed */ |
+ }else{ |
+ 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); |
+ codeExprOrVector(pParse, pRight, regBase+nEq, nTop); |
+ whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd); |
+ if( (pRangeEnd->wtFlags & TERM_VNULL)==0 |
+ && sqlite3ExprCanBeNull(pRight) |
+ ){ |
+ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); |
+ VdbeCoverage(v); |
+ } |
+ if( zEndAff ){ |
+ updateRangeAffinityStr(pRight, nTop, zEndAff); |
+ codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff); |
+ }else{ |
+ assert( pParse->db->mallocFailed ); |
+ } |
+ nConstraint += nTop; |
+ testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); |
+ |
+ if( sqlite3ExprIsVector(pRight)==0 ){ |
+ disableTerm(pLevel, pRangeEnd); |
+ }else{ |
+ endEq = 1; |
+ } |
+ }else if( bStopAtNull ){ |
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); |
+ endEq = 0; |
+ nConstraint++; |
+ } |
+ sqlite3DbFree(db, zStartAff); |
+ sqlite3DbFree(db, zEndAff); |
+ |
+ /* 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 */ |
+ if( omitTable ){ |
+ /* pIdx is a covering index. No need to access the main table. */ |
+ }else if( HasRowid(pIdx->pTable) ){ |
+ if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || ( |
+ (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE) |
+ && (pWInfo->eOnePass==ONEPASS_SINGLE) |
+ )){ |
+ iRowidReg = ++pParse->nMem; |
+ sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); |
+ sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); |
+ sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg); |
+ VdbeCoverage(v); |
+ }else{ |
+ codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur); |
+ } |
+ }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. */ |
+ 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_VIRTUAL ); |
+ testcase( pWC->a[iTerm].wtFlags & TERM_CODED ); |
+ if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue; |
+ if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; |
+ testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); |
+ pExpr = sqlite3ExprDup(db, pExpr, 0); |
+ pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr); |
+ } |
+ if( pAndExpr ){ |
+ pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr); |
+ } |
+ } |
+ |
+ /* 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_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE); |
+ 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 jmp1 = 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; |
+ int addrExplain = sqlite3WhereExplainOneScan( |
+ pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0 |
+ ); |
+ sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); |
+ |
+ /* 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); |
+ jmp1 = 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]; |
+ sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk); |
+ } |
+ |
+ /* 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 ){ |
+ jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); |
+ VdbeCoverage(v); |
+ } |
+ if( iSet>=0 ){ |
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); |
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid, |
+ r, nPk); |
+ if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); |
+ } |
+ |
+ /* Release the array of temp registers */ |
+ sqlite3ReleaseTempRange(pParse, r, nPk); |
+ } |
+ } |
+ |
+ /* 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( jmp1 ) sqlite3VdbeJumpHere(v, jmp1); |
+ |
+ /* 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; |
+ }else{ |
+ pCov = 0; |
+ } |
+ |
+ /* 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)); |
+ sqlite3VdbeGoto(v, 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->fg.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{ |
+ codeCursorHint(pTabItem, pWInfo, pLevel, 0); |
+ 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; |
+ } |
+ } |
+ |
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS |
+ pLevel->addrVisit = sqlite3VdbeCurrentAddr(v); |
+#endif |
+ |
+ /* 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; |
+ int skipLikeAddr = 0; |
+ 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_OR_SUBCLAUSE)!=0 ); |
+ pWInfo->untestedTerms = 1; |
+ continue; |
+ } |
+ pE = pTerm->pExpr; |
+ assert( pE!=0 ); |
+ if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ |
+ continue; |
+ } |
+ if( pTerm->wtFlags & TERM_LIKECOND ){ |
+ /* If the TERM_LIKECOND flag is set, that means that the range search |
+ ** is sufficient to guarantee that the LIKE operator is true, so we |
+ ** can skip the call to the like(A,B) function. But this only works |
+ ** for strings. So do not skip the call to the function on the pass |
+ ** that compares BLOBs. */ |
+#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS |
+ continue; |
+#else |
+ u32 x = pLevel->iLikeRepCntr; |
+ assert( x>0 ); |
+ skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1)); |
+ VdbeCoverage(v); |
+#endif |
+ } |
+ sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); |
+ if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr); |
+ pTerm->wtFlags |= TERM_CODED; |
+ } |
+ |
+ /* 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, sEAlt; |
+ WhereTerm *pAlt; |
+ if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; |
+ if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue; |
+ if( (pTerm->eOperator & WO_EQUIV)==0 ) 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 = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady, |
+ WO_EQ|WO_IN|WO_IS, 0); |
+ if( pAlt==0 ) continue; |
+ if( pAlt->wtFlags & (TERM_CODED) ) continue; |
+ testcase( pAlt->eOperator & WO_EQ ); |
+ testcase( pAlt->eOperator & WO_IS ); |
+ testcase( pAlt->eOperator & WO_IN ); |
+ VdbeModuleComment((v, "begin transitive constraint")); |
+ sEAlt = *pAlt->pExpr; |
+ sEAlt.pLeft = pE->pLeft; |
+ sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL); |
+ } |
+ |
+ /* 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; |
+ } |
+ } |
+ |
+ return pLevel->notReady; |
+} |
+ |
+/************** End of wherecode.c *******************************************/ |
+/************** Begin file whereexpr.c ***************************************/ |
+/* |
+** 2015-06-08 |
+** |
+** 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 file was originally part of where.c but was split out to improve |
+** readability and editabiliity. This file contains utility routines for |
+** analyzing Expr objects in the WHERE clause. |
+*/ |
+/* #include "sqliteInt.h" */ |
+/* #include "whereInt.h" */ |
+ |
+/* Forward declarations */ |
+static void exprAnalyze(SrcList*, WhereClause*, int); |
+ |
+/* |
+** Deallocate all memory associated with a WhereOrInfo object. |
+*/ |
+static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){ |
+ sqlite3WhereClauseClear(&p->wc); |
+ sqlite3DbFree(db, p); |
+} |
+ |
+/* |
+** Deallocate all memory associated with a WhereAndInfo object. |
+*/ |
+static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){ |
+ sqlite3WhereClauseClear(&p->wc); |
+ sqlite3DbFree(db, p); |
+} |
+ |
+/* |
+** 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, u16 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 = sqlite3DbMallocRawNN(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) - 270; |
+ }else{ |
+ pTerm->truthProb = 1; |
+ } |
+ pTerm->pExpr = sqlite3ExprSkipCollate(p); |
+ pTerm->wtFlags = wtFlags; |
+ pTerm->pWC = pWC; |
+ pTerm->iParent = -1; |
+ memset(&pTerm->eOperator, 0, |
+ sizeof(WhereTerm) - offsetof(WhereTerm,eOperator)); |
+ return idx; |
+} |
+ |
+/* |
+** 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", "IS", 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 || op==TK_IS; |
+} |
+ |
+/* |
+** 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 if( op==TK_IS ){ |
+ c = WO_IS; |
+ }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 ); |
+ assert( op!=TK_IS || c==WO_IS ); |
+ return c; |
+} |
+ |
+ |
+#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. The LHS must be a column |
+** that may only be NULL, a string, or a BLOB, never a number. (This means |
+** that virtual tables cannot participate in the LIKE optimization.) The |
+** collating sequence for the column on the LHS must be appropriate for |
+** the operator. |
+*/ |
+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 */ |
+ int rc; /* Result code to return */ |
+ |
+ 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) /* Value might be numeric */ |
+ ){ |
+ /* 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_BLOB); |
+ 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); |
+ } |
+ } |
+ }else{ |
+ z = 0; |
+ } |
+ } |
+ |
+ rc = (z!=0); |
+ sqlite3ValueFree(pVal); |
+ return rc; |
+} |
+#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ |
+ |
+ |
+#ifndef SQLITE_OMIT_VIRTUALTABLE |
+/* |
+** Check to see if the given expression is of the form |
+** |
+** column OP expr |
+** |
+** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a |
+** column of a virtual table. |
+** |
+** If it is then return TRUE. If not, return FALSE. |
+*/ |
+static int isMatchOfColumn( |
+ Expr *pExpr, /* Test this expression */ |
+ unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */ |
+){ |
+ static const struct Op2 { |
+ const char *zOp; |
+ unsigned char eOp2; |
+ } aOp[] = { |
+ { "match", SQLITE_INDEX_CONSTRAINT_MATCH }, |
+ { "glob", SQLITE_INDEX_CONSTRAINT_GLOB }, |
+ { "like", SQLITE_INDEX_CONSTRAINT_LIKE }, |
+ { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP } |
+ }; |
+ ExprList *pList; |
+ Expr *pCol; /* Column reference */ |
+ int i; |
+ |
+ if( pExpr->op!=TK_FUNCTION ){ |
+ return 0; |
+ } |
+ pList = pExpr->x.pList; |
+ if( pList==0 || pList->nExpr!=2 ){ |
+ return 0; |
+ } |
+ pCol = pList->a[1].pExpr; |
+ if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){ |
+ return 0; |
+ } |
+ for(i=0; i<ArraySize(aOp); i++){ |
+ if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){ |
+ *peOp2 = aOp[i].eOp2; |
+ return 1; |
+ } |
+ } |
+ return 0; |
+} |
+#endif /* SQLITE_OMIT_VIRTUALTABLE */ |
+ |
+/* |
+** 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; |
+ } |
+} |
+ |
+/* |
+** Mark term iChild as being a child of term iParent |
+*/ |
+static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){ |
+ pWC->a[iChild].iParent = iParent; |
+ pWC->a[iChild].truthProb = pWC->a[iParent].truthProb; |
+ pWC->a[iParent].nChild++; |
+} |
+ |
+/* |
+** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not |
+** a conjunction, then return just pTerm when N==0. If N is exceeds |
+** the number of available subterms, return NULL. |
+*/ |
+static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){ |
+ if( pTerm->eOperator!=WO_AND ){ |
+ return N==0 ? pTerm : 0; |
+ } |
+ if( N<pTerm->u.pAndInfo->wc.nTerm ){ |
+ return &pTerm->u.pAndInfo->wc.a[N]; |
+ } |
+ return 0; |
+} |
+ |
+/* |
+** Subterms pOne and pTwo are contained within WHERE clause pWC. The |
+** two subterms are in disjunction - they are OR-ed together. |
+** |
+** If these two terms are both of the form: "A op B" with the same |
+** A and B values but different operators and if the operators are |
+** compatible (if one is = and the other is <, for example) then |
+** add a new virtual AND term to pWC that is the combination of the |
+** two. |
+** |
+** Some examples: |
+** |
+** x<y OR x=y --> x<=y |
+** x=y OR x=y --> x=y |
+** x<=y OR x<y --> x<=y |
+** |
+** The following is NOT generated: |
+** |
+** x<y OR x>y --> x!=y |
+*/ |
+static void whereCombineDisjuncts( |
+ SrcList *pSrc, /* the FROM clause */ |
+ WhereClause *pWC, /* The complete WHERE clause */ |
+ WhereTerm *pOne, /* First disjunct */ |
+ WhereTerm *pTwo /* Second disjunct */ |
+){ |
+ u16 eOp = pOne->eOperator | pTwo->eOperator; |
+ sqlite3 *db; /* Database connection (for malloc) */ |
+ Expr *pNew; /* New virtual expression */ |
+ int op; /* Operator for the combined expression */ |
+ int idxNew; /* Index in pWC of the next virtual term */ |
+ |
+ if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; |
+ if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; |
+ if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp |
+ && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return; |
+ assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 ); |
+ assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 ); |
+ if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return; |
+ if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return; |
+ /* If we reach this point, it means the two subterms can be combined */ |
+ if( (eOp & (eOp-1))!=0 ){ |
+ if( eOp & (WO_LT|WO_LE) ){ |
+ eOp = WO_LE; |
+ }else{ |
+ assert( eOp & (WO_GT|WO_GE) ); |
+ eOp = WO_GE; |
+ } |
+ } |
+ db = pWC->pWInfo->pParse->db; |
+ pNew = sqlite3ExprDup(db, pOne->pExpr, 0); |
+ if( pNew==0 ) return; |
+ for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); } |
+ pNew->op = op; |
+ idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); |
+ exprAnalyze(pSrc, pWC, idxNew); |
+} |
+ |
+#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) |
+** (F) x>A OR (x=A AND y>=B) |
+** |
+** 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 there are exactly two disjuncts and one side has x>A and the other side |
+** has x=A (for the same x and A) then add a new virtual conjunct term to the |
+** WHERE clause of the form "x>=A". Example: |
+** |
+** x>A OR (x=A AND y>B) adds: x>=A |
+** |
+** The added conjunct can sometimes be helpful in query planning. |
+** |
+** CASE 3: |
+** |
+** 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 3. 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 3 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 3 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: |
+** |
+** If none of cases 1, 2, or 3 apply, then leave the eOperator set to |
+** zero. This term is not useful for search. |
+*/ |
+static void exprAnalyzeOrTerm( |
+ SrcList *pSrc, /* the FROM clause */ |
+ WhereClause *pWC, /* the complete WHERE clause */ |
+ int idxTerm /* Index of the OR-term to be analyzed */ |
+){ |
+ 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 */ |
+ |
+ /* |
+ ** 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; |
+ memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic)); |
+ sqlite3WhereClauseInit(pOrWc, pWInfo); |
+ sqlite3WhereSplit(pOrWc, pExpr, TK_OR); |
+ sqlite3WhereExprAnalyze(pSrc, pOrWc); |
+ if( db->mallocFailed ) return; |
+ assert( pOrWc->nTerm>=2 ); |
+ |
+ /* |
+ ** Compute the set of tables that might satisfy cases 1 or 3. |
+ */ |
+ 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 = sqlite3DbMallocRawNN(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; |
+ memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic)); |
+ sqlite3WhereClauseInit(pAndWC, pWC->pWInfo); |
+ sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND); |
+ sqlite3WhereExprAnalyze(pSrc, pAndWC); |
+ pAndWC->pOuter = pWC; |
+ if( !db->mallocFailed ){ |
+ for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){ |
+ assert( pAndTerm->pExpr ); |
+ if( allowedOp(pAndTerm->pExpr->op) |
+ || pAndTerm->eOperator==WO_MATCH |
+ ){ |
+ b |= sqlite3WhereGetMask(&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 = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor); |
+ if( pOrTerm->wtFlags & TERM_VIRTUAL ){ |
+ WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent]; |
+ b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor); |
+ } |
+ indexable &= b; |
+ if( (pOrTerm->eOperator & WO_EQ)==0 ){ |
+ chngToIN = 0; |
+ }else{ |
+ chngToIN &= b; |
+ } |
+ } |
+ } |
+ |
+ /* |
+ ** Record the set of tables that satisfy case 3. The set might be |
+ ** empty. |
+ */ |
+ pOrInfo->indexable = indexable; |
+ pTerm->eOperator = indexable==0 ? 0 : WO_OR; |
+ |
+ /* For a two-way OR, attempt to implementation case 2. |
+ */ |
+ if( indexable && pOrWc->nTerm==2 ){ |
+ int iOne = 0; |
+ WhereTerm *pOne; |
+ while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){ |
+ int iTwo = 0; |
+ WhereTerm *pTwo; |
+ while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){ |
+ whereCombineDisjuncts(pSrc, pWC, pOne, pTwo); |
+ } |
+ } |
+ } |
+ |
+ /* |
+ ** 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. |
+ ** |
+ ** 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. |
+ ** |
+ ** Note that terms of the form "table.column1=table.column2" (the |
+ ** same table on both sizes of the ==) cannot be optimized. |
+ */ |
+ 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 & sqlite3WhereGetMask(&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==sqlite3WhereGetMask(&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; |
+ } |
+ } |
+ } |
+ } |
+ |
+ /* 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); |
+ 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]; |
+ markTermAsChild(pWC, idxNew, idxTerm); |
+ }else{ |
+ sqlite3ExprListDelete(db, pList); |
+ } |
+ pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */ |
+ } |
+ } |
+} |
+#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */ |
+ |
+/* |
+** We already know that pExpr is a binary operator where both operands are |
+** column references. This routine checks to see if pExpr is an equivalence |
+** relation: |
+** 1. The SQLITE_Transitive optimization must be enabled |
+** 2. Must be either an == or an IS operator |
+** 3. Not originating in the ON clause of an OUTER JOIN |
+** 4. The affinities of A and B must be compatible |
+** 5a. Both operands use the same collating sequence OR |
+** 5b. The overall collating sequence is BINARY |
+** If this routine returns TRUE, that means that the RHS can be substituted |
+** for the LHS anyplace else in the WHERE clause where the LHS column occurs. |
+** This is an optimization. No harm comes from returning 0. But if 1 is |
+** returned when it should not be, then incorrect answers might result. |
+*/ |
+static int termIsEquivalence(Parse *pParse, Expr *pExpr){ |
+ char aff1, aff2; |
+ CollSeq *pColl; |
+ const char *zColl1, *zColl2; |
+ if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; |
+ if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; |
+ if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0; |
+ aff1 = sqlite3ExprAffinity(pExpr->pLeft); |
+ aff2 = sqlite3ExprAffinity(pExpr->pRight); |
+ if( aff1!=aff2 |
+ && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2)) |
+ ){ |
+ return 0; |
+ } |
+ pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight); |
+ if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1; |
+ pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); |
+ zColl1 = pColl ? pColl->zName : 0; |
+ pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight); |
+ zColl2 = pColl ? pColl->zName : 0; |
+ return sqlite3_stricmp(zColl1, zColl2)==0; |
+} |
+ |
+/* |
+** Recursively walk the expressions of a SELECT statement and generate |
+** a bitmask indicating which tables are used in that expression |
+** tree. |
+*/ |
+static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){ |
+ Bitmask mask = 0; |
+ while( pS ){ |
+ SrcList *pSrc = pS->pSrc; |
+ mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList); |
+ mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy); |
+ mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy); |
+ mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere); |
+ mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving); |
+ if( ALWAYS(pSrc!=0) ){ |
+ int i; |
+ for(i=0; i<pSrc->nSrc; i++){ |
+ mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect); |
+ mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn); |
+ } |
+ } |
+ pS = pS->pPrior; |
+ } |
+ return mask; |
+} |
+ |
+/* |
+** Expression pExpr is one operand of a comparison operator that might |
+** be useful for indexing. This routine checks to see if pExpr appears |
+** in any index. Return TRUE (1) if pExpr is an indexed term and return |
+** FALSE (0) if not. If TRUE is returned, also set *piCur to the cursor |
+** number of the table that is indexed and *piColumn to the column number |
+** of the column that is indexed, or XN_EXPR (-2) if an expression is being |
+** indexed. |
+** |
+** If pExpr is a TK_COLUMN column reference, then this routine always returns |
+** true even if that particular column is not indexed, because the column |
+** might be added to an automatic index later. |
+*/ |
+static int exprMightBeIndexed( |
+ SrcList *pFrom, /* The FROM clause */ |
+ int op, /* The specific comparison operator */ |
+ Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */ |
+ Expr *pExpr, /* An operand of a comparison operator */ |
+ int *piCur, /* Write the referenced table cursor number here */ |
+ int *piColumn /* Write the referenced table column number here */ |
+){ |
+ Index *pIdx; |
+ int i; |
+ int iCur; |
+ |
+ /* If this expression is a vector to the left or right of a |
+ ** inequality constraint (>, <, >= or <=), perform the processing |
+ ** on the first element of the vector. */ |
+ assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE ); |
+ assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE ); |
+ assert( op<=TK_GE ); |
+ if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){ |
+ pExpr = pExpr->x.pList->a[0].pExpr; |
+ } |
+ |
+ if( pExpr->op==TK_COLUMN ){ |
+ *piCur = pExpr->iTable; |
+ *piColumn = pExpr->iColumn; |
+ return 1; |
+ } |
+ if( mPrereq==0 ) return 0; /* No table references */ |
+ if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */ |
+ for(i=0; mPrereq>1; i++, mPrereq>>=1){} |
+ iCur = pFrom->a[i].iCursor; |
+ for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){ |
+ if( pIdx->aColExpr==0 ) continue; |
+ for(i=0; i<pIdx->nKeyCol; i++){ |
+ if( pIdx->aiColumn[i]!=XN_EXPR ) continue; |
+ if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){ |
+ *piCur = iCur; |
+ *piColumn = XN_EXPR; |
+ return 1; |
+ } |
+ } |
+ } |
+ return 0; |
+} |
+ |
+/* |
+** 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. |
+*/ |
+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; /* uppercase equivalent to lowercase */ |
+ int op; /* Top-level operator. pExpr->op */ |
+ Parse *pParse = pWInfo->pParse; /* Parsing context */ |
+ sqlite3 *db = pParse->db; /* Database connection */ |
+ unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */ |
+ int nLeft; /* Number of elements on left side vector */ |
+ |
+ if( db->mallocFailed ){ |
+ return; |
+ } |
+ pTerm = &pWC->a[idxTerm]; |
+ pMaskSet = &pWInfo->sMaskSet; |
+ pExpr = pTerm->pExpr; |
+ assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE ); |
+ prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft); |
+ op = pExpr->op; |
+ if( op==TK_IN ){ |
+ assert( pExpr->pRight==0 ); |
+ if( sqlite3ExprCheckIN(pParse, pExpr) ) return; |
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){ |
+ pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect); |
+ }else{ |
+ pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList); |
+ } |
+ }else if( op==TK_ISNULL ){ |
+ pTerm->prereqRight = 0; |
+ }else{ |
+ pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight); |
+ } |
+ prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr); |
+ if( ExprHasProperty(pExpr, EP_FromJoin) ){ |
+ Bitmask x = sqlite3WhereGetMask(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 */ |
+ if( (prereqAll>>1)>=x ){ |
+ sqlite3ErrorMsg(pParse, "ON clause references tables to its right"); |
+ return; |
+ } |
+ } |
+ pTerm->prereqAll = prereqAll; |
+ pTerm->leftCursor = -1; |
+ pTerm->iParent = -1; |
+ pTerm->eOperator = 0; |
+ if( allowedOp(op) ){ |
+ int iCur, iColumn; |
+ Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft); |
+ Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight); |
+ u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV; |
+ |
+ if( pTerm->iField>0 ){ |
+ assert( op==TK_IN ); |
+ assert( pLeft->op==TK_VECTOR ); |
+ pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr; |
+ } |
+ |
+ if( exprMightBeIndexed(pSrc, op, prereqLeft, pLeft, &iCur, &iColumn) ){ |
+ pTerm->leftCursor = iCur; |
+ pTerm->u.leftColumn = iColumn; |
+ pTerm->eOperator = operatorMask(op) & opMask; |
+ } |
+ if( op==TK_IS ) pTerm->wtFlags |= TERM_IS; |
+ if( pRight |
+ && exprMightBeIndexed(pSrc, op, pTerm->prereqRight, pRight, &iCur,&iColumn) |
+ ){ |
+ WhereTerm *pNew; |
+ Expr *pDup; |
+ u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */ |
+ assert( pTerm->iField==0 ); |
+ 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]; |
+ markTermAsChild(pWC, idxNew, idxTerm); |
+ if( op==TK_IS ) pNew->wtFlags |= TERM_IS; |
+ pTerm = &pWC->a[idxTerm]; |
+ pTerm->wtFlags |= TERM_COPIED; |
+ |
+ if( termIsEquivalence(pParse, pDup) ){ |
+ pTerm->eOperator |= WO_EQUIV; |
+ eExtraOp = WO_EQUIV; |
+ } |
+ }else{ |
+ pDup = pExpr; |
+ pNew = pTerm; |
+ } |
+ exprCommute(pParse, pDup); |
+ pNew->leftCursor = iCur; |
+ pNew->u.leftColumn = 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)); |
+ transferJoinMarkings(pNewExpr, pExpr); |
+ idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); |
+ testcase( idxNew==0 ); |
+ exprAnalyze(pSrc, pWC, idxNew); |
+ pTerm = &pWC->a[idxTerm]; |
+ markTermAsChild(pWC, idxNew, idxTerm); |
+ } |
+ } |
+#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 case is not significant (the default |
+ ** for LIKE) then the lower-bound is made all uppercase and the upper- |
+ ** bound is made all lowercase so that the bounds also work when comparing |
+ ** BLOBs. |
+ */ |
+ 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 */ |
+ const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC; |
+ |
+ pLeft = pExpr->x.pList->a[1].pExpr; |
+ pStr2 = sqlite3ExprDup(db, pStr1, 0); |
+ |
+ /* Convert the lower bound to upper-case and the upper bound to |
+ ** lower-case (upper-case is less than lower-case in ASCII) so that |
+ ** the range constraints also work for BLOBs |
+ */ |
+ if( noCase && !pParse->db->mallocFailed ){ |
+ int i; |
+ char c; |
+ pTerm->wtFlags |= TERM_LIKE; |
+ for(i=0; (c = pStr1->u.zToken[i])!=0; i++){ |
+ pStr1->u.zToken[i] = sqlite3Toupper(c); |
+ pStr2->u.zToken[i] = sqlite3Tolower(c); |
+ } |
+ } |
+ |
+ 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); |
+ transferJoinMarkings(pNewExpr1, pExpr); |
+ idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags); |
+ testcase( idxNew1==0 ); |
+ exprAnalyze(pSrc, pWC, idxNew1); |
+ pNewExpr2 = sqlite3ExprDup(db, pLeft, 0); |
+ pNewExpr2 = sqlite3PExpr(pParse, TK_LT, |
+ sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName), |
+ pStr2); |
+ transferJoinMarkings(pNewExpr2, pExpr); |
+ idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags); |
+ testcase( idxNew2==0 ); |
+ exprAnalyze(pSrc, pWC, idxNew2); |
+ pTerm = &pWC->a[idxTerm]; |
+ if( isComplete ){ |
+ markTermAsChild(pWC, idxNew1, idxTerm); |
+ markTermAsChild(pWC, idxNew2, idxTerm); |
+ } |
+ } |
+#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( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){ |
+ 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 = sqlite3WhereExprUsage(pMaskSet, pRight); |
+ prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft); |
+ if( (prereqExpr & prereqColumn)==0 ){ |
+ Expr *pNewExpr; |
+ pNewExpr = sqlite3PExpr(pParse, TK_MATCH, |
+ 0, sqlite3ExprDup(db, pRight, 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->eMatchOp = eOp2; |
+ markTermAsChild(pWC, idxNew, idxTerm); |
+ pTerm = &pWC->a[idxTerm]; |
+ pTerm->wtFlags |= TERM_COPIED; |
+ pNewTerm->prereqAll = pTerm->prereqAll; |
+ } |
+ } |
+#endif /* SQLITE_OMIT_VIRTUALTABLE */ |
+ |
+ /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create |
+ ** new terms for each component comparison - "a = ?" and "b = ?". The |
+ ** new terms completely replace the original vector comparison, which is |
+ ** no longer used. |
+ ** |
+ ** This is only required if at least one side of the comparison operation |
+ ** is not a sub-select. */ |
+ if( pWC->op==TK_AND |
+ && (pExpr->op==TK_EQ || pExpr->op==TK_IS) |
+ && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1 |
+ && sqlite3ExprVectorSize(pExpr->pRight)==nLeft |
+ && ( (pExpr->pLeft->flags & EP_xIsSelect)==0 |
+ || (pExpr->pRight->flags & EP_xIsSelect)==0) |
+ ){ |
+ int i; |
+ for(i=0; i<nLeft; i++){ |
+ int idxNew; |
+ Expr *pNew; |
+ Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i); |
+ Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i); |
+ |
+ pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight); |
+ transferJoinMarkings(pNew, pExpr); |
+ idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC); |
+ exprAnalyze(pSrc, pWC, idxNew); |
+ } |
+ pTerm = &pWC->a[idxTerm]; |
+ pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL; /* Disable the original */ |
+ pTerm->eOperator = 0; |
+ } |
+ |
+ /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create |
+ ** a virtual term for each vector component. The expression object |
+ ** used by each such virtual term is pExpr (the full vector IN(...) |
+ ** expression). The WhereTerm.iField variable identifies the index within |
+ ** the vector on the LHS that the virtual term represents. |
+ ** |
+ ** This only works if the RHS is a simple SELECT, not a compound |
+ */ |
+ if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0 |
+ && pExpr->pLeft->op==TK_VECTOR |
+ && pExpr->x.pSelect->pPrior==0 |
+ ){ |
+ int i; |
+ for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){ |
+ int idxNew; |
+ idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL); |
+ pWC->a[idxNew].iField = i+1; |
+ exprAnalyze(pSrc, pWC, idxNew); |
+ markTermAsChild(pWC, idxNew, idxTerm); |
+ } |
+ } |
+ |
+#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. |
+ */ |
+ if( pExpr->op==TK_NOTNULL |
+ && pExpr->pLeft->op==TK_COLUMN |
+ && pExpr->pLeft->iColumn>=0 |
+ && OptimizationEnabled(db, SQLITE_Stat34) |
+ ){ |
+ Expr *pNewExpr; |
+ Expr *pLeft = pExpr->pLeft; |
+ int idxNew; |
+ WhereTerm *pNewTerm; |
+ |
+ pNewExpr = sqlite3PExpr(pParse, TK_GT, |
+ sqlite3ExprDup(db, pLeft, 0), |
+ sqlite3ExprAlloc(db, TK_NULL, 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; |
+ markTermAsChild(pWC, idxNew, idxTerm); |
+ pTerm = &pWC->a[idxTerm]; |
+ 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. |
+ */ |
+ testcase( pTerm!=&pWC->a[idxTerm] ); |
+ pTerm = &pWC->a[idxTerm]; |
+ pTerm->prereqRight |= extraRight; |
+} |
+ |
+/*************************************************************************** |
+** Routines with file scope above. Interface to the rest of the where.c |
+** subsystem follows. |
+***************************************************************************/ |
+ |
+/* |
+** 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. |
+*/ |
+SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){ |
+ Expr *pE2 = sqlite3ExprSkipCollate(pExpr); |
+ pWC->op = op; |
+ if( pE2==0 ) return; |
+ if( pE2->op!=op ){ |
+ whereClauseInsert(pWC, pExpr, 0); |
+ }else{ |
+ sqlite3WhereSplit(pWC, pE2->pLeft, op); |
+ sqlite3WhereSplit(pWC, pE2->pRight, op); |
+ } |
+} |
+ |
+/* |
+** Initialize a preallocated WhereClause structure. |
+*/ |
+SQLITE_PRIVATE void sqlite3WhereClauseInit( |
+ 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; |
+} |
+ |
+/* |
+** Deallocate a WhereClause structure. The WhereClause structure |
+** itself is not freed. This routine is the inverse of |
+** sqlite3WhereClauseInit(). |
+*/ |
+SQLITE_PRIVATE void sqlite3WhereClauseClear(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); |
+ } |
+} |
+ |
+ |
+/* |
+** These routines walk (recursively) an expression tree and generate |
+** a bitmask indicating which tables are used in that expression |
+** tree. |
+*/ |
+SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){ |
+ Bitmask mask; |
+ if( p==0 ) return 0; |
+ if( p->op==TK_COLUMN ){ |
+ mask = sqlite3WhereGetMask(pMaskSet, p->iTable); |
+ return mask; |
+ } |
+ assert( !ExprHasProperty(p, EP_TokenOnly) ); |
+ mask = p->pRight ? sqlite3WhereExprUsage(pMaskSet, p->pRight) : 0; |
+ if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft); |
+ if( ExprHasProperty(p, EP_xIsSelect) ){ |
+ mask |= exprSelectUsage(pMaskSet, p->x.pSelect); |
+ }else if( p->x.pList ){ |
+ mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList); |
+ } |
+ return mask; |
+} |
+SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){ |
+ int i; |
+ Bitmask mask = 0; |
+ if( pList ){ |
+ for(i=0; i<pList->nExpr; i++){ |
+ mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr); |
+ } |
+ } |
+ return mask; |
+} |
+ |
+ |
+/* |
+** Call exprAnalyze on all terms in a WHERE clause. |
+** |
+** Note that exprAnalyze() might add new virtual terms onto the |
+** end of the WHERE clause. We do not want to analyze these new |
+** virtual terms, so start analyzing at the end and work forward |
+** so that the added virtual terms are never processed. |
+*/ |
+SQLITE_PRIVATE void sqlite3WhereExprAnalyze( |
+ SrcList *pTabList, /* the FROM clause */ |
+ WhereClause *pWC /* the WHERE clause to be analyzed */ |
+){ |
+ int i; |
+ for(i=pWC->nTerm-1; i>=0; i--){ |
+ exprAnalyze(pTabList, pWC, i); |
+ } |
+} |
+ |
+/* |
+** For table-valued-functions, transform the function arguments into |
+** new WHERE clause terms. |
+** |
+** Each function argument translates into an equality constraint against |
+** a HIDDEN column in the table. |
+*/ |
+SQLITE_PRIVATE void sqlite3WhereTabFuncArgs( |
+ Parse *pParse, /* Parsing context */ |
+ struct SrcList_item *pItem, /* The FROM clause term to process */ |
+ WhereClause *pWC /* Xfer function arguments to here */ |
+){ |
+ Table *pTab; |
+ int j, k; |
+ ExprList *pArgs; |
+ Expr *pColRef; |
+ Expr *pTerm; |
+ if( pItem->fg.isTabFunc==0 ) return; |
+ pTab = pItem->pTab; |
+ assert( pTab!=0 ); |
+ pArgs = pItem->u1.pFuncArg; |
+ if( pArgs==0 ) return; |
+ for(j=k=0; j<pArgs->nExpr; j++){ |
+ while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;} |
+ if( k>=pTab->nCol ){ |
+ sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d", |
+ pTab->zName, j); |
+ return; |
+ } |
+ pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0); |
+ if( pColRef==0 ) return; |
+ pColRef->iTable = pItem->iCursor; |
+ pColRef->iColumn = k++; |
+ pColRef->pTab = pTab; |
+ pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, |
+ sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0)); |
+ whereClauseInsert(pWC, pTerm, TERM_DYNAMIC); |
+ } |
+} |
+ |
+/************** End of whereexpr.c *******************************************/ |
+/************** Begin file where.c *******************************************/ |
+/* |
+** 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". |
+*/ |
+/* #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 |
+*/ |
+SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){ |
+ return pWInfo->nRowOut; |
+} |
+ |
+/* |
+** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this |
+** WHERE clause returns outputs for DISTINCT processing. |
+*/ |
+SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){ |
+ return pWInfo->eDistinct; |
+} |
+ |
+/* |
+** Return TRUE if the WHERE clause returns rows in ORDER BY order. |
+** Return FALSE if the output needs to be sorted. |
+*/ |
+SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){ |
+ return pWInfo->nOBSat; |
+} |
+ |
+/* |
+** Return TRUE if the innermost loop of the WHERE clause implementation |
+** returns rows in ORDER BY order for complete run of the inner loop. |
+** |
+** Across multiple iterations of outer loops, the output rows need not be |
+** sorted. As long as rows are sorted for just the innermost loop, this |
+** routine can return TRUE. |
+*/ |
+SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){ |
+ return pWInfo->bOrderedInnerLoop; |
+} |
+ |
+/* |
+** Return the VDBE address or label to jump to in order to continue |
+** immediately with the next row of a WHERE clause. |
+*/ |
+SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){ |
+ assert( pWInfo->iContinue!=0 ); |
+ return pWInfo->iContinue; |
+} |
+ |
+/* |
+** Return the VDBE address or label to jump to in order to break |
+** out of a WHERE loop. |
+*/ |
+SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ |
+ return pWInfo->iBreak; |
+} |
+ |
+/* |
+** 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 |
+** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data |
+** table and iaCur[1] gets the cursor used by an auxiliary index. |
+** Either value may be -1, indicating that cursor is not used. |
+** Any cursors returned will have been opened for writing. |
+** |
+** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is |
+** unable to use the ONEPASS optimization. |
+*/ |
+SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ |
+ memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2); |
+#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; |
+} |
+ |
+/* |
+** Move the content of pSrc into pDest |
+*/ |
+static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){ |
+ pDest->n = pSrc->n; |
+ memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0])); |
+} |
+ |
+/* |
+** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet. |
+** |
+** The new entry might overwrite an existing entry, or it might be |
+** appended, or it might be discarded. Do whatever is the right thing |
+** so that pSet keeps the N_OR_COST best entries seen so far. |
+*/ |
+static int whereOrInsert( |
+ WhereOrSet *pSet, /* The WhereOrSet to be updated */ |
+ Bitmask prereq, /* Prerequisites of the new entry */ |
+ LogEst rRun, /* Run-cost of the new entry */ |
+ LogEst nOut /* Number of outputs for the new entry */ |
+){ |
+ u16 i; |
+ WhereOrCost *p; |
+ for(i=pSet->n, p=pSet->a; i>0; i--, p++){ |
+ if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){ |
+ goto whereOrInsert_done; |
+ } |
+ if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){ |
+ return 0; |
+ } |
+ } |
+ if( pSet->n<N_OR_COST ){ |
+ p = &pSet->a[pSet->n++]; |
+ p->nOut = nOut; |
+ }else{ |
+ p = pSet->a; |
+ for(i=1; i<pSet->n; i++){ |
+ if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i; |
+ } |
+ if( p->rRun<=rRun ) return 0; |
+ } |
+whereOrInsert_done: |
+ p->prereq = prereq; |
+ p->rRun = rRun; |
+ if( p->nOut>nOut ) p->nOut = nOut; |
+ return 1; |
+} |
+ |
+/* |
+** Return the bitmask for the given cursor number. Return 0 if |
+** iCursor is not in the set. |
+*/ |
+SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){ |
+ int i; |
+ assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 ); |
+ for(i=0; i<pMaskSet->n; i++){ |
+ if( pMaskSet->ix[i]==iCursor ){ |
+ return MASKBIT(i); |
+ } |
+ } |
+ return 0; |
+} |
+ |
+/* |
+** Create a new mask for cursor iCursor. |
+** |
+** There is one cursor per table in the FROM clause. The number of |
+** tables in the FROM clause is limited by a test early in the |
+** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] |
+** array will never overflow. |
+*/ |
+static void createMask(WhereMaskSet *pMaskSet, int iCursor){ |
+ assert( pMaskSet->n < ArraySize(pMaskSet->ix) ); |
+ pMaskSet->ix[pMaskSet->n++] = iCursor; |
+} |
+ |
+/* |
+** 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 */ |
+ 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 */ |
+ |
+ assert( pScan->iEquiv<=pScan->nEquiv ); |
+ pWC = pScan->pWC; |
+ while(1){ |
+ iColumn = pScan->aiColumn[pScan->iEquiv-1]; |
+ iCur = pScan->aiCur[pScan->iEquiv-1]; |
+ assert( pWC!=0 ); |
+ do{ |
+ for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){ |
+ if( pTerm->leftCursor==iCur |
+ && pTerm->u.leftColumn==iColumn |
+ && (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->aiCur) |
+ && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN |
+ ){ |
+ int j; |
+ for(j=0; j<pScan->nEquiv; j++){ |
+ if( pScan->aiCur[j]==pX->iTable |
+ && pScan->aiColumn[j]==pX->iColumn ){ |
+ break; |
+ } |
+ } |
+ if( j==pScan->nEquiv ){ |
+ pScan->aiCur[j] = pX->iTable; |
+ pScan->aiColumn[j] = pX->iColumn; |
+ pScan->nEquiv++; |
+ } |
+ } |
+ if( (pTerm->eOperator & pScan->opMask)!=0 ){ |
+ /* Verify the affinity and collating sequence match */ |
+ if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){ |
+ CollSeq *pColl; |
+ Parse *pParse = pWC->pWInfo->pParse; |
+ pX = pTerm->pExpr; |
+ if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){ |
+ continue; |
+ } |
+ assert(pX->pLeft); |
+ pColl = sqlite3BinaryCompareCollSeq(pParse, |
+ pX->pLeft, pX->pRight); |
+ if( pColl==0 ) pColl = pParse->db->pDfltColl; |
+ if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){ |
+ continue; |
+ } |
+ } |
+ if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0 |
+ && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN |
+ && pX->iTable==pScan->aiCur[0] |
+ && pX->iColumn==pScan->aiColumn[0] |
+ ){ |
+ testcase( pTerm->eOperator & WO_IS ); |
+ continue; |
+ } |
+ pScan->pWC = pWC; |
+ pScan->k = k+1; |
+ return pTerm; |
+ } |
+ } |
+ } |
+ pWC = pWC->pOuter; |
+ k = 0; |
+ }while( pWC!=0 ); |
+ if( pScan->iEquiv>=pScan->nEquiv ) break; |
+ pWC = pScan->pOrigWC; |
+ k = 0; |
+ pScan->iEquiv++; |
+ } |
+ return 0; |
+} |
+ |
+/* |
+** Initialize a WHERE clause scanner object. Return a pointer to the |
+** first match. Return NULL if there are no matches. |
+** |
+** The scanner will be searching the WHERE clause pWC. It will look |
+** for terms of the form "X <op> <expr>" where X is column iColumn of table |
+** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx |
+** must be one of the indexes of table iCur. |
+** |
+** The <op> must be one of the operators described by opMask. |
+** |
+** If the search is for X and the WHERE clause contains terms of the |
+** form X=Y then this routine might also return terms of the form |
+** "Y <op> <expr>". The number of levels of transitivity is limited, |
+** but is enough to handle most commonly occurring SQL statements. |
+** |
+** If X is not the INTEGER PRIMARY KEY then X must be compatible with |
+** index pIdx. |
+*/ |
+static WhereTerm *whereScanInit( |
+ WhereScan *pScan, /* The WhereScan object being initialized */ |
+ WhereClause *pWC, /* The WHERE clause to be scanned */ |
+ int iCur, /* Cursor to scan for */ |
+ int iColumn, /* Column to scan for */ |
+ u32 opMask, /* Operator(s) to scan for */ |
+ Index *pIdx /* Must be compatible with this index */ |
+){ |
+ pScan->pOrigWC = pWC; |
+ pScan->pWC = pWC; |
+ pScan->pIdxExpr = 0; |
+ pScan->idxaff = 0; |
+ pScan->zCollName = 0; |
+ if( pIdx ){ |
+ int j = iColumn; |
+ iColumn = pIdx->aiColumn[j]; |
+ if( iColumn==XN_EXPR ){ |
+ pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr; |
+ pScan->zCollName = pIdx->azColl[j]; |
+ }else if( iColumn==pIdx->pTable->iPKey ){ |
+ iColumn = XN_ROWID; |
+ }else if( iColumn>=0 ){ |
+ pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; |
+ pScan->zCollName = pIdx->azColl[j]; |
+ } |
+ }else if( iColumn==XN_EXPR ){ |
+ return 0; |
+ } |
+ pScan->opMask = opMask; |
+ pScan->k = 0; |
+ pScan->aiCur[0] = iCur; |
+ pScan->aiColumn[0] = iColumn; |
+ pScan->nEquiv = 1; |
+ pScan->iEquiv = 1; |
+ return whereScanNext(pScan); |
+} |
+ |
+/* |
+** Search for a term in the WHERE clause that is of the form "X <op> <expr>" |
+** where X is a reference to the iColumn of table iCur or of index pIdx |
+** if pIdx!=0 and <op> is one of 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 it must be one of the indexes of table iCur. |
+** 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 |
+** 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 |
+** <expr> is a constant expression of some kind. Only return entries of |
+** the form "X <op> Y" where Y is a column in another table if no terms of |
+** 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. |
+*/ |
+SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm( |
+ WhereClause *pWC, /* The WHERE clause to be searched */ |
+ int iCur, /* Cursor number of LHS */ |
+ int iColumn, /* Column number of LHS */ |
+ Bitmask notReady, /* RHS must not overlap with this mask */ |
+ u32 op, /* Mask of WO_xx values describing operator */ |
+ Index *pIdx /* Must be compatible with this index, if not NULL */ |
+){ |
+ WhereTerm *pResult = 0; |
+ WhereTerm *p; |
+ 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&op)!=0 ){ |
+ testcase( p->eOperator & WO_IS ); |
+ return p; |
+ } |
+ if( pResult==0 ) pResult = p; |
+ } |
+ p = whereScanNext(&scan); |
+ } |
+ return pResult; |
+} |
+ |
+/* |
+** 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 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( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){ |
+ return i; |
+ } |
+ } |
+ } |
+ |
+ return -1; |
+} |
+ |
+/* |
+** Return TRUE if the iCol-th column of index pIdx is NOT NULL |
+*/ |
+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 */ |
+ |
+ } |
+} |
+ |
+/* |
+** Return true if the DISTINCT expression-list passed as the third argument |
+** is redundant. |
+** |
+** A DISTINCT list is redundant if any subset of the columns in the |
+** DISTINCT list are collectively unique and individually non-null. |
+*/ |
+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 */ |
+){ |
+ 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++){ |
+ 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; |
+ } |
+ } |
+ 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; |
+} |
+ |
+/* |
+** Convert OP_Column opcodes to OP_Copy in previously generated code. |
+** |
+** 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. |
+** |
+** 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 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) */ |
+){ |
+ 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; |
+ } |
+ } |
+ } |
+} |
+ |
+/* |
+** Two routines for printing the content of an sqlite3_index_info |
+** structure. Used for testing and debugging only. If neither |
+** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines |
+** are no-ops. |
+*/ |
+#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED) |
+static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ |
+ int i; |
+ if( !sqlite3WhereTrace ) return; |
+ for(i=0; i<p->nConstraint; i++){ |
+ sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n", |
+ i, |
+ p->aConstraint[i].iColumn, |
+ p->aConstraint[i].iTermOffset, |
+ p->aConstraint[i].op, |
+ p->aConstraint[i].usable); |
+ } |
+ for(i=0; i<p->nOrderBy; i++){ |
+ sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n", |
+ i, |
+ p->aOrderBy[i].iColumn, |
+ p->aOrderBy[i].desc); |
+ } |
+} |
+static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){ |
+ int i; |
+ if( !sqlite3WhereTrace ) return; |
+ for(i=0; i<p->nConstraint; i++){ |
+ sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", |
+ i, |
+ p->aConstraintUsage[i].argvIndex, |
+ p->aConstraintUsage[i].omit); |
+ } |
+ sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum); |
+ sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); |
+ sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); |
+ sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); |
+ sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows); |
+} |
+#else |
+#define TRACE_IDX_INPUTS(A) |
+#define TRACE_IDX_OUTPUTS(A) |
+#endif |
+ |
+#ifndef SQLITE_OMIT_AUTOMATIC_INDEX |
+/* |
+** Return TRUE if the WHERE clause term pTerm is of a form where it |
+** could be used with an index to access pSrc, assuming an appropriate |
+** index existed. |
+*/ |
+static int termCanDriveIndex( |
+ WhereTerm *pTerm, /* WHERE clause term to check */ |
+ struct SrcList_item *pSrc, /* Table we are trying to access */ |
+ Bitmask notReady /* Tables in outer loops of the join */ |
+){ |
+ char aff; |
+ if( pTerm->leftCursor!=pSrc->iCursor ) 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 |
+ |
+ |
+#ifndef SQLITE_OMIT_AUTOMATIC_INDEX |
+/* |
+** Generate code to construct the Index object for an automatic index |
+** and to set up the WhereLevel object pLevel so that the code generator |
+** makes use of the automatic index. |
+*/ |
+static void constructAutomaticIndex( |
+ Parse *pParse, /* The parsing context */ |
+ WhereClause *pWC, /* The WHERE clause */ |
+ struct SrcList_item *pSrc, /* The FROM clause term to get the next index */ |
+ Bitmask notReady, /* Mask of cursors that are not available */ |
+ WhereLevel *pLevel /* Write new index here */ |
+){ |
+ int nKeyCol; /* Number of columns in the constructed index */ |
+ WhereTerm *pTerm; /* A single term of the WHERE clause */ |
+ WhereTerm *pWCEnd; /* End of pWC->a[] */ |
+ Index *pIdx; /* Object describing the transient index */ |
+ Vdbe *v; /* Prepared statement under construction */ |
+ int addrInit; /* Address of the initialization bypass jump */ |
+ Table *pTable; /* The table being indexed */ |
+ int addrTop; /* Top of the index fill loop */ |
+ int regRecord; /* Register holding an index record */ |
+ int n; /* Column counter */ |
+ int i; /* Loop counter */ |
+ int mxBitCol; /* Maximum column in pSrc->colUsed */ |
+ CollSeq *pColl; /* Collating sequence to on a column */ |
+ WhereLoop *pLoop; /* The Loop object */ |
+ char *zNotUsed; /* Extra space on the end of pIdx */ |
+ 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. */ |
+ v = pParse->pVdbe; |
+ assert( v!=0 ); |
+ addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); |
+ |
+ /* Count the number of columns that will be added to the index |
+ ** and used to match WHERE clause constraints */ |
+ nKeyCol = 0; |
+ pTable = pSrc->pTab; |
+ pWCEnd = &pWC->a[pWC->nTerm]; |
+ 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); |
+ testcase( iCol==BMS ); |
+ testcase( iCol==BMS-1 ); |
+ if( !sentWarning ){ |
+ sqlite3_log(SQLITE_WARNING_AUTOINDEX, |
+ "automatic index on %s(%s)", pTable->zName, |
+ pTable->aCol[iCol].zName); |
+ sentWarning = 1; |
+ } |
+ if( (idxCols & cMask)==0 ){ |
+ if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){ |
+ goto end_auto_index_create; |
+ } |
+ pLoop->aLTerm[nKeyCol++] = pTerm; |
+ idxCols |= cMask; |
+ } |
+ } |
+ } |
+ assert( nKeyCol>0 ); |
+ pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol; |
+ pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED |
+ | WHERE_AUTO_INDEX; |
+ |
+ /* Count the number of additional columns needed to create a |
+ ** covering index. A "covering index" is an index that contains all |
+ ** columns that are needed by the query. With a covering index, the |
+ ** original table never needs to be accessed. Automatic indices must |
+ ** be a covering index because the index will not be updated if the |
+ ** original table changes and the index and table cannot both be used |
+ ** if they go out of sync. |
+ */ |
+ extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1)); |
+ mxBitCol = MIN(BMS-1,pTable->nCol); |
+ testcase( pTable->nCol==BMS-1 ); |
+ testcase( pTable->nCol==BMS-2 ); |
+ for(i=0; i<mxBitCol; i++){ |
+ if( extraCols & MASKBIT(i) ) nKeyCol++; |
+ } |
+ if( pSrc->colUsed & MASKBIT(BMS-1) ){ |
+ nKeyCol += pTable->nCol - BMS + 1; |
+ } |
+ |
+ /* Construct the Index object to describe this index */ |
+ pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed); |
+ if( pIdx==0 ) goto end_auto_index_create; |
+ pLoop->u.btree.pIndex = pIdx; |
+ pIdx->zName = "auto-index"; |
+ pIdx->pTable = pTable; |
+ n = 0; |
+ idxCols = 0; |
+ for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ |
+ if( termCanDriveIndex(pTerm, pSrc, notReady) ){ |
+ int iCol = pTerm->u.leftColumn; |
+ Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); |
+ testcase( iCol==BMS-1 ); |
+ testcase( iCol==BMS ); |
+ if( (idxCols & cMask)==0 ){ |
+ Expr *pX = pTerm->pExpr; |
+ idxCols |= cMask; |
+ pIdx->aiColumn[n] = pTerm->u.leftColumn; |
+ pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); |
+ pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY; |
+ n++; |
+ } |
+ } |
+ } |
+ assert( (u32)n==pLoop->u.btree.nEq ); |
+ |
+ /* Add additional columns needed to make the automatic index into |
+ ** a covering index */ |
+ for(i=0; i<mxBitCol; i++){ |
+ if( extraCols & MASKBIT(i) ){ |
+ pIdx->aiColumn[n] = i; |
+ 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] = sqlite3StrBINARY; |
+ n++; |
+ } |
+ } |
+ assert( n==nKeyCol ); |
+ pIdx->aiColumn[n] = XN_ROWID; |
+ pIdx->azColl[n] = sqlite3StrBINARY; |
+ |
+ /* Create the automatic index */ |
+ assert( pLevel->iIdxCur>=0 ); |
+ pLevel->iIdxCur = pParse->nTab++; |
+ sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1); |
+ sqlite3VdbeSetP4KeyInfo(pParse, pIdx); |
+ VdbeComment((v, "for %s", pTable->zName)); |
+ |
+ /* Fill the automatic index with content */ |
+ 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); |
+ regBase = sqlite3GenerateIndexKey( |
+ pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0 |
+ ); |
+ sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); |
+ sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); |
+ 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 */ |
+ |
+#ifndef SQLITE_OMIT_VIRTUALTABLE |
+/* |
+** Allocate and populate an sqlite3_index_info structure. It is the |
+** responsibility of the caller to eventually release the structure |
+** by passing the pointer returned by this function to sqlite3_free(). |
+*/ |
+static sqlite3_index_info *allocateIndexInfo( |
+ Parse *pParse, |
+ WhereClause *pWC, |
+ Bitmask mUnusable, /* Ignore terms with these prereqs */ |
+ struct SrcList_item *pSrc, |
+ ExprList *pOrderBy, |
+ u16 *pmNoOmit /* Mask of terms not to omit */ |
+){ |
+ int i, j; |
+ int nTerm; |
+ struct sqlite3_index_constraint *pIdxCons; |
+ struct sqlite3_index_orderby *pIdxOrderBy; |
+ struct sqlite3_index_constraint_usage *pUsage; |
+ WhereTerm *pTerm; |
+ int nOrderBy; |
+ sqlite3_index_info *pIdxInfo; |
+ u16 mNoOmit = 0; |
+ |
+ /* Count the number of possible WHERE clause constraints referring |
+ ** 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|WO_IS))==0 ) continue; |
+ if( pTerm->wtFlags & TERM_VNULL ) continue; |
+ assert( pTerm->u.leftColumn>=(-1) ); |
+ nTerm++; |
+ } |
+ |
+ /* If the ORDER BY clause contains only columns in the current |
+ ** virtual table then allocate space for the aOrderBy part of |
+ ** the sqlite3_index_info structure. |
+ */ |
+ nOrderBy = 0; |
+ if( pOrderBy ){ |
+ int n = pOrderBy->nExpr; |
+ for(i=0; i<n; i++){ |
+ Expr *pExpr = pOrderBy->a[i].pExpr; |
+ if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break; |
+ } |
+ if( i==n){ |
+ nOrderBy = n; |
+ } |
+ } |
+ |
+ /* Allocate the sqlite3_index_info structure |
+ */ |
+ pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) |
+ + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm |
+ + sizeof(*pIdxOrderBy)*nOrderBy ); |
+ if( pIdxInfo==0 ){ |
+ sqlite3ErrorMsg(pParse, "out of memory"); |
+ return 0; |
+ } |
+ |
+ /* Initialize the structure. The sqlite3_index_info structure contains |
+ ** many fields that are declared "const" to prevent xBestIndex from |
+ ** changing them. We have to do some funky casting in order to |
+ ** initialize those fields. |
+ */ |
+ pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1]; |
+ pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm]; |
+ pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; |
+ *(int*)&pIdxInfo->nConstraint = nTerm; |
+ *(int*)&pIdxInfo->nOrderBy = nOrderBy; |
+ *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons; |
+ *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy; |
+ *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage = |
+ pUsage; |
+ |
+ 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|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 |
+ ** following asserts verify this fact. */ |
+ assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); |
+ assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); |
+ assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); |
+ assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); |
+ assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); |
+ assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH ); |
+ assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) ); |
+ |
+ if( op & (WO_LT|WO_LE|WO_GT|WO_GE) |
+ && sqlite3ExprIsVector(pTerm->pExpr->pRight) |
+ ){ |
+ if( i<16 ) mNoOmit |= (1 << i); |
+ if( op==WO_LT ) pIdxCons[j].op = WO_LE; |
+ if( op==WO_GT ) pIdxCons[j].op = WO_GE; |
+ } |
+ |
+ j++; |
+ } |
+ for(i=0; i<nOrderBy; i++){ |
+ Expr *pExpr = pOrderBy->a[i].pExpr; |
+ pIdxOrderBy[i].iColumn = pExpr->iColumn; |
+ pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder; |
+ } |
+ |
+ *pmNoOmit = mNoOmit; |
+ return pIdxInfo; |
+} |
+ |
+/* |
+** The table object reference passed as the second argument to this function |
+** must represent a virtual table. This function invokes the xBestIndex() |
+** method of the virtual table with the sqlite3_index_info object that |
+** comes in as the 3rd argument to this function. |
+** |
+** If an error occurs, pParse is populated with an error message and a |
+** non-zero value is returned. Otherwise, 0 is returned and the output |
+** part of the sqlite3_index_info structure is left populated. |
+** |
+** Whether or not an error is returned, it is the responsibility of the |
+** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates |
+** that this is required. |
+*/ |
+static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){ |
+ sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab; |
+ int rc; |
+ |
+ TRACE_IDX_INPUTS(p); |
+ rc = pVtab->pModule->xBestIndex(pVtab, p); |
+ TRACE_IDX_OUTPUTS(p); |
+ |
+ if( rc!=SQLITE_OK ){ |
+ if( rc==SQLITE_NOMEM ){ |
+ sqlite3OomFault(pParse->db); |
+ }else if( !pVtab->zErrMsg ){ |
+ sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); |
+ }else{ |
+ sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg); |
+ } |
+ } |
+ sqlite3_free(pVtab->zErrMsg); |
+ pVtab->zErrMsg = 0; |
+ |
+#if 0 |
+ /* This error is now caught by the caller. |
+ ** Search for "xBestIndex malfunction" below */ |
+ for(i=0; i<p->nConstraint; i++){ |
+ if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){ |
+ sqlite3ErrorMsg(pParse, |
+ "table %s: xBestIndex returned an invalid plan", pTab->zName); |
+ } |
+ } |
+#endif |
+ |
+ return pParse->nErr; |
+} |
+#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 pRec |
+** aStat[1] Est. number of rows equal to pRec |
+** |
+** 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 int whereKeyStats( |
+ Parse *pParse, /* Database connection */ |
+ Index *pIdx, /* Index to consider domain of */ |
+ UnpackedRecord *pRec, /* Vector of values to consider */ |
+ int roundUp, /* Round up if true. Round down if false */ |
+ tRowcnt *aStat /* OUT: stats written here */ |
+){ |
+ 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 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 ); |
+ assert( pIdx->nSample>0 ); |
+ 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{ |
+ 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{ |
+ iSample = iTest; |
+ iCol = n-1; |
+ } |
+ }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( 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 */ |
+ |
+ 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{ |
+ /* 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{ |
+ iUpper = aSample[i].anLt[iCol]; |
+ } |
+ |
+ if( iLower>=iUpper ){ |
+ iGap = 0; |
+ }else{ |
+ iGap = iUpper - iLower; |
+ } |
+ if( roundUp ){ |
+ iGap = (iGap*2)/3; |
+ }else{ |
+ 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 */ |
+ |
+/* |
+** If it is not NULL, pTerm is a term that provides an upper or lower |
+** bound on a range scan. Without considering pTerm, it is estimated |
+** that the scan will visit nNew rows. This function returns the number |
+** estimated to be visited after taking pTerm into account. |
+** |
+** If the user explicitly specified a likelihood() value for this term, |
+** then the return value is the likelihood multiplied by the number of |
+** input rows. Otherwise, this function assumes that an "IS NOT NULL" term |
+** has a likelihood of 0.50, and any other term a likelihood of 0.25. |
+*/ |
+static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){ |
+ LogEst nRet = nNew; |
+ if( pTerm ){ |
+ if( pTerm->truthProb<=0 ){ |
+ nRet += pTerm->truthProb; |
+ }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){ |
+ nRet -= 20; assert( 20==sqlite3LogEst(4) ); |
+ } |
+ } |
+ return nRet; |
+} |
+ |
+ |
+#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
+/* |
+** Return the affinity for a single column of an index. |
+*/ |
+SQLITE_PRIVATE 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 |
+** range-scan on a skip-scan index. For example: |
+** |
+** CREATE INDEX i1 ON t1(a, b, c); |
+** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?; |
+** |
+** Value pLoop->nOut is currently set to the estimated number of rows |
+** visited for scanning (a=? AND b=?). This function reduces that estimate |
+** by some factor to account for the (c BETWEEN ? AND ?) expression based |
+** on the stat4 data for the index. this scan will be peformed multiple |
+** times (once for each (a,b) combination that matches a=?) is dealt with |
+** by the caller. |
+** |
+** It does this by scanning through all stat4 samples, comparing values |
+** extracted from pLower and pUpper with the corresponding column in each |
+** sample. If L and U are the number of samples found to be less than or |
+** equal to the values extracted from pLower and pUpper respectively, and |
+** N is the total number of samples, the pLoop->nOut value is adjusted |
+** as follows: |
+** |
+** nOut = nOut * ( min(U - L, 1) / N ) |
+** |
+** If pLower is NULL, or a value cannot be extracted from the term, L is |
+** set to zero. If pUpper is NULL, or a value cannot be extracted from it, |
+** U is set to N. |
+** |
+** Normally, this function sets *pbDone to 1 before returning. However, |
+** if no value can be extracted from either pLower or pUpper (and so the |
+** estimate of the number of rows delivered remains unchanged), *pbDone |
+** is left as is. |
+** |
+** If an error occurs, an SQLite error code is returned. Otherwise, |
+** SQLITE_OK. |
+*/ |
+static int whereRangeSkipScanEst( |
+ Parse *pParse, /* Parsing & code generating context */ |
+ WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ |
+ WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ |
+ WhereLoop *pLoop, /* Update the .nOut value of this loop */ |
+ int *pbDone /* Set to true if at least one expr. value extracted */ |
+){ |
+ Index *p = pLoop->u.btree.pIndex; |
+ int nEq = pLoop->u.btree.nEq; |
+ sqlite3 *db = pParse->db; |
+ int nLower = -1; |
+ int nUpper = p->nSample+1; |
+ int rc = SQLITE_OK; |
+ u8 aff = sqlite3IndexColumnAffinity(db, p, nEq); |
+ CollSeq *pColl; |
+ |
+ sqlite3_value *p1 = 0; /* Value extracted from pLower */ |
+ sqlite3_value *p2 = 0; /* Value extracted from pUpper */ |
+ sqlite3_value *pVal = 0; /* Value extracted from record */ |
+ |
+ pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]); |
+ if( pLower ){ |
+ rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1); |
+ nLower = 0; |
+ } |
+ if( pUpper && rc==SQLITE_OK ){ |
+ rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2); |
+ nUpper = p2 ? 0 : p->nSample; |
+ } |
+ |
+ if( p1 || p2 ){ |
+ int i; |
+ int nDiff; |
+ for(i=0; rc==SQLITE_OK && i<p->nSample; i++){ |
+ rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal); |
+ if( rc==SQLITE_OK && p1 ){ |
+ int res = sqlite3MemCompare(p1, pVal, pColl); |
+ if( res>=0 ) nLower++; |
+ } |
+ if( rc==SQLITE_OK && p2 ){ |
+ int res = sqlite3MemCompare(p2, pVal, pColl); |
+ if( res>=0 ) nUpper++; |
+ } |
+ } |
+ nDiff = (nUpper - nLower); |
+ if( nDiff<=0 ) nDiff = 1; |
+ |
+ /* If there is both an upper and lower bound specified, and the |
+ ** comparisons indicate that they are close together, use the fallback |
+ ** method (assume that the scan visits 1/64 of the rows) for estimating |
+ ** the number of rows visited. Otherwise, estimate the number of rows |
+ ** using the method described in the header comment for this function. */ |
+ if( nDiff!=1 || pUpper==0 || pLower==0 ){ |
+ int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff)); |
+ pLoop->nOut -= nAdjust; |
+ *pbDone = 1; |
+ WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n", |
+ nLower, nUpper, nAdjust*-1, pLoop->nOut)); |
+ } |
+ |
+ }else{ |
+ assert( *pbDone==0 ); |
+ } |
+ |
+ sqlite3ValueFree(p1); |
+ sqlite3ValueFree(p2); |
+ sqlite3ValueFree(pVal); |
+ |
+ return rc; |
+} |
+#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ |
+ |
+/* |
+** This function is used to estimate the number of rows that will be visited |
+** by scanning an index for a range of values. The range may have an upper |
+** bound, a lower bound, or both. The WHERE clause terms that set the upper |
+** and lower bounds are represented by pLower and pUpper respectively. For |
+** example, assuming that index p is on t1(a): |
+** |
+** ... FROM t1 WHERE a > ? AND a < ? ... |
+** |_____| |_____| |
+** | | |
+** pLower pUpper |
+** |
+** 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 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: |
+** |
+** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ... |
+** |
+** then nEq is set to 1 (as the range restricted column, b, is the second |
+** left-most column of the index). Or, if the query is: |
+** |
+** ... FROM t1 WHERE a > ? AND a < ? ... |
+** |
+** then nEq is set to 0. |
+** |
+** 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, 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. |
+** |
+** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be |
+** used, a single range inequality reduces the search space by a factor of 4. |
+** and a pair of constraints (x>? AND x<?) reduces the expected number of |
+** rows visited by a factor of 64. |
+*/ |
+static int whereRangeScanEst( |
+ Parse *pParse, /* Parsing & code generating context */ |
+ WhereLoopBuilder *pBuilder, |
+ WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ |
+ WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ |
+ WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */ |
+){ |
+ int rc = SQLITE_OK; |
+ int nOut = pLoop->nOut; |
+ LogEst nNew; |
+ |
+#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
+ Index *p = pLoop->u.btree.pIndex; |
+ int nEq = pLoop->u.btree.nEq; |
+ |
+ if( p->nSample>0 && nEq<p->nSampleCol ){ |
+ if( nEq==pBuilder->nRecValid ){ |
+ UnpackedRecord *pRec = pBuilder->pRec; |
+ tRowcnt a[2]; |
+ int nBtm = pLoop->u.btree.nBtm; |
+ int nTop = pLoop->u.btree.nTop; |
+ |
+ /* Variable iLower will be set to the estimate of the number of rows in |
+ ** the index that are less than the lower bound of the range query. The |
+ ** lower bound being the concatenation of $P and $L, where $P is the |
+ ** key-prefix formed by the nEq values matched against the nEq left-most |
+ ** columns of the index, and $L is the value in pLower. |
+ ** |
+ ** Or, if pLower is NULL or $L cannot be extracted from it (because it |
+ ** 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 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; /* 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; |
+ } |
+ /* Determine iLower and iUpper using ($P) only. */ |
+ if( nEq==0 ){ |
+ iLower = 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(). */ |
+ whereKeyStats(pParse, p, pRec, 0, a); |
+ iLower = a[0]; |
+ iUpper = a[0] + a[1]; |
+ } |
+ |
+ assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 ); |
+ assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 ); |
+ assert( p->aSortOrder!=0 ); |
+ if( p->aSortOrder[nEq] ){ |
+ /* The roles of pLower and pUpper are swapped for a DESC index */ |
+ SWAP(WhereTerm*, pLower, pUpper); |
+ SWAP(int, nBtm, nTop); |
+ } |
+ |
+ /* If possible, improve on the iLower estimate using ($P:$L). */ |
+ if( pLower ){ |
+ int n; /* Values extracted from pExpr */ |
+ Expr *pExpr = pLower->pExpr->pRight; |
+ rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n); |
+ if( rc==SQLITE_OK && n ){ |
+ tRowcnt iNew; |
+ u16 mask = WO_GT|WO_LE; |
+ if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); |
+ iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a); |
+ iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0); |
+ if( iNew>iLower ) iLower = iNew; |
+ nOut--; |
+ pLower = 0; |
+ } |
+ } |
+ |
+ /* If possible, improve on the iUpper estimate using ($P:$U). */ |
+ if( pUpper ){ |
+ int n; /* Values extracted from pExpr */ |
+ Expr *pExpr = pUpper->pExpr->pRight; |
+ rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n); |
+ if( rc==SQLITE_OK && n ){ |
+ tRowcnt iNew; |
+ u16 mask = WO_GT|WO_LE; |
+ if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); |
+ iUprIdx = whereKeyStats(pParse, p, pRec, 1, a); |
+ iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0); |
+ if( iNew<iUpper ) iUpper = iNew; |
+ nOut--; |
+ pUpper = 0; |
+ } |
+ } |
+ |
+ pBuilder->pRec = pRec; |
+ 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) ); |
+ } |
+ if( nNew<nOut ){ |
+ nOut = nNew; |
+ } |
+ WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n", |
+ (u32)iLower, (u32)iUpper, nOut)); |
+ } |
+ }else{ |
+ int bDone = 0; |
+ rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone); |
+ if( bDone ) return rc; |
+ } |
+ } |
+#else |
+ UNUSED_PARAMETER(pParse); |
+ UNUSED_PARAMETER(pBuilder); |
+ assert( pLower || pUpper ); |
+#endif |
+ assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 ); |
+ nNew = whereRangeAdjust(pLower, nOut); |
+ nNew = whereRangeAdjust(pUpper, nNew); |
+ |
+ /* 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 && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){ |
+ nNew -= 20; |
+ } |
+ |
+ nOut -= (pLower!=0) + (pUpper!=0); |
+ if( nNew<10 ) nNew = 10; |
+ if( nNew<nOut ) nOut = nNew; |
+#if defined(WHERETRACE_ENABLED) |
+ if( pLoop->nOut>nOut ){ |
+ WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n", |
+ pLoop->nOut, nOut)); |
+ } |
+#endif |
+ pLoop->nOut = (LogEst)nOut; |
+ return rc; |
+} |
+ |
+#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
+/* |
+** Estimate the number of rows that will be returned based on |
+** an equality constraint x=VALUE and where that VALUE occurs in |
+** the histogram data. This only works when x is the left-most |
+** column of an index and sqlite_stat3 histogram data is available |
+** for that index. When pExpr==NULL that means the constraint is |
+** "x IS NULL" instead of "x=VALUE". |
+** |
+** 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 whereEqualScanEst( |
+ Parse *pParse, /* Parsing & code generating context */ |
+ WhereLoopBuilder *pBuilder, |
+ Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */ |
+ tRowcnt *pnRow /* Write the revised row estimate here */ |
+){ |
+ Index *p = pBuilder->pNew->u.btree.pIndex; |
+ int nEq = pBuilder->pNew->u.btree.nEq; |
+ UnpackedRecord *pRec = pBuilder->pRec; |
+ 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; |
+ } |
+ |
+ rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, 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 %s(%d): %d\n", |
+ p->zName, nEq-1, (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 */ |
+ |
+ |
+#ifdef WHERETRACE_ENABLED |
+/* |
+** Print the content of a WhereTerm object |
+*/ |
+static void whereTermPrint(WhereTerm *pTerm, int iTerm){ |
+ if( pTerm==0 ){ |
+ sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm); |
+ }else{ |
+ char zType[4]; |
+ char zLeft[50]; |
+ memcpy(zType, "...", 4); |
+ 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'; |
+ if( pTerm->eOperator & WO_SINGLE ){ |
+ sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}", |
+ pTerm->leftCursor, pTerm->u.leftColumn); |
+ }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){ |
+ sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld", |
+ pTerm->u.pOrInfo->indexable); |
+ }else{ |
+ sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor); |
+ } |
+ sqlite3DebugPrintf( |
+ "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x", |
+ iTerm, pTerm, zType, zLeft, pTerm->truthProb, |
+ pTerm->eOperator, pTerm->wtFlags); |
+ if( pTerm->iField ){ |
+ sqlite3DebugPrintf(" iField=%d\n", pTerm->iField); |
+ }else{ |
+ sqlite3DebugPrintf("\n"); |
+ } |
+ sqlite3TreeViewExpr(0, pTerm->pExpr, 0); |
+ } |
+} |
+#endif |
+ |
+#ifdef WHERETRACE_ENABLED |
+/* |
+** Show the complete content of a WhereClause |
+*/ |
+SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){ |
+ int i; |
+ for(i=0; i<pWC->nTerm; i++){ |
+ whereTermPrint(&pWC->a[i], i); |
+ } |
+} |
+#endif |
+ |
+#ifdef WHERETRACE_ENABLED |
+/* |
+** Print a WhereLoop object for debugging purposes |
+*/ |
+static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){ |
+ WhereInfo *pWInfo = pWC->pWInfo; |
+ int nb = 1+(pWInfo->pTabList->nSrc+3)/4; |
+ struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab; |
+ Table *pTab = pItem->pTab; |
+ Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1; |
+ sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId, |
+ p->iTab, nb, p->maskSelf, nb, p->prereq & mAll); |
+ sqlite3DebugPrintf(" %12s", |
+ pItem->zAlias ? pItem->zAlias : pTab->zName); |
+ if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ |
+ const char *zName; |
+ if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){ |
+ if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){ |
+ int i = sqlite3Strlen30(zName) - 1; |
+ while( zName[i]!='_' ) i--; |
+ zName += i; |
+ } |
+ sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq); |
+ }else{ |
+ sqlite3DebugPrintf("%20s",""); |
+ } |
+ }else{ |
+ char *z; |
+ if( p->u.vtab.idxStr ){ |
+ z = sqlite3_mprintf("(%d,\"%s\",%x)", |
+ p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask); |
+ }else{ |
+ z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); |
+ } |
+ sqlite3DebugPrintf(" %-19s", z); |
+ sqlite3_free(z); |
+ } |
+ if( p->wsFlags & WHERE_SKIPSCAN ){ |
+ sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip); |
+ }else{ |
+ sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm); |
+ } |
+ sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); |
+ if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ |
+ int i; |
+ for(i=0; i<p->nLTerm; i++){ |
+ whereTermPrint(p->aLTerm[i], i); |
+ } |
+ } |
+} |
+#endif |
+ |
+/* |
+** Convert bulk memory into a valid WhereLoop that can be passed |
+** to whereLoopClear harmlessly. |
+*/ |
+static void whereLoopInit(WhereLoop *p){ |
+ p->aLTerm = p->aLTermSpace; |
+ p->nLTerm = 0; |
+ p->nLSlot = ArraySize(p->aLTermSpace); |
+ p->wsFlags = 0; |
+} |
+ |
+/* |
+** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact. |
+*/ |
+static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ |
+ if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){ |
+ if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){ |
+ sqlite3_free(p->u.vtab.idxStr); |
+ p->u.vtab.needFree = 0; |
+ 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); |
+ sqlite3DbFree(db, p->u.btree.pIndex); |
+ p->u.btree.pIndex = 0; |
+ } |
+ } |
+} |
+ |
+/* |
+** Deallocate internal memory used by a WhereLoop object |
+*/ |
+static void whereLoopClear(sqlite3 *db, WhereLoop *p){ |
+ if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); |
+ whereLoopClearUnion(db, p); |
+ whereLoopInit(p); |
+} |
+ |
+/* |
+** Increase the memory allocation for pLoop->aLTerm[] to be at least n. |
+*/ |
+static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){ |
+ WhereTerm **paNew; |
+ if( p->nLSlot>=n ) return SQLITE_OK; |
+ n = (n+7)&~7; |
+ paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n); |
+ if( paNew==0 ) return SQLITE_NOMEM_BKPT; |
+ memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot); |
+ if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); |
+ p->aLTerm = paNew; |
+ p->nLSlot = n; |
+ return SQLITE_OK; |
+} |
+ |
+/* |
+** Transfer content from the second pLoop into the first. |
+*/ |
+static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ |
+ whereLoopClearUnion(db, pTo); |
+ if( whereLoopResize(db, pTo, pFrom->nLTerm) ){ |
+ memset(&pTo->u, 0, sizeof(pTo->u)); |
+ return SQLITE_NOMEM_BKPT; |
+ } |
+ memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ); |
+ memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0])); |
+ if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){ |
+ pFrom->u.vtab.needFree = 0; |
+ }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){ |
+ pFrom->u.btree.pIndex = 0; |
+ } |
+ return SQLITE_OK; |
+} |
+ |
+/* |
+** Delete a WhereLoop object |
+*/ |
+static void whereLoopDelete(sqlite3 *db, WhereLoop *p){ |
+ whereLoopClear(db, p); |
+ sqlite3DbFree(db, p); |
+} |
+ |
+/* |
+** Free a WhereInfo structure |
+*/ |
+static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ |
+ if( ALWAYS(pWInfo) ){ |
+ 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; |
+ whereLoopDelete(db, p); |
+ } |
+ sqlite3DbFree(db, pWInfo); |
+ } |
+} |
+ |
+/* |
+** 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 |
+** by Y. |
+** |
+** 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. 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-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; |
+ } |
+ if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */ |
+ } |
+ return 1; /* All conditions meet */ |
+} |
+ |
+/* |
+** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so |
+** that: |
+** |
+** (1) pTemplate costs less than any other WhereLoops that are a proper |
+** subset of pTemplate |
+** |
+** (2) pTemplate costs more than any other WhereLoops for which pTemplate |
+** is a proper subset. |
+** |
+** 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. |
+*/ |
+static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){ |
+ if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return; |
+ for(; p; p=p->pNextLoop){ |
+ if( p->iTab!=pTemplate->iTab ) continue; |
+ if( (p->wsFlags & WHERE_INDEXED)==0 ) continue; |
+ if( whereLoopCheaperProperSubset(p, pTemplate) ){ |
+ /* Adjust pTemplate cost downward so that it is cheaper than its |
+ ** 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; |
+ } |
+ } |
+} |
+ |
+/* |
+** Search the list of WhereLoops in *ppPrev looking for one that can be |
+** supplanted by pTemplate. |
+** |
+** Return NULL if the WhereLoop list contains an entry that can supplant |
+** pTemplate, in other words if pTemplate does not belong on the list. |
+** |
+** If pX is a WhereLoop that pTemplate can supplant, then return the |
+** link that points to pX. |
+** |
+** If pTemplate cannot supplant any existing element of the list but needs |
+** to be added to the list, then return a pointer to the tail of the list. |
+*/ |
+static WhereLoop **whereLoopFindLesser( |
+ WhereLoop **ppPrev, |
+ const WhereLoop *pTemplate |
+){ |
+ WhereLoop *p; |
+ for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){ |
+ if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){ |
+ /* If either the iTab or iSortIdx values for two WhereLoop are different |
+ ** then those WhereLoops need to be considered separately. Neither is |
+ ** a candidate to replace the other. */ |
+ continue; |
+ } |
+ /* In the current implementation, the rSetup value is either zero |
+ ** or the cost of building an automatic index (NlogN) and the NlogN |
+ ** is the same for compatible WhereLoops. */ |
+ assert( p->rSetup==0 || pTemplate->rSetup==0 |
+ || p->rSetup==pTemplate->rSetup ); |
+ |
+ /* whereLoopAddBtree() always generates and inserts the automatic index |
+ ** case first. Hence compatible candidate WhereLoops never have a larger |
+ ** rSetup. Call this SETUP-INVARIANT */ |
+ assert( p->rSetup>=pTemplate->rSetup ); |
+ |
+ /* Any loop using an appliation-defined index (or PRIMARY KEY or |
+ ** UNIQUE constraint) with one or more == constraints is better |
+ ** 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 |
+ ){ |
+ break; |
+ } |
+ |
+ /* If existing WhereLoop p is better than pTemplate, pTemplate can be |
+ ** discarded. WhereLoop p is better if: |
+ ** (1) p has no more dependencies than pTemplate, and |
+ ** (2) p has an equal or lower cost than pTemplate |
+ */ |
+ if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */ |
+ && p->rSetup<=pTemplate->rSetup /* (2a) */ |
+ && p->rRun<=pTemplate->rRun /* (2b) */ |
+ && p->nOut<=pTemplate->nOut /* (2c) */ |
+ ){ |
+ return 0; /* Discard pTemplate */ |
+ } |
+ |
+ /* If pTemplate is always better than p, then cause p to be overwritten |
+ ** with pTemplate. pTemplate is better than p if: |
+ ** (1) pTemplate has no more dependences than p, and |
+ ** (2) pTemplate has an equal or lower cost than p. |
+ */ |
+ if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */ |
+ && p->rRun>=pTemplate->rRun /* (2a) */ |
+ && p->nOut>=pTemplate->nOut /* (2b) */ |
+ ){ |
+ assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */ |
+ break; /* Cause p to be overwritten by pTemplate */ |
+ } |
+ } |
+ return ppPrev; |
+} |
+ |
+/* |
+** Insert or replace a WhereLoop entry using the template supplied. |
+** |
+** An existing WhereLoop entry might be overwritten if the new template |
+** is better and has fewer dependencies. Or the template will be ignored |
+** and no insert will occur if an existing WhereLoop is faster and has |
+** fewer dependencies than the template. Otherwise a new WhereLoop is |
+** added based on the template. |
+** |
+** If pBuilder->pOrSet is not NULL then we care about only the |
+** prerequisites and rRun and nOut costs of the N best loops. That |
+** information is gathered in the pBuilder->pOrSet object. This special |
+** processing mode is used only for OR clause processing. |
+** |
+** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we |
+** still might overwrite similar loops with the new template if the |
+** new template is better. Loops may be overwritten if the following |
+** conditions are met: |
+** |
+** (1) They have the same iTab. |
+** (2) They have the same iSortIdx. |
+** (3) The template has same or fewer dependencies than the current loop |
+** (4) The template has the same or lower cost than the current loop |
+*/ |
+static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ |
+ WhereLoop **ppPrev, *p; |
+ WhereInfo *pWInfo = pBuilder->pWInfo; |
+ sqlite3 *db = pWInfo->pParse->db; |
+ int rc; |
+ |
+ /* If pBuilder->pOrSet is defined, then only keep track of the costs |
+ ** and prereqs. |
+ */ |
+ if( pBuilder->pOrSet!=0 ){ |
+ if( pTemplate->nLTerm ){ |
+#if WHERETRACE_ENABLED |
+ u16 n = pBuilder->pOrSet->n; |
+ int x = |
+#endif |
+ 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); |
+ } |
+#endif |
+ } |
+ return SQLITE_OK; |
+ } |
+ |
+ /* Look for an existing WhereLoop to replace with pTemplate |
+ */ |
+ whereLoopAdjustCost(pWInfo->pLoops, pTemplate); |
+ ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate); |
+ |
+ if( ppPrev==0 ){ |
+ /* There already exists a WhereLoop on the list that is better |
+ ** than pTemplate, so just ignore pTemplate */ |
+#if WHERETRACE_ENABLED /* 0x8 */ |
+ if( sqlite3WhereTrace & 0x8 ){ |
+ sqlite3DebugPrintf(" skip: "); |
+ whereLoopPrint(pTemplate, pBuilder->pWC); |
+ } |
+#endif |
+ return SQLITE_OK; |
+ }else{ |
+ p = *ppPrev; |
+ } |
+ |
+ /* If we reach this point it means that either p[] should be overwritten |
+ ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new |
+ ** WhereLoop and insert it. |
+ */ |
+#if WHERETRACE_ENABLED /* 0x8 */ |
+ if( sqlite3WhereTrace & 0x8 ){ |
+ if( p!=0 ){ |
+ sqlite3DebugPrintf("replace: "); |
+ whereLoopPrint(p, pBuilder->pWC); |
+ } |
+ sqlite3DebugPrintf(" add: "); |
+ whereLoopPrint(pTemplate, pBuilder->pWC); |
+ } |
+#endif |
+ if( p==0 ){ |
+ /* Allocate a new WhereLoop to add to the end of the list */ |
+ *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop)); |
+ if( p==0 ) return SQLITE_NOMEM_BKPT; |
+ whereLoopInit(p); |
+ p->pNextLoop = 0; |
+ }else{ |
+ /* We will be overwriting WhereLoop p[]. But before we do, first |
+ ** go through the rest of the list and delete any other entries besides |
+ ** p[] that are also supplated by pTemplate */ |
+ WhereLoop **ppTail = &p->pNextLoop; |
+ WhereLoop *pToDel; |
+ while( *ppTail ){ |
+ ppTail = whereLoopFindLesser(ppTail, pTemplate); |
+ if( ppTail==0 ) break; |
+ pToDel = *ppTail; |
+ if( pToDel==0 ) break; |
+ *ppTail = pToDel->pNextLoop; |
+#if WHERETRACE_ENABLED /* 0x8 */ |
+ if( sqlite3WhereTrace & 0x8 ){ |
+ sqlite3DebugPrintf(" delete: "); |
+ whereLoopPrint(pToDel, pBuilder->pWC); |
+ } |
+#endif |
+ whereLoopDelete(db, pToDel); |
+ } |
+ } |
+ rc = whereLoopXfer(db, p, pTemplate); |
+ if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ |
+ Index *pIndex = p->u.btree.pIndex; |
+ if( pIndex && pIndex->tnum==0 ){ |
+ p->u.btree.pIndex = 0; |
+ } |
+ } |
+ return rc; |
+} |
+ |
+/* |
+** 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. |
+* |
+** 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 */ |
+ WhereLoop *pLoop, /* The loop to adjust downward */ |
+ LogEst nRow /* Number of rows in the entire table */ |
+){ |
+ WhereTerm *pTerm, *pX; |
+ Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf); |
+ 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; |
+ if( (pTerm->prereqAll & notAllowed)!=0 ) continue; |
+ for(j=pLoop->nLTerm-1; j>=0; j--){ |
+ pX = pLoop->aLTerm[j]; |
+ if( pX==0 ) continue; |
+ if( pX==pTerm ) break; |
+ if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break; |
+ } |
+ 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|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; |
+ } |
+ } |
+ } |
+ } |
+ if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce; |
+} |
+ |
+/* |
+** Term pTerm is a vector range comparison operation. The first comparison |
+** in the vector can be optimized using column nEq of the index. This |
+** function returns the total number of vector elements that can be used |
+** as part of the range comparison. |
+** |
+** For example, if the query is: |
+** |
+** WHERE a = ? AND (b, c, d) > (?, ?, ?) |
+** |
+** and the index: |
+** |
+** CREATE INDEX ... ON (a, b, c, d, e) |
+** |
+** then this function would be invoked with nEq=1. The value returned in |
+** this case is 3. |
+*/ |
+static int whereRangeVectorLen( |
+ Parse *pParse, /* Parsing context */ |
+ int iCur, /* Cursor open on pIdx */ |
+ Index *pIdx, /* The index to be used for a inequality constraint */ |
+ int nEq, /* Number of prior equality constraints on same index */ |
+ WhereTerm *pTerm /* The vector inequality constraint */ |
+){ |
+ int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft); |
+ int i; |
+ |
+ nCmp = MIN(nCmp, (pIdx->nColumn - nEq)); |
+ for(i=1; i<nCmp; i++){ |
+ /* Test if comparison i of pTerm is compatible with column (i+nEq) |
+ ** of the index. If not, exit the loop. */ |
+ char aff; /* Comparison affinity */ |
+ char idxaff = 0; /* Indexed columns affinity */ |
+ CollSeq *pColl; /* Comparison collation sequence */ |
+ Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr; |
+ Expr *pRhs = pTerm->pExpr->pRight; |
+ if( pRhs->flags & EP_xIsSelect ){ |
+ pRhs = pRhs->x.pSelect->pEList->a[i].pExpr; |
+ }else{ |
+ pRhs = pRhs->x.pList->a[i].pExpr; |
+ } |
+ |
+ /* Check that the LHS of the comparison is a column reference to |
+ ** the right column of the right source table. And that the sort |
+ ** order of the index column is the same as the sort order of the |
+ ** leftmost index column. */ |
+ if( pLhs->op!=TK_COLUMN |
+ || pLhs->iTable!=iCur |
+ || pLhs->iColumn!=pIdx->aiColumn[i+nEq] |
+ || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq] |
+ ){ |
+ break; |
+ } |
+ |
+ testcase( pLhs->iColumn==XN_ROWID ); |
+ aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs)); |
+ idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn); |
+ if( aff!=idxaff ) break; |
+ |
+ pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); |
+ if( pColl==0 ) break; |
+ if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break; |
+ } |
+ return i; |
+} |
+ |
+/* |
+** Adjust the cost C by the costMult facter T. This only occurs if |
+** compiled with -DSQLITE_ENABLE_COSTMULT |
+*/ |
+#ifdef SQLITE_ENABLE_COSTMULT |
+# define ApplyCostMultiplier(C,T) C += T |
+#else |
+# define ApplyCostMultiplier(C,T) |
+#endif |
+ |
+/* |
+** We have so far matched pBuilder->pNew->u.btree.nEq terms of the |
+** index pIndex. Try to match one more. |
+** |
+** When this function is called, pBuilder->pNew->nOut contains the |
+** number of rows expected to be visited by filtering using the nEq |
+** terms only. If it is modified, this value is restored before this |
+** function returns. |
+** |
+** If pProbe->tnum==0, that means pIndex is a fake index used for the |
+** INTEGER PRIMARY KEY. |
+*/ |
+static int whereLoopAddBtreeIndex( |
+ WhereLoopBuilder *pBuilder, /* The WhereLoop factory */ |
+ struct SrcList_item *pSrc, /* FROM clause term being analyzed */ |
+ Index *pProbe, /* An index on pSrc */ |
+ LogEst nInMul /* log(Number of iterations due to IN) */ |
+){ |
+ WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */ |
+ Parse *pParse = pWInfo->pParse; /* Parsing context */ |
+ sqlite3 *db = pParse->db; /* Database connection malloc context */ |
+ WhereLoop *pNew; /* Template WhereLoop under construction */ |
+ WhereTerm *pTerm; /* A WhereTerm under consideration */ |
+ int opMask; /* Valid operators for constraints */ |
+ WhereScan scan; /* Iterator for WHERE terms */ |
+ 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_nBtm; /* Original value of pNew->u.btree.nBtm */ |
+ u16 saved_nTop; /* Original value of pNew->u.btree.nTop */ |
+ 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 rc = SQLITE_OK; /* Return code */ |
+ LogEst rSize; /* Number of rows in the table */ |
+ LogEst rLogSize; /* Logarithm of table size */ |
+ WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */ |
+ |
+ pNew = pBuilder->pNew; |
+ if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; |
+ WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n", |
+ pProbe->zName, pNew->u.btree.nEq)); |
+ |
+ assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 ); |
+ assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 ); |
+ if( pNew->wsFlags & WHERE_BTM_LIMIT ){ |
+ opMask = WO_LT|WO_LE; |
+ }else{ |
+ assert( pNew->u.btree.nBtm==0 ); |
+ 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 ); |
+ |
+ saved_nEq = pNew->u.btree.nEq; |
+ saved_nBtm = pNew->u.btree.nBtm; |
+ saved_nTop = pNew->u.btree.nTop; |
+ 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); |
+ for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){ |
+ u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */ |
+ LogEst rCostIdx; |
+ LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */ |
+ int nIn = 0; |
+#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
+ int nRecValid = pBuilder->nRecValid; |
+#endif |
+ if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0) |
+ && 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; |
+ |
+ /* Do not allow IS constraints from the WHERE clause to be used by the |
+ ** right table of a LEFT JOIN. Only constraints in the ON clause are |
+ ** allowed */ |
+ if( (pSrc->fg.jointype & JT_LEFT)!=0 |
+ && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) |
+ && (eOp & (WO_IS|WO_ISNULL))!=0 |
+ ){ |
+ testcase( eOp & WO_IS ); |
+ testcase( eOp & WO_ISNULL ); |
+ continue; |
+ } |
+ |
+ pNew->wsFlags = saved_wsFlags; |
+ pNew->u.btree.nEq = saved_nEq; |
+ pNew->u.btree.nBtm = saved_nBtm; |
+ pNew->u.btree.nTop = saved_nTop; |
+ pNew->nLTerm = saved_nLTerm; |
+ if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ |
+ pNew->aLTerm[pNew->nLTerm++] = pTerm; |
+ pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf; |
+ |
+ assert( nInMul==0 |
+ || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 |
+ || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 |
+ || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 |
+ ); |
+ |
+ if( eOp & WO_IN ){ |
+ Expr *pExpr = pTerm->pExpr; |
+ pNew->wsFlags |= WHERE_COLUMN_IN; |
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){ |
+ /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ |
+ int i; |
+ nIn = 46; assert( 46==sqlite3LogEst(25) ); |
+ |
+ /* The expression may actually be of the form (x, y) IN (SELECT...). |
+ ** In this case there is a separate term for each of (x) and (y). |
+ ** However, the nIn multiplier should only be applied once, not once |
+ ** for each such term. The following loop checks that pTerm is the |
+ ** first such term in use, and sets nIn back to 0 if it is not. */ |
+ for(i=0; i<pNew->nLTerm-1; i++){ |
+ if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0; |
+ } |
+ }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ |
+ /* "x IN (value, value, ...)" */ |
+ nIn = sqlite3LogEst(pExpr->x.pList->nExpr); |
+ assert( nIn>0 ); /* RHS always has 2 or more terms... The parser |
+ ** changes "x IN (?)" into "x=?". */ |
+ } |
+ }else if( eOp & (WO_EQ|WO_IS) ){ |
+ int iCol = pProbe->aiColumn[saved_nEq]; |
+ pNew->wsFlags |= WHERE_COLUMN_EQ; |
+ 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; |
+ } |
+ } |
+ }else if( eOp & WO_ISNULL ){ |
+ pNew->wsFlags |= WHERE_COLUMN_NULL; |
+ }else if( eOp & (WO_GT|WO_GE) ){ |
+ testcase( eOp & WO_GT ); |
+ testcase( eOp & WO_GE ); |
+ pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT; |
+ pNew->u.btree.nBtm = whereRangeVectorLen( |
+ pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm |
+ ); |
+ 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; |
+ pNew->u.btree.nTop = 1; |
+ } |
+ }else{ |
+ assert( eOp & (WO_LT|WO_LE) ); |
+ testcase( eOp & WO_LT ); |
+ testcase( eOp & WO_LE ); |
+ pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT; |
+ pNew->u.btree.nTop = whereRangeVectorLen( |
+ pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm |
+ ); |
+ pTop = pTerm; |
+ pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ? |
+ pNew->aLTerm[pNew->nLTerm-2] : 0; |
+ } |
+ |
+ /* At this point pNew->nOut is set to the number of rows expected to |
+ ** be visited by the index scan before considering term pTerm, or the |
+ ** values of nIn and nInMul. In other words, assuming that all |
+ ** "x IN(...)" terms are replaced with "x = ?". This block updates |
+ ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */ |
+ assert( pNew->nOut==saved_nOut ); |
+ if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ |
+ /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4 |
+ ** data, using some other estimate. */ |
+ whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew); |
+ }else{ |
+ int nEq = ++pNew->u.btree.nEq; |
+ assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) ); |
+ |
+ assert( pNew->nOut==saved_nOut ); |
+ if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){ |
+ assert( (eOp & WO_IN) || nIn==0 ); |
+ testcase( eOp & WO_IN ); |
+ pNew->nOut += pTerm->truthProb; |
+ pNew->nOut -= nIn; |
+ }else{ |
+#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
+ tRowcnt nOut = 0; |
+ if( nInMul==0 |
+ && pProbe->nSample |
+ && pNew->u.btree.nEq<=pProbe->nSampleCol |
+ && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect)) |
+ ){ |
+ Expr *pExpr = pTerm->pExpr; |
+ 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{ |
+ rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut); |
+ } |
+ if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; |
+ if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */ |
+ if( nOut ){ |
+ pNew->nOut = sqlite3LogEst(nOut); |
+ if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut; |
+ pNew->nOut -= nIn; |
+ } |
+ } |
+ if( nOut==0 ) |
+#endif |
+ { |
+ pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]); |
+ if( eOp & WO_ISNULL ){ |
+ /* TUNING: If there is no likelihood() value, assume that a |
+ ** "col IS NULL" expression matches twice as many rows |
+ ** as (col=?). */ |
+ pNew->nOut += 10; |
+ } |
+ } |
+ } |
+ } |
+ |
+ /* Set rCostIdx to the cost of visiting selected rows in index. Add |
+ ** it to pNew->rRun, which is currently set to the cost of the index |
+ ** seek only. Then, if this is a non-covering index, add the cost of |
+ ** visiting the rows in the main table. */ |
+ rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow; |
+ pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx); |
+ if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){ |
+ pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16); |
+ } |
+ ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult); |
+ |
+ nOutUnadjusted = pNew->nOut; |
+ pNew->rRun += nInMul + nIn; |
+ pNew->nOut += nInMul + nIn; |
+ whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize); |
+ rc = whereLoopInsert(pBuilder, pNew); |
+ |
+ if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ |
+ pNew->nOut = saved_nOut; |
+ }else{ |
+ pNew->nOut = nOutUnadjusted; |
+ } |
+ |
+ if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 |
+ && pNew->u.btree.nEq<pProbe->nColumn |
+ ){ |
+ whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); |
+ } |
+ pNew->nOut = saved_nOut; |
+#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
+ pBuilder->nRecValid = nRecValid; |
+#endif |
+ } |
+ pNew->prereq = saved_prereq; |
+ pNew->u.btree.nEq = saved_nEq; |
+ pNew->u.btree.nBtm = saved_nBtm; |
+ pNew->u.btree.nTop = saved_nTop; |
+ 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; |
+ } |
+ |
+ WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n", |
+ pProbe->zName, saved_nEq, rc)); |
+ return rc; |
+} |
+ |
+/* |
+** Return True if it is possible that pIndex might be useful in |
+** implementing the ORDER BY clause in pBuilder. |
+** |
+** Return False if pBuilder does not contain an ORDER BY clause or |
+** if there is no way for pIndex to be useful in implementing that |
+** ORDER BY clause. |
+*/ |
+static int indexMightHelpWithOrderBy( |
+ WhereLoopBuilder *pBuilder, |
+ Index *pIndex, |
+ 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 && 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; |
+} |
+ |
+/* |
+** Return a bitmask where 1s indicate that the corresponding column of |
+** the table is used by an index. Only the first 63 columns are considered. |
+*/ |
+static Bitmask columnsInIndex(Index *pIdx){ |
+ Bitmask m = 0; |
+ int j; |
+ for(j=pIdx->nColumn-1; j>=0; j--){ |
+ int x = pIdx->aiColumn[j]; |
+ if( x>=0 ){ |
+ testcase( x==BMS-1 ); |
+ testcase( x==BMS-2 ); |
+ if( x<BMS-1 ) m |= MASKBIT(x); |
+ } |
+ } |
+ return m; |
+} |
+ |
+/* Check to see if a partial index with pPartIndexWhere can be used |
+** in the current query. Return true if it can be and false if not. |
+*/ |
+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++){ |
+ Expr *pExpr = pTerm->pExpr; |
+ if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab) |
+ && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab) |
+ ){ |
+ return 1; |
+ } |
+ } |
+ return 0; |
+} |
+ |
+/* |
+** Add all WhereLoop objects for a single table of the join where the table |
+** is identified by pBuilder->pNew->iTab. That table is guaranteed to be |
+** a b-tree table, not a virtual table. |
+** |
+** The costs (WhereLoop.rRun) of the b-tree loops added by this function |
+** are calculated as follows: |
+** |
+** For a full scan, assuming the table (or index) contains nRow rows: |
+** |
+** cost = nRow * 3.0 // full-table scan |
+** cost = nRow * K // scan of covering index |
+** cost = nRow * (K+3.0) // scan of non-covering index |
+** |
+** where K is a value between 1.1 and 3.0 set based on the relative |
+** estimated average size of the index and table records. |
+** |
+** For an index scan, where nVisit is the number of index rows visited |
+** by the scan, and nSeek is the number of seek operations required on |
+** the index b-tree: |
+** |
+** cost = nSeek * (log(nRow) + K * nVisit) // covering index |
+** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index |
+** |
+** Normally, nSeek is 1. nSeek values greater than 1 come about if the |
+** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when |
+** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans. |
+** |
+** The estimated values (nRow, nVisit, nSeek) often contain a large amount |
+** of uncertainty. For this reason, scoring is designed to pick plans that |
+** "do the least harm" if the estimates are inaccurate. For example, a |
+** log(nRow) factor is omitted from a non-covering index scan in order to |
+** bias the scoring in favor of using an index, since the worst-case |
+** performance of using an index is far better than the worst-case performance |
+** of a full table scan. |
+*/ |
+static int whereLoopAddBtree( |
+ WhereLoopBuilder *pBuilder, /* WHERE clause information */ |
+ Bitmask mPrereq /* Extra prerequesites for using this table */ |
+){ |
+ WhereInfo *pWInfo; /* WHERE analysis context */ |
+ Index *pProbe; /* An index we are evaluating */ |
+ Index sPk; /* A fake index object for the primary key */ |
+ LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */ |
+ i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */ |
+ SrcList *pTabList; /* The FROM clause */ |
+ struct SrcList_item *pSrc; /* The FROM clause btree term to add */ |
+ WhereLoop *pNew; /* Template WhereLoop object */ |
+ int rc = SQLITE_OK; /* Return code */ |
+ int iSortIdx = 1; /* Index number */ |
+ int b; /* A boolean value */ |
+ LogEst rSize; /* number of rows in the table */ |
+ LogEst rLogSize; /* Logarithm of the number of rows in the table */ |
+ WhereClause *pWC; /* The parsed WHERE clause */ |
+ Table *pTab; /* Table being queried */ |
+ |
+ pNew = pBuilder->pNew; |
+ pWInfo = pBuilder->pWInfo; |
+ pTabList = pWInfo->pTabList; |
+ pSrc = pTabList->a + pNew->iTab; |
+ pTab = pSrc->pTab; |
+ pWC = pBuilder->pWC; |
+ assert( !IsVirtual(pSrc->pTab) ); |
+ |
+ if( pSrc->pIBIndex ){ |
+ /* An INDEXED BY clause specifies a particular index to use */ |
+ pProbe = pSrc->pIBIndex; |
+ }else if( !HasRowid(pTab) ){ |
+ pProbe = pTab->pIndex; |
+ }else{ |
+ /* There is no INDEXED BY clause. Create a fake Index object in local |
+ ** variable sPk to represent the rowid primary key index. Make this |
+ ** fake index the first in a chain of Index objects with all of the real |
+ ** indices to follow */ |
+ Index *pFirst; /* First of real indices on the table */ |
+ memset(&sPk, 0, sizeof(Index)); |
+ sPk.nKeyCol = 1; |
+ sPk.nColumn = 1; |
+ sPk.aiColumn = &aiColumnPk; |
+ sPk.aiRowLogEst = aiRowEstPk; |
+ sPk.onError = OE_Replace; |
+ sPk.pTable = pTab; |
+ sPk.szIdxRow = pTab->szTabRow; |
+ aiRowEstPk[0] = pTab->nRowLogEst; |
+ aiRowEstPk[1] = 0; |
+ pFirst = pSrc->pTab->pIndex; |
+ 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; |
+ } |
+ pProbe = &sPk; |
+ } |
+ rSize = pTab->nRowLogEst; |
+ rLogSize = estLog(rSize); |
+ |
+#ifndef SQLITE_OMIT_AUTOMATIC_INDEX |
+ /* Automatic indexes */ |
+ if( !pBuilder->pOrSet /* Not part of an OR optimization */ |
+ && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 |
+ && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0 |
+ && 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; |
+ WhereTerm *pWCEnd = pWC->a + pWC->nTerm; |
+ for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){ |
+ if( pTerm->prereqRight & pNew->maskSelf ) continue; |
+ if( termCanDriveIndex(pTerm, pSrc, 0) ){ |
+ pNew->u.btree.nEq = 1; |
+ pNew->nSkip = 0; |
+ pNew->u.btree.pIndex = 0; |
+ pNew->nLTerm = 1; |
+ pNew->aLTerm[0] = pTerm; |
+ /* TUNING: One-time cost for computing the automatic index is |
+ ** estimated to be X*N*log2(N) where N is the number of rows in |
+ ** the table being indexed and where X is 7 (LogEst=28) for normal |
+ ** tables or 1.375 (LogEst=4) for views and subqueries. The value |
+ ** of X is smaller for views and subqueries so that the query planner |
+ ** will be more aggressive about generating automatic indexes for |
+ ** those objects, since there is no opportunity to add schema |
+ ** indexes on subqueries and views. */ |
+ pNew->rSetup = rLogSize + rSize + 4; |
+ if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){ |
+ pNew->rSetup += 24; |
+ } |
+ ApplyCostMultiplier(pNew->rSetup, pTab->costMult); |
+ if( pNew->rSetup<0 ) pNew->rSetup = 0; |
+ /* TUNING: Each index lookup yields 20 rows in the table. This |
+ ** is more than the usual guess of 10 rows, since we have no way |
+ ** of knowing how selective the index will ultimately be. It would |
+ ** not be unreasonable to make this value much larger. */ |
+ pNew->nOut = 43; assert( 43==sqlite3LogEst(20) ); |
+ pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut); |
+ pNew->wsFlags = WHERE_AUTO_INDEX; |
+ pNew->prereq = mPrereq | pTerm->prereqRight; |
+ rc = whereLoopInsert(pBuilder, pNew); |
+ } |
+ } |
+ } |
+#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ |
+ |
+ /* Loop over all indices |
+ */ |
+ for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){ |
+ if( pProbe->pPartIdxWhere!=0 |
+ && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){ |
+ testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */ |
+ continue; /* Partial index inappropriate for this query */ |
+ } |
+ rSize = pProbe->aiRowLogEst[0]; |
+ pNew->u.btree.nEq = 0; |
+ pNew->u.btree.nBtm = 0; |
+ pNew->u.btree.nTop = 0; |
+ pNew->nSkip = 0; |
+ pNew->nLTerm = 0; |
+ pNew->iSortIdx = 0; |
+ pNew->rSetup = 0; |
+ pNew->prereq = mPrereq; |
+ pNew->nOut = rSize; |
+ pNew->u.btree.pIndex = pProbe; |
+ b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor); |
+ /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */ |
+ assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 ); |
+ if( pProbe->tnum<=0 ){ |
+ /* Integer primary key index */ |
+ pNew->wsFlags = WHERE_IPK; |
+ |
+ /* Full table scan */ |
+ pNew->iSortIdx = b ? iSortIdx : 0; |
+ /* TUNING: Cost of full table scan is (N*3.0). */ |
+ pNew->rRun = rSize + 16; |
+ ApplyCostMultiplier(pNew->rRun, pTab->costMult); |
+ whereLoopOutputAdjust(pWC, pNew, rSize); |
+ rc = whereLoopInsert(pBuilder, pNew); |
+ pNew->nOut = rSize; |
+ if( rc ) break; |
+ }else{ |
+ Bitmask m; |
+ if( pProbe->isCovering ){ |
+ pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED; |
+ m = 0; |
+ }else{ |
+ m = pSrc->colUsed & ~columnsInIndex(pProbe); |
+ pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED; |
+ } |
+ |
+ /* Full scan via index */ |
+ if( b |
+ || !HasRowid(pTab) |
+ || pProbe->pPartIdxWhere!=0 |
+ || ( m==0 |
+ && pProbe->bUnordered==0 |
+ && (pProbe->szIdxRow<pTab->szTabRow) |
+ && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 |
+ && sqlite3GlobalConfig.bUseCis |
+ && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan) |
+ ) |
+ ){ |
+ pNew->iSortIdx = b ? iSortIdx : 0; |
+ |
+ /* The cost of visiting the index rows is N*K, where K is |
+ ** between 1.1 and 3.0, depending on the relative sizes of the |
+ ** index and table rows. */ |
+ pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow; |
+ if( m!=0 ){ |
+ /* If this is a non-covering index scan, add in the cost of |
+ ** doing table lookups. The cost will be 3x the number of |
+ ** lookups. Take into account WHERE clause terms that can be |
+ ** satisfied using just the index, and that do not require a |
+ ** table lookup. */ |
+ LogEst nLookup = rSize + 16; /* Base cost: N*3 */ |
+ int ii; |
+ int iCur = pSrc->iCursor; |
+ WhereClause *pWC2 = &pWInfo->sWC; |
+ for(ii=0; ii<pWC2->nTerm; ii++){ |
+ WhereTerm *pTerm = &pWC2->a[ii]; |
+ if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){ |
+ break; |
+ } |
+ /* pTerm can be evaluated using just the index. So reduce |
+ ** the expected number of table lookups accordingly */ |
+ if( pTerm->truthProb<=0 ){ |
+ nLookup += pTerm->truthProb; |
+ }else{ |
+ nLookup--; |
+ if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19; |
+ } |
+ } |
+ |
+ pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup); |
+ } |
+ ApplyCostMultiplier(pNew->rRun, pTab->costMult); |
+ whereLoopOutputAdjust(pWC, pNew, rSize); |
+ rc = whereLoopInsert(pBuilder, pNew); |
+ pNew->nOut = rSize; |
+ if( rc ) break; |
+ } |
+ } |
+ |
+ rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); |
+#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
+ sqlite3Stat4ProbeFree(pBuilder->pRec); |
+ pBuilder->nRecValid = 0; |
+ pBuilder->pRec = 0; |
+#endif |
+ |
+ /* If there was an INDEXED BY clause, then only that one index is |
+ ** considered. */ |
+ if( pSrc->pIBIndex ) break; |
+ } |
+ return rc; |
+} |
+ |
+#ifndef SQLITE_OMIT_VIRTUALTABLE |
+ |
+/* |
+** Argument pIdxInfo is already populated with all constraints that may |
+** be used by the virtual table identified by pBuilder->pNew->iTab. This |
+** function marks a subset of those constraints usable, invokes the |
+** xBestIndex method and adds the returned plan to pBuilder. |
+** |
+** A constraint is marked usable if: |
+** |
+** * Argument mUsable indicates that its prerequisites are available, and |
+** |
+** * It is not one of the operators specified in the mExclude mask passed |
+** as the fourth argument (which in practice is either WO_IN or 0). |
+** |
+** Argument mPrereq is a mask of tables that must be scanned before the |
+** virtual table in question. These are added to the plans prerequisites |
+** before it is added to pBuilder. |
+** |
+** Output parameter *pbIn is set to true if the plan added to pBuilder |
+** uses one or more WO_IN terms, or false otherwise. |
+*/ |
+static int whereLoopAddVirtualOne( |
+ WhereLoopBuilder *pBuilder, |
+ Bitmask mPrereq, /* Mask of tables that must be used. */ |
+ Bitmask mUsable, /* Mask of usable tables */ |
+ u16 mExclude, /* Exclude terms using these operators */ |
+ sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */ |
+ u16 mNoOmit, /* Do not omit these constraints */ |
+ int *pbIn /* OUT: True if plan uses an IN(...) op */ |
+){ |
+ WhereClause *pWC = pBuilder->pWC; |
+ struct sqlite3_index_constraint *pIdxCons; |
+ struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage; |
+ int i; |
+ int mxTerm; |
+ int rc = SQLITE_OK; |
+ WhereLoop *pNew = pBuilder->pNew; |
+ Parse *pParse = pBuilder->pWInfo->pParse; |
+ struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab]; |
+ int nConstraint = pIdxInfo->nConstraint; |
+ |
+ assert( (mUsable & mPrereq)==mPrereq ); |
+ *pbIn = 0; |
+ pNew->prereq = mPrereq; |
+ |
+ /* Set the usable flag on the subset of constraints identified by |
+ ** arguments mUsable and mExclude. */ |
+ pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; |
+ for(i=0; i<nConstraint; i++, pIdxCons++){ |
+ WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset]; |
+ pIdxCons->usable = 0; |
+ if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight |
+ && (pTerm->eOperator & mExclude)==0 |
+ ){ |
+ pIdxCons->usable = 1; |
+ } |
+ } |
+ |
+ /* Initialize the output fields of the sqlite3_index_info structure */ |
+ memset(pUsage, 0, sizeof(pUsage[0])*nConstraint); |
+ assert( pIdxInfo->needToFreeIdxStr==0 ); |
+ pIdxInfo->idxStr = 0; |
+ pIdxInfo->idxNum = 0; |
+ pIdxInfo->orderByConsumed = 0; |
+ pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; |
+ pIdxInfo->estimatedRows = 25; |
+ pIdxInfo->idxFlags = 0; |
+ pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed; |
+ |
+ /* Invoke the virtual table xBestIndex() method */ |
+ rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo); |
+ if( rc ) return rc; |
+ |
+ mxTerm = -1; |
+ assert( pNew->nLSlot>=nConstraint ); |
+ for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0; |
+ pNew->u.vtab.omitMask = 0; |
+ pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; |
+ for(i=0; i<nConstraint; i++, pIdxCons++){ |
+ int iTerm; |
+ if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){ |
+ WhereTerm *pTerm; |
+ int j = pIdxCons->iTermOffset; |
+ if( iTerm>=nConstraint |
+ || j<0 |
+ || j>=pWC->nTerm |
+ || pNew->aLTerm[iTerm]!=0 |
+ || pIdxCons->usable==0 |
+ ){ |
+ rc = SQLITE_ERROR; |
+ sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName); |
+ return rc; |
+ } |
+ testcase( iTerm==nConstraint-1 ); |
+ testcase( j==0 ); |
+ testcase( j==pWC->nTerm-1 ); |
+ pTerm = &pWC->a[j]; |
+ pNew->prereq |= pTerm->prereqRight; |
+ assert( iTerm<pNew->nLSlot ); |
+ pNew->aLTerm[iTerm] = pTerm; |
+ if( iTerm>mxTerm ) mxTerm = iTerm; |
+ testcase( iTerm==15 ); |
+ testcase( iTerm==16 ); |
+ if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm; |
+ if( (pTerm->eOperator & WO_IN)!=0 ){ |
+ /* A virtual table that is constrained by an IN clause may not |
+ ** consume the ORDER BY clause because (1) the order of IN terms |
+ ** is not necessarily related to the order of output terms and |
+ ** (2) Multiple outputs from a single IN value will not merge |
+ ** together. */ |
+ pIdxInfo->orderByConsumed = 0; |
+ pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE; |
+ *pbIn = 1; assert( (mExclude & WO_IN)==0 ); |
+ } |
+ } |
+ } |
+ pNew->u.vtab.omitMask &= ~mNoOmit; |
+ |
+ pNew->nLTerm = mxTerm+1; |
+ assert( pNew->nLTerm<=pNew->nLSlot ); |
+ pNew->u.vtab.idxNum = pIdxInfo->idxNum; |
+ pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr; |
+ pIdxInfo->needToFreeIdxStr = 0; |
+ pNew->u.vtab.idxStr = pIdxInfo->idxStr; |
+ pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ? |
+ pIdxInfo->nOrderBy : 0); |
+ 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; |
+ } |
+ rc = whereLoopInsert(pBuilder, pNew); |
+ if( pNew->u.vtab.needFree ){ |
+ sqlite3_free(pNew->u.vtab.idxStr); |
+ pNew->u.vtab.needFree = 0; |
+ } |
+ WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n", |
+ *pbIn, (sqlite3_uint64)mPrereq, |
+ (sqlite3_uint64)(pNew->prereq & ~mPrereq))); |
+ |
+ return rc; |
+} |
+ |
+ |
+/* |
+** 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 mPrereq and |
+** mUnusable are set to 0. Otherwise, mPrereq 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 mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6). |
+** |
+** All the tables in mPrereq must be scanned before the current virtual |
+** table. So any terms for which all prerequisites are satisfied by |
+** mPrereq 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 mPrereq, /* Tables that must be scanned before this one */ |
+ Bitmask mUnusable /* Tables that must be scanned after this one */ |
+){ |
+ int rc = SQLITE_OK; /* Return code */ |
+ WhereInfo *pWInfo; /* WHERE analysis context */ |
+ Parse *pParse; /* The parsing context */ |
+ WhereClause *pWC; /* The WHERE clause */ |
+ struct SrcList_item *pSrc; /* The FROM clause term to search */ |
+ sqlite3_index_info *p; /* Object to pass to xBestIndex() */ |
+ int nConstraint; /* Number of constraints in p */ |
+ int bIn; /* True if plan uses IN(...) operator */ |
+ WhereLoop *pNew; |
+ Bitmask mBest; /* Tables used by best possible plan */ |
+ u16 mNoOmit; |
+ |
+ assert( (mPrereq & mUnusable)==0 ); |
+ pWInfo = pBuilder->pWInfo; |
+ pParse = pWInfo->pParse; |
+ pWC = pBuilder->pWC; |
+ pNew = pBuilder->pNew; |
+ pSrc = &pWInfo->pTabList->a[pNew->iTab]; |
+ assert( IsVirtual(pSrc->pTab) ); |
+ p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy, |
+ &mNoOmit); |
+ if( p==0 ) return SQLITE_NOMEM_BKPT; |
+ pNew->rSetup = 0; |
+ pNew->wsFlags = WHERE_VIRTUALTABLE; |
+ pNew->nLTerm = 0; |
+ pNew->u.vtab.needFree = 0; |
+ nConstraint = p->nConstraint; |
+ if( whereLoopResize(pParse->db, pNew, nConstraint) ){ |
+ sqlite3DbFree(pParse->db, p); |
+ return SQLITE_NOMEM_BKPT; |
+ } |
+ |
+ /* First call xBestIndex() with all constraints usable. */ |
+ WHERETRACE(0x40, (" VirtualOne: all usable\n")); |
+ rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn); |
+ |
+ /* If the call to xBestIndex() with all terms enabled produced a plan |
+ ** that does not require any source tables (IOW: a plan with mBest==0), |
+ ** then there is no point in making any further calls to xBestIndex() |
+ ** since they will all return the same result (if the xBestIndex() |
+ ** implementation is sane). */ |
+ if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){ |
+ int seenZero = 0; /* True if a plan with no prereqs seen */ |
+ int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */ |
+ Bitmask mPrev = 0; |
+ Bitmask mBestNoIn = 0; |
+ |
+ /* If the plan produced by the earlier call uses an IN(...) term, call |
+ ** xBestIndex again, this time with IN(...) terms disabled. */ |
+ if( bIn ){ |
+ WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n")); |
+ rc = whereLoopAddVirtualOne( |
+ pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn); |
+ assert( bIn==0 ); |
+ mBestNoIn = pNew->prereq & ~mPrereq; |
+ if( mBestNoIn==0 ){ |
+ seenZero = 1; |
+ seenZeroNoIN = 1; |
+ } |
+ } |
+ |
+ /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq) |
+ ** in the set of terms that apply to the current virtual table. */ |
+ while( rc==SQLITE_OK ){ |
+ int i; |
+ Bitmask mNext = ALLBITS; |
+ assert( mNext>0 ); |
+ for(i=0; i<nConstraint; i++){ |
+ Bitmask mThis = ( |
+ pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq |
+ ); |
+ if( mThis>mPrev && mThis<mNext ) mNext = mThis; |
+ } |
+ mPrev = mNext; |
+ if( mNext==ALLBITS ) break; |
+ if( mNext==mBest || mNext==mBestNoIn ) continue; |
+ WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n", |
+ (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext)); |
+ rc = whereLoopAddVirtualOne( |
+ pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn); |
+ if( pNew->prereq==mPrereq ){ |
+ seenZero = 1; |
+ if( bIn==0 ) seenZeroNoIN = 1; |
+ } |
+ } |
+ |
+ /* If the calls to xBestIndex() in the above loop did not find a plan |
+ ** that requires no source tables at all (i.e. one guaranteed to be |
+ ** usable), make a call here with all source tables disabled */ |
+ if( rc==SQLITE_OK && seenZero==0 ){ |
+ WHERETRACE(0x40, (" VirtualOne: all disabled\n")); |
+ rc = whereLoopAddVirtualOne( |
+ pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn); |
+ if( bIn==0 ) seenZeroNoIN = 1; |
+ } |
+ |
+ /* If the calls to xBestIndex() have so far failed to find a plan |
+ ** that requires no source tables at all and does not use an IN(...) |
+ ** operator, make a final call to obtain one here. */ |
+ if( rc==SQLITE_OK && seenZeroNoIN==0 ){ |
+ WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n")); |
+ rc = whereLoopAddVirtualOne( |
+ pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn); |
+ } |
+ } |
+ |
+ if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr); |
+ sqlite3DbFree(pParse->db, p); |
+ return rc; |
+} |
+#endif /* SQLITE_OMIT_VIRTUALTABLE */ |
+ |
+/* |
+** Add WhereLoop entries to handle OR terms. This works for either |
+** btrees or virtual tables. |
+*/ |
+static int whereLoopAddOr( |
+ WhereLoopBuilder *pBuilder, |
+ Bitmask mPrereq, |
+ Bitmask mUnusable |
+){ |
+ WhereInfo *pWInfo = pBuilder->pWInfo; |
+ WhereClause *pWC; |
+ WhereLoop *pNew; |
+ WhereTerm *pTerm, *pWCEnd; |
+ int rc = SQLITE_OK; |
+ int iCur; |
+ WhereClause tempWC; |
+ WhereLoopBuilder sSubBuild; |
+ WhereOrSet sSum, sCur; |
+ struct SrcList_item *pItem; |
+ |
+ pWC = pBuilder->pWC; |
+ pWCEnd = pWC->a + pWC->nTerm; |
+ pNew = pBuilder->pNew; |
+ memset(&sSum, 0, sizeof(sSum)); |
+ pItem = pWInfo->pTabList->a + pNew->iTab; |
+ iCur = pItem->iCursor; |
+ |
+ for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){ |
+ if( (pTerm->eOperator & WO_OR)!=0 |
+ && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 |
+ ){ |
+ WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc; |
+ WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm]; |
+ WhereTerm *pOrTerm; |
+ int once = 1; |
+ int i, j; |
+ |
+ sSubBuild = *pBuilder; |
+ sSubBuild.pOrderBy = 0; |
+ sSubBuild.pOrSet = &sCur; |
+ |
+ WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm)); |
+ for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){ |
+ if( (pOrTerm->eOperator & WO_AND)!=0 ){ |
+ sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc; |
+ }else if( pOrTerm->leftCursor==iCur ){ |
+ tempWC.pWInfo = pWC->pWInfo; |
+ tempWC.pOuter = pWC; |
+ tempWC.op = TK_AND; |
+ tempWC.nTerm = 1; |
+ tempWC.a = pOrTerm; |
+ sSubBuild.pWC = &tempWC; |
+ }else{ |
+ continue; |
+ } |
+ sCur.n = 0; |
+#ifdef WHERETRACE_ENABLED |
+ WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", |
+ (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm)); |
+ if( sqlite3WhereTrace & 0x400 ){ |
+ sqlite3WhereClausePrint(sSubBuild.pWC); |
+ } |
+#endif |
+#ifndef SQLITE_OMIT_VIRTUALTABLE |
+ if( IsVirtual(pItem->pTab) ){ |
+ rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable); |
+ }else |
+#endif |
+ { |
+ rc = whereLoopAddBtree(&sSubBuild, mPrereq); |
+ } |
+ if( rc==SQLITE_OK ){ |
+ rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable); |
+ } |
+ assert( rc==SQLITE_OK || sCur.n==0 ); |
+ if( sCur.n==0 ){ |
+ sSum.n = 0; |
+ break; |
+ }else if( once ){ |
+ whereOrMove(&sSum, &sCur); |
+ once = 0; |
+ }else{ |
+ WhereOrSet sPrev; |
+ whereOrMove(&sPrev, &sSum); |
+ sSum.n = 0; |
+ for(i=0; i<sPrev.n; i++){ |
+ for(j=0; j<sCur.n; j++){ |
+ whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq, |
+ sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun), |
+ sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut)); |
+ } |
+ } |
+ } |
+ } |
+ pNew->nLTerm = 1; |
+ pNew->aLTerm[0] = pTerm; |
+ pNew->wsFlags = WHERE_MULTI_OR; |
+ pNew->rSetup = 0; |
+ pNew->iSortIdx = 0; |
+ memset(&pNew->u, 0, sizeof(pNew->u)); |
+ for(i=0; rc==SQLITE_OK && i<sSum.n; i++){ |
+ /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs |
+ ** of all sub-scans required by the OR-scan. However, due to rounding |
+ ** errors, it may be that the cost of the OR-scan is equal to its |
+ ** most expensive sub-scan. Add the smallest possible penalty |
+ ** (equivalent to multiplying the cost by 1.07) to ensure that |
+ ** this does not happen. Otherwise, for WHERE clauses such as the |
+ ** following where there is an index on "y": |
+ ** |
+ ** WHERE likelihood(x=?, 0.99) OR y=? |
+ ** |
+ ** the planner may elect to "OR" together a full-table scan and an |
+ ** index lookup. And other similarly odd results. */ |
+ pNew->rRun = sSum.a[i].rRun + 1; |
+ pNew->nOut = sSum.a[i].nOut; |
+ pNew->prereq = sSum.a[i].prereq; |
+ rc = whereLoopInsert(pBuilder, pNew); |
+ } |
+ WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm)); |
+ } |
+ } |
+ return rc; |
+} |
+ |
+/* |
+** Add all WhereLoop objects for all tables |
+*/ |
+static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ |
+ WhereInfo *pWInfo = pBuilder->pWInfo; |
+ Bitmask mPrereq = 0; |
+ Bitmask mPrior = 0; |
+ int iTab; |
+ SrcList *pTabList = pWInfo->pTabList; |
+ struct SrcList_item *pItem; |
+ struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel]; |
+ sqlite3 *db = pWInfo->pParse->db; |
+ int rc = SQLITE_OK; |
+ 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; pItem<pEnd; iTab++, pItem++){ |
+ Bitmask mUnusable = 0; |
+ pNew->iTab = iTab; |
+ 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. */ |
+ mPrereq = mPrior; |
+ } |
+ priorJointype = pItem->fg.jointype; |
+#ifndef SQLITE_OMIT_VIRTUALTABLE |
+ if( IsVirtual(pItem->pTab) ){ |
+ 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, mPrereq, mUnusable); |
+ }else |
+#endif /* SQLITE_OMIT_VIRTUALTABLE */ |
+ { |
+ rc = whereLoopAddBtree(pBuilder, mPrereq); |
+ } |
+ if( rc==SQLITE_OK ){ |
+ rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable); |
+ } |
+ mPrior |= pNew->maskSelf; |
+ if( rc || db->mallocFailed ) break; |
+ } |
+ |
+ whereLoopClear(db, pNew); |
+ return rc; |
+} |
+ |
+/* |
+** Examine a WherePath (with the addition of the extra WhereLoop of the 5th |
+** parameters) to see if it outputs rows in the requested ORDER BY |
+** (or GROUP BY) without requiring a separate sort operation. Return N: |
+** |
+** N>0: N terms of the ORDER BY clause are satisfied |
+** N==0: No terms of the ORDER BY clause are satisfied |
+** N<0: Unknown yet how many terms of ORDER BY might be satisfied. |
+** |
+** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as |
+** strict. With GROUP BY and DISTINCT the only requirement is that |
+** equivalent rows appear immediately adjacent to one another. GROUP BY |
+** and DISTINCT do not require rows to appear in any particular order as long |
+** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT |
+** the pOrderBy terms can be matched in any order. With ORDER BY, the |
+** pOrderBy terms must be matched in strict left-to-right order. |
+*/ |
+static i8 wherePathSatisfiesOrderBy( |
+ WhereInfo *pWInfo, /* The WHERE clause */ |
+ ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */ |
+ WherePath *pPath, /* The WherePath to check */ |
+ u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */ |
+ u16 nLoop, /* Number of entries in pPath->aLoop[] */ |
+ WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */ |
+ Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */ |
+){ |
+ u8 revSet; /* True if rev is known */ |
+ u8 rev; /* Composite sort order */ |
+ u8 revIdx; /* Index sort order */ |
+ u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */ |
+ u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */ |
+ u8 isMatch; /* iColumn matches a term of the ORDER BY clause */ |
+ u16 eqOpMask; /* Allowed equality operators */ |
+ u16 nKeyCol; /* Number of key columns in pIndex */ |
+ u16 nColumn; /* Total number of ordered columns in the index */ |
+ u16 nOrderBy; /* Number terms in the ORDER BY clause */ |
+ int iLoop; /* Index of WhereLoop in pPath being processed */ |
+ int i, j; /* Loop counters */ |
+ int iCur; /* Cursor number for current WhereLoop */ |
+ int iColumn; /* A column number within table iCur */ |
+ WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */ |
+ WhereTerm *pTerm; /* A single term of the WHERE clause */ |
+ Expr *pOBExpr; /* An expression from the ORDER BY clause */ |
+ CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */ |
+ Index *pIndex; /* The index associated with pLoop */ |
+ sqlite3 *db = pWInfo->pParse->db; /* Database connection */ |
+ Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */ |
+ Bitmask obDone; /* Mask of all ORDER BY terms */ |
+ Bitmask orderDistinctMask; /* Mask of all well-ordered loops */ |
+ Bitmask ready; /* Mask of inner loops */ |
+ |
+ /* |
+ ** We say the WhereLoop is "one-row" if it generates no more than one |
+ ** row of output. A WhereLoop is one-row if all of the following are true: |
+ ** (a) All index columns match with WHERE_COLUMN_EQ. |
+ ** (b) The index is unique |
+ ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row. |
+ ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags. |
+ ** |
+ ** We say the WhereLoop is "order-distinct" if the set of columns from |
+ ** that WhereLoop that are in the ORDER BY clause are different for every |
+ ** row of the WhereLoop. Every one-row WhereLoop is automatically |
+ ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause |
+ ** is not order-distinct. To be order-distinct is not quite the same as being |
+ ** UNIQUE since a UNIQUE column or index can have multiple rows that |
+ ** are NULL and NULL values are equivalent for the purpose of order-distinct. |
+ ** To be order-distinct, the columns must be UNIQUE and NOT NULL. |
+ ** |
+ ** The rowid for a table is always UNIQUE and NOT NULL so whenever the |
+ ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is |
+ ** automatically order-distinct. |
+ */ |
+ |
+ assert( pOrderBy!=0 ); |
+ if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0; |
+ |
+ nOrderBy = pOrderBy->nExpr; |
+ testcase( nOrderBy==BMS-1 ); |
+ if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */ |
+ isOrderDistinct = 1; |
+ obDone = MASKBIT(nOrderBy)-1; |
+ orderDistinctMask = 0; |
+ ready = 0; |
+ eqOpMask = WO_EQ | WO_IS | WO_ISNULL; |
+ if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN; |
+ for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){ |
+ if( iLoop>0 ) ready |= pLoop->maskSelf; |
+ if( iLoop<nLoop ){ |
+ pLoop = pPath->aLoop[iLoop]; |
+ if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue; |
+ }else{ |
+ pLoop = pLast; |
+ } |
+ if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){ |
+ if( pLoop->u.vtab.isOrdered ) obSat = obDone; |
+ break; |
+ } |
+ iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor; |
+ |
+ /* Mark off any ORDER BY term X that is a column in the table of |
+ ** the current loop for which there is term in the WHERE |
+ ** clause of the form X IS NULL or X=? that reference only outer |
+ ** loops. |
+ */ |
+ for(i=0; i<nOrderBy; i++){ |
+ if( MASKBIT(i) & obSat ) continue; |
+ pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr); |
+ if( pOBExpr->op!=TK_COLUMN ) continue; |
+ if( pOBExpr->iTable!=iCur ) continue; |
+ pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, |
+ ~ready, eqOpMask, 0); |
+ if( pTerm==0 ) continue; |
+ if( pTerm->eOperator==WO_IN ){ |
+ /* IN terms are only valid for sorting in the ORDER BY LIMIT |
+ ** optimization, and then only if they are actually used |
+ ** by the query plan */ |
+ assert( wctrlFlags & WHERE_ORDERBY_LIMIT ); |
+ for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){} |
+ if( j>=pLoop->nLTerm ) continue; |
+ } |
+ 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; |
+ z1 = pColl->zName; |
+ pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr); |
+ if( !pColl ) pColl = db->pDfltColl; |
+ z2 = pColl->zName; |
+ if( sqlite3StrICmp(z1, z2)!=0 ) continue; |
+ testcase( pTerm->pExpr->op==TK_IS ); |
+ } |
+ obSat |= MASKBIT(i); |
+ } |
+ |
+ if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){ |
+ if( pLoop->wsFlags & WHERE_IPK ){ |
+ pIndex = 0; |
+ nKeyCol = 0; |
+ nColumn = 1; |
+ }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){ |
+ return 0; |
+ }else{ |
+ nKeyCol = pIndex->nKeyCol; |
+ nColumn = pIndex->nColumn; |
+ assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) ); |
+ assert( pIndex->aiColumn[nColumn-1]==XN_ROWID |
+ || !HasRowid(pIndex->pTable)); |
+ isOrderDistinct = IsUniqueIndex(pIndex); |
+ } |
+ |
+ /* Loop through all columns of the index and deal with the ones |
+ ** that are not constrained by == or IN. |
+ */ |
+ rev = revSet = 0; |
+ distinctColumns = 0; |
+ for(j=0; j<nColumn; j++){ |
+ u8 bOnce = 1; /* True to run the ORDER BY search loop */ |
+ |
+ assert( j>=pLoop->u.btree.nEq |
+ || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip) |
+ ); |
+ if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){ |
+ u16 eOp = pLoop->aLTerm[j]->eOperator; |
+ |
+ /* Skip over == and IS and ISNULL terms. (Also skip IN terms when |
+ ** doing WHERE_ORDERBY_LIMIT processing). |
+ ** |
+ ** If the current term is a column of an ((?,?) IN (SELECT...)) |
+ ** expression for which the SELECT returns more than one column, |
+ ** check that it is the only column used by this loop. Otherwise, |
+ ** if it is one of two or more, none of the columns can be |
+ ** considered to match an ORDER BY term. */ |
+ if( (eOp & eqOpMask)!=0 ){ |
+ if( eOp & WO_ISNULL ){ |
+ testcase( isOrderDistinct ); |
+ isOrderDistinct = 0; |
+ } |
+ continue; |
+ }else if( ALWAYS(eOp & WO_IN) ){ |
+ /* ALWAYS() justification: eOp is an equality operator due to the |
+ ** j<pLoop->u.btree.nEq constraint above. Any equality other |
+ ** than WO_IN is captured by the previous "if". So this one |
+ ** always has to be WO_IN. */ |
+ Expr *pX = pLoop->aLTerm[j]->pExpr; |
+ for(i=j+1; i<pLoop->u.btree.nEq; i++){ |
+ if( pLoop->aLTerm[i]->pExpr==pX ){ |
+ assert( (pLoop->aLTerm[i]->eOperator & WO_IN) ); |
+ bOnce = 0; |
+ break; |
+ } |
+ } |
+ } |
+ } |
+ |
+ /* Get the column number in the table (iColumn) and sort order |
+ ** (revIdx) for the j-th column of the index. |
+ */ |
+ if( pIndex ){ |
+ iColumn = pIndex->aiColumn[j]; |
+ revIdx = pIndex->aSortOrder[j]; |
+ if( iColumn==pIndex->pTable->iPKey ) iColumn = -1; |
+ }else{ |
+ iColumn = XN_ROWID; |
+ revIdx = 0; |
+ } |
+ |
+ /* An unconstrained column that might be NULL means that this |
+ ** WhereLoop is not well-ordered |
+ */ |
+ if( isOrderDistinct |
+ && iColumn>=0 |
+ && j>=pLoop->u.btree.nEq |
+ && pIndex->pTable->aCol[iColumn].notNull==0 |
+ ){ |
+ isOrderDistinct = 0; |
+ } |
+ |
+ /* Find the ORDER BY term that corresponds to the j-th column |
+ ** of the index and mark that ORDER BY term off |
+ */ |
+ isMatch = 0; |
+ for(i=0; bOnce && i<nOrderBy; i++){ |
+ if( MASKBIT(i) & obSat ) continue; |
+ pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr); |
+ testcase( wctrlFlags & WHERE_GROUPBY ); |
+ testcase( wctrlFlags & WHERE_DISTINCTBY ); |
+ if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0; |
+ 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; |
+ if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; |
+ } |
+ isMatch = 1; |
+ break; |
+ } |
+ if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){ |
+ /* Make sure the sort order is compatible in an ORDER BY clause. |
+ ** Sort order is irrelevant for a GROUP BY clause. */ |
+ if( revSet ){ |
+ if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0; |
+ }else{ |
+ rev = revIdx ^ pOrderBy->a[i].sortOrder; |
+ if( rev ) *pRevMask |= MASKBIT(iLoop); |
+ revSet = 1; |
+ } |
+ } |
+ if( isMatch ){ |
+ if( iColumn==XN_ROWID ){ |
+ testcase( distinctColumns==0 ); |
+ distinctColumns = 1; |
+ } |
+ obSat |= MASKBIT(i); |
+ }else{ |
+ /* No match found */ |
+ if( j==0 || j<nKeyCol ){ |
+ testcase( isOrderDistinct!=0 ); |
+ isOrderDistinct = 0; |
+ } |
+ break; |
+ } |
+ } /* end Loop over all index columns */ |
+ if( distinctColumns ){ |
+ testcase( isOrderDistinct==0 ); |
+ isOrderDistinct = 1; |
+ } |
+ } /* end-if not one-row */ |
+ |
+ /* Mark off any other ORDER BY terms that reference pLoop */ |
+ if( isOrderDistinct ){ |
+ orderDistinctMask |= pLoop->maskSelf; |
+ for(i=0; i<nOrderBy; i++){ |
+ Expr *p; |
+ Bitmask mTerm; |
+ if( MASKBIT(i) & obSat ) continue; |
+ p = pOrderBy->a[i].pExpr; |
+ mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p); |
+ if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue; |
+ if( (mTerm&~orderDistinctMask)==0 ){ |
+ obSat |= MASKBIT(i); |
+ } |
+ } |
+ } |
+ } /* End the loop over all WhereLoops from outer-most down to inner-most */ |
+ if( obSat==obDone ) return (i8)nOrderBy; |
+ if( !isOrderDistinct ){ |
+ for(i=nOrderBy-1; i>0; i--){ |
+ Bitmask m = MASKBIT(i) - 1; |
+ if( (obSat&m)==m ) return i; |
+ } |
+ return 0; |
+ } |
+ return -1; |
+} |
+ |
+ |
+/* |
+** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(), |
+** the planner assumes that the specified pOrderBy list is actually a GROUP |
+** BY clause - and so any order that groups rows as required satisfies the |
+** request. |
+** |
+** Normally, in this case it is not possible for the caller to determine |
+** whether or not the rows are really being delivered in sorted order, or |
+** just in some other order that provides the required grouping. However, |
+** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then |
+** this function may be called on the returned WhereInfo object. It returns |
+** true if the rows really will be sorted in the specified order, or false |
+** otherwise. |
+** |
+** For example, assuming: |
+** |
+** CREATE INDEX i1 ON t1(x, Y); |
+** |
+** then |
+** |
+** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1 |
+** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0 |
+*/ |
+SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){ |
+ assert( pWInfo->wctrlFlags & WHERE_GROUPBY ); |
+ assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP ); |
+ return pWInfo->sorted; |
+} |
+ |
+#ifdef WHERETRACE_ENABLED |
+/* For debugging use only: */ |
+static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){ |
+ static char zName[65]; |
+ int i; |
+ for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; } |
+ if( pLast ) zName[i++] = pLast->cId; |
+ zName[i] = 0; |
+ return zName; |
+} |
+#endif |
+ |
+/* |
+** Return the cost of sorting nRow rows, assuming that the keys have |
+** nOrderby columns and that the first nSorted columns are already in |
+** order. |
+*/ |
+static LogEst whereSortingCost( |
+ WhereInfo *pWInfo, |
+ LogEst nRow, |
+ int nOrderBy, |
+ int nSorted |
+){ |
+ /* TUNING: Estimated cost of a full external sort, where N is |
+ ** the number of rows to sort is: |
+ ** |
+ ** cost = (3.0 * N * log(N)). |
+ ** |
+ ** Or, if the order-by clause has X terms but only the last Y |
+ ** terms are out of order, then block-sorting will reduce the |
+ ** sorting cost to: |
+ ** |
+ ** cost = (3.0 * N * log(N)) * (Y/X) |
+ ** |
+ ** The (Y/X) term is implemented using stack variable rScale |
+ ** below. */ |
+ LogEst rScale, rSortCost; |
+ assert( nOrderBy>0 && 66==sqlite3LogEst(100) ); |
+ rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66; |
+ rSortCost = nRow + rScale + 16; |
+ |
+ /* Multiple by log(M) where M is the number of output rows. |
+ ** Use the LIMIT for M if it is smaller */ |
+ if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){ |
+ nRow = pWInfo->iLimit; |
+ } |
+ rSortCost += estLog(nRow); |
+ return rSortCost; |
+} |
+ |
+/* |
+** Given the list of WhereLoop objects at pWInfo->pLoops, this routine |
+** attempts to find the lowest cost path that visits each WhereLoop |
+** once. This path is then loaded into the pWInfo->a[].pWLoop fields. |
+** |
+** Assume that the total number of output rows that will need to be sorted |
+** will be nRowEst (in the 10*log2 representation). Or, ignore sorting |
+** costs if nRowEst==0. |
+** |
+** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation |
+** error occurs. |
+*/ |
+static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ |
+ int mxChoice; /* Maximum number of simultaneous paths tracked */ |
+ int nLoop; /* Number of terms in the join */ |
+ Parse *pParse; /* Parsing context */ |
+ sqlite3 *db; /* The database connection */ |
+ int iLoop; /* Loop counter over the terms of the join */ |
+ int ii, jj; /* Loop counters */ |
+ int mxI = 0; /* Index of next entry to replace */ |
+ int nOrderBy; /* Number of ORDER BY clause terms */ |
+ LogEst mxCost = 0; /* Maximum cost of a set of paths */ |
+ LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */ |
+ int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */ |
+ WherePath *aFrom; /* All nFrom paths at the previous level */ |
+ WherePath *aTo; /* The nTo best paths at the current level */ |
+ WherePath *pFrom; /* An element of aFrom[] that we are working on */ |
+ WherePath *pTo; /* An element of aTo[] that we are working on */ |
+ WhereLoop *pWLoop; /* One of the WhereLoop objects */ |
+ WhereLoop **pX; /* Used to divy up the pSpace memory */ |
+ LogEst *aSortCost = 0; /* Sorting and partial sorting costs */ |
+ char *pSpace; /* Temporary memory used by this routine */ |
+ int nSpace; /* Bytes of space allocated at pSpace */ |
+ |
+ pParse = pWInfo->pParse; |
+ db = pParse->db; |
+ nLoop = pWInfo->nLevel; |
+ /* TUNING: For simple queries, only the best path is tracked. |
+ ** For 2-way joins, the 5 best paths are followed. |
+ ** For joins of 3 or more tables, track the 10 best paths */ |
+ mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10); |
+ assert( nLoop<=pWInfo->pTabList->nSrc ); |
+ WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst)); |
+ |
+ /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this |
+ ** case the purpose of this call is to estimate the number of rows returned |
+ ** by the overall query. Once this estimate has been obtained, the caller |
+ ** will invoke this function a second time, passing the estimate as the |
+ ** nRowEst parameter. */ |
+ if( pWInfo->pOrderBy==0 || nRowEst==0 ){ |
+ nOrderBy = 0; |
+ }else{ |
+ nOrderBy = pWInfo->pOrderBy->nExpr; |
+ } |
+ |
+ /* Allocate and initialize space for aTo, aFrom and aSortCost[] */ |
+ nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2; |
+ nSpace += sizeof(LogEst) * nOrderBy; |
+ pSpace = sqlite3DbMallocRawNN(db, nSpace); |
+ if( pSpace==0 ) return SQLITE_NOMEM_BKPT; |
+ aTo = (WherePath*)pSpace; |
+ aFrom = aTo+mxChoice; |
+ memset(aFrom, 0, sizeof(aFrom[0])); |
+ pX = (WhereLoop**)(aFrom+mxChoice); |
+ for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){ |
+ pFrom->aLoop = pX; |
+ } |
+ if( nOrderBy ){ |
+ /* If there is an ORDER BY clause and it is not being ignored, set up |
+ ** space for the aSortCost[] array. Each element of the aSortCost array |
+ ** is either zero - meaning it has not yet been initialized - or the |
+ ** cost of sorting nRowEst rows of data where the first X terms of |
+ ** the ORDER BY clause are already in order, where X is the array |
+ ** index. */ |
+ aSortCost = (LogEst*)pX; |
+ memset(aSortCost, 0, sizeof(LogEst) * nOrderBy); |
+ } |
+ assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] ); |
+ assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX ); |
+ |
+ /* Seed the search with a single WherePath containing zero WhereLoops. |
+ ** |
+ ** 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, 48); assert( 48==sqlite3LogEst(28) ); |
+ nFrom = 1; |
+ assert( aFrom[0].isOrdered==0 ); |
+ if( nOrderBy ){ |
+ /* If nLoop is zero, then there are no FROM terms in the query. Since |
+ ** in this case the query may return a maximum of one row, the results |
+ ** are already in the requested order. Set isOrdered to nOrderBy to |
+ ** indicate this. Or, if nLoop is greater than zero, set isOrdered to |
+ ** -1, indicating that the result set may or may not be ordered, |
+ ** depending on the loops added to the current plan. */ |
+ aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy; |
+ } |
+ |
+ /* Compute successively longer WherePaths using the previous generation |
+ ** of WherePaths as the basis for the next. Keep track of the mxChoice |
+ ** best paths at each generation */ |
+ for(iLoop=0; iLoop<nLoop; iLoop++){ |
+ nTo = 0; |
+ for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){ |
+ for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ |
+ LogEst nOut; /* Rows visited by (pFrom+pWLoop) */ |
+ LogEst rCost; /* Cost of path (pFrom+pWLoop) */ |
+ LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */ |
+ i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */ |
+ Bitmask maskNew; /* Mask of src visited by (..) */ |
+ Bitmask revMask = 0; /* Mask of rev-order loops for (..) */ |
+ |
+ if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue; |
+ if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue; |
+ if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){ |
+ /* Do not use an automatic index if the this loop is expected |
+ ** to run less than 2 times. */ |
+ assert( 10==sqlite3LogEst(2) ); |
+ continue; |
+ } |
+ /* At this point, pWLoop is a candidate to be the next loop. |
+ ** Compute its cost */ |
+ rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow); |
+ rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted); |
+ nOut = pFrom->nRow + pWLoop->nOut; |
+ maskNew = pFrom->maskLoop | pWLoop->maskSelf; |
+ if( isOrdered<0 ){ |
+ isOrdered = wherePathSatisfiesOrderBy(pWInfo, |
+ pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags, |
+ iLoop, pWLoop, &revMask); |
+ }else{ |
+ revMask = pFrom->revLoop; |
+ } |
+ if( isOrdered>=0 && isOrdered<nOrderBy ){ |
+ if( aSortCost[isOrdered]==0 ){ |
+ aSortCost[isOrdered] = whereSortingCost( |
+ pWInfo, nRowEst, nOrderBy, isOrdered |
+ ); |
+ } |
+ rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]); |
+ |
+ WHERETRACE(0x002, |
+ ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n", |
+ aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy, |
+ rUnsorted, rCost)); |
+ }else{ |
+ rCost = rUnsorted; |
+ } |
+ |
+ /* Check to see if pWLoop should be added to the set of |
+ ** mxChoice best-so-far paths. |
+ ** |
+ ** First look for an existing path among best-so-far paths |
+ ** that covers the same set of loops and has the same isOrdered |
+ ** setting as the current path candidate. |
+ ** |
+ ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent |
+ ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range |
+ ** of legal values for isOrdered, -1..64. |
+ */ |
+ for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){ |
+ if( pTo->maskLoop==maskNew |
+ && ((pTo->isOrdered^isOrdered)&0x80)==0 |
+ ){ |
+ testcase( jj==nTo-1 ); |
+ break; |
+ } |
+ } |
+ if( jj>=nTo ){ |
+ /* None of the existing best-so-far paths match the candidate. */ |
+ if( nTo>=mxChoice |
+ && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted)) |
+ ){ |
+ /* The current candidate is no better than any of the mxChoice |
+ ** paths currently in the best-so-far buffer. So discard |
+ ** this candidate as not viable. */ |
+#ifdef WHERETRACE_ENABLED /* 0x4 */ |
+ if( sqlite3WhereTrace&0x4 ){ |
+ sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n", |
+ wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, |
+ isOrdered>=0 ? isOrdered+'0' : '?'); |
+ } |
+#endif |
+ continue; |
+ } |
+ /* If we reach this points it means that the new candidate path |
+ ** needs to be added to the set of best-so-far paths. */ |
+ if( nTo<mxChoice ){ |
+ /* Increase the size of the aTo set by one */ |
+ jj = nTo++; |
+ }else{ |
+ /* New path replaces the prior worst to keep count below mxChoice */ |
+ jj = mxI; |
+ } |
+ pTo = &aTo[jj]; |
+#ifdef WHERETRACE_ENABLED /* 0x4 */ |
+ if( sqlite3WhereTrace&0x4 ){ |
+ sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n", |
+ wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, |
+ isOrdered>=0 ? isOrdered+'0' : '?'); |
+ } |
+#endif |
+ }else{ |
+ /* Control reaches here if best-so-far path pTo=aTo[jj] covers the |
+ ** same set of loops and has the sam isOrdered setting as the |
+ ** candidate path. Check to see if the candidate should replace |
+ ** pTo or if the candidate should be skipped */ |
+ if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){ |
+#ifdef WHERETRACE_ENABLED /* 0x4 */ |
+ if( sqlite3WhereTrace&0x4 ){ |
+ sqlite3DebugPrintf( |
+ "Skip %s cost=%-3d,%3d order=%c", |
+ wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, |
+ isOrdered>=0 ? isOrdered+'0' : '?'); |
+ sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n", |
+ wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, |
+ pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); |
+ } |
+#endif |
+ /* Discard the candidate path from further consideration */ |
+ testcase( pTo->rCost==rCost ); |
+ continue; |
+ } |
+ testcase( pTo->rCost==rCost+1 ); |
+ /* Control reaches here if the candidate path is better than the |
+ ** pTo path. Replace pTo with the candidate. */ |
+#ifdef WHERETRACE_ENABLED /* 0x4 */ |
+ if( sqlite3WhereTrace&0x4 ){ |
+ sqlite3DebugPrintf( |
+ "Update %s cost=%-3d,%3d order=%c", |
+ wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, |
+ isOrdered>=0 ? isOrdered+'0' : '?'); |
+ sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n", |
+ wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, |
+ pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); |
+ } |
+#endif |
+ } |
+ /* pWLoop is a winner. Add it to the set of best so far */ |
+ pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf; |
+ pTo->revLoop = revMask; |
+ pTo->nRow = nOut; |
+ pTo->rCost = rCost; |
+ pTo->rUnsorted = rUnsorted; |
+ pTo->isOrdered = isOrdered; |
+ memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop); |
+ pTo->aLoop[iLoop] = pWLoop; |
+ if( nTo>=mxChoice ){ |
+ mxI = 0; |
+ mxCost = aTo[0].rCost; |
+ mxUnsorted = aTo[0].nRow; |
+ for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){ |
+ if( pTo->rCost>mxCost |
+ || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) |
+ ){ |
+ mxCost = pTo->rCost; |
+ mxUnsorted = pTo->rUnsorted; |
+ mxI = jj; |
+ } |
+ } |
+ } |
+ } |
+ } |
+ |
+#ifdef WHERETRACE_ENABLED /* >=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", |
+ wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, |
+ pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?'); |
+ if( pTo->isOrdered>0 ){ |
+ sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); |
+ }else{ |
+ sqlite3DebugPrintf("\n"); |
+ } |
+ } |
+ } |
+#endif |
+ |
+ /* Swap the roles of aFrom and aTo for the next generation */ |
+ pFrom = aTo; |
+ aTo = aFrom; |
+ aFrom = pFrom; |
+ nFrom = nTo; |
+ } |
+ |
+ if( nFrom==0 ){ |
+ sqlite3ErrorMsg(pParse, "no query solution"); |
+ sqlite3DbFree(db, pSpace); |
+ return SQLITE_ERROR; |
+ } |
+ |
+ /* Find the lowest cost path. pFrom will be left pointing to that path */ |
+ pFrom = aFrom; |
+ for(ii=1; ii<nFrom; ii++){ |
+ if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii]; |
+ } |
+ assert( pWInfo->nLevel==nLoop ); |
+ /* Load the lowest cost path into pWInfo */ |
+ for(iLoop=0; iLoop<nLoop; iLoop++){ |
+ WhereLevel *pLevel = pWInfo->a + iLoop; |
+ pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop]; |
+ pLevel->iFrom = pWLoop->iTab; |
+ pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor; |
+ } |
+ if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 |
+ && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0 |
+ && pWInfo->eDistinct==WHERE_DISTINCT_NOOP |
+ && nRowEst |
+ ){ |
+ Bitmask notUsed; |
+ int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinctSet, pFrom, |
+ WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], ¬Used); |
+ if( rc==pWInfo->pDistinctSet->nExpr ){ |
+ pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; |
+ } |
+ } |
+ if( pWInfo->pOrderBy ){ |
+ if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){ |
+ if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){ |
+ pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; |
+ } |
+ }else{ |
+ pWInfo->nOBSat = pFrom->isOrdered; |
+ pWInfo->revMask = pFrom->revLoop; |
+ if( pWInfo->nOBSat<=0 ){ |
+ pWInfo->nOBSat = 0; |
+ if( nLoop>0 ){ |
+ u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags; |
+ if( (wsFlags & WHERE_ONEROW)==0 |
+ && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN) |
+ ){ |
+ Bitmask m = 0; |
+ int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom, |
+ WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m); |
+ testcase( wsFlags & WHERE_IPK ); |
+ testcase( wsFlags & WHERE_COLUMN_IN ); |
+ if( rc==pWInfo->pOrderBy->nExpr ){ |
+ pWInfo->bOrderedInnerLoop = 1; |
+ pWInfo->revMask = m; |
+ } |
+ } |
+ } |
+ } |
+ } |
+ if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP) |
+ && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0 |
+ ){ |
+ Bitmask revMask = 0; |
+ int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, |
+ pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask |
+ ); |
+ assert( pWInfo->sorted==0 ); |
+ if( nOrder==pWInfo->pOrderBy->nExpr ){ |
+ pWInfo->sorted = 1; |
+ pWInfo->revMask = revMask; |
+ } |
+ } |
+ } |
+ |
+ |
+ pWInfo->nRowOut = pFrom->nRow; |
+ |
+ /* Free temporary memory and return success */ |
+ sqlite3DbFree(db, pSpace); |
+ return SQLITE_OK; |
+} |
+ |
+/* |
+** Most queries use only a single table (they are not joins) and have |
+** simple == constraints against indexed fields. This routine attempts |
+** to plan those simple cases using much less ceremony than the |
+** general-purpose query planner, and thereby yield faster sqlite3_prepare() |
+** times for the common case. |
+** |
+** Return non-zero on success, if this query can be handled by this |
+** no-frills query planner. Return zero if this query needs the |
+** general-purpose query planner. |
+*/ |
+static int whereShortCut(WhereLoopBuilder *pBuilder){ |
+ WhereInfo *pWInfo; |
+ struct SrcList_item *pItem; |
+ WhereClause *pWC; |
+ WhereTerm *pTerm; |
+ WhereLoop *pLoop; |
+ int iCur; |
+ int j; |
+ Table *pTab; |
+ Index *pIdx; |
+ |
+ pWInfo = pBuilder->pWInfo; |
+ if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0; |
+ assert( pWInfo->pTabList->nSrc>=1 ); |
+ pItem = pWInfo->pTabList->a; |
+ pTab = pItem->pTab; |
+ if( IsVirtual(pTab) ) return 0; |
+ if( pItem->fg.isIndexedBy ) return 0; |
+ iCur = pItem->iCursor; |
+ pWC = &pWInfo->sWC; |
+ pLoop = pBuilder->pNew; |
+ pLoop->wsFlags = 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; |
+ pLoop->u.btree.nEq = 1; |
+ /* TUNING: Cost of a rowid lookup is 10 */ |
+ pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */ |
+ }else{ |
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ |
+ int opMask; |
+ assert( pLoop->aLTermSpace==pLoop->aLTerm ); |
+ 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 = 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; |
+ pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; |
+ if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){ |
+ pLoop->wsFlags |= WHERE_IDX_ONLY; |
+ } |
+ pLoop->nLTerm = j; |
+ pLoop->u.btree.nEq = j; |
+ pLoop->u.btree.pIndex = pIdx; |
+ /* TUNING: Cost of a unique index lookup is 15 */ |
+ pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */ |
+ break; |
+ } |
+ } |
+ if( pLoop->wsFlags ){ |
+ pLoop->nOut = (LogEst)1; |
+ pWInfo->a[0].pWLoop = pLoop; |
+ pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); |
+ pWInfo->a[0].iTabCur = iCur; |
+ pWInfo->nRowOut = 1; |
+ if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr; |
+ if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ |
+ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; |
+ } |
+#ifdef SQLITE_DEBUG |
+ pLoop->cId = '0'; |
+#endif |
+ return 1; |
+ } |
+ return 0; |
+} |
+ |
+/* |
+** Generate the beginning of the loop used for WHERE clause processing. |
+** The return value is a pointer to an opaque structure that contains |
+** information needed to terminate the loop. Later, the calling routine |
+** should invoke sqlite3WhereEnd() with the return value of this function |
+** in order to complete the WHERE clause processing. |
+** |
+** If an error occurs, this routine returns NULL. |
+** |
+** The basic idea is to do a nested loop, one loop for each table in |
+** the FROM clause of a select. (INSERT and UPDATE statements are the |
+** same as a SELECT with only a single table in the FROM clause.) For |
+** example, if the SQL is this: |
+** |
+** SELECT * FROM t1, t2, t3 WHERE ...; |
+** |
+** Then the code generated is conceptually like the following: |
+** |
+** foreach row1 in t1 do \ Code generated |
+** foreach row2 in t2 do |-- by sqlite3WhereBegin() |
+** foreach row3 in t3 do / |
+** ... |
+** end \ Code generated |
+** end |-- by sqlite3WhereEnd() |
+** end / |
+** |
+** Note that the loops might not be nested in the order in which they |
+** appear in the FROM clause if a different order is better able to make |
+** use of indices. Note also that when the IN operator appears in |
+** the WHERE clause, it might result in additional nested loops for |
+** scanning through all values on the right-hand side of the IN. |
+** |
+** There are Btree cursors associated with each table. t1 uses cursor |
+** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor. |
+** And so forth. This routine generates code to open those VDBE cursors |
+** and sqlite3WhereEnd() generates the code to close them. |
+** |
+** The code that sqlite3WhereBegin() generates leaves the cursors named |
+** in pTabList pointing at their appropriate entries. The [...] code |
+** can use OP_Column and OP_Rowid opcodes on these cursors to extract |
+** data from the various tables of the loop. |
+** |
+** If the WHERE clause is empty, the foreach loops must each scan their |
+** entire tables. Thus a three-way join is an O(N^3) operation. But if |
+** the tables have indices and there are terms in the WHERE clause that |
+** refer to those indices, a complete table scan can be avoided and the |
+** code will run much faster. Most of the work of this routine is checking |
+** to see if there are indices that can be used to speed up the loop. |
+** |
+** Terms of the WHERE clause are also used to limit which rows actually |
+** make it to the "..." in the middle of the loop. After each "foreach", |
+** terms of the WHERE clause that use only terms in that loop and outer |
+** loops are evaluated and if false a jump is made around all subsequent |
+** inner loops (or around the "..." if the test occurs within the inner- |
+** most loop) |
+** |
+** OUTER JOINS |
+** |
+** An outer join of tables t1 and t2 is conceptally coded as follows: |
+** |
+** foreach row1 in t1 do |
+** flag = 0 |
+** foreach row2 in t2 do |
+** start: |
+** ... |
+** flag = 1 |
+** end |
+** if flag==0 then |
+** move the row2 cursor to a null row |
+** goto start |
+** fi |
+** end |
+** |
+** ORDER BY CLAUSE PROCESSING |
+** |
+** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause |
+** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement |
+** if there is one. If there is no ORDER BY clause or if this routine |
+** is called from an UPDATE or DELETE statement, then pOrderBy is NULL. |
+** |
+** The iIdxCur parameter is the cursor number of an index. If |
+** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index |
+** to use for OR clause processing. The WHERE clause should use this |
+** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is |
+** the first cursor in an array of cursors for all indices. iIdxCur should |
+** be used to compute the appropriate cursor depending on which index is |
+** used. |
+*/ |
+SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( |
+ Parse *pParse, /* The parser context */ |
+ SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */ |
+ Expr *pWhere, /* The WHERE clause */ |
+ ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */ |
+ ExprList *pDistinctSet, /* Try not to output two rows that duplicate these */ |
+ u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */ |
+ int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number |
+ ** If WHERE_USE_LIMIT, then the limit amount */ |
+){ |
+ int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */ |
+ int nTabList; /* Number of elements in pTabList */ |
+ WhereInfo *pWInfo; /* Will become the return value of this function */ |
+ Vdbe *v = pParse->pVdbe; /* The virtual database engine */ |
+ Bitmask notReady; /* Cursors that are not yet positioned */ |
+ WhereLoopBuilder sWLB; /* The WhereLoop builder */ |
+ WhereMaskSet *pMaskSet; /* The expression mask set */ |
+ WhereLevel *pLevel; /* A single level in pWInfo->a[] */ |
+ WhereLoop *pLoop; /* Pointer to a single WhereLoop object */ |
+ int ii; /* Loop counter */ |
+ sqlite3 *db; /* Database connection */ |
+ int rc; /* Return code */ |
+ u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */ |
+ |
+ assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || ( |
+ (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 |
+ && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 |
+ )); |
+ |
+ /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */ |
+ assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 |
+ || (wctrlFlags & WHERE_USE_LIMIT)==0 ); |
+ |
+ /* Variable initialization */ |
+ db = pParse->db; |
+ memset(&sWLB, 0, sizeof(sWLB)); |
+ |
+ /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */ |
+ testcase( pOrderBy && pOrderBy->nExpr==BMS-1 ); |
+ if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0; |
+ sWLB.pOrderBy = pOrderBy; |
+ |
+ /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via |
+ ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */ |
+ if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){ |
+ wctrlFlags &= ~WHERE_WANT_DISTINCT; |
+ } |
+ |
+ /* The number of tables in the FROM clause is limited by the number of |
+ ** bits in a Bitmask |
+ */ |
+ testcase( pTabList->nSrc==BMS ); |
+ if( pTabList->nSrc>BMS ){ |
+ sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); |
+ return 0; |
+ } |
+ |
+ /* This function normally generates a nested loop for all tables in |
+ ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should |
+ ** only generate code for the first table in pTabList and assume that |
+ ** any cursors associated with subsequent tables are uninitialized. |
+ */ |
+ nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc; |
+ |
+ /* Allocate and initialize the WhereInfo structure that will become the |
+ ** return value. A single allocation is used to store the WhereInfo |
+ ** struct, the contents of WhereInfo.a[], the WhereClause structure |
+ ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte |
+ ** field (type Bitmask) it must be aligned on an 8-byte boundary on |
+ ** some architectures. Hence the ROUND8() below. |
+ */ |
+ nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel)); |
+ pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop)); |
+ if( db->mallocFailed ){ |
+ sqlite3DbFree(db, pWInfo); |
+ pWInfo = 0; |
+ goto whereBeginError; |
+ } |
+ pWInfo->pParse = pParse; |
+ pWInfo->pTabList = pTabList; |
+ pWInfo->pOrderBy = pOrderBy; |
+ pWInfo->pDistinctSet = pDistinctSet; |
+ pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1; |
+ pWInfo->nLevel = nTabList; |
+ pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v); |
+ pWInfo->wctrlFlags = wctrlFlags; |
+ pWInfo->iLimit = iAuxArg; |
+ pWInfo->savedNQueryLoop = pParse->nQueryLoop; |
+ memset(&pWInfo->nOBSat, 0, |
+ offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat)); |
+ memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel)); |
+ assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */ |
+ pMaskSet = &pWInfo->sMaskSet; |
+ sWLB.pWInfo = pWInfo; |
+ sWLB.pWC = &pWInfo->sWC; |
+ sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo); |
+ assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) ); |
+ whereLoopInit(sWLB.pNew); |
+#ifdef SQLITE_DEBUG |
+ sWLB.pNew->cId = '*'; |
+#endif |
+ |
+ /* Split the WHERE clause into separate subexpressions where each |
+ ** subexpression is separated by an AND operator. |
+ */ |
+ initMaskSet(pMaskSet); |
+ 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. |
+ */ |
+ for(ii=0; ii<sWLB.pWC->nTerm; ii++){ |
+ if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){ |
+ sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak, |
+ SQLITE_JUMPIFNULL); |
+ sWLB.pWC->a[ii].wtFlags |= TERM_CODED; |
+ } |
+ } |
+ |
+ /* Special case: No FROM clause |
+ */ |
+ if( nTabList==0 ){ |
+ if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr; |
+ if( wctrlFlags & WHERE_WANT_DISTINCT ){ |
+ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; |
+ } |
+ } |
+ |
+ /* Assign a bit from the bitmask to every term in the FROM clause. |
+ ** |
+ ** 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 |
+ ** equal to pTabList->nSrc but might be shortened to 1 if the |
+ ** WHERE_OR_SUBCLAUSE flag is set. |
+ */ |
+ for(ii=0; ii<pTabList->nSrc; ii++){ |
+ createMask(pMaskSet, pTabList->a[ii].iCursor); |
+ sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC); |
+ } |
+#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. */ |
+ sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC); |
+ if( db->mallocFailed ) goto whereBeginError; |
+ |
+ if( wctrlFlags & WHERE_WANT_DISTINCT ){ |
+ if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pDistinctSet) ){ |
+ /* The DISTINCT marking is pointless. Ignore it. */ |
+ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; |
+ }else if( pOrderBy==0 ){ |
+ /* Try to ORDER BY the result set to make distinct processing easier */ |
+ pWInfo->wctrlFlags |= WHERE_DISTINCTBY; |
+ pWInfo->pOrderBy = pDistinctSet; |
+ } |
+ } |
+ |
+ /* Construct the WhereLoop objects */ |
+#if defined(WHERETRACE_ENABLED) |
+ if( sqlite3WhereTrace & 0xffff ){ |
+ sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags); |
+ if( wctrlFlags & WHERE_USE_LIMIT ){ |
+ sqlite3DebugPrintf(", limit: %d", iAuxArg); |
+ } |
+ sqlite3DebugPrintf(")\n"); |
+ } |
+ if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */ |
+ sqlite3WhereClausePrint(sWLB.pWC); |
+ } |
+#endif |
+ |
+ if( nTabList!=1 || whereShortCut(&sWLB)==0 ){ |
+ rc = whereLoopAddAll(&sWLB); |
+ if( rc ) goto whereBeginError; |
+ |
+#ifdef WHERETRACE_ENABLED |
+ if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */ |
+ WhereLoop *p; |
+ int i; |
+ 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); |
+ } |
+ } |
+#endif |
+ |
+ wherePathSolver(pWInfo, 0); |
+ if( db->mallocFailed ) goto whereBeginError; |
+ if( pWInfo->pOrderBy ){ |
+ wherePathSolver(pWInfo, pWInfo->nRowOut+1); |
+ if( db->mallocFailed ) goto whereBeginError; |
+ } |
+ } |
+ if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){ |
+ pWInfo->revMask = ALLBITS; |
+ } |
+ if( pParse->nErr || NEVER(db->mallocFailed) ){ |
+ goto whereBeginError; |
+ } |
+#ifdef WHERETRACE_ENABLED |
+ if( sqlite3WhereTrace ){ |
+ sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); |
+ if( pWInfo->nOBSat>0 ){ |
+ sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask); |
+ } |
+ switch( pWInfo->eDistinct ){ |
+ case WHERE_DISTINCT_UNIQUE: { |
+ sqlite3DebugPrintf(" DISTINCT=unique"); |
+ break; |
+ } |
+ case WHERE_DISTINCT_ORDERED: { |
+ sqlite3DebugPrintf(" DISTINCT=ordered"); |
+ break; |
+ } |
+ case WHERE_DISTINCT_UNORDERED: { |
+ sqlite3DebugPrintf(" DISTINCT=unordered"); |
+ break; |
+ } |
+ } |
+ sqlite3DebugPrintf("\n"); |
+ for(ii=0; ii<pWInfo->nLevel; ii++){ |
+ whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC); |
+ } |
+ } |
+#endif |
+ /* Attempt to omit tables from the join that do not effect the result */ |
+ if( pWInfo->nLevel>=2 |
+ && pDistinctSet!=0 |
+ && OptimizationEnabled(db, SQLITE_OmitNoopJoin) |
+ ){ |
+ Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pDistinctSet); |
+ 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].fg.jointype & JT_LEFT)==0 ) break; |
+ if( (wctrlFlags & WHERE_WANT_DISTINCT)==0 |
+ && (pLoop->wsFlags & WHERE_ONEROW)==0 |
+ ){ |
+ break; |
+ } |
+ if( (tabUsed & pLoop->maskSelf)!=0 ) break; |
+ pEnd = sWLB.pWC->a + sWLB.pWC->nTerm; |
+ for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){ |
+ if( (pTerm->prereqAll & pLoop->maskSelf)!=0 |
+ && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) |
+ ){ |
+ break; |
+ } |
+ } |
+ if( pTerm<pEnd ) break; |
+ WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId)); |
+ pWInfo->nLevel--; |
+ nTabList--; |
+ } |
+ } |
+ WHERETRACE(0xffff,("*** Optimizer Finished ***\n")); |
+ pWInfo->pParse->nQueryLoop += pWInfo->nRowOut; |
+ |
+ /* If the caller is an UPDATE or DELETE statement that is requesting |
+ ** to use a one-pass algorithm, determine if this is appropriate. |
+ */ |
+ assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); |
+ 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 |
+ && 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. |
+ */ |
+ for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){ |
+ Table *pTab; /* Table to open */ |
+ int iDb; /* Index of database containing table/index */ |
+ struct SrcList_item *pTabItem; |
+ |
+ pTabItem = &pTabList->a[pLevel->iFrom]; |
+ pTab = pTabItem->pTab; |
+ iDb = sqlite3SchemaToIndex(db, pTab->pSchema); |
+ pLoop = pLevel->pWLoop; |
+ if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){ |
+ /* Do nothing */ |
+ }else |
+#ifndef SQLITE_OMIT_VIRTUALTABLE |
+ if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ |
+ const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); |
+ int iCur = pTabItem->iCursor; |
+ sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); |
+ }else if( IsVirtual(pTab) ){ |
+ /* noop */ |
+ }else |
+#endif |
+ if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 |
+ && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){ |
+ int op = OP_OpenRead; |
+ 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->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++){} |
+ sqlite3VdbeChangeP4(v, -1, 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); |
+ } |
+ if( pLoop->wsFlags & WHERE_INDEXED ){ |
+ Index *pIx = pLoop->u.btree.pIndex; |
+ int iIndexCur; |
+ int op = OP_OpenRead; |
+ /* iAuxArg is always set if to a positive value if ONEPASS is possible */ |
+ assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 ); |
+ if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx) |
+ && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 |
+ ){ |
+ /* This is one term of an OR-optimization using the PRIMARY KEY of a |
+ ** WITHOUT ROWID table. No need for a separate index */ |
+ iIndexCur = pLevel->iTabCur; |
+ op = 0; |
+ }else if( pWInfo->eOnePass!=ONEPASS_OFF ){ |
+ Index *pJ = pTabItem->pTab->pIndex; |
+ iIndexCur = iAuxArg; |
+ assert( wctrlFlags & WHERE_ONEPASS_DESIRED ); |
+ while( ALWAYS(pJ) && pJ!=pIx ){ |
+ iIndexCur++; |
+ pJ = pJ->pNext; |
+ } |
+ op = OP_OpenWrite; |
+ pWInfo->aiCurOnePass[1] = iIndexCur; |
+ }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){ |
+ iIndexCur = iAuxArg; |
+ op = OP_ReopenIdx; |
+ }else{ |
+ iIndexCur = pParse->nTab++; |
+ } |
+ pLevel->iIdxCur = iIndexCur; |
+ assert( pIx->pSchema==pTab->pSchema ); |
+ assert( iIndexCur>=0 ); |
+ 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); |
+ } |
+ pWInfo->iTop = sqlite3VdbeCurrentAddr(v); |
+ if( db->mallocFailed ) goto whereBeginError; |
+ |
+ /* Generate the code to do the search. Each iteration of the for |
+ ** loop below generates code for a single nested loop of the VM |
+ ** program. |
+ */ |
+ 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, |
+ &pTabList->a[pLevel->iFrom], notReady, pLevel); |
+ if( db->mallocFailed ) goto whereBeginError; |
+ } |
+#endif |
+ addrExplain = sqlite3WhereExplainOneScan( |
+ pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags |
+ ); |
+ pLevel->addrBody = sqlite3VdbeCurrentAddr(v); |
+ notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady); |
+ pWInfo->iContinue = pLevel->addrCont; |
+ if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){ |
+ sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain); |
+ } |
+ } |
+ |
+ /* Done. */ |
+ VdbeModuleComment((v, "Begin WHERE-core")); |
+ return pWInfo; |
+ |
+ /* Jump here if malloc fails */ |
+whereBeginError: |
+ if( pWInfo ){ |
+ pParse->nQueryLoop = pWInfo->savedNQueryLoop; |
+ whereInfoFree(db, pWInfo); |
+ } |
+ return 0; |
+} |
+ |
+/* |
+** Generate the end of the WHERE loop. See comments on |
+** sqlite3WhereBegin() for additional information. |
+*/ |
+SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ |
+ Parse *pParse = pWInfo->pParse; |
+ Vdbe *v = pParse->pVdbe; |
+ int i; |
+ WhereLevel *pLevel; |
+ WhereLoop *pLoop; |
+ SrcList *pTabList = pWInfo->pTabList; |
+ sqlite3 *db = pParse->db; |
+ |
+ /* Generate loop termination code. |
+ */ |
+ VdbeModuleComment((v, "End WHERE-core")); |
+ sqlite3ExprCacheClear(pParse); |
+ for(i=pWInfo->nLevel-1; i>=0; i--){ |
+ int addr; |
+ pLevel = &pWInfo->a[i]; |
+ pLoop = pLevel->pWLoop; |
+ sqlite3VdbeResolveLabel(v, pLevel->addrCont); |
+ if( pLevel->op!=OP_Noop ){ |
+ sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3); |
+ sqlite3VdbeChangeP5(v, pLevel->p5); |
+ VdbeCoverage(v); |
+ VdbeCoverageIf(v, pLevel->op==OP_Next); |
+ VdbeCoverageIf(v, pLevel->op==OP_Prev); |
+ VdbeCoverageIf(v, pLevel->op==OP_VNext); |
+ } |
+ if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){ |
+ struct InLoop *pIn; |
+ int j; |
+ sqlite3VdbeResolveLabel(v, pLevel->addrNxt); |
+ for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ |
+ sqlite3VdbeJumpHere(v, pIn->addrInTop+1); |
+ if( pIn->eEndLoopOp!=OP_Noop ){ |
+ sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); |
+ VdbeCoverage(v); |
+ VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen); |
+ VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen); |
+ } |
+ sqlite3VdbeJumpHere(v, pIn->addrInTop-1); |
+ } |
+ } |
+ sqlite3VdbeResolveLabel(v, pLevel->addrBrk); |
+ if( 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 ){ |
+ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1), |
+ pLevel->addrLikeRep); |
+ VdbeCoverage(v); |
+ } |
+#endif |
+ if( pLevel->iLeftJoin ){ |
+ int ws = pLoop->wsFlags; |
+ addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v); |
+ assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 ); |
+ if( (ws & WHERE_IDX_ONLY)==0 ){ |
+ sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); |
+ } |
+ if( (ws & WHERE_INDEXED) |
+ || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx) |
+ ){ |
+ sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); |
+ } |
+ if( pLevel->op==OP_Return ){ |
+ sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); |
+ }else{ |
+ sqlite3VdbeGoto(v, pLevel->addrFirst); |
+ } |
+ sqlite3VdbeJumpHere(v, addr); |
+ } |
+ VdbeModuleComment((v, "End WHERE-loop%d: %s", i, |
+ pWInfo->pTabList->a[pLevel->iFrom].pTab->zName)); |
+ } |
+ |
+ /* The "break" point is here, just past the end of the outer loop. |
+ ** Set it. |
+ */ |
+ sqlite3VdbeResolveLabel(v, pWInfo->iBreak); |
+ |
+ assert( pWInfo->nLevel<=pTabList->nSrc ); |
+ for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){ |
+ int k, last; |
+ VdbeOp *pOp; |
+ Index *pIdx = 0; |
+ struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; |
+ Table *pTab = pTabItem->pTab; |
+ assert( pTab!=0 ); |
+ pLoop = pLevel->pWLoop; |
+ |
+ /* For a co-routine, change all OP_Column references to the table of |
+ ** the co-routine into OP_Copy of result contained in a register. |
+ ** OP_Rowid becomes OP_Null. |
+ */ |
+ if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){ |
+ translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur, |
+ pTabItem->regResult, 0); |
+ continue; |
+ } |
+ |
+ /* If this scan uses an index, make VDBE code substitutions to read data |
+ ** from the index instead of from the table where possible. In some cases |
+ ** this optimization prevents the table from ever being read, which can |
+ ** yield a significant performance boost. |
+ ** |
+ ** Calls to the code generator in between sqlite3WhereBegin and |
+ ** sqlite3WhereEnd will have created code that references the table |
+ ** directly. This loop scans all that code looking for opcodes |
+ ** that reference the table and converts them into opcodes that |
+ ** reference the index. |
+ */ |
+ if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){ |
+ pIdx = pLoop->u.btree.pIndex; |
+ }else if( pLoop->wsFlags & WHERE_MULTI_OR ){ |
+ pIdx = pLevel->u.pCovidx; |
+ } |
+ if( pIdx |
+ && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable)) |
+ && !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 ){ |
+ int x = pOp->p2; |
+ assert( pIdx->pTable==pTab ); |
+ if( !HasRowid(pTab) ){ |
+ Index *pPk = sqlite3PrimaryKeyIndex(pTab); |
+ x = pPk->aiColumn[x]; |
+ assert( x>=0 ); |
+ } |
+ x = sqlite3ColumnOfIndex(pIdx, x); |
+ if( x>=0 ){ |
+ pOp->p2 = x; |
+ pOp->p1 = pLevel->iIdxCur; |
+ } |
+ assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 |
+ || pWInfo->eOnePass ); |
+ }else if( pOp->opcode==OP_Rowid ){ |
+ pOp->p1 = pLevel->iIdxCur; |
+ pOp->opcode = OP_IdxRowid; |
+ } |
+ } |
+ } |
+ } |
+ |
+ /* Final cleanup |
+ */ |
+ pParse->nQueryLoop = pWInfo->savedNQueryLoop; |
+ whereInfoFree(db, pWInfo); |
+ return; |
+} |
+ |
+/************** End of where.c ***********************************************/ |
+/************** Begin file parse.c *******************************************/ |
+/* |
+** 2000-05-29 |
+** |
+** 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. |
+** |
+************************************************************************* |
+** Driver template for the LEMON parser generator. |
+** |
+** The "lemon" program processes an LALR(1) input grammar file, then uses |
+** this template to construct a parser. The "lemon" program inserts text |
+** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the |
+** interstitial "-" characters) contained in this template is changed into |
+** the value of the %name directive from the grammar. Otherwise, the content |
+** of this template is copied straight through into the generate parser |
+** source file. |
+** |
+** The following is the concatenation of all %include directives from the |
+** input grammar file: |
+*/ |
+/* #include <stdio.h> */ |
+/************ Begin %include sections from the grammar ************************/ |
+ |
+/* #include "sqliteInt.h" */ |
+ |
+/* |
+** Disable all error recovery processing in the parser push-down |
+** automaton. |
+*/ |
+#define YYNOERRORRECOVERY 1 |
+ |
+/* |
+** Make yytestcase() the same as testcase() |
+*/ |
+#define yytestcase(X) testcase(X) |
+ |
+/* |
+** Indicate that sqlite3ParserFree() will never be called with a null |
+** pointer. |
+*/ |
+#define YYPARSEFREENEVERNULL 1 |
+ |
+/* |
+** In the amalgamation, the parse.c file generated by lemon and the |
+** tokenize.c file are concatenated. In that case, sqlite3RunParser() |
+** has access to the the size of the yyParser object and so the parser |
+** engine can be allocated from stack. In that case, only the |
+** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked |
+** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be |
+** omitted. |
+*/ |
+#ifdef SQLITE_AMALGAMATION |
+# define sqlite3Parser_ENGINEALWAYSONSTACK 1 |
+#endif |
+ |
+/* |
+** Alternative datatype for the argument to the malloc() routine passed |
+** into sqlite3ParserAlloc(). The default is size_t. |
+*/ |
+#define YYMALLOCARGTYPE u64 |
+ |
+/* |
+** An instance of this structure holds information about the |
+** LIMIT clause of a SELECT statement. |
+*/ |
+struct LimitVal { |
+ Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */ |
+ Expr *pOffset; /* The OFFSET expression. NULL if there is none */ |
+}; |
+ |
+/* |
+** An instance of the following structure describes the event of a |
+** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT, |
+** TK_DELETE, or TK_INSTEAD. If the event is of the form |
+** |
+** UPDATE ON (a,b,c) |
+** |
+** Then the "b" IdList records the list "a,b,c". |
+*/ |
+struct TrigEvent { int a; IdList * b; }; |
+ |
+/* |
+** Disable lookaside memory allocation for objects that might be |
+** shared across database connections. |
+*/ |
+static void disableLookaside(Parse *pParse){ |
+ pParse->disableLookaside++; |
+ pParse->db->lookaside.bDisable++; |
+} |
+ |
+ |
+ /* |
+ ** For a compound SELECT statement, make sure p->pPrior->pNext==p for |
+ ** all elements in the list. And make sure list length does not exceed |
+ ** SQLITE_LIMIT_COMPOUND_SELECT. |
+ */ |
+ static void parserDoubleLinkSelect(Parse *pParse, Select *p){ |
+ if( p->pPrior ){ |
+ Select *pNext = 0, *pLoop; |
+ int mxSelect, cnt = 0; |
+ for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){ |
+ pLoop->pNext = pNext; |
+ pLoop->selFlags |= SF_Compound; |
+ } |
+ if( (p->selFlags & SF_MultiValue)==0 && |
+ (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 && |
+ cnt>mxSelect |
+ ){ |
+ sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); |
+ } |
+ } |
+ } |
+ |
+ /* This is a utility routine used to set the ExprSpan.zStart and |
+ ** ExprSpan.zEnd values of pOut so that the span covers the complete |
+ ** range of text beginning with pStart and going to the end of pEnd. |
+ */ |
+ static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){ |
+ pOut->zStart = pStart->z; |
+ pOut->zEnd = &pEnd->z[pEnd->n]; |
+ } |
+ |
+ /* Construct a new Expr object from a single identifier. Use the |
+ ** new Expr to populate pOut. Set the span of pOut to be the identifier |
+ ** that created the expression. |
+ */ |
+ static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){ |
+ Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1); |
+ if( p ){ |
+ memset(p, 0, sizeof(Expr)); |
+ p->op = (u8)op; |
+ p->flags = EP_Leaf; |
+ p->iAgg = -1; |
+ p->u.zToken = (char*)&p[1]; |
+ memcpy(p->u.zToken, t.z, t.n); |
+ p->u.zToken[t.n] = 0; |
+ if( sqlite3Isquote(p->u.zToken[0]) ){ |
+ if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted; |
+ sqlite3Dequote(p->u.zToken); |
+ } |
+#if SQLITE_MAX_EXPR_DEPTH>0 |
+ p->nHeight = 1; |
+#endif |
+ } |
+ pOut->pExpr = p; |
+ pOut->zStart = t.z; |
+ pOut->zEnd = &t.z[t.n]; |
+ } |
+ |
+ /* This routine constructs a binary expression node out of two ExprSpan |
+ ** objects and uses the result to populate a new ExprSpan object. |
+ */ |
+ static void spanBinaryExpr( |
+ Parse *pParse, /* The parsing context. Errors accumulate here */ |
+ int op, /* The binary operation */ |
+ ExprSpan *pLeft, /* The left operand, and output */ |
+ ExprSpan *pRight /* The right operand */ |
+ ){ |
+ pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr); |
+ pLeft->zEnd = pRight->zEnd; |
+ } |
+ |
+ /* If doNot is true, then add a TK_NOT Expr-node wrapper around the |
+ ** outside of *ppExpr. |
+ */ |
+ static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){ |
+ if( doNot ){ |
+ pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0); |
+ } |
+ } |
+ |
+ /* Construct an expression node for a unary postfix operator |
+ */ |
+ static void spanUnaryPostfix( |
+ Parse *pParse, /* Parsing context to record errors */ |
+ int op, /* The operator */ |
+ ExprSpan *pOperand, /* The operand, and output */ |
+ Token *pPostOp /* The operand token for setting the span */ |
+ ){ |
+ pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0); |
+ pOperand->zEnd = &pPostOp->z[pPostOp->n]; |
+ } |
+ |
+ /* A routine to convert a binary TK_IS or TK_ISNOT expression into a |
+ ** unary TK_ISNULL or TK_NOTNULL expression. */ |
+ static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){ |
+ sqlite3 *db = pParse->db; |
+ if( pA && pY && pY->op==TK_NULL ){ |
+ pA->op = (u8)op; |
+ sqlite3ExprDelete(db, pA->pRight); |
+ pA->pRight = 0; |
+ } |
+ } |
+ |
+ /* Construct an expression node for a unary prefix operator |
+ */ |
+ static void spanUnaryPrefix( |
+ ExprSpan *pOut, /* Write the new expression node here */ |
+ Parse *pParse, /* Parsing context to record errors */ |
+ int op, /* The operator */ |
+ ExprSpan *pOperand, /* The operand */ |
+ Token *pPreOp /* The operand token for setting the span */ |
+ ){ |
+ pOut->zStart = pPreOp->z; |
+ pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0); |
+ pOut->zEnd = pOperand->zEnd; |
+ } |
+ |
+ /* Add a single new term to an ExprList that is used to store a |
+ ** list of identifiers. Report an error if the ID list contains |
+ ** a COLLATE clause or an ASC or DESC keyword, except ignore the |
+ ** error while parsing a legacy schema. |
+ */ |
+ static ExprList *parserAddExprIdListTerm( |
+ Parse *pParse, |
+ ExprList *pPrior, |
+ Token *pIdToken, |
+ int hasCollate, |
+ int sortOrder |
+ ){ |
+ ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0); |
+ if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED) |
+ && pParse->db->init.busy==0 |
+ ){ |
+ sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"", |
+ pIdToken->n, pIdToken->z); |
+ } |
+ sqlite3ExprListSetName(pParse, p, pIdToken, 1); |
+ return p; |
+ } |
+/**************** End of %include directives **********************************/ |
+/* These constants specify the various numeric values for terminal symbols |
+** in a format understandable to "makeheaders". This section is blank unless |
+** "lemon" is run with the "-m" command-line option. |
+***************** Begin makeheaders token definitions *************************/ |
+/**************** End makeheaders token definitions ***************************/ |
+ |
+/* The next sections is a series of control #defines. |
+** various aspects of the generated parser. |
+** YYCODETYPE is the data type used to store the integer codes |
+** that represent terminal and non-terminal symbols. |
+** "unsigned char" is used if there are fewer than |
+** 256 symbols. Larger types otherwise. |
+** YYNOCODE is a number of type YYCODETYPE that is not used for |
+** any terminal or nonterminal symbol. |
+** YYFALLBACK If defined, this indicates that one or more tokens |
+** (also known as: "terminal symbols") have fall-back |
+** values which should be used if the original symbol |
+** would not parse. This permits keywords to sometimes |
+** be used as identifiers, for example. |
+** YYACTIONTYPE is the data type used for "action codes" - numbers |
+** that indicate what to do in response to the next |
+** token. |
+** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal |
+** symbols. Background: A "minor type" is a semantic |
+** value associated with a terminal or non-terminal |
+** symbols. For example, for an "ID" terminal symbol, |
+** the minor type might be the name of the identifier. |
+** Each non-terminal can have a different minor type. |
+** Terminal symbols all have the same minor type, though. |
+** This macros defines the minor type for terminal |
+** symbols. |
+** YYMINORTYPE is the data type used for all minor types. |
+** This is typically a union of many types, one of |
+** which is sqlite3ParserTOKENTYPE. The entry in the union |
+** for terminal symbols is called "yy0". |
+** YYSTACKDEPTH is the maximum depth of the parser's stack. If |
+** zero the stack is dynamically sized using realloc() |
+** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument |
+** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument |
+** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser |
+** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser |
+** YYERRORSYMBOL is the code number of the error symbol. If not |
+** defined, then do no error processing. |
+** YYNSTATE the combined number of states. |
+** YYNRULE the number of rules in the grammar |
+** YY_MAX_SHIFT Maximum value for shift actions |
+** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions |
+** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions |
+** YY_MIN_REDUCE Maximum value for reduce actions |
+** YY_ERROR_ACTION The yy_action[] code for syntax error |
+** YY_ACCEPT_ACTION The yy_action[] code for accept |
+** YY_NO_ACTION The yy_action[] code for no-op |
+*/ |
+#ifndef INTERFACE |
+# define INTERFACE 1 |
+#endif |
+/************* Begin control #defines *****************************************/ |
+#define YYCODETYPE unsigned char |
+#define YYNOCODE 252 |
+#define YYACTIONTYPE unsigned short int |
+#define YYWILDCARD 96 |
+#define sqlite3ParserTOKENTYPE Token |
+typedef union { |
+ int yyinit; |
+ sqlite3ParserTOKENTYPE yy0; |
+ Expr* yy72; |
+ TriggerStep* yy145; |
+ ExprList* yy148; |
+ SrcList* yy185; |
+ ExprSpan yy190; |
+ int yy194; |
+ Select* yy243; |
+ IdList* yy254; |
+ With* yy285; |
+ struct TrigEvent yy332; |
+ struct LimitVal yy354; |
+ struct {int value; int mask;} yy497; |
+} YYMINORTYPE; |
+#ifndef YYSTACKDEPTH |
+#define YYSTACKDEPTH 100 |
+#endif |
+#define sqlite3ParserARG_SDECL Parse *pParse; |
+#define sqlite3ParserARG_PDECL ,Parse *pParse |
+#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse |
+#define sqlite3ParserARG_STORE yypParser->pParse = pParse |
+#define YYFALLBACK 1 |
+#define YYNSTATE 456 |
+#define YYNRULE 332 |
+#define YY_MAX_SHIFT 455 |
+#define YY_MIN_SHIFTREDUCE 668 |
+#define YY_MAX_SHIFTREDUCE 999 |
+#define YY_MIN_REDUCE 1000 |
+#define YY_MAX_REDUCE 1331 |
+#define YY_ERROR_ACTION 1332 |
+#define YY_ACCEPT_ACTION 1333 |
+#define YY_NO_ACTION 1334 |
+/************* End control #defines *******************************************/ |
+ |
+/* Define the yytestcase() macro to be a no-op if is not already defined |
+** otherwise. |
+** |
+** Applications can choose to define yytestcase() in the %include section |
+** to a macro that can assist in verifying code coverage. For production |
+** code the yytestcase() macro should be turned off. But it is useful |
+** for testing. |
+*/ |
+#ifndef yytestcase |
+# define yytestcase(X) |
+#endif |
+ |
+ |
+/* Next are the tables used to determine what action to take based on the |
+** current state and lookahead token. These tables are used to implement |
+** functions that take a state number and lookahead value and return an |
+** action integer. |
+** |
+** Suppose the action integer is N. Then the action is determined as |
+** follows |
+** |
+** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead |
+** token onto the stack and goto state N. |
+** |
+** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then |
+** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE. |
+** |
+** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE |
+** and YY_MAX_REDUCE |
+** |
+** N == YY_ERROR_ACTION A syntax error has occurred. |
+** |
+** N == YY_ACCEPT_ACTION The parser accepts its input. |
+** |
+** N == YY_NO_ACTION No such action. Denotes unused |
+** slots in the yy_action[] table. |
+** |
+** The action table is constructed as a single large table named yy_action[]. |
+** Given state S and lookahead X, the action is computed as either: |
+** |
+** (A) N = yy_action[ yy_shift_ofst[S] + X ] |
+** (B) N = yy_default[S] |
+** |
+** The (A) formula is preferred. The B formula is used instead if: |
+** (1) The yy_shift_ofst[S]+X value is out of range, or |
+** (2) yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or |
+** (3) yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT. |
+** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that |
+** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X. |
+** Hence only tests (1) and (2) need to be evaluated.) |
+** |
+** The formulas above are for computing the action when the lookahead is |
+** a terminal symbol. If the lookahead is a non-terminal (as occurs after |
+** a reduce action) then the yy_reduce_ofst[] array is used in place of |
+** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of |
+** YY_SHIFT_USE_DFLT. |
+** |
+** The following are the tables generated in this section: |
+** |
+** yy_action[] A single table containing all actions. |
+** yy_lookahead[] A table containing the lookahead for each entry in |
+** yy_action. Used to detect hash collisions. |
+** yy_shift_ofst[] For each state, the offset into yy_action for |
+** shifting terminals. |
+** yy_reduce_ofst[] For each state, the offset into yy_action for |
+** shifting non-terminals after a reduce. |
+** yy_default[] Default action for each state. |
+** |
+*********** Begin parsing tables **********************************************/ |
+#define YY_ACTTAB_COUNT (1567) |
+static const YYACTIONTYPE yy_action[] = { |
+ /* 0 */ 325, 832, 351, 825, 5, 203, 203, 819, 99, 100, |
+ /* 10 */ 90, 842, 842, 854, 857, 846, 846, 97, 97, 98, |
+ /* 20 */ 98, 98, 98, 301, 96, 96, 96, 96, 95, 95, |
+ /* 30 */ 94, 94, 94, 93, 351, 325, 977, 977, 824, 824, |
+ /* 40 */ 826, 947, 354, 99, 100, 90, 842, 842, 854, 857, |
+ /* 50 */ 846, 846, 97, 97, 98, 98, 98, 98, 338, 96, |
+ /* 60 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351, |
+ /* 70 */ 95, 95, 94, 94, 94, 93, 351, 791, 977, 977, |
+ /* 80 */ 325, 94, 94, 94, 93, 351, 792, 75, 99, 100, |
+ /* 90 */ 90, 842, 842, 854, 857, 846, 846, 97, 97, 98, |
+ /* 100 */ 98, 98, 98, 450, 96, 96, 96, 96, 95, 95, |
+ /* 110 */ 94, 94, 94, 93, 351, 1333, 155, 155, 2, 325, |
+ /* 120 */ 275, 146, 132, 52, 52, 93, 351, 99, 100, 90, |
+ /* 130 */ 842, 842, 854, 857, 846, 846, 97, 97, 98, 98, |
+ /* 140 */ 98, 98, 101, 96, 96, 96, 96, 95, 95, 94, |
+ /* 150 */ 94, 94, 93, 351, 958, 958, 325, 268, 428, 413, |
+ /* 160 */ 411, 61, 752, 752, 99, 100, 90, 842, 842, 854, |
+ /* 170 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 60, |
+ /* 180 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, |
+ /* 190 */ 351, 325, 270, 329, 273, 277, 959, 960, 250, 99, |
+ /* 200 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, |
+ /* 210 */ 98, 98, 98, 98, 301, 96, 96, 96, 96, 95, |
+ /* 220 */ 95, 94, 94, 94, 93, 351, 325, 938, 1326, 698, |
+ /* 230 */ 706, 1326, 242, 412, 99, 100, 90, 842, 842, 854, |
+ /* 240 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 347, |
+ /* 250 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, |
+ /* 260 */ 351, 325, 938, 1327, 384, 699, 1327, 381, 379, 99, |
+ /* 270 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, |
+ /* 280 */ 98, 98, 98, 98, 701, 96, 96, 96, 96, 95, |
+ /* 290 */ 95, 94, 94, 94, 93, 351, 325, 92, 89, 178, |
+ /* 300 */ 833, 936, 373, 700, 99, 100, 90, 842, 842, 854, |
+ /* 310 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 375, |
+ /* 320 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, |
+ /* 330 */ 351, 325, 1276, 947, 354, 818, 936, 739, 739, 99, |
+ /* 340 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, |
+ /* 350 */ 98, 98, 98, 98, 230, 96, 96, 96, 96, 95, |
+ /* 360 */ 95, 94, 94, 94, 93, 351, 325, 969, 227, 92, |
+ /* 370 */ 89, 178, 373, 300, 99, 100, 90, 842, 842, 854, |
+ /* 380 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 921, |
+ /* 390 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, |
+ /* 400 */ 351, 325, 449, 447, 447, 447, 147, 737, 737, 99, |
+ /* 410 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, |
+ /* 420 */ 98, 98, 98, 98, 296, 96, 96, 96, 96, 95, |
+ /* 430 */ 95, 94, 94, 94, 93, 351, 325, 419, 231, 958, |
+ /* 440 */ 958, 158, 25, 422, 99, 100, 90, 842, 842, 854, |
+ /* 450 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 450, |
+ /* 460 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, |
+ /* 470 */ 351, 443, 224, 224, 420, 958, 958, 962, 325, 52, |
+ /* 480 */ 52, 959, 960, 176, 415, 78, 99, 100, 90, 842, |
+ /* 490 */ 842, 854, 857, 846, 846, 97, 97, 98, 98, 98, |
+ /* 500 */ 98, 379, 96, 96, 96, 96, 95, 95, 94, 94, |
+ /* 510 */ 94, 93, 351, 325, 428, 418, 298, 959, 960, 962, |
+ /* 520 */ 81, 99, 88, 90, 842, 842, 854, 857, 846, 846, |
+ /* 530 */ 97, 97, 98, 98, 98, 98, 717, 96, 96, 96, |
+ /* 540 */ 96, 95, 95, 94, 94, 94, 93, 351, 325, 843, |
+ /* 550 */ 843, 855, 858, 996, 318, 343, 379, 100, 90, 842, |
+ /* 560 */ 842, 854, 857, 846, 846, 97, 97, 98, 98, 98, |
+ /* 570 */ 98, 450, 96, 96, 96, 96, 95, 95, 94, 94, |
+ /* 580 */ 94, 93, 351, 325, 350, 350, 350, 260, 377, 340, |
+ /* 590 */ 929, 52, 52, 90, 842, 842, 854, 857, 846, 846, |
+ /* 600 */ 97, 97, 98, 98, 98, 98, 361, 96, 96, 96, |
+ /* 610 */ 96, 95, 95, 94, 94, 94, 93, 351, 86, 445, |
+ /* 620 */ 847, 3, 1203, 361, 360, 378, 344, 813, 958, 958, |
+ /* 630 */ 1300, 86, 445, 729, 3, 212, 169, 287, 405, 282, |
+ /* 640 */ 404, 199, 232, 450, 300, 760, 83, 84, 280, 245, |
+ /* 650 */ 262, 365, 251, 85, 352, 352, 92, 89, 178, 83, |
+ /* 660 */ 84, 242, 412, 52, 52, 448, 85, 352, 352, 246, |
+ /* 670 */ 959, 960, 194, 455, 670, 402, 399, 398, 448, 243, |
+ /* 680 */ 221, 114, 434, 776, 361, 450, 397, 268, 747, 224, |
+ /* 690 */ 224, 132, 132, 198, 832, 434, 452, 451, 428, 427, |
+ /* 700 */ 819, 415, 734, 713, 132, 52, 52, 832, 268, 452, |
+ /* 710 */ 451, 734, 194, 819, 363, 402, 399, 398, 450, 1271, |
+ /* 720 */ 1271, 23, 958, 958, 86, 445, 397, 3, 228, 429, |
+ /* 730 */ 895, 824, 824, 826, 827, 19, 203, 720, 52, 52, |
+ /* 740 */ 428, 408, 439, 249, 824, 824, 826, 827, 19, 229, |
+ /* 750 */ 403, 153, 83, 84, 761, 177, 241, 450, 721, 85, |
+ /* 760 */ 352, 352, 120, 157, 959, 960, 58, 977, 409, 355, |
+ /* 770 */ 330, 448, 268, 428, 430, 320, 790, 32, 32, 86, |
+ /* 780 */ 445, 776, 3, 341, 98, 98, 98, 98, 434, 96, |
+ /* 790 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351, |
+ /* 800 */ 832, 120, 452, 451, 813, 887, 819, 83, 84, 977, |
+ /* 810 */ 813, 132, 410, 920, 85, 352, 352, 132, 407, 789, |
+ /* 820 */ 958, 958, 92, 89, 178, 917, 448, 262, 370, 261, |
+ /* 830 */ 82, 914, 80, 262, 370, 261, 776, 824, 824, 826, |
+ /* 840 */ 827, 19, 934, 434, 96, 96, 96, 96, 95, 95, |
+ /* 850 */ 94, 94, 94, 93, 351, 832, 74, 452, 451, 958, |
+ /* 860 */ 958, 819, 959, 960, 120, 92, 89, 178, 945, 2, |
+ /* 870 */ 918, 965, 268, 1, 976, 76, 445, 762, 3, 708, |
+ /* 880 */ 901, 901, 387, 958, 958, 757, 919, 371, 740, 778, |
+ /* 890 */ 756, 257, 824, 824, 826, 827, 19, 417, 741, 450, |
+ /* 900 */ 24, 959, 960, 83, 84, 369, 958, 958, 177, 226, |
+ /* 910 */ 85, 352, 352, 885, 315, 314, 313, 215, 311, 10, |
+ /* 920 */ 10, 683, 448, 349, 348, 959, 960, 909, 777, 157, |
+ /* 930 */ 120, 958, 958, 337, 776, 416, 711, 310, 450, 434, |
+ /* 940 */ 450, 321, 450, 791, 103, 200, 175, 450, 959, 960, |
+ /* 950 */ 908, 832, 792, 452, 451, 9, 9, 819, 10, 10, |
+ /* 960 */ 52, 52, 51, 51, 180, 716, 248, 10, 10, 171, |
+ /* 970 */ 170, 167, 339, 959, 960, 247, 984, 702, 702, 450, |
+ /* 980 */ 715, 233, 686, 982, 889, 983, 182, 914, 824, 824, |
+ /* 990 */ 826, 827, 19, 183, 256, 423, 132, 181, 394, 10, |
+ /* 1000 */ 10, 889, 891, 749, 958, 958, 917, 268, 985, 198, |
+ /* 1010 */ 985, 349, 348, 425, 415, 299, 817, 832, 326, 825, |
+ /* 1020 */ 120, 332, 133, 819, 268, 98, 98, 98, 98, 91, |
+ /* 1030 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, |
+ /* 1040 */ 351, 157, 810, 371, 382, 359, 959, 960, 358, 268, |
+ /* 1050 */ 450, 918, 368, 324, 824, 824, 826, 450, 709, 450, |
+ /* 1060 */ 264, 380, 889, 450, 877, 746, 253, 919, 255, 433, |
+ /* 1070 */ 36, 36, 234, 450, 234, 120, 269, 37, 37, 12, |
+ /* 1080 */ 12, 334, 272, 27, 27, 450, 330, 118, 450, 162, |
+ /* 1090 */ 742, 280, 450, 38, 38, 450, 985, 356, 985, 450, |
+ /* 1100 */ 709, 1210, 450, 132, 450, 39, 39, 450, 40, 40, |
+ /* 1110 */ 450, 362, 41, 41, 450, 42, 42, 450, 254, 28, |
+ /* 1120 */ 28, 450, 29, 29, 31, 31, 450, 43, 43, 450, |
+ /* 1130 */ 44, 44, 450, 714, 45, 45, 450, 11, 11, 767, |
+ /* 1140 */ 450, 46, 46, 450, 268, 450, 105, 105, 450, 47, |
+ /* 1150 */ 47, 450, 48, 48, 450, 237, 33, 33, 450, 172, |
+ /* 1160 */ 49, 49, 450, 50, 50, 34, 34, 274, 122, 122, |
+ /* 1170 */ 450, 123, 123, 450, 124, 124, 450, 898, 56, 56, |
+ /* 1180 */ 450, 897, 35, 35, 450, 267, 450, 817, 450, 817, |
+ /* 1190 */ 106, 106, 450, 53, 53, 385, 107, 107, 450, 817, |
+ /* 1200 */ 108, 108, 817, 450, 104, 104, 121, 121, 119, 119, |
+ /* 1210 */ 450, 117, 112, 112, 450, 276, 450, 225, 111, 111, |
+ /* 1220 */ 450, 730, 450, 109, 109, 450, 673, 674, 675, 912, |
+ /* 1230 */ 110, 110, 317, 998, 55, 55, 57, 57, 692, 331, |
+ /* 1240 */ 54, 54, 26, 26, 696, 30, 30, 317, 937, 197, |
+ /* 1250 */ 196, 195, 335, 281, 336, 446, 331, 745, 689, 436, |
+ /* 1260 */ 440, 444, 120, 72, 386, 223, 175, 345, 757, 933, |
+ /* 1270 */ 20, 286, 319, 756, 815, 372, 374, 202, 202, 202, |
+ /* 1280 */ 263, 395, 285, 74, 208, 21, 696, 719, 718, 884, |
+ /* 1290 */ 120, 120, 120, 120, 120, 754, 278, 828, 77, 74, |
+ /* 1300 */ 726, 727, 785, 783, 880, 202, 999, 208, 894, 893, |
+ /* 1310 */ 894, 893, 694, 816, 763, 116, 774, 1290, 431, 432, |
+ /* 1320 */ 302, 999, 390, 303, 823, 697, 691, 680, 159, 289, |
+ /* 1330 */ 679, 884, 681, 952, 291, 218, 293, 7, 316, 828, |
+ /* 1340 */ 173, 805, 259, 364, 252, 911, 376, 713, 295, 435, |
+ /* 1350 */ 308, 168, 955, 993, 135, 400, 990, 284, 882, 881, |
+ /* 1360 */ 205, 928, 926, 59, 333, 62, 144, 156, 130, 72, |
+ /* 1370 */ 802, 366, 367, 393, 137, 185, 189, 160, 139, 383, |
+ /* 1380 */ 67, 896, 140, 141, 142, 148, 389, 812, 775, 266, |
+ /* 1390 */ 219, 190, 154, 391, 913, 876, 271, 406, 191, 322, |
+ /* 1400 */ 682, 733, 192, 342, 732, 724, 731, 711, 723, 421, |
+ /* 1410 */ 705, 71, 323, 6, 204, 771, 288, 79, 297, 346, |
+ /* 1420 */ 772, 704, 290, 283, 703, 770, 292, 294, 967, 239, |
+ /* 1430 */ 769, 102, 862, 438, 426, 240, 424, 442, 73, 213, |
+ /* 1440 */ 688, 238, 22, 453, 953, 214, 217, 216, 454, 677, |
+ /* 1450 */ 676, 671, 753, 125, 115, 235, 126, 669, 353, 166, |
+ /* 1460 */ 127, 244, 179, 357, 306, 304, 305, 307, 113, 892, |
+ /* 1470 */ 327, 890, 811, 328, 134, 128, 136, 138, 743, 258, |
+ /* 1480 */ 907, 184, 143, 129, 910, 186, 63, 64, 145, 187, |
+ /* 1490 */ 906, 65, 8, 66, 13, 188, 202, 899, 265, 149, |
+ /* 1500 */ 987, 388, 150, 685, 161, 392, 285, 193, 279, 396, |
+ /* 1510 */ 151, 401, 68, 14, 15, 722, 69, 236, 831, 131, |
+ /* 1520 */ 830, 860, 70, 751, 16, 414, 755, 4, 174, 220, |
+ /* 1530 */ 222, 784, 201, 152, 779, 77, 74, 17, 18, 875, |
+ /* 1540 */ 861, 859, 916, 864, 915, 207, 206, 942, 163, 437, |
+ /* 1550 */ 948, 943, 164, 209, 1002, 441, 863, 165, 210, 829, |
+ /* 1560 */ 695, 87, 312, 211, 1292, 1291, 309, |
+}; |
+static const YYCODETYPE yy_lookahead[] = { |
+ /* 0 */ 19, 95, 53, 97, 22, 24, 24, 101, 27, 28, |
+ /* 10 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, |
+ /* 20 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48, |
+ /* 30 */ 49, 50, 51, 52, 53, 19, 55, 55, 132, 133, |
+ /* 40 */ 134, 1, 2, 27, 28, 29, 30, 31, 32, 33, |
+ /* 50 */ 34, 35, 36, 37, 38, 39, 40, 41, 187, 43, |
+ /* 60 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, |
+ /* 70 */ 47, 48, 49, 50, 51, 52, 53, 61, 97, 97, |
+ /* 80 */ 19, 49, 50, 51, 52, 53, 70, 26, 27, 28, |
+ /* 90 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, |
+ /* 100 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48, |
+ /* 110 */ 49, 50, 51, 52, 53, 144, 145, 146, 147, 19, |
+ /* 120 */ 16, 22, 92, 172, 173, 52, 53, 27, 28, 29, |
+ /* 130 */ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, |
+ /* 140 */ 40, 41, 81, 43, 44, 45, 46, 47, 48, 49, |
+ /* 150 */ 50, 51, 52, 53, 55, 56, 19, 152, 207, 208, |
+ /* 160 */ 115, 24, 117, 118, 27, 28, 29, 30, 31, 32, |
+ /* 170 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 79, |
+ /* 180 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, |
+ /* 190 */ 53, 19, 88, 157, 90, 23, 97, 98, 193, 27, |
+ /* 200 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, |
+ /* 210 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47, |
+ /* 220 */ 48, 49, 50, 51, 52, 53, 19, 22, 23, 172, |
+ /* 230 */ 23, 26, 119, 120, 27, 28, 29, 30, 31, 32, |
+ /* 240 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 187, |
+ /* 250 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, |
+ /* 260 */ 53, 19, 22, 23, 228, 23, 26, 231, 152, 27, |
+ /* 270 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, |
+ /* 280 */ 38, 39, 40, 41, 172, 43, 44, 45, 46, 47, |
+ /* 290 */ 48, 49, 50, 51, 52, 53, 19, 221, 222, 223, |
+ /* 300 */ 23, 96, 152, 172, 27, 28, 29, 30, 31, 32, |
+ /* 310 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 152, |
+ /* 320 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, |
+ /* 330 */ 53, 19, 0, 1, 2, 23, 96, 190, 191, 27, |
+ /* 340 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, |
+ /* 350 */ 38, 39, 40, 41, 238, 43, 44, 45, 46, 47, |
+ /* 360 */ 48, 49, 50, 51, 52, 53, 19, 185, 218, 221, |
+ /* 370 */ 222, 223, 152, 152, 27, 28, 29, 30, 31, 32, |
+ /* 380 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 241, |
+ /* 390 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, |
+ /* 400 */ 53, 19, 152, 168, 169, 170, 22, 190, 191, 27, |
+ /* 410 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, |
+ /* 420 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47, |
+ /* 430 */ 48, 49, 50, 51, 52, 53, 19, 19, 218, 55, |
+ /* 440 */ 56, 24, 22, 152, 27, 28, 29, 30, 31, 32, |
+ /* 450 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 152, |
+ /* 460 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, |
+ /* 470 */ 53, 250, 194, 195, 56, 55, 56, 55, 19, 172, |
+ /* 480 */ 173, 97, 98, 152, 206, 138, 27, 28, 29, 30, |
+ /* 490 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, |
+ /* 500 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50, |
+ /* 510 */ 51, 52, 53, 19, 207, 208, 152, 97, 98, 97, |
+ /* 520 */ 138, 27, 28, 29, 30, 31, 32, 33, 34, 35, |
+ /* 530 */ 36, 37, 38, 39, 40, 41, 181, 43, 44, 45, |
+ /* 540 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 30, |
+ /* 550 */ 31, 32, 33, 247, 248, 19, 152, 28, 29, 30, |
+ /* 560 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, |
+ /* 570 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50, |
+ /* 580 */ 51, 52, 53, 19, 168, 169, 170, 238, 19, 53, |
+ /* 590 */ 152, 172, 173, 29, 30, 31, 32, 33, 34, 35, |
+ /* 600 */ 36, 37, 38, 39, 40, 41, 152, 43, 44, 45, |
+ /* 610 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 20, |
+ /* 620 */ 101, 22, 23, 169, 170, 56, 207, 85, 55, 56, |
+ /* 630 */ 23, 19, 20, 26, 22, 99, 100, 101, 102, 103, |
+ /* 640 */ 104, 105, 238, 152, 152, 210, 47, 48, 112, 152, |
+ /* 650 */ 108, 109, 110, 54, 55, 56, 221, 222, 223, 47, |
+ /* 660 */ 48, 119, 120, 172, 173, 66, 54, 55, 56, 152, |
+ /* 670 */ 97, 98, 99, 148, 149, 102, 103, 104, 66, 154, |
+ /* 680 */ 23, 156, 83, 26, 230, 152, 113, 152, 163, 194, |
+ /* 690 */ 195, 92, 92, 30, 95, 83, 97, 98, 207, 208, |
+ /* 700 */ 101, 206, 179, 180, 92, 172, 173, 95, 152, 97, |
+ /* 710 */ 98, 188, 99, 101, 219, 102, 103, 104, 152, 119, |
+ /* 720 */ 120, 196, 55, 56, 19, 20, 113, 22, 193, 163, |
+ /* 730 */ 11, 132, 133, 134, 135, 136, 24, 65, 172, 173, |
+ /* 740 */ 207, 208, 250, 152, 132, 133, 134, 135, 136, 193, |
+ /* 750 */ 78, 84, 47, 48, 49, 98, 199, 152, 86, 54, |
+ /* 760 */ 55, 56, 196, 152, 97, 98, 209, 55, 163, 244, |
+ /* 770 */ 107, 66, 152, 207, 208, 164, 175, 172, 173, 19, |
+ /* 780 */ 20, 124, 22, 111, 38, 39, 40, 41, 83, 43, |
+ /* 790 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, |
+ /* 800 */ 95, 196, 97, 98, 85, 152, 101, 47, 48, 97, |
+ /* 810 */ 85, 92, 207, 193, 54, 55, 56, 92, 49, 175, |
+ /* 820 */ 55, 56, 221, 222, 223, 12, 66, 108, 109, 110, |
+ /* 830 */ 137, 163, 139, 108, 109, 110, 26, 132, 133, 134, |
+ /* 840 */ 135, 136, 152, 83, 43, 44, 45, 46, 47, 48, |
+ /* 850 */ 49, 50, 51, 52, 53, 95, 26, 97, 98, 55, |
+ /* 860 */ 56, 101, 97, 98, 196, 221, 222, 223, 146, 147, |
+ /* 870 */ 57, 171, 152, 22, 26, 19, 20, 49, 22, 179, |
+ /* 880 */ 108, 109, 110, 55, 56, 116, 73, 219, 75, 124, |
+ /* 890 */ 121, 152, 132, 133, 134, 135, 136, 163, 85, 152, |
+ /* 900 */ 232, 97, 98, 47, 48, 237, 55, 56, 98, 5, |
+ /* 910 */ 54, 55, 56, 193, 10, 11, 12, 13, 14, 172, |
+ /* 920 */ 173, 17, 66, 47, 48, 97, 98, 152, 124, 152, |
+ /* 930 */ 196, 55, 56, 186, 124, 152, 106, 160, 152, 83, |
+ /* 940 */ 152, 164, 152, 61, 22, 211, 212, 152, 97, 98, |
+ /* 950 */ 152, 95, 70, 97, 98, 172, 173, 101, 172, 173, |
+ /* 960 */ 172, 173, 172, 173, 60, 181, 62, 172, 173, 47, |
+ /* 970 */ 48, 123, 186, 97, 98, 71, 100, 55, 56, 152, |
+ /* 980 */ 181, 186, 21, 107, 152, 109, 82, 163, 132, 133, |
+ /* 990 */ 134, 135, 136, 89, 16, 207, 92, 93, 19, 172, |
+ /* 1000 */ 173, 169, 170, 195, 55, 56, 12, 152, 132, 30, |
+ /* 1010 */ 134, 47, 48, 186, 206, 225, 152, 95, 114, 97, |
+ /* 1020 */ 196, 245, 246, 101, 152, 38, 39, 40, 41, 42, |
+ /* 1030 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, |
+ /* 1040 */ 53, 152, 163, 219, 152, 141, 97, 98, 193, 152, |
+ /* 1050 */ 152, 57, 91, 164, 132, 133, 134, 152, 55, 152, |
+ /* 1060 */ 152, 237, 230, 152, 103, 193, 88, 73, 90, 75, |
+ /* 1070 */ 172, 173, 183, 152, 185, 196, 152, 172, 173, 172, |
+ /* 1080 */ 173, 217, 152, 172, 173, 152, 107, 22, 152, 24, |
+ /* 1090 */ 193, 112, 152, 172, 173, 152, 132, 242, 134, 152, |
+ /* 1100 */ 97, 140, 152, 92, 152, 172, 173, 152, 172, 173, |
+ /* 1110 */ 152, 100, 172, 173, 152, 172, 173, 152, 140, 172, |
+ /* 1120 */ 173, 152, 172, 173, 172, 173, 152, 172, 173, 152, |
+ /* 1130 */ 172, 173, 152, 152, 172, 173, 152, 172, 173, 213, |
+ /* 1140 */ 152, 172, 173, 152, 152, 152, 172, 173, 152, 172, |
+ /* 1150 */ 173, 152, 172, 173, 152, 210, 172, 173, 152, 26, |
+ /* 1160 */ 172, 173, 152, 172, 173, 172, 173, 152, 172, 173, |
+ /* 1170 */ 152, 172, 173, 152, 172, 173, 152, 59, 172, 173, |
+ /* 1180 */ 152, 63, 172, 173, 152, 193, 152, 152, 152, 152, |
+ /* 1190 */ 172, 173, 152, 172, 173, 77, 172, 173, 152, 152, |
+ /* 1200 */ 172, 173, 152, 152, 172, 173, 172, 173, 172, 173, |
+ /* 1210 */ 152, 22, 172, 173, 152, 152, 152, 22, 172, 173, |
+ /* 1220 */ 152, 152, 152, 172, 173, 152, 7, 8, 9, 163, |
+ /* 1230 */ 172, 173, 22, 23, 172, 173, 172, 173, 166, 167, |
+ /* 1240 */ 172, 173, 172, 173, 55, 172, 173, 22, 23, 108, |
+ /* 1250 */ 109, 110, 217, 152, 217, 166, 167, 163, 163, 163, |
+ /* 1260 */ 163, 163, 196, 130, 217, 211, 212, 217, 116, 23, |
+ /* 1270 */ 22, 101, 26, 121, 23, 23, 23, 26, 26, 26, |
+ /* 1280 */ 23, 23, 112, 26, 26, 37, 97, 100, 101, 55, |
+ /* 1290 */ 196, 196, 196, 196, 196, 23, 23, 55, 26, 26, |
+ /* 1300 */ 7, 8, 23, 152, 23, 26, 96, 26, 132, 132, |
+ /* 1310 */ 134, 134, 23, 152, 152, 26, 152, 122, 152, 191, |
+ /* 1320 */ 152, 96, 234, 152, 152, 152, 152, 152, 197, 210, |
+ /* 1330 */ 152, 97, 152, 152, 210, 233, 210, 198, 150, 97, |
+ /* 1340 */ 184, 201, 239, 214, 214, 201, 239, 180, 214, 227, |
+ /* 1350 */ 200, 198, 155, 67, 243, 176, 69, 175, 175, 175, |
+ /* 1360 */ 122, 159, 159, 240, 159, 240, 22, 220, 27, 130, |
+ /* 1370 */ 201, 18, 159, 18, 189, 158, 158, 220, 192, 159, |
+ /* 1380 */ 137, 236, 192, 192, 192, 189, 74, 189, 159, 235, |
+ /* 1390 */ 159, 158, 22, 177, 201, 201, 159, 107, 158, 177, |
+ /* 1400 */ 159, 174, 158, 76, 174, 182, 174, 106, 182, 125, |
+ /* 1410 */ 174, 107, 177, 22, 159, 216, 215, 137, 159, 53, |
+ /* 1420 */ 216, 176, 215, 174, 174, 216, 215, 215, 174, 229, |
+ /* 1430 */ 216, 129, 224, 177, 126, 229, 127, 177, 128, 25, |
+ /* 1440 */ 162, 226, 26, 161, 13, 153, 6, 153, 151, 151, |
+ /* 1450 */ 151, 151, 205, 165, 178, 178, 165, 4, 3, 22, |
+ /* 1460 */ 165, 142, 15, 94, 202, 204, 203, 201, 16, 23, |
+ /* 1470 */ 249, 23, 120, 249, 246, 111, 131, 123, 20, 16, |
+ /* 1480 */ 1, 125, 123, 111, 56, 64, 37, 37, 131, 122, |
+ /* 1490 */ 1, 37, 5, 37, 22, 107, 26, 80, 140, 80, |
+ /* 1500 */ 87, 72, 107, 20, 24, 19, 112, 105, 23, 79, |
+ /* 1510 */ 22, 79, 22, 22, 22, 58, 22, 79, 23, 68, |
+ /* 1520 */ 23, 23, 26, 116, 22, 26, 23, 22, 122, 23, |
+ /* 1530 */ 23, 56, 64, 22, 124, 26, 26, 64, 64, 23, |
+ /* 1540 */ 23, 23, 23, 11, 23, 22, 26, 23, 22, 24, |
+ /* 1550 */ 1, 23, 22, 26, 251, 24, 23, 22, 122, 23, |
+ /* 1560 */ 23, 22, 15, 122, 122, 122, 23, |
+}; |
+#define YY_SHIFT_USE_DFLT (1567) |
+#define YY_SHIFT_COUNT (455) |
+#define YY_SHIFT_MIN (-94) |
+#define YY_SHIFT_MAX (1549) |
+static const short yy_shift_ofst[] = { |
+ /* 0 */ 40, 599, 904, 612, 760, 760, 760, 760, 725, -19, |
+ /* 10 */ 16, 16, 100, 760, 760, 760, 760, 760, 760, 760, |
+ /* 20 */ 876, 876, 573, 542, 719, 600, 61, 137, 172, 207, |
+ /* 30 */ 242, 277, 312, 347, 382, 417, 459, 459, 459, 459, |
+ /* 40 */ 459, 459, 459, 459, 459, 459, 459, 459, 459, 459, |
+ /* 50 */ 459, 459, 459, 494, 459, 529, 564, 564, 705, 760, |
+ /* 60 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760, |
+ /* 70 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760, |
+ /* 80 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760, |
+ /* 90 */ 856, 760, 760, 760, 760, 760, 760, 760, 760, 760, |
+ /* 100 */ 760, 760, 760, 760, 987, 746, 746, 746, 746, 746, |
+ /* 110 */ 801, 23, 32, 949, 961, 979, 964, 964, 949, 73, |
+ /* 120 */ 113, -51, 1567, 1567, 1567, 536, 536, 536, 99, 99, |
+ /* 130 */ 813, 813, 667, 205, 240, 949, 949, 949, 949, 949, |
+ /* 140 */ 949, 949, 949, 949, 949, 949, 949, 949, 949, 949, |
+ /* 150 */ 949, 949, 949, 949, 949, 332, 1011, 422, 422, 113, |
+ /* 160 */ 30, 30, 30, 30, 30, 30, 1567, 1567, 1567, 922, |
+ /* 170 */ -94, -94, 384, 613, 828, 420, 765, 804, 851, 949, |
+ /* 180 */ 949, 949, 949, 949, 949, 949, 949, 949, 949, 949, |
+ /* 190 */ 949, 949, 949, 949, 949, 672, 672, 672, 949, 949, |
+ /* 200 */ 657, 949, 949, 949, -18, 949, 949, 994, 949, 949, |
+ /* 210 */ 949, 949, 949, 949, 949, 949, 949, 949, 772, 1118, |
+ /* 220 */ 712, 712, 712, 810, 45, 769, 1219, 1133, 418, 418, |
+ /* 230 */ 569, 1133, 569, 830, 607, 663, 882, 418, 693, 882, |
+ /* 240 */ 882, 848, 1152, 1065, 1286, 1238, 1238, 1287, 1287, 1238, |
+ /* 250 */ 1344, 1341, 1239, 1353, 1353, 1353, 1353, 1238, 1355, 1239, |
+ /* 260 */ 1344, 1341, 1341, 1239, 1238, 1355, 1243, 1312, 1238, 1238, |
+ /* 270 */ 1355, 1370, 1238, 1355, 1238, 1355, 1370, 1290, 1290, 1290, |
+ /* 280 */ 1327, 1370, 1290, 1301, 1290, 1327, 1290, 1290, 1284, 1304, |
+ /* 290 */ 1284, 1304, 1284, 1304, 1284, 1304, 1238, 1391, 1238, 1280, |
+ /* 300 */ 1370, 1366, 1366, 1370, 1302, 1308, 1310, 1309, 1239, 1414, |
+ /* 310 */ 1416, 1431, 1431, 1440, 1440, 1440, 1440, 1567, 1567, 1567, |
+ /* 320 */ 1567, 1567, 1567, 1567, 1567, 519, 978, 1210, 1225, 104, |
+ /* 330 */ 1141, 1189, 1246, 1248, 1251, 1252, 1253, 1257, 1258, 1273, |
+ /* 340 */ 1003, 1187, 1293, 1170, 1272, 1279, 1234, 1281, 1176, 1177, |
+ /* 350 */ 1289, 1242, 1195, 1453, 1455, 1437, 1319, 1447, 1369, 1452, |
+ /* 360 */ 1446, 1448, 1352, 1345, 1364, 1354, 1458, 1356, 1463, 1479, |
+ /* 370 */ 1359, 1357, 1449, 1450, 1454, 1456, 1372, 1428, 1421, 1367, |
+ /* 380 */ 1489, 1487, 1472, 1388, 1358, 1417, 1470, 1419, 1413, 1429, |
+ /* 390 */ 1395, 1480, 1483, 1486, 1394, 1402, 1488, 1430, 1490, 1491, |
+ /* 400 */ 1485, 1492, 1432, 1457, 1494, 1438, 1451, 1495, 1497, 1498, |
+ /* 410 */ 1496, 1407, 1502, 1503, 1505, 1499, 1406, 1506, 1507, 1475, |
+ /* 420 */ 1468, 1511, 1410, 1509, 1473, 1510, 1474, 1516, 1509, 1517, |
+ /* 430 */ 1518, 1519, 1520, 1521, 1523, 1532, 1524, 1526, 1525, 1527, |
+ /* 440 */ 1528, 1530, 1531, 1527, 1533, 1535, 1536, 1537, 1539, 1436, |
+ /* 450 */ 1441, 1442, 1443, 1543, 1547, 1549, |
+}; |
+#define YY_REDUCE_USE_DFLT (-130) |
+#define YY_REDUCE_COUNT (324) |
+#define YY_REDUCE_MIN (-129) |
+#define YY_REDUCE_MAX (1300) |
+static const short yy_reduce_ofst[] = { |
+ /* 0 */ -29, 566, 525, 605, -49, 307, 491, 533, 668, 435, |
+ /* 10 */ 601, 644, 148, 747, 786, 795, 419, 788, 827, 790, |
+ /* 20 */ 454, 832, 889, 495, 824, 734, 76, 76, 76, 76, |
+ /* 30 */ 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, |
+ /* 40 */ 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, |
+ /* 50 */ 76, 76, 76, 76, 76, 76, 76, 76, 783, 898, |
+ /* 60 */ 905, 907, 911, 921, 933, 936, 940, 943, 947, 950, |
+ /* 70 */ 952, 955, 958, 962, 965, 969, 974, 977, 980, 984, |
+ /* 80 */ 988, 991, 993, 996, 999, 1002, 1006, 1010, 1018, 1021, |
+ /* 90 */ 1024, 1028, 1032, 1034, 1036, 1040, 1046, 1051, 1058, 1062, |
+ /* 100 */ 1064, 1068, 1070, 1073, 76, 76, 76, 76, 76, 76, |
+ /* 110 */ 76, 76, 76, 855, 36, 523, 235, 416, 777, 76, |
+ /* 120 */ 278, 76, 76, 76, 76, 700, 700, 700, 150, 220, |
+ /* 130 */ 147, 217, 221, 306, 306, 611, 5, 535, 556, 620, |
+ /* 140 */ 720, 872, 897, 116, 864, 349, 1035, 1037, 404, 1047, |
+ /* 150 */ 992, -129, 1050, 492, 62, 722, 879, 1072, 1089, 808, |
+ /* 160 */ 1066, 1094, 1095, 1096, 1097, 1098, 776, 1054, 557, 57, |
+ /* 170 */ 112, 131, 167, 182, 250, 272, 291, 331, 364, 438, |
+ /* 180 */ 497, 517, 591, 653, 690, 739, 775, 798, 892, 908, |
+ /* 190 */ 924, 930, 1015, 1063, 1069, 355, 784, 799, 981, 1101, |
+ /* 200 */ 926, 1151, 1161, 1162, 945, 1164, 1166, 1128, 1168, 1171, |
+ /* 210 */ 1172, 250, 1173, 1174, 1175, 1178, 1180, 1181, 1088, 1102, |
+ /* 220 */ 1119, 1124, 1126, 926, 1131, 1139, 1188, 1140, 1129, 1130, |
+ /* 230 */ 1103, 1144, 1107, 1179, 1156, 1167, 1182, 1134, 1122, 1183, |
+ /* 240 */ 1184, 1150, 1153, 1197, 1111, 1202, 1203, 1123, 1125, 1205, |
+ /* 250 */ 1147, 1185, 1169, 1186, 1190, 1191, 1192, 1213, 1217, 1193, |
+ /* 260 */ 1157, 1196, 1198, 1194, 1220, 1218, 1145, 1154, 1229, 1231, |
+ /* 270 */ 1233, 1216, 1237, 1240, 1241, 1244, 1222, 1227, 1230, 1232, |
+ /* 280 */ 1223, 1235, 1236, 1245, 1249, 1226, 1250, 1254, 1199, 1201, |
+ /* 290 */ 1204, 1207, 1209, 1211, 1214, 1212, 1255, 1208, 1259, 1215, |
+ /* 300 */ 1256, 1200, 1206, 1260, 1247, 1261, 1263, 1262, 1266, 1278, |
+ /* 310 */ 1282, 1292, 1294, 1297, 1298, 1299, 1300, 1221, 1224, 1228, |
+ /* 320 */ 1288, 1291, 1276, 1277, 1295, |
+}; |
+static const YYACTIONTYPE yy_default[] = { |
+ /* 0 */ 1281, 1271, 1271, 1271, 1203, 1203, 1203, 1203, 1271, 1096, |
+ /* 10 */ 1125, 1125, 1255, 1332, 1332, 1332, 1332, 1332, 1332, 1202, |
+ /* 20 */ 1332, 1332, 1332, 1332, 1271, 1100, 1131, 1332, 1332, 1332, |
+ /* 30 */ 1332, 1204, 1205, 1332, 1332, 1332, 1254, 1256, 1141, 1140, |
+ /* 40 */ 1139, 1138, 1237, 1112, 1136, 1129, 1133, 1204, 1198, 1199, |
+ /* 50 */ 1197, 1201, 1205, 1332, 1132, 1167, 1182, 1166, 1332, 1332, |
+ /* 60 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 70 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 80 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 90 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 100 */ 1332, 1332, 1332, 1332, 1176, 1181, 1188, 1180, 1177, 1169, |
+ /* 110 */ 1168, 1170, 1171, 1332, 1019, 1067, 1332, 1332, 1332, 1172, |
+ /* 120 */ 1332, 1173, 1185, 1184, 1183, 1262, 1289, 1288, 1332, 1332, |
+ /* 130 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 140 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 150 */ 1332, 1332, 1332, 1332, 1332, 1281, 1271, 1025, 1025, 1332, |
+ /* 160 */ 1271, 1271, 1271, 1271, 1271, 1271, 1267, 1100, 1091, 1332, |
+ /* 170 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 180 */ 1259, 1257, 1332, 1218, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 190 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 200 */ 1332, 1332, 1332, 1332, 1096, 1332, 1332, 1332, 1332, 1332, |
+ /* 210 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1283, 1332, 1232, |
+ /* 220 */ 1096, 1096, 1096, 1098, 1080, 1090, 1004, 1135, 1114, 1114, |
+ /* 230 */ 1321, 1135, 1321, 1042, 1303, 1039, 1125, 1114, 1200, 1125, |
+ /* 240 */ 1125, 1097, 1090, 1332, 1324, 1105, 1105, 1323, 1323, 1105, |
+ /* 250 */ 1146, 1070, 1135, 1076, 1076, 1076, 1076, 1105, 1016, 1135, |
+ /* 260 */ 1146, 1070, 1070, 1135, 1105, 1016, 1236, 1318, 1105, 1105, |
+ /* 270 */ 1016, 1211, 1105, 1016, 1105, 1016, 1211, 1068, 1068, 1068, |
+ /* 280 */ 1057, 1211, 1068, 1042, 1068, 1057, 1068, 1068, 1118, 1113, |
+ /* 290 */ 1118, 1113, 1118, 1113, 1118, 1113, 1105, 1206, 1105, 1332, |
+ /* 300 */ 1211, 1215, 1215, 1211, 1130, 1119, 1128, 1126, 1135, 1022, |
+ /* 310 */ 1060, 1286, 1286, 1282, 1282, 1282, 1282, 1329, 1329, 1267, |
+ /* 320 */ 1298, 1298, 1044, 1044, 1298, 1332, 1332, 1332, 1332, 1332, |
+ /* 330 */ 1332, 1293, 1332, 1220, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 340 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 350 */ 1332, 1332, 1152, 1332, 1000, 1264, 1332, 1332, 1263, 1332, |
+ /* 360 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 370 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1320, |
+ /* 380 */ 1332, 1332, 1332, 1332, 1332, 1332, 1235, 1234, 1332, 1332, |
+ /* 390 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 400 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, |
+ /* 410 */ 1332, 1082, 1332, 1332, 1332, 1307, 1332, 1332, 1332, 1332, |
+ /* 420 */ 1332, 1332, 1332, 1127, 1332, 1120, 1332, 1332, 1311, 1332, |
+ /* 430 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1273, |
+ /* 440 */ 1332, 1332, 1332, 1272, 1332, 1332, 1332, 1332, 1332, 1154, |
+ /* 450 */ 1332, 1153, 1157, 1332, 1010, 1332, |
+}; |
+/********** End of lemon-generated parsing tables *****************************/ |
+ |
+/* The next table maps tokens (terminal symbols) into fallback tokens. |
+** If a construct like the following: |
+** |
+** %fallback ID X Y Z. |
+** |
+** appears in the grammar, then ID becomes a fallback token for X, Y, |
+** and Z. Whenever one of the tokens X, Y, or Z is input to the parser |
+** but it does not parse, the type of the token is changed to ID and |
+** the parse is retried before an error is thrown. |
+** |
+** This feature can be used, for example, to cause some keywords in a language |
+** to revert to identifiers if they keyword does not apply in the context where |
+** it appears. |
+*/ |
+#ifdef YYFALLBACK |
+static const YYCODETYPE yyFallback[] = { |
+ 0, /* $ => nothing */ |
+ 0, /* SEMI => nothing */ |
+ 55, /* EXPLAIN => ID */ |
+ 55, /* QUERY => ID */ |
+ 55, /* PLAN => ID */ |
+ 55, /* BEGIN => ID */ |
+ 0, /* TRANSACTION => nothing */ |
+ 55, /* DEFERRED => ID */ |
+ 55, /* IMMEDIATE => ID */ |
+ 55, /* EXCLUSIVE => ID */ |
+ 0, /* COMMIT => nothing */ |
+ 55, /* END => ID */ |
+ 55, /* ROLLBACK => ID */ |
+ 55, /* SAVEPOINT => ID */ |
+ 55, /* RELEASE => ID */ |
+ 0, /* TO => nothing */ |
+ 0, /* TABLE => nothing */ |
+ 0, /* CREATE => nothing */ |
+ 55, /* IF => ID */ |
+ 0, /* NOT => nothing */ |
+ 0, /* EXISTS => nothing */ |
+ 55, /* TEMP => ID */ |
+ 0, /* LP => nothing */ |
+ 0, /* RP => nothing */ |
+ 0, /* AS => nothing */ |
+ 55, /* WITHOUT => ID */ |
+ 0, /* COMMA => nothing */ |
+ 0, /* OR => nothing */ |
+ 0, /* AND => nothing */ |
+ 0, /* IS => nothing */ |
+ 55, /* MATCH => ID */ |
+ 55, /* LIKE_KW => ID */ |
+ 0, /* BETWEEN => nothing */ |
+ 0, /* IN => nothing */ |
+ 0, /* ISNULL => nothing */ |
+ 0, /* NOTNULL => nothing */ |
+ 0, /* NE => nothing */ |
+ 0, /* EQ => nothing */ |
+ 0, /* GT => nothing */ |
+ 0, /* LE => nothing */ |
+ 0, /* LT => nothing */ |
+ 0, /* GE => nothing */ |
+ 0, /* ESCAPE => nothing */ |
+ 0, /* BITAND => nothing */ |
+ 0, /* BITOR => nothing */ |
+ 0, /* LSHIFT => nothing */ |
+ 0, /* RSHIFT => nothing */ |
+ 0, /* PLUS => nothing */ |
+ 0, /* MINUS => nothing */ |
+ 0, /* STAR => nothing */ |
+ 0, /* SLASH => nothing */ |
+ 0, /* REM => nothing */ |
+ 0, /* CONCAT => nothing */ |
+ 0, /* COLLATE => nothing */ |
+ 0, /* BITNOT => nothing */ |
+ 0, /* ID => nothing */ |
+ 0, /* INDEXED => nothing */ |
+ 55, /* ABORT => ID */ |
+ 55, /* ACTION => ID */ |
+ 55, /* AFTER => ID */ |
+ 55, /* ANALYZE => ID */ |
+ 55, /* ASC => ID */ |
+ 55, /* ATTACH => ID */ |
+ 55, /* BEFORE => ID */ |
+ 55, /* BY => ID */ |
+ 55, /* CASCADE => ID */ |
+ 55, /* CAST => ID */ |
+ 55, /* COLUMNKW => ID */ |
+ 55, /* CONFLICT => ID */ |
+ 55, /* DATABASE => ID */ |
+ 55, /* DESC => ID */ |
+ 55, /* DETACH => ID */ |
+ 55, /* EACH => ID */ |
+ 55, /* FAIL => ID */ |
+ 55, /* FOR => ID */ |
+ 55, /* IGNORE => ID */ |
+ 55, /* INITIALLY => ID */ |
+ 55, /* INSTEAD => ID */ |
+ 55, /* NO => ID */ |
+ 55, /* KEY => ID */ |
+ 55, /* OF => ID */ |
+ 55, /* OFFSET => ID */ |
+ 55, /* PRAGMA => ID */ |
+ 55, /* RAISE => ID */ |
+ 55, /* RECURSIVE => ID */ |
+ 55, /* REPLACE => ID */ |
+ 55, /* RESTRICT => ID */ |
+ 55, /* ROW => ID */ |
+ 55, /* TRIGGER => ID */ |
+ 55, /* VACUUM => ID */ |
+ 55, /* VIEW => ID */ |
+ 55, /* VIRTUAL => ID */ |
+ 55, /* WITH => ID */ |
+ 55, /* REINDEX => ID */ |
+ 55, /* RENAME => ID */ |
+ 55, /* CTIME_KW => ID */ |
+}; |
+#endif /* YYFALLBACK */ |
+ |
+/* The following structure represents a single element of the |
+** parser's stack. Information stored includes: |
+** |
+** + The state number for the parser at this level of the stack. |
+** |
+** + The value of the token stored at this level of the stack. |
+** (In other words, the "major" token.) |
+** |
+** + The semantic value stored at this level of the stack. This is |
+** the information used by the action routines in the grammar. |
+** It is sometimes called the "minor" token. |
+** |
+** After the "shift" half of a SHIFTREDUCE action, the stateno field |
+** actually contains the reduce action for the second half of the |
+** SHIFTREDUCE. |
+*/ |
+struct yyStackEntry { |
+ YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */ |
+ YYCODETYPE major; /* The major token value. This is the code |
+ ** number for the token at this stack level */ |
+ YYMINORTYPE minor; /* The user-supplied minor token value. This |
+ ** is the value of the token */ |
+}; |
+typedef struct yyStackEntry yyStackEntry; |
+ |
+/* The state of the parser is completely contained in an instance of |
+** the following structure */ |
+struct yyParser { |
+ yyStackEntry *yytos; /* Pointer to top element of the stack */ |
+#ifdef YYTRACKMAXSTACKDEPTH |
+ int yyhwm; /* High-water mark of the stack */ |
+#endif |
+#ifndef YYNOERRORRECOVERY |
+ int yyerrcnt; /* Shifts left before out of the error */ |
+#endif |
+ sqlite3ParserARG_SDECL /* A place to hold %extra_argument */ |
+#if YYSTACKDEPTH<=0 |
+ int yystksz; /* Current side of the stack */ |
+ yyStackEntry *yystack; /* The parser's stack */ |
+ yyStackEntry yystk0; /* First stack entry */ |
+#else |
+ yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ |
+#endif |
+}; |
+typedef struct yyParser yyParser; |
+ |
+#ifndef NDEBUG |
+/* #include <stdio.h> */ |
+static FILE *yyTraceFILE = 0; |
+static char *yyTracePrompt = 0; |
+#endif /* NDEBUG */ |
+ |
+#ifndef NDEBUG |
+/* |
+** Turn parser tracing on by giving a stream to which to write the trace |
+** and a prompt to preface each trace message. Tracing is turned off |
+** by making either argument NULL |
+** |
+** Inputs: |
+** <ul> |
+** <li> A FILE* to which trace output should be written. |
+** If NULL, then tracing is turned off. |
+** <li> A prefix string written at the beginning of every |
+** line of trace output. If NULL, then tracing is |
+** turned off. |
+** </ul> |
+** |
+** Outputs: |
+** None. |
+*/ |
+SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){ |
+ yyTraceFILE = TraceFILE; |
+ yyTracePrompt = zTracePrompt; |
+ if( yyTraceFILE==0 ) yyTracePrompt = 0; |
+ else if( yyTracePrompt==0 ) yyTraceFILE = 0; |
+} |
+#endif /* NDEBUG */ |
+ |
+#ifndef NDEBUG |
+/* For tracing shifts, the names of all terminals and nonterminals |
+** are required. The following table supplies these names */ |
+static const char *const yyTokenName[] = { |
+ "$", "SEMI", "EXPLAIN", "QUERY", |
+ "PLAN", "BEGIN", "TRANSACTION", "DEFERRED", |
+ "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END", |
+ "ROLLBACK", "SAVEPOINT", "RELEASE", "TO", |
+ "TABLE", "CREATE", "IF", "NOT", |
+ "EXISTS", "TEMP", "LP", "RP", |
+ "AS", "WITHOUT", "COMMA", "OR", |
+ "AND", "IS", "MATCH", "LIKE_KW", |
+ "BETWEEN", "IN", "ISNULL", "NOTNULL", |
+ "NE", "EQ", "GT", "LE", |
+ "LT", "GE", "ESCAPE", "BITAND", |
+ "BITOR", "LSHIFT", "RSHIFT", "PLUS", |
+ "MINUS", "STAR", "SLASH", "REM", |
+ "CONCAT", "COLLATE", "BITNOT", "ID", |
+ "INDEXED", "ABORT", "ACTION", "AFTER", |
+ "ANALYZE", "ASC", "ATTACH", "BEFORE", |
+ "BY", "CASCADE", "CAST", "COLUMNKW", |
+ "CONFLICT", "DATABASE", "DESC", "DETACH", |
+ "EACH", "FAIL", "FOR", "IGNORE", |
+ "INITIALLY", "INSTEAD", "NO", "KEY", |
+ "OF", "OFFSET", "PRAGMA", "RAISE", |
+ "RECURSIVE", "REPLACE", "RESTRICT", "ROW", |
+ "TRIGGER", "VACUUM", "VIEW", "VIRTUAL", |
+ "WITH", "REINDEX", "RENAME", "CTIME_KW", |
+ "ANY", "STRING", "JOIN_KW", "CONSTRAINT", |
+ "DEFAULT", "NULL", "PRIMARY", "UNIQUE", |
+ "CHECK", "REFERENCES", "AUTOINCR", "ON", |
+ "INSERT", "DELETE", "UPDATE", "SET", |
+ "DEFERRABLE", "FOREIGN", "DROP", "UNION", |
+ "ALL", "EXCEPT", "INTERSECT", "SELECT", |
+ "VALUES", "DISTINCT", "DOT", "FROM", |
+ "JOIN", "USING", "ORDER", "GROUP", |
+ "HAVING", "LIMIT", "WHERE", "INTO", |
+ "FLOAT", "BLOB", "INTEGER", "VARIABLE", |
+ "CASE", "WHEN", "THEN", "ELSE", |
+ "INDEX", "ALTER", "ADD", "error", |
+ "input", "cmdlist", "ecmd", "explain", |
+ "cmdx", "cmd", "transtype", "trans_opt", |
+ "nm", "savepoint_opt", "create_table", "create_table_args", |
+ "createkw", "temp", "ifnotexists", "dbnm", |
+ "columnlist", "conslist_opt", "table_options", "select", |
+ "columnname", "carglist", "typetoken", "typename", |
+ "signed", "plus_num", "minus_num", "ccons", |
+ "term", "expr", "onconf", "sortorder", |
+ "autoinc", "eidlist_opt", "refargs", "defer_subclause", |
+ "refarg", "refact", "init_deferred_pred_opt", "conslist", |
+ "tconscomma", "tcons", "sortlist", "eidlist", |
+ "defer_subclause_opt", "orconf", "resolvetype", "raisetype", |
+ "ifexists", "fullname", "selectnowith", "oneselect", |
+ "with", "multiselect_op", "distinct", "selcollist", |
+ "from", "where_opt", "groupby_opt", "having_opt", |
+ "orderby_opt", "limit_opt", "values", "nexprlist", |
+ "exprlist", "sclp", "as", "seltablist", |
+ "stl_prefix", "joinop", "indexed_opt", "on_opt", |
+ "using_opt", "idlist", "setlist", "insert_cmd", |
+ "idlist_opt", "likeop", "between_op", "in_op", |
+ "paren_exprlist", "case_operand", "case_exprlist", "case_else", |
+ "uniqueflag", "collate", "nmnum", "trigger_decl", |
+ "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause", |
+ "when_clause", "trigger_cmd", "trnm", "tridxby", |
+ "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt", |
+ "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken", |
+ "lp", "anylist", "wqlist", |
+}; |
+#endif /* NDEBUG */ |
+ |
+#ifndef NDEBUG |
+/* For tracing reduce actions, the names of all rules are required. |
+*/ |
+static const char *const yyRuleName[] = { |
+ /* 0 */ "explain ::= EXPLAIN", |
+ /* 1 */ "explain ::= EXPLAIN QUERY PLAN", |
+ /* 2 */ "cmdx ::= cmd", |
+ /* 3 */ "cmd ::= BEGIN transtype trans_opt", |
+ /* 4 */ "transtype ::=", |
+ /* 5 */ "transtype ::= DEFERRED", |
+ /* 6 */ "transtype ::= IMMEDIATE", |
+ /* 7 */ "transtype ::= EXCLUSIVE", |
+ /* 8 */ "cmd ::= COMMIT trans_opt", |
+ /* 9 */ "cmd ::= END trans_opt", |
+ /* 10 */ "cmd ::= ROLLBACK trans_opt", |
+ /* 11 */ "cmd ::= SAVEPOINT nm", |
+ /* 12 */ "cmd ::= RELEASE savepoint_opt nm", |
+ /* 13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm", |
+ /* 14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm", |
+ /* 15 */ "createkw ::= CREATE", |
+ /* 16 */ "ifnotexists ::=", |
+ /* 17 */ "ifnotexists ::= IF NOT EXISTS", |
+ /* 18 */ "temp ::= TEMP", |
+ /* 19 */ "temp ::=", |
+ /* 20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options", |
+ /* 21 */ "create_table_args ::= AS select", |
+ /* 22 */ "table_options ::=", |
+ /* 23 */ "table_options ::= WITHOUT nm", |
+ /* 24 */ "columnname ::= nm typetoken", |
+ /* 25 */ "typetoken ::=", |
+ /* 26 */ "typetoken ::= typename LP signed RP", |
+ /* 27 */ "typetoken ::= typename LP signed COMMA signed RP", |
+ /* 28 */ "typename ::= typename ID|STRING", |
+ /* 29 */ "ccons ::= CONSTRAINT nm", |
+ /* 30 */ "ccons ::= DEFAULT term", |
+ /* 31 */ "ccons ::= DEFAULT LP expr RP", |
+ /* 32 */ "ccons ::= DEFAULT PLUS term", |
+ /* 33 */ "ccons ::= DEFAULT MINUS term", |
+ /* 34 */ "ccons ::= DEFAULT ID|INDEXED", |
+ /* 35 */ "ccons ::= NOT NULL onconf", |
+ /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc", |
+ /* 37 */ "ccons ::= UNIQUE onconf", |
+ /* 38 */ "ccons ::= CHECK LP expr RP", |
+ /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs", |
+ /* 40 */ "ccons ::= defer_subclause", |
+ /* 41 */ "ccons ::= COLLATE ID|STRING", |
+ /* 42 */ "autoinc ::=", |
+ /* 43 */ "autoinc ::= AUTOINCR", |
+ /* 44 */ "refargs ::=", |
+ /* 45 */ "refargs ::= refargs refarg", |
+ /* 46 */ "refarg ::= MATCH nm", |
+ /* 47 */ "refarg ::= ON INSERT refact", |
+ /* 48 */ "refarg ::= ON DELETE refact", |
+ /* 49 */ "refarg ::= ON UPDATE refact", |
+ /* 50 */ "refact ::= SET NULL", |
+ /* 51 */ "refact ::= SET DEFAULT", |
+ /* 52 */ "refact ::= CASCADE", |
+ /* 53 */ "refact ::= RESTRICT", |
+ /* 54 */ "refact ::= NO ACTION", |
+ /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt", |
+ /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt", |
+ /* 57 */ "init_deferred_pred_opt ::=", |
+ /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED", |
+ /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE", |
+ /* 60 */ "conslist_opt ::=", |
+ /* 61 */ "tconscomma ::= COMMA", |
+ /* 62 */ "tcons ::= CONSTRAINT nm", |
+ /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf", |
+ /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf", |
+ /* 65 */ "tcons ::= CHECK LP expr RP onconf", |
+ /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt", |
+ /* 67 */ "defer_subclause_opt ::=", |
+ /* 68 */ "onconf ::=", |
+ /* 69 */ "onconf ::= ON CONFLICT resolvetype", |
+ /* 70 */ "orconf ::=", |
+ /* 71 */ "orconf ::= OR resolvetype", |
+ /* 72 */ "resolvetype ::= IGNORE", |
+ /* 73 */ "resolvetype ::= REPLACE", |
+ /* 74 */ "cmd ::= DROP TABLE ifexists fullname", |
+ /* 75 */ "ifexists ::= IF EXISTS", |
+ /* 76 */ "ifexists ::=", |
+ /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select", |
+ /* 78 */ "cmd ::= DROP VIEW ifexists fullname", |
+ /* 79 */ "cmd ::= select", |
+ /* 80 */ "select ::= with selectnowith", |
+ /* 81 */ "selectnowith ::= selectnowith multiselect_op oneselect", |
+ /* 82 */ "multiselect_op ::= UNION", |
+ /* 83 */ "multiselect_op ::= UNION ALL", |
+ /* 84 */ "multiselect_op ::= EXCEPT|INTERSECT", |
+ /* 85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt", |
+ /* 86 */ "values ::= VALUES LP nexprlist RP", |
+ /* 87 */ "values ::= values COMMA LP exprlist RP", |
+ /* 88 */ "distinct ::= DISTINCT", |
+ /* 89 */ "distinct ::= ALL", |
+ /* 90 */ "distinct ::=", |
+ /* 91 */ "sclp ::=", |
+ /* 92 */ "selcollist ::= sclp expr as", |
+ /* 93 */ "selcollist ::= sclp STAR", |
+ /* 94 */ "selcollist ::= sclp nm DOT STAR", |
+ /* 95 */ "as ::= AS nm", |
+ /* 96 */ "as ::=", |
+ /* 97 */ "from ::=", |
+ /* 98 */ "from ::= FROM seltablist", |
+ /* 99 */ "stl_prefix ::= seltablist joinop", |
+ /* 100 */ "stl_prefix ::=", |
+ /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt", |
+ /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt", |
+ /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt", |
+ /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt", |
+ /* 105 */ "dbnm ::=", |
+ /* 106 */ "dbnm ::= DOT nm", |
+ /* 107 */ "fullname ::= nm dbnm", |
+ /* 108 */ "joinop ::= COMMA|JOIN", |
+ /* 109 */ "joinop ::= JOIN_KW JOIN", |
+ /* 110 */ "joinop ::= JOIN_KW nm JOIN", |
+ /* 111 */ "joinop ::= JOIN_KW nm nm JOIN", |
+ /* 112 */ "on_opt ::= ON expr", |
+ /* 113 */ "on_opt ::=", |
+ /* 114 */ "indexed_opt ::=", |
+ /* 115 */ "indexed_opt ::= INDEXED BY nm", |
+ /* 116 */ "indexed_opt ::= NOT INDEXED", |
+ /* 117 */ "using_opt ::= USING LP idlist RP", |
+ /* 118 */ "using_opt ::=", |
+ /* 119 */ "orderby_opt ::=", |
+ /* 120 */ "orderby_opt ::= ORDER BY sortlist", |
+ /* 121 */ "sortlist ::= sortlist COMMA expr sortorder", |
+ /* 122 */ "sortlist ::= expr sortorder", |
+ /* 123 */ "sortorder ::= ASC", |
+ /* 124 */ "sortorder ::= DESC", |
+ /* 125 */ "sortorder ::=", |
+ /* 126 */ "groupby_opt ::=", |
+ /* 127 */ "groupby_opt ::= GROUP BY nexprlist", |
+ /* 128 */ "having_opt ::=", |
+ /* 129 */ "having_opt ::= HAVING expr", |
+ /* 130 */ "limit_opt ::=", |
+ /* 131 */ "limit_opt ::= LIMIT expr", |
+ /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr", |
+ /* 133 */ "limit_opt ::= LIMIT expr COMMA expr", |
+ /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt", |
+ /* 135 */ "where_opt ::=", |
+ /* 136 */ "where_opt ::= WHERE expr", |
+ /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt", |
+ /* 138 */ "setlist ::= setlist COMMA nm EQ expr", |
+ /* 139 */ "setlist ::= setlist COMMA LP idlist RP EQ expr", |
+ /* 140 */ "setlist ::= nm EQ expr", |
+ /* 141 */ "setlist ::= LP idlist RP EQ expr", |
+ /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select", |
+ /* 143 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES", |
+ /* 144 */ "insert_cmd ::= INSERT orconf", |
+ /* 145 */ "insert_cmd ::= REPLACE", |
+ /* 146 */ "idlist_opt ::=", |
+ /* 147 */ "idlist_opt ::= LP idlist RP", |
+ /* 148 */ "idlist ::= idlist COMMA nm", |
+ /* 149 */ "idlist ::= nm", |
+ /* 150 */ "expr ::= LP expr RP", |
+ /* 151 */ "term ::= NULL", |
+ /* 152 */ "expr ::= ID|INDEXED", |
+ /* 153 */ "expr ::= JOIN_KW", |
+ /* 154 */ "expr ::= nm DOT nm", |
+ /* 155 */ "expr ::= nm DOT nm DOT nm", |
+ /* 156 */ "term ::= FLOAT|BLOB", |
+ /* 157 */ "term ::= STRING", |
+ /* 158 */ "term ::= INTEGER", |
+ /* 159 */ "expr ::= VARIABLE", |
+ /* 160 */ "expr ::= expr COLLATE ID|STRING", |
+ /* 161 */ "expr ::= CAST LP expr AS typetoken RP", |
+ /* 162 */ "expr ::= ID|INDEXED LP distinct exprlist RP", |
+ /* 163 */ "expr ::= ID|INDEXED LP STAR RP", |
+ /* 164 */ "term ::= CTIME_KW", |
+ /* 165 */ "expr ::= LP nexprlist COMMA expr RP", |
+ /* 166 */ "expr ::= expr AND expr", |
+ /* 167 */ "expr ::= expr OR expr", |
+ /* 168 */ "expr ::= expr LT|GT|GE|LE expr", |
+ /* 169 */ "expr ::= expr EQ|NE expr", |
+ /* 170 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr", |
+ /* 171 */ "expr ::= expr PLUS|MINUS expr", |
+ /* 172 */ "expr ::= expr STAR|SLASH|REM expr", |
+ /* 173 */ "expr ::= expr CONCAT expr", |
+ /* 174 */ "likeop ::= LIKE_KW|MATCH", |
+ /* 175 */ "likeop ::= NOT LIKE_KW|MATCH", |
+ /* 176 */ "expr ::= expr likeop expr", |
+ /* 177 */ "expr ::= expr likeop expr ESCAPE expr", |
+ /* 178 */ "expr ::= expr ISNULL|NOTNULL", |
+ /* 179 */ "expr ::= expr NOT NULL", |
+ /* 180 */ "expr ::= expr IS expr", |
+ /* 181 */ "expr ::= expr IS NOT expr", |
+ /* 182 */ "expr ::= NOT expr", |
+ /* 183 */ "expr ::= BITNOT expr", |
+ /* 184 */ "expr ::= MINUS expr", |
+ /* 185 */ "expr ::= PLUS expr", |
+ /* 186 */ "between_op ::= BETWEEN", |
+ /* 187 */ "between_op ::= NOT BETWEEN", |
+ /* 188 */ "expr ::= expr between_op expr AND expr", |
+ /* 189 */ "in_op ::= IN", |
+ /* 190 */ "in_op ::= NOT IN", |
+ /* 191 */ "expr ::= expr in_op LP exprlist RP", |
+ /* 192 */ "expr ::= LP select RP", |
+ /* 193 */ "expr ::= expr in_op LP select RP", |
+ /* 194 */ "expr ::= expr in_op nm dbnm paren_exprlist", |
+ /* 195 */ "expr ::= EXISTS LP select RP", |
+ /* 196 */ "expr ::= CASE case_operand case_exprlist case_else END", |
+ /* 197 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr", |
+ /* 198 */ "case_exprlist ::= WHEN expr THEN expr", |
+ /* 199 */ "case_else ::= ELSE expr", |
+ /* 200 */ "case_else ::=", |
+ /* 201 */ "case_operand ::= expr", |
+ /* 202 */ "case_operand ::=", |
+ /* 203 */ "exprlist ::=", |
+ /* 204 */ "nexprlist ::= nexprlist COMMA expr", |
+ /* 205 */ "nexprlist ::= expr", |
+ /* 206 */ "paren_exprlist ::=", |
+ /* 207 */ "paren_exprlist ::= LP exprlist RP", |
+ /* 208 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt", |
+ /* 209 */ "uniqueflag ::= UNIQUE", |
+ /* 210 */ "uniqueflag ::=", |
+ /* 211 */ "eidlist_opt ::=", |
+ /* 212 */ "eidlist_opt ::= LP eidlist RP", |
+ /* 213 */ "eidlist ::= eidlist COMMA nm collate sortorder", |
+ /* 214 */ "eidlist ::= nm collate sortorder", |
+ /* 215 */ "collate ::=", |
+ /* 216 */ "collate ::= COLLATE ID|STRING", |
+ /* 217 */ "cmd ::= DROP INDEX ifexists fullname", |
+ /* 218 */ "cmd ::= VACUUM", |
+ /* 219 */ "cmd ::= VACUUM nm", |
+ /* 220 */ "cmd ::= PRAGMA nm dbnm", |
+ /* 221 */ "cmd ::= PRAGMA nm dbnm EQ nmnum", |
+ /* 222 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP", |
+ /* 223 */ "cmd ::= PRAGMA nm dbnm EQ minus_num", |
+ /* 224 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP", |
+ /* 225 */ "plus_num ::= PLUS INTEGER|FLOAT", |
+ /* 226 */ "minus_num ::= MINUS INTEGER|FLOAT", |
+ /* 227 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END", |
+ /* 228 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause", |
+ /* 229 */ "trigger_time ::= BEFORE", |
+ /* 230 */ "trigger_time ::= AFTER", |
+ /* 231 */ "trigger_time ::= INSTEAD OF", |
+ /* 232 */ "trigger_time ::=", |
+ /* 233 */ "trigger_event ::= DELETE|INSERT", |
+ /* 234 */ "trigger_event ::= UPDATE", |
+ /* 235 */ "trigger_event ::= UPDATE OF idlist", |
+ /* 236 */ "when_clause ::=", |
+ /* 237 */ "when_clause ::= WHEN expr", |
+ /* 238 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", |
+ /* 239 */ "trigger_cmd_list ::= trigger_cmd SEMI", |
+ /* 240 */ "trnm ::= nm DOT nm", |
+ /* 241 */ "tridxby ::= INDEXED BY nm", |
+ /* 242 */ "tridxby ::= NOT INDEXED", |
+ /* 243 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt", |
+ /* 244 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select", |
+ /* 245 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt", |
+ /* 246 */ "trigger_cmd ::= select", |
+ /* 247 */ "expr ::= RAISE LP IGNORE RP", |
+ /* 248 */ "expr ::= RAISE LP raisetype COMMA nm RP", |
+ /* 249 */ "raisetype ::= ROLLBACK", |
+ /* 250 */ "raisetype ::= ABORT", |
+ /* 251 */ "raisetype ::= FAIL", |
+ /* 252 */ "cmd ::= DROP TRIGGER ifexists fullname", |
+ /* 253 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", |
+ /* 254 */ "cmd ::= DETACH database_kw_opt expr", |
+ /* 255 */ "key_opt ::=", |
+ /* 256 */ "key_opt ::= KEY expr", |
+ /* 257 */ "cmd ::= REINDEX", |
+ /* 258 */ "cmd ::= REINDEX nm dbnm", |
+ /* 259 */ "cmd ::= ANALYZE", |
+ /* 260 */ "cmd ::= ANALYZE nm dbnm", |
+ /* 261 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", |
+ /* 262 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist", |
+ /* 263 */ "add_column_fullname ::= fullname", |
+ /* 264 */ "cmd ::= create_vtab", |
+ /* 265 */ "cmd ::= create_vtab LP vtabarglist RP", |
+ /* 266 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm", |
+ /* 267 */ "vtabarg ::=", |
+ /* 268 */ "vtabargtoken ::= ANY", |
+ /* 269 */ "vtabargtoken ::= lp anylist RP", |
+ /* 270 */ "lp ::= LP", |
+ /* 271 */ "with ::=", |
+ /* 272 */ "with ::= WITH wqlist", |
+ /* 273 */ "with ::= WITH RECURSIVE wqlist", |
+ /* 274 */ "wqlist ::= nm eidlist_opt AS LP select RP", |
+ /* 275 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP", |
+ /* 276 */ "input ::= cmdlist", |
+ /* 277 */ "cmdlist ::= cmdlist ecmd", |
+ /* 278 */ "cmdlist ::= ecmd", |
+ /* 279 */ "ecmd ::= SEMI", |
+ /* 280 */ "ecmd ::= explain cmdx SEMI", |
+ /* 281 */ "explain ::=", |
+ /* 282 */ "trans_opt ::=", |
+ /* 283 */ "trans_opt ::= TRANSACTION", |
+ /* 284 */ "trans_opt ::= TRANSACTION nm", |
+ /* 285 */ "savepoint_opt ::= SAVEPOINT", |
+ /* 286 */ "savepoint_opt ::=", |
+ /* 287 */ "cmd ::= create_table create_table_args", |
+ /* 288 */ "columnlist ::= columnlist COMMA columnname carglist", |
+ /* 289 */ "columnlist ::= columnname carglist", |
+ /* 290 */ "nm ::= ID|INDEXED", |
+ /* 291 */ "nm ::= STRING", |
+ /* 292 */ "nm ::= JOIN_KW", |
+ /* 293 */ "typetoken ::= typename", |
+ /* 294 */ "typename ::= ID|STRING", |
+ /* 295 */ "signed ::= plus_num", |
+ /* 296 */ "signed ::= minus_num", |
+ /* 297 */ "carglist ::= carglist ccons", |
+ /* 298 */ "carglist ::=", |
+ /* 299 */ "ccons ::= NULL onconf", |
+ /* 300 */ "conslist_opt ::= COMMA conslist", |
+ /* 301 */ "conslist ::= conslist tconscomma tcons", |
+ /* 302 */ "conslist ::= tcons", |
+ /* 303 */ "tconscomma ::=", |
+ /* 304 */ "defer_subclause_opt ::= defer_subclause", |
+ /* 305 */ "resolvetype ::= raisetype", |
+ /* 306 */ "selectnowith ::= oneselect", |
+ /* 307 */ "oneselect ::= values", |
+ /* 308 */ "sclp ::= selcollist COMMA", |
+ /* 309 */ "as ::= ID|STRING", |
+ /* 310 */ "expr ::= term", |
+ /* 311 */ "exprlist ::= nexprlist", |
+ /* 312 */ "nmnum ::= plus_num", |
+ /* 313 */ "nmnum ::= nm", |
+ /* 314 */ "nmnum ::= ON", |
+ /* 315 */ "nmnum ::= DELETE", |
+ /* 316 */ "nmnum ::= DEFAULT", |
+ /* 317 */ "plus_num ::= INTEGER|FLOAT", |
+ /* 318 */ "foreach_clause ::=", |
+ /* 319 */ "foreach_clause ::= FOR EACH ROW", |
+ /* 320 */ "trnm ::= nm", |
+ /* 321 */ "tridxby ::=", |
+ /* 322 */ "database_kw_opt ::= DATABASE", |
+ /* 323 */ "database_kw_opt ::=", |
+ /* 324 */ "kwcolumn_opt ::=", |
+ /* 325 */ "kwcolumn_opt ::= COLUMNKW", |
+ /* 326 */ "vtabarglist ::= vtabarg", |
+ /* 327 */ "vtabarglist ::= vtabarglist COMMA vtabarg", |
+ /* 328 */ "vtabarg ::= vtabarg vtabargtoken", |
+ /* 329 */ "anylist ::=", |
+ /* 330 */ "anylist ::= anylist LP anylist RP", |
+ /* 331 */ "anylist ::= anylist ANY", |
+}; |
+#endif /* NDEBUG */ |
+ |
+ |
+#if YYSTACKDEPTH<=0 |
+/* |
+** Try to increase the size of the parser stack. Return the number |
+** of errors. Return 0 on success. |
+*/ |
+static int yyGrowStack(yyParser *p){ |
+ int newSize; |
+ int idx; |
+ yyStackEntry *pNew; |
+ |
+ newSize = p->yystksz*2 + 100; |
+ idx = p->yytos ? (int)(p->yytos - p->yystack) : 0; |
+ if( p->yystack==&p->yystk0 ){ |
+ pNew = malloc(newSize*sizeof(pNew[0])); |
+ if( pNew ) pNew[0] = p->yystk0; |
+ }else{ |
+ pNew = realloc(p->yystack, newSize*sizeof(pNew[0])); |
+ } |
+ if( pNew ){ |
+ p->yystack = pNew; |
+ p->yytos = &p->yystack[idx]; |
+#ifndef NDEBUG |
+ if( yyTraceFILE ){ |
+ fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n", |
+ yyTracePrompt, p->yystksz, newSize); |
+ } |
+#endif |
+ p->yystksz = newSize; |
+ } |
+ return pNew==0; |
+} |
+#endif |
+ |
+/* Datatype of the argument to the memory allocated passed as the |
+** second argument to sqlite3ParserAlloc() below. This can be changed by |
+** putting an appropriate #define in the %include section of the input |
+** grammar. |
+*/ |
+#ifndef YYMALLOCARGTYPE |
+# define YYMALLOCARGTYPE size_t |
+#endif |
+ |
+/* Initialize a new parser that has already been allocated. |
+*/ |
+SQLITE_PRIVATE void sqlite3ParserInit(void *yypParser){ |
+ yyParser *pParser = (yyParser*)yypParser; |
+#ifdef YYTRACKMAXSTACKDEPTH |
+ pParser->yyhwm = 0; |
+#endif |
+#if YYSTACKDEPTH<=0 |
+ pParser->yytos = NULL; |
+ pParser->yystack = NULL; |
+ pParser->yystksz = 0; |
+ if( yyGrowStack(pParser) ){ |
+ pParser->yystack = &pParser->yystk0; |
+ pParser->yystksz = 1; |
+ } |
+#endif |
+#ifndef YYNOERRORRECOVERY |
+ pParser->yyerrcnt = -1; |
+#endif |
+ pParser->yytos = pParser->yystack; |
+ pParser->yystack[0].stateno = 0; |
+ pParser->yystack[0].major = 0; |
+} |
+ |
+#ifndef sqlite3Parser_ENGINEALWAYSONSTACK |
+/* |
+** This function allocates a new parser. |
+** The only argument is a pointer to a function which works like |
+** malloc. |
+** |
+** Inputs: |
+** A pointer to the function used to allocate memory. |
+** |
+** Outputs: |
+** A pointer to a parser. This pointer is used in subsequent calls |
+** to sqlite3Parser and sqlite3ParserFree. |
+*/ |
+SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){ |
+ yyParser *pParser; |
+ pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) ); |
+ if( pParser ) sqlite3ParserInit(pParser); |
+ return pParser; |
+} |
+#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */ |
+ |
+ |
+/* The following function deletes the "minor type" or semantic value |
+** associated with a symbol. The symbol can be either a terminal |
+** or nonterminal. "yymajor" is the symbol code, and "yypminor" is |
+** a pointer to the value to be deleted. The code used to do the |
+** deletions is derived from the %destructor and/or %token_destructor |
+** directives of the input grammar. |
+*/ |
+static void yy_destructor( |
+ yyParser *yypParser, /* The parser */ |
+ YYCODETYPE yymajor, /* Type code for object to destroy */ |
+ YYMINORTYPE *yypminor /* The object to be destroyed */ |
+){ |
+ sqlite3ParserARG_FETCH; |
+ switch( yymajor ){ |
+ /* Here is inserted the actions which take place when a |
+ ** terminal or non-terminal is destroyed. This can happen |
+ ** when the symbol is popped from the stack during a |
+ ** reduce or during error processing or when a parser is |
+ ** being destroyed before it is finished parsing. |
+ ** |
+ ** Note: during a reduce, the only symbols destroyed are those |
+ ** which appear on the RHS of the rule, but which are *not* used |
+ ** inside the C code. |
+ */ |
+/********* Begin destructor definitions ***************************************/ |
+ case 163: /* select */ |
+ case 194: /* selectnowith */ |
+ case 195: /* oneselect */ |
+ case 206: /* values */ |
+{ |
+sqlite3SelectDelete(pParse->db, (yypminor->yy243)); |
+} |
+ break; |
+ case 172: /* term */ |
+ case 173: /* expr */ |
+{ |
+sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr); |
+} |
+ break; |
+ case 177: /* eidlist_opt */ |
+ case 186: /* sortlist */ |
+ case 187: /* eidlist */ |
+ case 199: /* selcollist */ |
+ case 202: /* groupby_opt */ |
+ case 204: /* orderby_opt */ |
+ case 207: /* nexprlist */ |
+ case 208: /* exprlist */ |
+ case 209: /* sclp */ |
+ case 218: /* setlist */ |
+ case 224: /* paren_exprlist */ |
+ case 226: /* case_exprlist */ |
+{ |
+sqlite3ExprListDelete(pParse->db, (yypminor->yy148)); |
+} |
+ break; |
+ case 193: /* fullname */ |
+ case 200: /* from */ |
+ case 211: /* seltablist */ |
+ case 212: /* stl_prefix */ |
+{ |
+sqlite3SrcListDelete(pParse->db, (yypminor->yy185)); |
+} |
+ break; |
+ case 196: /* with */ |
+ case 250: /* wqlist */ |
+{ |
+sqlite3WithDelete(pParse->db, (yypminor->yy285)); |
+} |
+ break; |
+ case 201: /* where_opt */ |
+ case 203: /* having_opt */ |
+ case 215: /* on_opt */ |
+ case 225: /* case_operand */ |
+ case 227: /* case_else */ |
+ case 236: /* when_clause */ |
+ case 241: /* key_opt */ |
+{ |
+sqlite3ExprDelete(pParse->db, (yypminor->yy72)); |
+} |
+ break; |
+ case 216: /* using_opt */ |
+ case 217: /* idlist */ |
+ case 220: /* idlist_opt */ |
+{ |
+sqlite3IdListDelete(pParse->db, (yypminor->yy254)); |
+} |
+ break; |
+ case 232: /* trigger_cmd_list */ |
+ case 237: /* trigger_cmd */ |
+{ |
+sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145)); |
+} |
+ break; |
+ case 234: /* trigger_event */ |
+{ |
+sqlite3IdListDelete(pParse->db, (yypminor->yy332).b); |
+} |
+ break; |
+/********* End destructor definitions *****************************************/ |
+ default: break; /* If no destructor action specified: do nothing */ |
+ } |
+} |
+ |
+/* |
+** Pop the parser's stack once. |
+** |
+** If there is a destructor routine associated with the token which |
+** is popped from the stack, then call it. |
+*/ |
+static void yy_pop_parser_stack(yyParser *pParser){ |
+ yyStackEntry *yytos; |
+ assert( pParser->yytos!=0 ); |
+ assert( pParser->yytos > pParser->yystack ); |
+ yytos = pParser->yytos--; |
+#ifndef NDEBUG |
+ if( yyTraceFILE ){ |
+ fprintf(yyTraceFILE,"%sPopping %s\n", |
+ yyTracePrompt, |
+ yyTokenName[yytos->major]); |
+ } |
+#endif |
+ yy_destructor(pParser, yytos->major, &yytos->minor); |
+} |
+ |
+/* |
+** Clear all secondary memory allocations from the parser |
+*/ |
+SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){ |
+ yyParser *pParser = (yyParser*)p; |
+ while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser); |
+#if YYSTACKDEPTH<=0 |
+ if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack); |
+#endif |
+} |
+ |
+#ifndef sqlite3Parser_ENGINEALWAYSONSTACK |
+/* |
+** Deallocate and destroy a parser. Destructors are called for |
+** all stack elements before shutting the parser down. |
+** |
+** If the YYPARSEFREENEVERNULL macro exists (for example because it |
+** is defined in a %include section of the input grammar) then it is |
+** assumed that the input pointer is never NULL. |
+*/ |
+SQLITE_PRIVATE void sqlite3ParserFree( |
+ void *p, /* The parser to be deleted */ |
+ void (*freeProc)(void*) /* Function used to reclaim memory */ |
+){ |
+#ifndef YYPARSEFREENEVERNULL |
+ if( p==0 ) return; |
+#endif |
+ sqlite3ParserFinalize(p); |
+ (*freeProc)(p); |
+} |
+#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */ |
+ |
+/* |
+** Return the peak depth of the stack for a parser. |
+*/ |
+#ifdef YYTRACKMAXSTACKDEPTH |
+SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){ |
+ yyParser *pParser = (yyParser*)p; |
+ return pParser->yyhwm; |
+} |
+#endif |
+ |
+/* |
+** Find the appropriate action for a parser given the terminal |
+** look-ahead token iLookAhead. |
+*/ |
+static unsigned int yy_find_shift_action( |
+ yyParser *pParser, /* The parser */ |
+ YYCODETYPE iLookAhead /* The look-ahead token */ |
+){ |
+ int i; |
+ int stateno = pParser->yytos->stateno; |
+ |
+ if( stateno>=YY_MIN_REDUCE ) return stateno; |
+ assert( stateno <= YY_SHIFT_COUNT ); |
+ do{ |
+ i = yy_shift_ofst[stateno]; |
+ assert( iLookAhead!=YYNOCODE ); |
+ i += iLookAhead; |
+ if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ |
+#ifdef YYFALLBACK |
+ YYCODETYPE iFallback; /* Fallback token */ |
+ if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0]) |
+ && (iFallback = yyFallback[iLookAhead])!=0 ){ |
+#ifndef NDEBUG |
+ if( yyTraceFILE ){ |
+ fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n", |
+ yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); |
+ } |
+#endif |
+ assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */ |
+ iLookAhead = iFallback; |
+ continue; |
+ } |
+#endif |
+#ifdef YYWILDCARD |
+ { |
+ int j = i - iLookAhead + YYWILDCARD; |
+ if( |
+#if YY_SHIFT_MIN+YYWILDCARD<0 |
+ j>=0 && |
+#endif |
+#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT |
+ j<YY_ACTTAB_COUNT && |
+#endif |
+ yy_lookahead[j]==YYWILDCARD && iLookAhead>0 |
+ ){ |
+#ifndef NDEBUG |
+ if( yyTraceFILE ){ |
+ fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n", |
+ yyTracePrompt, yyTokenName[iLookAhead], |
+ yyTokenName[YYWILDCARD]); |
+ } |
+#endif /* NDEBUG */ |
+ return yy_action[j]; |
+ } |
+ } |
+#endif /* YYWILDCARD */ |
+ return yy_default[stateno]; |
+ }else{ |
+ return yy_action[i]; |
+ } |
+ }while(1); |
+} |
+ |
+/* |
+** Find the appropriate action for a parser given the non-terminal |
+** look-ahead token iLookAhead. |
+*/ |
+static int yy_find_reduce_action( |
+ int stateno, /* Current state number */ |
+ YYCODETYPE iLookAhead /* The look-ahead token */ |
+){ |
+ int i; |
+#ifdef YYERRORSYMBOL |
+ if( stateno>YY_REDUCE_COUNT ){ |
+ return yy_default[stateno]; |
+ } |
+#else |
+ assert( stateno<=YY_REDUCE_COUNT ); |
+#endif |
+ i = yy_reduce_ofst[stateno]; |
+ assert( i!=YY_REDUCE_USE_DFLT ); |
+ assert( iLookAhead!=YYNOCODE ); |
+ i += iLookAhead; |
+#ifdef YYERRORSYMBOL |
+ if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ |
+ return yy_default[stateno]; |
+ } |
+#else |
+ assert( i>=0 && i<YY_ACTTAB_COUNT ); |
+ assert( yy_lookahead[i]==iLookAhead ); |
+#endif |
+ return yy_action[i]; |
+} |
+ |
+/* |
+** The following routine is called if the stack overflows. |
+*/ |
+static void yyStackOverflow(yyParser *yypParser){ |
+ sqlite3ParserARG_FETCH; |
+#ifndef NDEBUG |
+ if( yyTraceFILE ){ |
+ fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); |
+ } |
+#endif |
+ while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser); |
+ /* Here code is inserted which will execute if the parser |
+ ** stack every overflows */ |
+/******** Begin %stack_overflow code ******************************************/ |
+ |
+ sqlite3ErrorMsg(pParse, "parser stack overflow"); |
+/******** End %stack_overflow code ********************************************/ |
+ sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */ |
+} |
+ |
+/* |
+** Print tracing information for a SHIFT action |
+*/ |
+#ifndef NDEBUG |
+static void yyTraceShift(yyParser *yypParser, int yyNewState){ |
+ if( yyTraceFILE ){ |
+ if( yyNewState<YYNSTATE ){ |
+ fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n", |
+ yyTracePrompt,yyTokenName[yypParser->yytos->major], |
+ yyNewState); |
+ }else{ |
+ fprintf(yyTraceFILE,"%sShift '%s'\n", |
+ yyTracePrompt,yyTokenName[yypParser->yytos->major]); |
+ } |
+ } |
+} |
+#else |
+# define yyTraceShift(X,Y) |
+#endif |
+ |
+/* |
+** Perform a shift action. |
+*/ |
+static void yy_shift( |
+ yyParser *yypParser, /* The parser to be shifted */ |
+ int yyNewState, /* The new state to shift in */ |
+ int yyMajor, /* The major token to shift in */ |
+ sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */ |
+){ |
+ yyStackEntry *yytos; |
+ yypParser->yytos++; |
+#ifdef YYTRACKMAXSTACKDEPTH |
+ if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){ |
+ yypParser->yyhwm++; |
+ assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) ); |
+ } |
+#endif |
+#if YYSTACKDEPTH>0 |
+ if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH] ){ |
+ yypParser->yytos--; |
+ yyStackOverflow(yypParser); |
+ return; |
+ } |
+#else |
+ if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){ |
+ if( yyGrowStack(yypParser) ){ |
+ yypParser->yytos--; |
+ yyStackOverflow(yypParser); |
+ return; |
+ } |
+ } |
+#endif |
+ if( yyNewState > YY_MAX_SHIFT ){ |
+ yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE; |
+ } |
+ yytos = yypParser->yytos; |
+ yytos->stateno = (YYACTIONTYPE)yyNewState; |
+ yytos->major = (YYCODETYPE)yyMajor; |
+ yytos->minor.yy0 = yyMinor; |
+ yyTraceShift(yypParser, yyNewState); |
+} |
+ |
+/* The following table contains information about every rule that |
+** is used during the reduce. |
+*/ |
+static const struct { |
+ YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ |
+ unsigned char nrhs; /* Number of right-hand side symbols in the rule */ |
+} yyRuleInfo[] = { |
+ { 147, 1 }, |
+ { 147, 3 }, |
+ { 148, 1 }, |
+ { 149, 3 }, |
+ { 150, 0 }, |
+ { 150, 1 }, |
+ { 150, 1 }, |
+ { 150, 1 }, |
+ { 149, 2 }, |
+ { 149, 2 }, |
+ { 149, 2 }, |
+ { 149, 2 }, |
+ { 149, 3 }, |
+ { 149, 5 }, |
+ { 154, 6 }, |
+ { 156, 1 }, |
+ { 158, 0 }, |
+ { 158, 3 }, |
+ { 157, 1 }, |
+ { 157, 0 }, |
+ { 155, 5 }, |
+ { 155, 2 }, |
+ { 162, 0 }, |
+ { 162, 2 }, |
+ { 164, 2 }, |
+ { 166, 0 }, |
+ { 166, 4 }, |
+ { 166, 6 }, |
+ { 167, 2 }, |
+ { 171, 2 }, |
+ { 171, 2 }, |
+ { 171, 4 }, |
+ { 171, 3 }, |
+ { 171, 3 }, |
+ { 171, 2 }, |
+ { 171, 3 }, |
+ { 171, 5 }, |
+ { 171, 2 }, |
+ { 171, 4 }, |
+ { 171, 4 }, |
+ { 171, 1 }, |
+ { 171, 2 }, |
+ { 176, 0 }, |
+ { 176, 1 }, |
+ { 178, 0 }, |
+ { 178, 2 }, |
+ { 180, 2 }, |
+ { 180, 3 }, |
+ { 180, 3 }, |
+ { 180, 3 }, |
+ { 181, 2 }, |
+ { 181, 2 }, |
+ { 181, 1 }, |
+ { 181, 1 }, |
+ { 181, 2 }, |
+ { 179, 3 }, |
+ { 179, 2 }, |
+ { 182, 0 }, |
+ { 182, 2 }, |
+ { 182, 2 }, |
+ { 161, 0 }, |
+ { 184, 1 }, |
+ { 185, 2 }, |
+ { 185, 7 }, |
+ { 185, 5 }, |
+ { 185, 5 }, |
+ { 185, 10 }, |
+ { 188, 0 }, |
+ { 174, 0 }, |
+ { 174, 3 }, |
+ { 189, 0 }, |
+ { 189, 2 }, |
+ { 190, 1 }, |
+ { 190, 1 }, |
+ { 149, 4 }, |
+ { 192, 2 }, |
+ { 192, 0 }, |
+ { 149, 9 }, |
+ { 149, 4 }, |
+ { 149, 1 }, |
+ { 163, 2 }, |
+ { 194, 3 }, |
+ { 197, 1 }, |
+ { 197, 2 }, |
+ { 197, 1 }, |
+ { 195, 9 }, |
+ { 206, 4 }, |
+ { 206, 5 }, |
+ { 198, 1 }, |
+ { 198, 1 }, |
+ { 198, 0 }, |
+ { 209, 0 }, |
+ { 199, 3 }, |
+ { 199, 2 }, |
+ { 199, 4 }, |
+ { 210, 2 }, |
+ { 210, 0 }, |
+ { 200, 0 }, |
+ { 200, 2 }, |
+ { 212, 2 }, |
+ { 212, 0 }, |
+ { 211, 7 }, |
+ { 211, 9 }, |
+ { 211, 7 }, |
+ { 211, 7 }, |
+ { 159, 0 }, |
+ { 159, 2 }, |
+ { 193, 2 }, |
+ { 213, 1 }, |
+ { 213, 2 }, |
+ { 213, 3 }, |
+ { 213, 4 }, |
+ { 215, 2 }, |
+ { 215, 0 }, |
+ { 214, 0 }, |
+ { 214, 3 }, |
+ { 214, 2 }, |
+ { 216, 4 }, |
+ { 216, 0 }, |
+ { 204, 0 }, |
+ { 204, 3 }, |
+ { 186, 4 }, |
+ { 186, 2 }, |
+ { 175, 1 }, |
+ { 175, 1 }, |
+ { 175, 0 }, |
+ { 202, 0 }, |
+ { 202, 3 }, |
+ { 203, 0 }, |
+ { 203, 2 }, |
+ { 205, 0 }, |
+ { 205, 2 }, |
+ { 205, 4 }, |
+ { 205, 4 }, |
+ { 149, 6 }, |
+ { 201, 0 }, |
+ { 201, 2 }, |
+ { 149, 8 }, |
+ { 218, 5 }, |
+ { 218, 7 }, |
+ { 218, 3 }, |
+ { 218, 5 }, |
+ { 149, 6 }, |
+ { 149, 7 }, |
+ { 219, 2 }, |
+ { 219, 1 }, |
+ { 220, 0 }, |
+ { 220, 3 }, |
+ { 217, 3 }, |
+ { 217, 1 }, |
+ { 173, 3 }, |
+ { 172, 1 }, |
+ { 173, 1 }, |
+ { 173, 1 }, |
+ { 173, 3 }, |
+ { 173, 5 }, |
+ { 172, 1 }, |
+ { 172, 1 }, |
+ { 172, 1 }, |
+ { 173, 1 }, |
+ { 173, 3 }, |
+ { 173, 6 }, |
+ { 173, 5 }, |
+ { 173, 4 }, |
+ { 172, 1 }, |
+ { 173, 5 }, |
+ { 173, 3 }, |
+ { 173, 3 }, |
+ { 173, 3 }, |
+ { 173, 3 }, |
+ { 173, 3 }, |
+ { 173, 3 }, |
+ { 173, 3 }, |
+ { 173, 3 }, |
+ { 221, 1 }, |
+ { 221, 2 }, |
+ { 173, 3 }, |
+ { 173, 5 }, |
+ { 173, 2 }, |
+ { 173, 3 }, |
+ { 173, 3 }, |
+ { 173, 4 }, |
+ { 173, 2 }, |
+ { 173, 2 }, |
+ { 173, 2 }, |
+ { 173, 2 }, |
+ { 222, 1 }, |
+ { 222, 2 }, |
+ { 173, 5 }, |
+ { 223, 1 }, |
+ { 223, 2 }, |
+ { 173, 5 }, |
+ { 173, 3 }, |
+ { 173, 5 }, |
+ { 173, 5 }, |
+ { 173, 4 }, |
+ { 173, 5 }, |
+ { 226, 5 }, |
+ { 226, 4 }, |
+ { 227, 2 }, |
+ { 227, 0 }, |
+ { 225, 1 }, |
+ { 225, 0 }, |
+ { 208, 0 }, |
+ { 207, 3 }, |
+ { 207, 1 }, |
+ { 224, 0 }, |
+ { 224, 3 }, |
+ { 149, 12 }, |
+ { 228, 1 }, |
+ { 228, 0 }, |
+ { 177, 0 }, |
+ { 177, 3 }, |
+ { 187, 5 }, |
+ { 187, 3 }, |
+ { 229, 0 }, |
+ { 229, 2 }, |
+ { 149, 4 }, |
+ { 149, 1 }, |
+ { 149, 2 }, |
+ { 149, 3 }, |
+ { 149, 5 }, |
+ { 149, 6 }, |
+ { 149, 5 }, |
+ { 149, 6 }, |
+ { 169, 2 }, |
+ { 170, 2 }, |
+ { 149, 5 }, |
+ { 231, 11 }, |
+ { 233, 1 }, |
+ { 233, 1 }, |
+ { 233, 2 }, |
+ { 233, 0 }, |
+ { 234, 1 }, |
+ { 234, 1 }, |
+ { 234, 3 }, |
+ { 236, 0 }, |
+ { 236, 2 }, |
+ { 232, 3 }, |
+ { 232, 2 }, |
+ { 238, 3 }, |
+ { 239, 3 }, |
+ { 239, 2 }, |
+ { 237, 7 }, |
+ { 237, 5 }, |
+ { 237, 5 }, |
+ { 237, 1 }, |
+ { 173, 4 }, |
+ { 173, 6 }, |
+ { 191, 1 }, |
+ { 191, 1 }, |
+ { 191, 1 }, |
+ { 149, 4 }, |
+ { 149, 6 }, |
+ { 149, 3 }, |
+ { 241, 0 }, |
+ { 241, 2 }, |
+ { 149, 1 }, |
+ { 149, 3 }, |
+ { 149, 1 }, |
+ { 149, 3 }, |
+ { 149, 6 }, |
+ { 149, 7 }, |
+ { 242, 1 }, |
+ { 149, 1 }, |
+ { 149, 4 }, |
+ { 244, 8 }, |
+ { 246, 0 }, |
+ { 247, 1 }, |
+ { 247, 3 }, |
+ { 248, 1 }, |
+ { 196, 0 }, |
+ { 196, 2 }, |
+ { 196, 3 }, |
+ { 250, 6 }, |
+ { 250, 8 }, |
+ { 144, 1 }, |
+ { 145, 2 }, |
+ { 145, 1 }, |
+ { 146, 1 }, |
+ { 146, 3 }, |
+ { 147, 0 }, |
+ { 151, 0 }, |
+ { 151, 1 }, |
+ { 151, 2 }, |
+ { 153, 1 }, |
+ { 153, 0 }, |
+ { 149, 2 }, |
+ { 160, 4 }, |
+ { 160, 2 }, |
+ { 152, 1 }, |
+ { 152, 1 }, |
+ { 152, 1 }, |
+ { 166, 1 }, |
+ { 167, 1 }, |
+ { 168, 1 }, |
+ { 168, 1 }, |
+ { 165, 2 }, |
+ { 165, 0 }, |
+ { 171, 2 }, |
+ { 161, 2 }, |
+ { 183, 3 }, |
+ { 183, 1 }, |
+ { 184, 0 }, |
+ { 188, 1 }, |
+ { 190, 1 }, |
+ { 194, 1 }, |
+ { 195, 1 }, |
+ { 209, 2 }, |
+ { 210, 1 }, |
+ { 173, 1 }, |
+ { 208, 1 }, |
+ { 230, 1 }, |
+ { 230, 1 }, |
+ { 230, 1 }, |
+ { 230, 1 }, |
+ { 230, 1 }, |
+ { 169, 1 }, |
+ { 235, 0 }, |
+ { 235, 3 }, |
+ { 238, 1 }, |
+ { 239, 0 }, |
+ { 240, 1 }, |
+ { 240, 0 }, |
+ { 243, 0 }, |
+ { 243, 1 }, |
+ { 245, 1 }, |
+ { 245, 3 }, |
+ { 246, 2 }, |
+ { 249, 0 }, |
+ { 249, 4 }, |
+ { 249, 2 }, |
+}; |
+ |
+static void yy_accept(yyParser*); /* Forward Declaration */ |
+ |
+/* |
+** Perform a reduce action and the shift that must immediately |
+** follow the reduce. |
+*/ |
+static void yy_reduce( |
+ yyParser *yypParser, /* The parser */ |
+ unsigned int yyruleno /* Number of the rule by which to reduce */ |
+){ |
+ int yygoto; /* The next state */ |
+ int yyact; /* The next action */ |
+ yyStackEntry *yymsp; /* The top of the parser's stack */ |
+ int yysize; /* Amount to pop the stack */ |
+ sqlite3ParserARG_FETCH; |
+ yymsp = yypParser->yytos; |
+#ifndef NDEBUG |
+ if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ |
+ yysize = yyRuleInfo[yyruleno].nrhs; |
+ fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt, |
+ yyRuleName[yyruleno], yymsp[-yysize].stateno); |
+ } |
+#endif /* NDEBUG */ |
+ |
+ /* Check that the stack is large enough to grow by a single entry |
+ ** if the RHS of the rule is empty. This ensures that there is room |
+ ** enough on the stack to push the LHS value */ |
+ if( yyRuleInfo[yyruleno].nrhs==0 ){ |
+#ifdef YYTRACKMAXSTACKDEPTH |
+ if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){ |
+ yypParser->yyhwm++; |
+ assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack)); |
+ } |
+#endif |
+#if YYSTACKDEPTH>0 |
+ if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH-1] ){ |
+ yyStackOverflow(yypParser); |
+ return; |
+ } |
+#else |
+ if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){ |
+ if( yyGrowStack(yypParser) ){ |
+ yyStackOverflow(yypParser); |
+ return; |
+ } |
+ yymsp = yypParser->yytos; |
+ } |
+#endif |
+ } |
+ |
+ switch( yyruleno ){ |
+ /* Beginning here are the reduction cases. A typical example |
+ ** follows: |
+ ** case 0: |
+ ** #line <lineno> <grammarfile> |
+ ** { ... } // User supplied code |
+ ** #line <lineno> <thisfile> |
+ ** break; |
+ */ |
+/********** Begin reduce actions **********************************************/ |
+ YYMINORTYPE yylhsminor; |
+ case 0: /* explain ::= EXPLAIN */ |
+{ pParse->explain = 1; } |
+ break; |
+ case 1: /* explain ::= EXPLAIN QUERY PLAN */ |
+{ pParse->explain = 2; } |
+ break; |
+ case 2: /* cmdx ::= cmd */ |
+{ sqlite3FinishCoding(pParse); } |
+ break; |
+ case 3: /* cmd ::= BEGIN transtype trans_opt */ |
+{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);} |
+ break; |
+ case 4: /* transtype ::= */ |
+{yymsp[1].minor.yy194 = TK_DEFERRED;} |
+ break; |
+ case 5: /* transtype ::= DEFERRED */ |
+ case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6); |
+ case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7); |
+{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/} |
+ break; |
+ case 8: /* cmd ::= COMMIT trans_opt */ |
+ case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9); |
+{sqlite3CommitTransaction(pParse);} |
+ break; |
+ case 10: /* cmd ::= ROLLBACK trans_opt */ |
+{sqlite3RollbackTransaction(pParse);} |
+ break; |
+ case 11: /* cmd ::= SAVEPOINT nm */ |
+{ |
+ sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0); |
+} |
+ break; |
+ case 12: /* cmd ::= RELEASE savepoint_opt nm */ |
+{ |
+ sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0); |
+} |
+ break; |
+ case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ |
+{ |
+ sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0); |
+} |
+ break; |
+ case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */ |
+{ |
+ sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194); |
+} |
+ break; |
+ case 15: /* createkw ::= CREATE */ |
+{disableLookaside(pParse);} |
+ break; |
+ case 16: /* ifnotexists ::= */ |
+ case 19: /* temp ::= */ yytestcase(yyruleno==19); |
+ case 22: /* table_options ::= */ yytestcase(yyruleno==22); |
+ case 42: /* autoinc ::= */ yytestcase(yyruleno==42); |
+ case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57); |
+ case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67); |
+ case 76: /* ifexists ::= */ yytestcase(yyruleno==76); |
+ case 90: /* distinct ::= */ yytestcase(yyruleno==90); |
+ case 215: /* collate ::= */ yytestcase(yyruleno==215); |
+{yymsp[1].minor.yy194 = 0;} |
+ break; |
+ case 17: /* ifnotexists ::= IF NOT EXISTS */ |
+{yymsp[-2].minor.yy194 = 1;} |
+ break; |
+ case 18: /* temp ::= TEMP */ |
+ case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43); |
+{yymsp[0].minor.yy194 = 1;} |
+ break; |
+ case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */ |
+{ |
+ sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0); |
+} |
+ break; |
+ case 21: /* create_table_args ::= AS select */ |
+{ |
+ sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243); |
+ sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243); |
+} |
+ break; |
+ case 23: /* table_options ::= WITHOUT nm */ |
+{ |
+ if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){ |
+ yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid; |
+ }else{ |
+ yymsp[-1].minor.yy194 = 0; |
+ sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z); |
+ } |
+} |
+ break; |
+ case 24: /* columnname ::= nm typetoken */ |
+{sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);} |
+ break; |
+ case 25: /* typetoken ::= */ |
+ case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60); |
+ case 96: /* as ::= */ yytestcase(yyruleno==96); |
+{yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;} |
+ break; |
+ case 26: /* typetoken ::= typename LP signed RP */ |
+{ |
+ yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z); |
+} |
+ break; |
+ case 27: /* typetoken ::= typename LP signed COMMA signed RP */ |
+{ |
+ yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z); |
+} |
+ break; |
+ case 28: /* typename ::= typename ID|STRING */ |
+{yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);} |
+ break; |
+ case 29: /* ccons ::= CONSTRAINT nm */ |
+ case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62); |
+{pParse->constraintName = yymsp[0].minor.yy0;} |
+ break; |
+ case 30: /* ccons ::= DEFAULT term */ |
+ case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32); |
+{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);} |
+ break; |
+ case 31: /* ccons ::= DEFAULT LP expr RP */ |
+{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);} |
+ break; |
+ case 33: /* ccons ::= DEFAULT MINUS term */ |
+{ |
+ ExprSpan v; |
+ v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0); |
+ v.zStart = yymsp[-1].minor.yy0.z; |
+ v.zEnd = yymsp[0].minor.yy190.zEnd; |
+ sqlite3AddDefaultValue(pParse,&v); |
+} |
+ break; |
+ case 34: /* ccons ::= DEFAULT ID|INDEXED */ |
+{ |
+ ExprSpan v; |
+ spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0); |
+ sqlite3AddDefaultValue(pParse,&v); |
+} |
+ break; |
+ case 35: /* ccons ::= NOT NULL onconf */ |
+{sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);} |
+ break; |
+ case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ |
+{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);} |
+ break; |
+ case 37: /* ccons ::= UNIQUE onconf */ |
+{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0, |
+ SQLITE_IDXTYPE_UNIQUE);} |
+ break; |
+ case 38: /* ccons ::= CHECK LP expr RP */ |
+{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);} |
+ break; |
+ case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */ |
+{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);} |
+ break; |
+ case 40: /* ccons ::= defer_subclause */ |
+{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);} |
+ break; |
+ case 41: /* ccons ::= COLLATE ID|STRING */ |
+{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);} |
+ break; |
+ case 44: /* refargs ::= */ |
+{ yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */} |
+ break; |
+ case 45: /* refargs ::= refargs refarg */ |
+{ yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; } |
+ break; |
+ case 46: /* refarg ::= MATCH nm */ |
+{ yymsp[-1].minor.yy497.value = 0; yymsp[-1].minor.yy497.mask = 0x000000; } |
+ break; |
+ case 47: /* refarg ::= ON INSERT refact */ |
+{ yymsp[-2].minor.yy497.value = 0; yymsp[-2].minor.yy497.mask = 0x000000; } |
+ break; |
+ case 48: /* refarg ::= ON DELETE refact */ |
+{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194; yymsp[-2].minor.yy497.mask = 0x0000ff; } |
+ break; |
+ case 49: /* refarg ::= ON UPDATE refact */ |
+{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8; yymsp[-2].minor.yy497.mask = 0x00ff00; } |
+ break; |
+ case 50: /* refact ::= SET NULL */ |
+{ yymsp[-1].minor.yy194 = OE_SetNull; /* EV: R-33326-45252 */} |
+ break; |
+ case 51: /* refact ::= SET DEFAULT */ |
+{ yymsp[-1].minor.yy194 = OE_SetDflt; /* EV: R-33326-45252 */} |
+ break; |
+ case 52: /* refact ::= CASCADE */ |
+{ yymsp[0].minor.yy194 = OE_Cascade; /* EV: R-33326-45252 */} |
+ break; |
+ case 53: /* refact ::= RESTRICT */ |
+{ yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */} |
+ break; |
+ case 54: /* refact ::= NO ACTION */ |
+{ yymsp[-1].minor.yy194 = OE_None; /* EV: R-33326-45252 */} |
+ break; |
+ case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ |
+{yymsp[-2].minor.yy194 = 0;} |
+ break; |
+ case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ |
+ case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71); |
+ case 144: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==144); |
+{yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;} |
+ break; |
+ case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ |
+ case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75); |
+ case 187: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==187); |
+ case 190: /* in_op ::= NOT IN */ yytestcase(yyruleno==190); |
+ case 216: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==216); |
+{yymsp[-1].minor.yy194 = 1;} |
+ break; |
+ case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ |
+{yymsp[-1].minor.yy194 = 0;} |
+ break; |
+ case 61: /* tconscomma ::= COMMA */ |
+{pParse->constraintName.n = 0;} |
+ break; |
+ case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ |
+{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);} |
+ break; |
+ case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */ |
+{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0, |
+ SQLITE_IDXTYPE_UNIQUE);} |
+ break; |
+ case 65: /* tcons ::= CHECK LP expr RP onconf */ |
+{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);} |
+ break; |
+ case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ |
+{ |
+ sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194); |
+ sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194); |
+} |
+ break; |
+ case 68: /* onconf ::= */ |
+ case 70: /* orconf ::= */ yytestcase(yyruleno==70); |
+{yymsp[1].minor.yy194 = OE_Default;} |
+ break; |
+ case 69: /* onconf ::= ON CONFLICT resolvetype */ |
+{yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;} |
+ break; |
+ case 72: /* resolvetype ::= IGNORE */ |
+{yymsp[0].minor.yy194 = OE_Ignore;} |
+ break; |
+ case 73: /* resolvetype ::= REPLACE */ |
+ case 145: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==145); |
+{yymsp[0].minor.yy194 = OE_Replace;} |
+ break; |
+ case 74: /* cmd ::= DROP TABLE ifexists fullname */ |
+{ |
+ sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194); |
+} |
+ break; |
+ case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */ |
+{ |
+ sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194); |
+} |
+ break; |
+ case 78: /* cmd ::= DROP VIEW ifexists fullname */ |
+{ |
+ sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194); |
+} |
+ break; |
+ case 79: /* cmd ::= select */ |
+{ |
+ SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0}; |
+ sqlite3Select(pParse, yymsp[0].minor.yy243, &dest); |
+ sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243); |
+} |
+ break; |
+ case 80: /* select ::= with selectnowith */ |
+{ |
+ Select *p = yymsp[0].minor.yy243; |
+ if( p ){ |
+ p->pWith = yymsp[-1].minor.yy285; |
+ parserDoubleLinkSelect(pParse, p); |
+ }else{ |
+ sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285); |
+ } |
+ yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/ |
+} |
+ break; |
+ case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */ |
+{ |
+ Select *pRhs = yymsp[0].minor.yy243; |
+ Select *pLhs = yymsp[-2].minor.yy243; |
+ if( pRhs && pRhs->pPrior ){ |
+ SrcList *pFrom; |
+ Token x; |
+ x.n = 0; |
+ parserDoubleLinkSelect(pParse, pRhs); |
+ pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0); |
+ pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0); |
+ } |
+ if( pRhs ){ |
+ pRhs->op = (u8)yymsp[-1].minor.yy194; |
+ pRhs->pPrior = pLhs; |
+ if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue; |
+ pRhs->selFlags &= ~SF_MultiValue; |
+ if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1; |
+ }else{ |
+ sqlite3SelectDelete(pParse->db, pLhs); |
+ } |
+ yymsp[-2].minor.yy243 = pRhs; |
+} |
+ break; |
+ case 82: /* multiselect_op ::= UNION */ |
+ case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84); |
+{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/} |
+ break; |
+ case 83: /* multiselect_op ::= UNION ALL */ |
+{yymsp[-1].minor.yy194 = TK_ALL;} |
+ break; |
+ case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ |
+{ |
+#if SELECTTRACE_ENABLED |
+ Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/ |
+#endif |
+ yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset); |
+#if SELECTTRACE_ENABLED |
+ /* Populate the Select.zSelName[] string that is used to help with |
+ ** query planner debugging, to differentiate between multiple Select |
+ ** objects in a complex query. |
+ ** |
+ ** If the SELECT keyword is immediately followed by a C-style comment |
+ ** then extract the first few alphanumeric characters from within that |
+ ** comment to be the zSelName value. Otherwise, the label is #N where |
+ ** is an integer that is incremented with each SELECT statement seen. |
+ */ |
+ if( yymsp[-8].minor.yy243!=0 ){ |
+ const char *z = s.z+6; |
+ int i; |
+ sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d", |
+ ++pParse->nSelect); |
+ while( z[0]==' ' ) z++; |
+ if( z[0]=='/' && z[1]=='*' ){ |
+ z += 2; |
+ while( z[0]==' ' ) z++; |
+ for(i=0; sqlite3Isalnum(z[i]); i++){} |
+ sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z); |
+ } |
+ } |
+#endif /* SELECTRACE_ENABLED */ |
+} |
+ break; |
+ case 86: /* values ::= VALUES LP nexprlist RP */ |
+{ |
+ yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0); |
+} |
+ break; |
+ case 87: /* values ::= values COMMA LP exprlist RP */ |
+{ |
+ Select *pRight, *pLeft = yymsp[-4].minor.yy243; |
+ pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0); |
+ if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue; |
+ if( pRight ){ |
+ pRight->op = TK_ALL; |
+ pRight->pPrior = pLeft; |
+ yymsp[-4].minor.yy243 = pRight; |
+ }else{ |
+ yymsp[-4].minor.yy243 = pLeft; |
+ } |
+} |
+ break; |
+ case 88: /* distinct ::= DISTINCT */ |
+{yymsp[0].minor.yy194 = SF_Distinct;} |
+ break; |
+ case 89: /* distinct ::= ALL */ |
+{yymsp[0].minor.yy194 = SF_All;} |
+ break; |
+ case 91: /* sclp ::= */ |
+ case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119); |
+ case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126); |
+ case 203: /* exprlist ::= */ yytestcase(yyruleno==203); |
+ case 206: /* paren_exprlist ::= */ yytestcase(yyruleno==206); |
+ case 211: /* eidlist_opt ::= */ yytestcase(yyruleno==211); |
+{yymsp[1].minor.yy148 = 0;} |
+ break; |
+ case 92: /* selcollist ::= sclp expr as */ |
+{ |
+ yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr); |
+ if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1); |
+ sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190); |
+} |
+ break; |
+ case 93: /* selcollist ::= sclp STAR */ |
+{ |
+ Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0); |
+ yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p); |
+} |
+ break; |
+ case 94: /* selcollist ::= sclp nm DOT STAR */ |
+{ |
+ Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0); |
+ Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); |
+ Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight); |
+ yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot); |
+} |
+ break; |
+ case 95: /* as ::= AS nm */ |
+ case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106); |
+ case 225: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==225); |
+ case 226: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==226); |
+{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;} |
+ break; |
+ case 97: /* from ::= */ |
+{yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));} |
+ break; |
+ case 98: /* from ::= FROM seltablist */ |
+{ |
+ yymsp[-1].minor.yy185 = yymsp[0].minor.yy185; |
+ sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185); |
+} |
+ break; |
+ case 99: /* stl_prefix ::= seltablist joinop */ |
+{ |
+ if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194; |
+} |
+ break; |
+ case 100: /* stl_prefix ::= */ |
+{yymsp[1].minor.yy185 = 0;} |
+ break; |
+ case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ |
+{ |
+ yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); |
+ sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0); |
+} |
+ break; |
+ case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */ |
+{ |
+ yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); |
+ sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148); |
+} |
+ break; |
+ case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */ |
+{ |
+ yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); |
+ } |
+ break; |
+ case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ |
+{ |
+ if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){ |
+ yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185; |
+ }else if( yymsp[-4].minor.yy185->nSrc==1 ){ |
+ yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); |
+ if( yymsp[-6].minor.yy185 ){ |
+ struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1]; |
+ struct SrcList_item *pOld = yymsp[-4].minor.yy185->a; |
+ pNew->zName = pOld->zName; |
+ pNew->zDatabase = pOld->zDatabase; |
+ pNew->pSelect = pOld->pSelect; |
+ pOld->zName = pOld->zDatabase = 0; |
+ pOld->pSelect = 0; |
+ } |
+ sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185); |
+ }else{ |
+ Select *pSubquery; |
+ sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185); |
+ pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0); |
+ yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); |
+ } |
+ } |
+ break; |
+ case 105: /* dbnm ::= */ |
+ case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114); |
+{yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;} |
+ break; |
+ case 107: /* fullname ::= nm dbnm */ |
+{yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/} |
+ break; |
+ case 108: /* joinop ::= COMMA|JOIN */ |
+{ yymsp[0].minor.yy194 = JT_INNER; } |
+ break; |
+ case 109: /* joinop ::= JOIN_KW JOIN */ |
+{yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/} |
+ break; |
+ case 110: /* joinop ::= JOIN_KW nm JOIN */ |
+{yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/} |
+ break; |
+ case 111: /* joinop ::= JOIN_KW nm nm JOIN */ |
+{yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/} |
+ break; |
+ case 112: /* on_opt ::= ON expr */ |
+ case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129); |
+ case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136); |
+ case 199: /* case_else ::= ELSE expr */ yytestcase(yyruleno==199); |
+{yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;} |
+ break; |
+ case 113: /* on_opt ::= */ |
+ case 128: /* having_opt ::= */ yytestcase(yyruleno==128); |
+ case 135: /* where_opt ::= */ yytestcase(yyruleno==135); |
+ case 200: /* case_else ::= */ yytestcase(yyruleno==200); |
+ case 202: /* case_operand ::= */ yytestcase(yyruleno==202); |
+{yymsp[1].minor.yy72 = 0;} |
+ break; |
+ case 115: /* indexed_opt ::= INDEXED BY nm */ |
+{yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;} |
+ break; |
+ case 116: /* indexed_opt ::= NOT INDEXED */ |
+{yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;} |
+ break; |
+ case 117: /* using_opt ::= USING LP idlist RP */ |
+{yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;} |
+ break; |
+ case 118: /* using_opt ::= */ |
+ case 146: /* idlist_opt ::= */ yytestcase(yyruleno==146); |
+{yymsp[1].minor.yy254 = 0;} |
+ break; |
+ case 120: /* orderby_opt ::= ORDER BY sortlist */ |
+ case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127); |
+{yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;} |
+ break; |
+ case 121: /* sortlist ::= sortlist COMMA expr sortorder */ |
+{ |
+ yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr); |
+ sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194); |
+} |
+ break; |
+ case 122: /* sortlist ::= expr sortorder */ |
+{ |
+ yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/ |
+ sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194); |
+} |
+ break; |
+ case 123: /* sortorder ::= ASC */ |
+{yymsp[0].minor.yy194 = SQLITE_SO_ASC;} |
+ break; |
+ case 124: /* sortorder ::= DESC */ |
+{yymsp[0].minor.yy194 = SQLITE_SO_DESC;} |
+ break; |
+ case 125: /* sortorder ::= */ |
+{yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;} |
+ break; |
+ case 130: /* limit_opt ::= */ |
+{yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;} |
+ break; |
+ case 131: /* limit_opt ::= LIMIT expr */ |
+{yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;} |
+ break; |
+ case 132: /* limit_opt ::= LIMIT expr OFFSET expr */ |
+{yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;} |
+ break; |
+ case 133: /* limit_opt ::= LIMIT expr COMMA expr */ |
+{yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;} |
+ break; |
+ case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */ |
+{ |
+ sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1); |
+ sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0); |
+ sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72); |
+} |
+ break; |
+ case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */ |
+{ |
+ sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1); |
+ sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0); |
+ sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list"); |
+ sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194); |
+} |
+ break; |
+ case 138: /* setlist ::= setlist COMMA nm EQ expr */ |
+{ |
+ yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr); |
+ sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1); |
+} |
+ break; |
+ case 139: /* setlist ::= setlist COMMA LP idlist RP EQ expr */ |
+{ |
+ yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr); |
+} |
+ break; |
+ case 140: /* setlist ::= nm EQ expr */ |
+{ |
+ yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr); |
+ sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1); |
+} |
+ yymsp[-2].minor.yy148 = yylhsminor.yy148; |
+ break; |
+ case 141: /* setlist ::= LP idlist RP EQ expr */ |
+{ |
+ yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr); |
+} |
+ break; |
+ case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */ |
+{ |
+ sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1); |
+ sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194); |
+} |
+ break; |
+ case 143: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */ |
+{ |
+ sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1); |
+ sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194); |
+} |
+ break; |
+ case 147: /* idlist_opt ::= LP idlist RP */ |
+{yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;} |
+ break; |
+ case 148: /* idlist ::= idlist COMMA nm */ |
+{yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);} |
+ break; |
+ case 149: /* idlist ::= nm */ |
+{yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/} |
+ break; |
+ case 150: /* expr ::= LP expr RP */ |
+{spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;} |
+ break; |
+ case 151: /* term ::= NULL */ |
+ case 156: /* term ::= FLOAT|BLOB */ yytestcase(yyruleno==156); |
+ case 157: /* term ::= STRING */ yytestcase(yyruleno==157); |
+{spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/} |
+ break; |
+ case 152: /* expr ::= ID|INDEXED */ |
+ case 153: /* expr ::= JOIN_KW */ yytestcase(yyruleno==153); |
+{spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/} |
+ break; |
+ case 154: /* expr ::= nm DOT nm */ |
+{ |
+ Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); |
+ Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1); |
+ spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ |
+ yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2); |
+} |
+ break; |
+ case 155: /* expr ::= nm DOT nm DOT nm */ |
+{ |
+ Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1); |
+ Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); |
+ Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1); |
+ Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3); |
+ spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ |
+ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4); |
+} |
+ break; |
+ case 158: /* term ::= INTEGER */ |
+{ |
+ yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1); |
+ yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z; |
+ yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n; |
+ if( yylhsminor.yy190.pExpr ) yylhsminor.yy190.pExpr->flags |= EP_Leaf; |
+} |
+ yymsp[0].minor.yy190 = yylhsminor.yy190; |
+ break; |
+ case 159: /* expr ::= VARIABLE */ |
+{ |
+ if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){ |
+ u32 n = yymsp[0].minor.yy0.n; |
+ spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0); |
+ sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n); |
+ }else{ |
+ /* When doing a nested parse, one can include terms in an expression |
+ ** that look like this: #1 #2 ... These terms refer to registers |
+ ** in the virtual machine. #N is the N-th register. */ |
+ Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/ |
+ assert( t.n>=2 ); |
+ spanSet(&yymsp[0].minor.yy190, &t, &t); |
+ if( pParse->nested==0 ){ |
+ sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t); |
+ yymsp[0].minor.yy190.pExpr = 0; |
+ }else{ |
+ yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0); |
+ if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable); |
+ } |
+ } |
+} |
+ break; |
+ case 160: /* expr ::= expr COLLATE ID|STRING */ |
+{ |
+ yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1); |
+ yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; |
+} |
+ break; |
+ case 161: /* expr ::= CAST LP expr AS typetoken RP */ |
+{ |
+ spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ |
+ yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1); |
+ sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, 0); |
+} |
+ break; |
+ case 162: /* expr ::= ID|INDEXED LP distinct exprlist RP */ |
+{ |
+ if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){ |
+ sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0); |
+ } |
+ yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0); |
+ spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); |
+ if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){ |
+ yylhsminor.yy190.pExpr->flags |= EP_Distinct; |
+ } |
+} |
+ yymsp[-4].minor.yy190 = yylhsminor.yy190; |
+ break; |
+ case 163: /* expr ::= ID|INDEXED LP STAR RP */ |
+{ |
+ yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0); |
+ spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); |
+} |
+ yymsp[-3].minor.yy190 = yylhsminor.yy190; |
+ break; |
+ case 164: /* term ::= CTIME_KW */ |
+{ |
+ yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0); |
+ spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0); |
+} |
+ yymsp[0].minor.yy190 = yylhsminor.yy190; |
+ break; |
+ case 165: /* expr ::= LP nexprlist COMMA expr RP */ |
+{ |
+ ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr); |
+ yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0); |
+ if( yylhsminor.yy190.pExpr ){ |
+ yylhsminor.yy190.pExpr->x.pList = pList; |
+ spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0); |
+ }else{ |
+ sqlite3ExprListDelete(pParse->db, pList); |
+ } |
+} |
+ yymsp[-4].minor.yy190 = yylhsminor.yy190; |
+ break; |
+ case 166: /* expr ::= expr AND expr */ |
+ case 167: /* expr ::= expr OR expr */ yytestcase(yyruleno==167); |
+ case 168: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==168); |
+ case 169: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==169); |
+ case 170: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==170); |
+ case 171: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==171); |
+ case 172: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==172); |
+ case 173: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==173); |
+{spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);} |
+ break; |
+ case 174: /* likeop ::= LIKE_KW|MATCH */ |
+{yymsp[0].minor.yy0=yymsp[0].minor.yy0;/*A-overwrites-X*/} |
+ break; |
+ case 175: /* likeop ::= NOT LIKE_KW|MATCH */ |
+{yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/} |
+ break; |
+ case 176: /* expr ::= expr likeop expr */ |
+{ |
+ ExprList *pList; |
+ int bNot = yymsp[-1].minor.yy0.n & 0x80000000; |
+ yymsp[-1].minor.yy0.n &= 0x7fffffff; |
+ pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr); |
+ pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr); |
+ yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0); |
+ exprNot(pParse, bNot, &yymsp[-2].minor.yy190); |
+ yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; |
+ if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc; |
+} |
+ break; |
+ case 177: /* expr ::= expr likeop expr ESCAPE expr */ |
+{ |
+ ExprList *pList; |
+ int bNot = yymsp[-3].minor.yy0.n & 0x80000000; |
+ yymsp[-3].minor.yy0.n &= 0x7fffffff; |
+ pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); |
+ pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr); |
+ pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr); |
+ yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0); |
+ exprNot(pParse, bNot, &yymsp[-4].minor.yy190); |
+ yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; |
+ if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc; |
+} |
+ break; |
+ case 178: /* expr ::= expr ISNULL|NOTNULL */ |
+{spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);} |
+ break; |
+ case 179: /* expr ::= expr NOT NULL */ |
+{spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);} |
+ break; |
+ case 180: /* expr ::= expr IS expr */ |
+{ |
+ spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190); |
+ binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL); |
+} |
+ break; |
+ case 181: /* expr ::= expr IS NOT expr */ |
+{ |
+ spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190); |
+ binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL); |
+} |
+ break; |
+ case 182: /* expr ::= NOT expr */ |
+ case 183: /* expr ::= BITNOT expr */ yytestcase(yyruleno==183); |
+{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} |
+ break; |
+ case 184: /* expr ::= MINUS expr */ |
+{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} |
+ break; |
+ case 185: /* expr ::= PLUS expr */ |
+{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} |
+ break; |
+ case 186: /* between_op ::= BETWEEN */ |
+ case 189: /* in_op ::= IN */ yytestcase(yyruleno==189); |
+{yymsp[0].minor.yy194 = 0;} |
+ break; |
+ case 188: /* expr ::= expr between_op expr AND expr */ |
+{ |
+ ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); |
+ pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr); |
+ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0); |
+ if( yymsp[-4].minor.yy190.pExpr ){ |
+ yymsp[-4].minor.yy190.pExpr->x.pList = pList; |
+ }else{ |
+ sqlite3ExprListDelete(pParse->db, pList); |
+ } |
+ exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); |
+ yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; |
+} |
+ break; |
+ case 191: /* expr ::= expr in_op LP exprlist RP */ |
+{ |
+ if( yymsp[-1].minor.yy148==0 ){ |
+ /* Expressions of the form |
+ ** |
+ ** expr1 IN () |
+ ** expr1 NOT IN () |
+ ** |
+ ** simplify to constants 0 (false) and 1 (true), respectively, |
+ ** regardless of the value of expr1. |
+ */ |
+ sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr); |
+ yymsp[-4].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy194],1); |
+ }else if( yymsp[-1].minor.yy148->nExpr==1 ){ |
+ /* Expressions of the form: |
+ ** |
+ ** expr1 IN (?1) |
+ ** expr1 NOT IN (?2) |
+ ** |
+ ** with exactly one value on the RHS can be simplified to something |
+ ** like this: |
+ ** |
+ ** expr1 == ?1 |
+ ** expr1 <> ?2 |
+ ** |
+ ** But, the RHS of the == or <> is marked with the EP_Generic flag |
+ ** so that it may not contribute to the computation of comparison |
+ ** affinity or the collating sequence to use for comparison. Otherwise, |
+ ** the semantics would be subtly different from IN or NOT IN. |
+ */ |
+ Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr; |
+ yymsp[-1].minor.yy148->a[0].pExpr = 0; |
+ sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148); |
+ /* pRHS cannot be NULL because a malloc error would have been detected |
+ ** before now and control would have never reached this point */ |
+ if( ALWAYS(pRHS) ){ |
+ pRHS->flags &= ~EP_Collate; |
+ pRHS->flags |= EP_Generic; |
+ } |
+ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS); |
+ }else{ |
+ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0); |
+ if( yymsp[-4].minor.yy190.pExpr ){ |
+ yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148; |
+ sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr); |
+ }else{ |
+ sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148); |
+ } |
+ exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); |
+ } |
+ yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; |
+ } |
+ break; |
+ case 192: /* expr ::= LP select RP */ |
+{ |
+ spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ |
+ yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0); |
+ sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243); |
+ } |
+ break; |
+ case 193: /* expr ::= expr in_op LP select RP */ |
+{ |
+ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0); |
+ sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243); |
+ exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); |
+ yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; |
+ } |
+ break; |
+ case 194: /* expr ::= expr in_op nm dbnm paren_exprlist */ |
+{ |
+ SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); |
+ Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0); |
+ if( yymsp[0].minor.yy148 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148); |
+ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0); |
+ sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect); |
+ exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); |
+ yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n]; |
+ } |
+ break; |
+ case 195: /* expr ::= EXISTS LP select RP */ |
+{ |
+ Expr *p; |
+ spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ |
+ p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0); |
+ sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243); |
+ } |
+ break; |
+ case 196: /* expr ::= CASE case_operand case_exprlist case_else END */ |
+{ |
+ spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/ |
+ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0); |
+ if( yymsp[-4].minor.yy190.pExpr ){ |
+ yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148; |
+ sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr); |
+ }else{ |
+ sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148); |
+ sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72); |
+ } |
+} |
+ break; |
+ case 197: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ |
+{ |
+ yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr); |
+ yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr); |
+} |
+ break; |
+ case 198: /* case_exprlist ::= WHEN expr THEN expr */ |
+{ |
+ yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); |
+ yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr); |
+} |
+ break; |
+ case 201: /* case_operand ::= expr */ |
+{yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/} |
+ break; |
+ case 204: /* nexprlist ::= nexprlist COMMA expr */ |
+{yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);} |
+ break; |
+ case 205: /* nexprlist ::= expr */ |
+{yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/} |
+ break; |
+ case 207: /* paren_exprlist ::= LP exprlist RP */ |
+ case 212: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==212); |
+{yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;} |
+ break; |
+ case 208: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */ |
+{ |
+ sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, |
+ sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194, |
+ &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF); |
+} |
+ break; |
+ case 209: /* uniqueflag ::= UNIQUE */ |
+ case 250: /* raisetype ::= ABORT */ yytestcase(yyruleno==250); |
+{yymsp[0].minor.yy194 = OE_Abort;} |
+ break; |
+ case 210: /* uniqueflag ::= */ |
+{yymsp[1].minor.yy194 = OE_None;} |
+ break; |
+ case 213: /* eidlist ::= eidlist COMMA nm collate sortorder */ |
+{ |
+ yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); |
+} |
+ break; |
+ case 214: /* eidlist ::= nm collate sortorder */ |
+{ |
+ yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/ |
+} |
+ break; |
+ case 217: /* cmd ::= DROP INDEX ifexists fullname */ |
+{sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);} |
+ break; |
+ case 218: /* cmd ::= VACUUM */ |
+{sqlite3Vacuum(pParse,0);} |
+ break; |
+ case 219: /* cmd ::= VACUUM nm */ |
+{sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);} |
+ break; |
+ case 220: /* cmd ::= PRAGMA nm dbnm */ |
+{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);} |
+ break; |
+ case 221: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ |
+{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);} |
+ break; |
+ case 222: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ |
+{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);} |
+ break; |
+ case 223: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ |
+{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);} |
+ break; |
+ case 224: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */ |
+{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);} |
+ break; |
+ case 227: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ |
+{ |
+ Token all; |
+ all.z = yymsp[-3].minor.yy0.z; |
+ all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n; |
+ sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all); |
+} |
+ break; |
+ case 228: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ |
+{ |
+ sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194); |
+ yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/ |
+} |
+ break; |
+ case 229: /* trigger_time ::= BEFORE */ |
+{ yymsp[0].minor.yy194 = TK_BEFORE; } |
+ break; |
+ case 230: /* trigger_time ::= AFTER */ |
+{ yymsp[0].minor.yy194 = TK_AFTER; } |
+ break; |
+ case 231: /* trigger_time ::= INSTEAD OF */ |
+{ yymsp[-1].minor.yy194 = TK_INSTEAD;} |
+ break; |
+ case 232: /* trigger_time ::= */ |
+{ yymsp[1].minor.yy194 = TK_BEFORE; } |
+ break; |
+ case 233: /* trigger_event ::= DELETE|INSERT */ |
+ case 234: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==234); |
+{yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;} |
+ break; |
+ case 235: /* trigger_event ::= UPDATE OF idlist */ |
+{yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;} |
+ break; |
+ case 236: /* when_clause ::= */ |
+ case 255: /* key_opt ::= */ yytestcase(yyruleno==255); |
+{ yymsp[1].minor.yy72 = 0; } |
+ break; |
+ case 237: /* when_clause ::= WHEN expr */ |
+ case 256: /* key_opt ::= KEY expr */ yytestcase(yyruleno==256); |
+{ yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; } |
+ break; |
+ case 238: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ |
+{ |
+ assert( yymsp[-2].minor.yy145!=0 ); |
+ yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145; |
+ yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145; |
+} |
+ break; |
+ case 239: /* trigger_cmd_list ::= trigger_cmd SEMI */ |
+{ |
+ assert( yymsp[-1].minor.yy145!=0 ); |
+ yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145; |
+} |
+ break; |
+ case 240: /* trnm ::= nm DOT nm */ |
+{ |
+ yymsp[-2].minor.yy0 = yymsp[0].minor.yy0; |
+ sqlite3ErrorMsg(pParse, |
+ "qualified table names are not allowed on INSERT, UPDATE, and DELETE " |
+ "statements within triggers"); |
+} |
+ break; |
+ case 241: /* tridxby ::= INDEXED BY nm */ |
+{ |
+ sqlite3ErrorMsg(pParse, |
+ "the INDEXED BY clause is not allowed on UPDATE or DELETE statements " |
+ "within triggers"); |
+} |
+ break; |
+ case 242: /* tridxby ::= NOT INDEXED */ |
+{ |
+ sqlite3ErrorMsg(pParse, |
+ "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements " |
+ "within triggers"); |
+} |
+ break; |
+ case 243: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */ |
+{yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);} |
+ break; |
+ case 244: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */ |
+{yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/} |
+ break; |
+ case 245: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */ |
+{yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);} |
+ break; |
+ case 246: /* trigger_cmd ::= select */ |
+{yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/} |
+ break; |
+ case 247: /* expr ::= RAISE LP IGNORE RP */ |
+{ |
+ spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ |
+ yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0); |
+ if( yymsp[-3].minor.yy190.pExpr ){ |
+ yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore; |
+ } |
+} |
+ break; |
+ case 248: /* expr ::= RAISE LP raisetype COMMA nm RP */ |
+{ |
+ spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ |
+ yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1); |
+ if( yymsp[-5].minor.yy190.pExpr ) { |
+ yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194; |
+ } |
+} |
+ break; |
+ case 249: /* raisetype ::= ROLLBACK */ |
+{yymsp[0].minor.yy194 = OE_Rollback;} |
+ break; |
+ case 251: /* raisetype ::= FAIL */ |
+{yymsp[0].minor.yy194 = OE_Fail;} |
+ break; |
+ case 252: /* cmd ::= DROP TRIGGER ifexists fullname */ |
+{ |
+ sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194); |
+} |
+ break; |
+ case 253: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ |
+{ |
+ sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72); |
+} |
+ break; |
+ case 254: /* cmd ::= DETACH database_kw_opt expr */ |
+{ |
+ sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr); |
+} |
+ break; |
+ case 257: /* cmd ::= REINDEX */ |
+{sqlite3Reindex(pParse, 0, 0);} |
+ break; |
+ case 258: /* cmd ::= REINDEX nm dbnm */ |
+{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} |
+ break; |
+ case 259: /* cmd ::= ANALYZE */ |
+{sqlite3Analyze(pParse, 0, 0);} |
+ break; |
+ case 260: /* cmd ::= ANALYZE nm dbnm */ |
+{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} |
+ break; |
+ case 261: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ |
+{ |
+ sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0); |
+} |
+ break; |
+ case 262: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ |
+{ |
+ yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n; |
+ sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0); |
+} |
+ break; |
+ case 263: /* add_column_fullname ::= fullname */ |
+{ |
+ disableLookaside(pParse); |
+ sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185); |
+} |
+ break; |
+ case 264: /* cmd ::= create_vtab */ |
+{sqlite3VtabFinishParse(pParse,0);} |
+ break; |
+ case 265: /* cmd ::= create_vtab LP vtabarglist RP */ |
+{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);} |
+ break; |
+ case 266: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ |
+{ |
+ sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194); |
+} |
+ break; |
+ case 267: /* vtabarg ::= */ |
+{sqlite3VtabArgInit(pParse);} |
+ break; |
+ case 268: /* vtabargtoken ::= ANY */ |
+ case 269: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==269); |
+ case 270: /* lp ::= LP */ yytestcase(yyruleno==270); |
+{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);} |
+ break; |
+ case 271: /* with ::= */ |
+{yymsp[1].minor.yy285 = 0;} |
+ break; |
+ case 272: /* with ::= WITH wqlist */ |
+{ yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; } |
+ break; |
+ case 273: /* with ::= WITH RECURSIVE wqlist */ |
+{ yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; } |
+ break; |
+ case 274: /* wqlist ::= nm eidlist_opt AS LP select RP */ |
+{ |
+ yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/ |
+} |
+ break; |
+ case 275: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */ |
+{ |
+ yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); |
+} |
+ break; |
+ default: |
+ /* (276) input ::= cmdlist */ yytestcase(yyruleno==276); |
+ /* (277) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==277); |
+ /* (278) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=278); |
+ /* (279) ecmd ::= SEMI */ yytestcase(yyruleno==279); |
+ /* (280) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==280); |
+ /* (281) explain ::= */ yytestcase(yyruleno==281); |
+ /* (282) trans_opt ::= */ yytestcase(yyruleno==282); |
+ /* (283) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==283); |
+ /* (284) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==284); |
+ /* (285) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==285); |
+ /* (286) savepoint_opt ::= */ yytestcase(yyruleno==286); |
+ /* (287) cmd ::= create_table create_table_args */ yytestcase(yyruleno==287); |
+ /* (288) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==288); |
+ /* (289) columnlist ::= columnname carglist */ yytestcase(yyruleno==289); |
+ /* (290) nm ::= ID|INDEXED */ yytestcase(yyruleno==290); |
+ /* (291) nm ::= STRING */ yytestcase(yyruleno==291); |
+ /* (292) nm ::= JOIN_KW */ yytestcase(yyruleno==292); |
+ /* (293) typetoken ::= typename */ yytestcase(yyruleno==293); |
+ /* (294) typename ::= ID|STRING */ yytestcase(yyruleno==294); |
+ /* (295) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=295); |
+ /* (296) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=296); |
+ /* (297) carglist ::= carglist ccons */ yytestcase(yyruleno==297); |
+ /* (298) carglist ::= */ yytestcase(yyruleno==298); |
+ /* (299) ccons ::= NULL onconf */ yytestcase(yyruleno==299); |
+ /* (300) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==300); |
+ /* (301) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==301); |
+ /* (302) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=302); |
+ /* (303) tconscomma ::= */ yytestcase(yyruleno==303); |
+ /* (304) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=304); |
+ /* (305) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=305); |
+ /* (306) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=306); |
+ /* (307) oneselect ::= values */ yytestcase(yyruleno==307); |
+ /* (308) sclp ::= selcollist COMMA */ yytestcase(yyruleno==308); |
+ /* (309) as ::= ID|STRING */ yytestcase(yyruleno==309); |
+ /* (310) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=310); |
+ /* (311) exprlist ::= nexprlist */ yytestcase(yyruleno==311); |
+ /* (312) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=312); |
+ /* (313) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=313); |
+ /* (314) nmnum ::= ON */ yytestcase(yyruleno==314); |
+ /* (315) nmnum ::= DELETE */ yytestcase(yyruleno==315); |
+ /* (316) nmnum ::= DEFAULT */ yytestcase(yyruleno==316); |
+ /* (317) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==317); |
+ /* (318) foreach_clause ::= */ yytestcase(yyruleno==318); |
+ /* (319) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==319); |
+ /* (320) trnm ::= nm */ yytestcase(yyruleno==320); |
+ /* (321) tridxby ::= */ yytestcase(yyruleno==321); |
+ /* (322) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==322); |
+ /* (323) database_kw_opt ::= */ yytestcase(yyruleno==323); |
+ /* (324) kwcolumn_opt ::= */ yytestcase(yyruleno==324); |
+ /* (325) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==325); |
+ /* (326) vtabarglist ::= vtabarg */ yytestcase(yyruleno==326); |
+ /* (327) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==327); |
+ /* (328) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==328); |
+ /* (329) anylist ::= */ yytestcase(yyruleno==329); |
+ /* (330) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==330); |
+ /* (331) anylist ::= anylist ANY */ yytestcase(yyruleno==331); |
+ break; |
+/********** End reduce actions ************************************************/ |
+ }; |
+ assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) ); |
+ yygoto = yyRuleInfo[yyruleno].lhs; |
+ yysize = yyRuleInfo[yyruleno].nrhs; |
+ yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto); |
+ if( yyact <= YY_MAX_SHIFTREDUCE ){ |
+ if( yyact>YY_MAX_SHIFT ){ |
+ yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE; |
+ } |
+ yymsp -= yysize-1; |
+ yypParser->yytos = yymsp; |
+ yymsp->stateno = (YYACTIONTYPE)yyact; |
+ yymsp->major = (YYCODETYPE)yygoto; |
+ yyTraceShift(yypParser, yyact); |
+ }else{ |
+ assert( yyact == YY_ACCEPT_ACTION ); |
+ yypParser->yytos -= yysize; |
+ yy_accept(yypParser); |
+ } |
+} |
+ |
+/* |
+** The following code executes when the parse fails |
+*/ |
+#ifndef YYNOERRORRECOVERY |
+static void yy_parse_failed( |
+ yyParser *yypParser /* The parser */ |
+){ |
+ sqlite3ParserARG_FETCH; |
+#ifndef NDEBUG |
+ if( yyTraceFILE ){ |
+ fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); |
+ } |
+#endif |
+ while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser); |
+ /* Here code is inserted which will be executed whenever the |
+ ** parser fails */ |
+/************ Begin %parse_failure code ***************************************/ |
+/************ End %parse_failure code *****************************************/ |
+ sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ |
+} |
+#endif /* YYNOERRORRECOVERY */ |
+ |
+/* |
+** The following code executes when a syntax error first occurs. |
+*/ |
+static void yy_syntax_error( |
+ yyParser *yypParser, /* The parser */ |
+ int yymajor, /* The major type of the error token */ |
+ sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */ |
+){ |
+ sqlite3ParserARG_FETCH; |
+#define TOKEN yyminor |
+/************ Begin %syntax_error code ****************************************/ |
+ |
+ UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */ |
+ assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */ |
+ sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); |
+/************ End %syntax_error code ******************************************/ |
+ sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ |
+} |
+ |
+/* |
+** The following is executed when the parser accepts |
+*/ |
+static void yy_accept( |
+ yyParser *yypParser /* The parser */ |
+){ |
+ sqlite3ParserARG_FETCH; |
+#ifndef NDEBUG |
+ if( yyTraceFILE ){ |
+ fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); |
+ } |
+#endif |
+#ifndef YYNOERRORRECOVERY |
+ yypParser->yyerrcnt = -1; |
+#endif |
+ assert( yypParser->yytos==yypParser->yystack ); |
+ /* Here code is inserted which will be executed whenever the |
+ ** parser accepts */ |
+/*********** Begin %parse_accept code *****************************************/ |
+/*********** End %parse_accept code *******************************************/ |
+ sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ |
+} |
+ |
+/* The main parser program. |
+** The first argument is a pointer to a structure obtained from |
+** "sqlite3ParserAlloc" which describes the current state of the parser. |
+** The second argument is the major token number. The third is |
+** the minor token. The fourth optional argument is whatever the |
+** user wants (and specified in the grammar) and is available for |
+** use by the action routines. |
+** |
+** Inputs: |
+** <ul> |
+** <li> A pointer to the parser (an opaque structure.) |
+** <li> The major token number. |
+** <li> The minor token number. |
+** <li> An option argument of a grammar-specified type. |
+** </ul> |
+** |
+** Outputs: |
+** None. |
+*/ |
+SQLITE_PRIVATE void sqlite3Parser( |
+ void *yyp, /* The parser */ |
+ int yymajor, /* The major token code number */ |
+ sqlite3ParserTOKENTYPE yyminor /* The value for the token */ |
+ sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */ |
+){ |
+ YYMINORTYPE yyminorunion; |
+ unsigned int yyact; /* The parser action. */ |
+#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) |
+ int yyendofinput; /* True if we are at the end of input */ |
+#endif |
+#ifdef YYERRORSYMBOL |
+ int yyerrorhit = 0; /* True if yymajor has invoked an error */ |
+#endif |
+ yyParser *yypParser; /* The parser */ |
+ |
+ yypParser = (yyParser*)yyp; |
+ assert( yypParser->yytos!=0 ); |
+#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) |
+ yyendofinput = (yymajor==0); |
+#endif |
+ sqlite3ParserARG_STORE; |
+ |
+#ifndef NDEBUG |
+ if( yyTraceFILE ){ |
+ fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]); |
+ } |
+#endif |
+ |
+ do{ |
+ yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor); |
+ if( yyact <= YY_MAX_SHIFTREDUCE ){ |
+ yy_shift(yypParser,yyact,yymajor,yyminor); |
+#ifndef YYNOERRORRECOVERY |
+ yypParser->yyerrcnt--; |
+#endif |
+ yymajor = YYNOCODE; |
+ }else if( yyact <= YY_MAX_REDUCE ){ |
+ yy_reduce(yypParser,yyact-YY_MIN_REDUCE); |
+ }else{ |
+ assert( yyact == YY_ERROR_ACTION ); |
+ yyminorunion.yy0 = yyminor; |
+#ifdef YYERRORSYMBOL |
+ int yymx; |
+#endif |
+#ifndef NDEBUG |
+ if( yyTraceFILE ){ |
+ fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); |
+ } |
+#endif |
+#ifdef YYERRORSYMBOL |
+ /* A syntax error has occurred. |
+ ** The response to an error depends upon whether or not the |
+ ** grammar defines an error token "ERROR". |
+ ** |
+ ** This is what we do if the grammar does define ERROR: |
+ ** |
+ ** * Call the %syntax_error function. |
+ ** |
+ ** * Begin popping the stack until we enter a state where |
+ ** it is legal to shift the error symbol, then shift |
+ ** the error symbol. |
+ ** |
+ ** * Set the error count to three. |
+ ** |
+ ** * Begin accepting and shifting new tokens. No new error |
+ ** processing will occur until three tokens have been |
+ ** shifted successfully. |
+ ** |
+ */ |
+ if( yypParser->yyerrcnt<0 ){ |
+ yy_syntax_error(yypParser,yymajor,yyminor); |
+ } |
+ yymx = yypParser->yytos->major; |
+ if( yymx==YYERRORSYMBOL || yyerrorhit ){ |
+#ifndef NDEBUG |
+ if( yyTraceFILE ){ |
+ fprintf(yyTraceFILE,"%sDiscard input token %s\n", |
+ yyTracePrompt,yyTokenName[yymajor]); |
+ } |
+#endif |
+ yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion); |
+ yymajor = YYNOCODE; |
+ }else{ |
+ while( yypParser->yytos >= yypParser->yystack |
+ && yymx != YYERRORSYMBOL |
+ && (yyact = yy_find_reduce_action( |
+ yypParser->yytos->stateno, |
+ YYERRORSYMBOL)) >= YY_MIN_REDUCE |
+ ){ |
+ yy_pop_parser_stack(yypParser); |
+ } |
+ if( yypParser->yytos < yypParser->yystack || yymajor==0 ){ |
+ yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); |
+ yy_parse_failed(yypParser); |
+#ifndef YYNOERRORRECOVERY |
+ yypParser->yyerrcnt = -1; |
+#endif |
+ yymajor = YYNOCODE; |
+ }else if( yymx!=YYERRORSYMBOL ){ |
+ yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor); |
+ } |
+ } |
+ yypParser->yyerrcnt = 3; |
+ yyerrorhit = 1; |
+#elif defined(YYNOERRORRECOVERY) |
+ /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to |
+ ** do any kind of error recovery. Instead, simply invoke the syntax |
+ ** error routine and continue going as if nothing had happened. |
+ ** |
+ ** Applications can set this macro (for example inside %include) if |
+ ** they intend to abandon the parse upon the first syntax error seen. |
+ */ |
+ yy_syntax_error(yypParser,yymajor, yyminor); |
+ yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); |
+ yymajor = YYNOCODE; |
+ |
+#else /* YYERRORSYMBOL is not defined */ |
+ /* This is what we do if the grammar does not define ERROR: |
+ ** |
+ ** * Report an error message, and throw away the input token. |
+ ** |
+ ** * If the input token is $, then fail the parse. |
+ ** |
+ ** As before, subsequent error messages are suppressed until |
+ ** three input tokens have been successfully shifted. |
+ */ |
+ if( yypParser->yyerrcnt<=0 ){ |
+ yy_syntax_error(yypParser,yymajor, yyminor); |
+ } |
+ yypParser->yyerrcnt = 3; |
+ yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); |
+ if( yyendofinput ){ |
+ yy_parse_failed(yypParser); |
+#ifndef YYNOERRORRECOVERY |
+ yypParser->yyerrcnt = -1; |
+#endif |
+ } |
+ yymajor = YYNOCODE; |
+#endif |
+ } |
+ }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack ); |
+#ifndef NDEBUG |
+ if( yyTraceFILE ){ |
+ yyStackEntry *i; |
+ char cDiv = '['; |
+ fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt); |
+ for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){ |
+ fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]); |
+ cDiv = ' '; |
+ } |
+ fprintf(yyTraceFILE,"]\n"); |
+ } |
+#endif |
+ return; |
+} |
+ |
+/************** End of parse.c ***********************************************/ |
+/************** Begin file tokenize.c ****************************************/ |
+/* |
+** 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. |
+** |
+************************************************************************* |
+** An tokenizer for SQL |
+** |
+** This file contains C code that splits an SQL input string up into |
+** individual tokens and sends those tokens one-by-one over to the |
+** parser for analysis. |
+*/ |
+/* #include "sqliteInt.h" */ |
+/* #include <stdlib.h> */ |
+ |
+/* Character classes for tokenizing |
+** |
+** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented |
+** using a lookup table, whereas a switch() directly on c uses a binary search. |
+** The lookup table is much faster. To maximize speed, and to ensure that |
+** a lookup table is used, all of the classes need to be small integers and |
+** all of them need to be used within the switch. |
+*/ |
+#define CC_X 0 /* The letter 'x', or start of BLOB literal */ |
+#define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */ |
+#define CC_ID 2 /* unicode characters usable in IDs */ |
+#define CC_DIGIT 3 /* Digits */ |
+#define CC_DOLLAR 4 /* '$' */ |
+#define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */ |
+#define CC_VARNUM 6 /* '?'. Numeric SQL variables */ |
+#define CC_SPACE 7 /* Space characters */ |
+#define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */ |
+#define CC_QUOTE2 9 /* '['. [...] style quoted ids */ |
+#define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */ |
+#define CC_MINUS 11 /* '-'. Minus or SQL-style comment */ |
+#define CC_LT 12 /* '<'. Part of < or <= or <> */ |
+#define CC_GT 13 /* '>'. Part of > or >= */ |
+#define CC_EQ 14 /* '='. Part of = or == */ |
+#define CC_BANG 15 /* '!'. Part of != */ |
+#define CC_SLASH 16 /* '/'. / or c-style comment */ |
+#define CC_LP 17 /* '(' */ |
+#define CC_RP 18 /* ')' */ |
+#define CC_SEMI 19 /* ';' */ |
+#define CC_PLUS 20 /* '+' */ |
+#define CC_STAR 21 /* '*' */ |
+#define CC_PERCENT 22 /* '%' */ |
+#define CC_COMMA 23 /* ',' */ |
+#define CC_AND 24 /* '&' */ |
+#define CC_TILDA 25 /* '~' */ |
+#define CC_DOT 26 /* '.' */ |
+#define CC_ILLEGAL 27 /* Illegal character */ |
+ |
+static const unsigned char aiClass[] = { |
+#ifdef SQLITE_ASCII |
+/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */ |
+/* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27, |
+/* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, |
+/* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16, |
+/* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6, |
+/* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
+/* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1, |
+/* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
+/* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27, |
+/* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, |
+/* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, |
+/* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, |
+/* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, |
+/* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, |
+/* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, |
+/* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, |
+/* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 |
+#endif |
+#ifdef SQLITE_EBCDIC |
+/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */ |
+/* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27, |
+/* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, |
+/* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, |
+/* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, |
+/* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10, |
+/* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27, |
+/* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6, |
+/* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8, |
+/* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, |
+/* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, |
+/* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27, |
+/* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27, |
+/* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, |
+/* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, |
+/* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27, |
+/* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27, |
+#endif |
+}; |
+ |
+/* |
+** The charMap() macro maps alphabetic characters (only) into their |
+** lower-case ASCII equivalent. On ASCII machines, this is just |
+** an upper-to-lower case map. On EBCDIC machines we also need |
+** to adjust the encoding. The mapping is only valid for alphabetics |
+** which are the only characters for which this feature is used. |
+** |
+** Used by keywordhash.h |
+*/ |
+#ifdef SQLITE_ASCII |
+# define charMap(X) sqlite3UpperToLower[(unsigned char)X] |
+#endif |
+#ifdef SQLITE_EBCDIC |
+# define charMap(X) ebcdicToAscii[(unsigned char)X] |
+const unsigned char ebcdicToAscii[] = { |
+/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ |
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ |
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ |
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ |
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */ |
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */ |
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */ |
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */ |
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */ |
+ 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */ |
+ 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */ |
+ 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */ |
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ |
+ 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */ |
+ 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */ |
+ 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */ |
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */ |
+}; |
+#endif |
+ |
+/* |
+** The sqlite3KeywordCode function looks up an identifier to determine if |
+** it is a keyword. If it is a keyword, the token code of that keyword is |
+** returned. If the input is not a keyword, TK_ID is returned. |
+** |
+** The implementation of this routine was generated by a program, |
+** mkkeywordhash.c, located in the tool subdirectory of the distribution. |
+** The output of the mkkeywordhash.c program is written into a file |
+** named keywordhash.h and then included into this source file by |
+** the #include below. |
+*/ |
+/************** Include keywordhash.h in the middle of tokenize.c ************/ |
+/************** Begin file keywordhash.h *************************************/ |
+/***** This file contains automatically generated code ****** |
+** |
+** The code in this file has been automatically generated by |
+** |
+** sqlite/tool/mkkeywordhash.c |
+** |
+** The code in this file implements a function that determines whether |
+** or not a given identifier is really an SQL keyword. The same thing |
+** might be implemented more directly using a hand-written hash table. |
+** But by using this automatically generated code, the size of the code |
+** is substantially reduced. This is important for embedded applications |
+** on platforms with limited memory. |
+*/ |
+/* Hash score: 182 */ |
+static int keywordCode(const char *z, int n, int *pType){ |
+ /* zText[] encodes 834 bytes of keywords in 554 bytes */ |
+ /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */ |
+ /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */ |
+ /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */ |
+ /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */ |
+ /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */ |
+ /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */ |
+ /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */ |
+ /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */ |
+ /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */ |
+ /* VACUUMVIEWINITIALLY */ |
+ static const char zText[553] = { |
+ 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H', |
+ 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G', |
+ 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A', |
+ 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F', |
+ 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N', |
+ 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I', |
+ 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E', |
+ 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E', |
+ 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T', |
+ 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q', |
+ 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S', |
+ 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A', |
+ 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E', |
+ 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A', |
+ 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A', |
+ 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A', |
+ 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J', |
+ 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L', |
+ 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E', |
+ 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H', |
+ 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E', |
+ 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E', |
+ 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M', |
+ 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R', |
+ 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A', |
+ 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D', |
+ 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O', |
+ 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T', |
+ 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R', |
+ 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M', |
+ 'V','I','E','W','I','N','I','T','I','A','L','L','Y', |
+ }; |
+ static const unsigned char aHash[127] = { |
+ 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0, |
+ 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0, |
+ 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71, |
+ 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44, |
+ 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25, |
+ 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0, |
+ 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14, |
+ 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113, |
+ 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0, |
+ 29, 0, 86, 63, 64, 0, 20, 61, 0, 56, |
+ }; |
+ static const unsigned char aNext[124] = { |
+ 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, |
+ 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, |
+ 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
+ 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50, |
+ 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38, |
+ 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0, |
+ 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34, |
+ 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8, |
+ 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37, |
+ 73, 83, 0, 35, 68, 0, 0, |
+ }; |
+ static const unsigned char aLen[124] = { |
+ 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6, |
+ 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6, |
+ 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10, |
+ 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7, |
+ 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4, |
+ 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4, |
+ 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7, |
+ 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8, |
+ 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8, |
+ 3, 5, 5, 6, 4, 9, 3, |
+ }; |
+ static const unsigned short int aOffset[124] = { |
+ 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33, |
+ 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81, |
+ 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152, |
+ 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192, |
+ 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246, |
+ 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318, |
+ 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380, |
+ 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459, |
+ 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513, |
+ 521, 524, 529, 534, 540, 544, 549, |
+ }; |
+ static const unsigned char aCode[124] = { |
+ TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE, |
+ TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN, |
+ TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD, |
+ TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE, |
+ TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE, |
+ TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW, |
+ TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT, |
+ TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO, |
+ TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP, |
+ TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH, |
+ TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP, |
+ TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN, |
+ TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW, |
+ TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE, |
+ TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN, |
+ TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA, |
+ TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN, |
+ TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND, |
+ TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST, |
+ TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW, |
+ TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS, |
+ TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW, |
+ TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT, |
+ TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING, |
+ TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL, |
+ }; |
+ int i, j; |
+ const char *zKW; |
+ if( n>=2 ){ |
+ i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127; |
+ for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){ |
+ if( aLen[i]!=n ) continue; |
+ j = 0; |
+ zKW = &zText[aOffset[i]]; |
+#ifdef SQLITE_ASCII |
+ while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; } |
+#endif |
+#ifdef SQLITE_EBCDIC |
+ while( j<n && toupper(z[j])==zKW[j] ){ j++; } |
+#endif |
+ if( j<n ) continue; |
+ testcase( i==0 ); /* REINDEX */ |
+ testcase( i==1 ); /* INDEXED */ |
+ testcase( i==2 ); /* INDEX */ |
+ testcase( i==3 ); /* DESC */ |
+ testcase( i==4 ); /* ESCAPE */ |
+ testcase( i==5 ); /* EACH */ |
+ testcase( i==6 ); /* CHECK */ |
+ testcase( i==7 ); /* KEY */ |
+ testcase( i==8 ); /* BEFORE */ |
+ testcase( i==9 ); /* FOREIGN */ |
+ testcase( i==10 ); /* FOR */ |
+ testcase( i==11 ); /* IGNORE */ |
+ testcase( i==12 ); /* REGEXP */ |
+ testcase( i==13 ); /* EXPLAIN */ |
+ testcase( i==14 ); /* INSTEAD */ |
+ testcase( i==15 ); /* ADD */ |
+ testcase( i==16 ); /* DATABASE */ |
+ testcase( i==17 ); /* AS */ |
+ testcase( i==18 ); /* SELECT */ |
+ testcase( i==19 ); /* TABLE */ |
+ testcase( i==20 ); /* LEFT */ |
+ testcase( i==21 ); /* THEN */ |
+ testcase( i==22 ); /* END */ |
+ testcase( i==23 ); /* DEFERRABLE */ |
+ testcase( i==24 ); /* ELSE */ |
+ testcase( i==25 ); /* EXCEPT */ |
+ testcase( i==26 ); /* TRANSACTION */ |
+ testcase( i==27 ); /* ACTION */ |
+ testcase( i==28 ); /* ON */ |
+ testcase( i==29 ); /* NATURAL */ |
+ testcase( i==30 ); /* ALTER */ |
+ testcase( i==31 ); /* RAISE */ |
+ testcase( i==32 ); /* EXCLUSIVE */ |
+ testcase( i==33 ); /* EXISTS */ |
+ testcase( i==34 ); /* SAVEPOINT */ |
+ testcase( i==35 ); /* INTERSECT */ |
+ testcase( i==36 ); /* TRIGGER */ |
+ testcase( i==37 ); /* REFERENCES */ |
+ testcase( i==38 ); /* CONSTRAINT */ |
+ testcase( i==39 ); /* INTO */ |
+ testcase( i==40 ); /* OFFSET */ |
+ testcase( i==41 ); /* OF */ |
+ testcase( i==42 ); /* SET */ |
+ testcase( i==43 ); /* TEMPORARY */ |
+ testcase( i==44 ); /* TEMP */ |
+ testcase( i==45 ); /* OR */ |
+ testcase( i==46 ); /* UNIQUE */ |
+ testcase( i==47 ); /* QUERY */ |
+ testcase( i==48 ); /* WITHOUT */ |
+ testcase( i==49 ); /* WITH */ |
+ testcase( i==50 ); /* OUTER */ |
+ testcase( i==51 ); /* RELEASE */ |
+ testcase( i==52 ); /* ATTACH */ |
+ testcase( i==53 ); /* HAVING */ |
+ testcase( i==54 ); /* GROUP */ |
+ testcase( i==55 ); /* UPDATE */ |
+ testcase( i==56 ); /* BEGIN */ |
+ testcase( i==57 ); /* INNER */ |
+ testcase( i==58 ); /* RECURSIVE */ |
+ testcase( i==59 ); /* BETWEEN */ |
+ testcase( i==60 ); /* NOTNULL */ |
+ testcase( i==61 ); /* NOT */ |
+ testcase( i==62 ); /* NO */ |
+ testcase( i==63 ); /* NULL */ |
+ testcase( i==64 ); /* LIKE */ |
+ testcase( i==65 ); /* CASCADE */ |
+ testcase( i==66 ); /* ASC */ |
+ testcase( i==67 ); /* DELETE */ |
+ testcase( i==68 ); /* CASE */ |
+ testcase( i==69 ); /* COLLATE */ |
+ testcase( i==70 ); /* CREATE */ |
+ testcase( i==71 ); /* CURRENT_DATE */ |
+ testcase( i==72 ); /* DETACH */ |
+ testcase( i==73 ); /* IMMEDIATE */ |
+ testcase( i==74 ); /* JOIN */ |
+ testcase( i==75 ); /* INSERT */ |
+ testcase( i==76 ); /* MATCH */ |
+ testcase( i==77 ); /* PLAN */ |
+ testcase( i==78 ); /* ANALYZE */ |
+ testcase( i==79 ); /* PRAGMA */ |
+ testcase( i==80 ); /* ABORT */ |
+ testcase( i==81 ); /* VALUES */ |
+ testcase( i==82 ); /* VIRTUAL */ |
+ testcase( i==83 ); /* LIMIT */ |
+ testcase( i==84 ); /* WHEN */ |
+ testcase( i==85 ); /* WHERE */ |
+ testcase( i==86 ); /* RENAME */ |
+ testcase( i==87 ); /* AFTER */ |
+ testcase( i==88 ); /* REPLACE */ |
+ testcase( i==89 ); /* AND */ |
+ testcase( i==90 ); /* DEFAULT */ |
+ testcase( i==91 ); /* AUTOINCREMENT */ |
+ testcase( i==92 ); /* TO */ |
+ testcase( i==93 ); /* IN */ |
+ testcase( i==94 ); /* CAST */ |
+ testcase( i==95 ); /* COLUMN */ |
+ testcase( i==96 ); /* COMMIT */ |
+ testcase( i==97 ); /* CONFLICT */ |
+ testcase( i==98 ); /* CROSS */ |
+ testcase( i==99 ); /* CURRENT_TIMESTAMP */ |
+ testcase( i==100 ); /* CURRENT_TIME */ |
+ testcase( i==101 ); /* PRIMARY */ |
+ testcase( i==102 ); /* DEFERRED */ |
+ testcase( i==103 ); /* DISTINCT */ |
+ testcase( i==104 ); /* IS */ |
+ testcase( i==105 ); /* DROP */ |
+ testcase( i==106 ); /* FAIL */ |
+ testcase( i==107 ); /* FROM */ |
+ testcase( i==108 ); /* FULL */ |
+ testcase( i==109 ); /* GLOB */ |
+ testcase( i==110 ); /* BY */ |
+ testcase( i==111 ); /* IF */ |
+ testcase( i==112 ); /* ISNULL */ |
+ testcase( i==113 ); /* ORDER */ |
+ testcase( i==114 ); /* RESTRICT */ |
+ testcase( i==115 ); /* RIGHT */ |
+ testcase( i==116 ); /* ROLLBACK */ |
+ testcase( i==117 ); /* ROW */ |
+ testcase( i==118 ); /* UNION */ |
+ testcase( i==119 ); /* USING */ |
+ testcase( i==120 ); /* VACUUM */ |
+ testcase( i==121 ); /* VIEW */ |
+ testcase( i==122 ); /* INITIALLY */ |
+ testcase( i==123 ); /* ALL */ |
+ *pType = aCode[i]; |
+ break; |
+ } |
+ } |
+ return n; |
+} |
+SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){ |
+ int id = TK_ID; |
+ keywordCode((char*)z, n, &id); |
+ return id; |
+} |
+#define SQLITE_N_KEYWORD 124 |
+ |
+/************** End of keywordhash.h *****************************************/ |
+/************** Continuing where we left off in tokenize.c *******************/ |
+ |
+ |
+/* |
+** If X is a character that can be used in an identifier then |
+** IdChar(X) will be true. Otherwise it is false. |
+** |
+** For ASCII, any character with the high-order bit set is |
+** allowed in an identifier. For 7-bit characters, |
+** sqlite3IsIdChar[X] must be 1. |
+** |
+** For EBCDIC, the rules are more complex but have the same |
+** end result. |
+** |
+** Ticket #1066. the SQL standard does not allow '$' in the |
+** middle of identifiers. But many SQL implementations do. |
+** SQLite will allow '$' in identifiers for compatibility. |
+** But the feature is undocumented. |
+*/ |
+#ifdef SQLITE_ASCII |
+#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) |
+#endif |
+#ifdef SQLITE_EBCDIC |
+SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = { |
+/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ |
+ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */ |
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */ |
+ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */ |
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */ |
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */ |
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */ |
+ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */ |
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ |
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */ |
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */ |
+ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */ |
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */ |
+}; |
+#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) |
+#endif |
+ |
+/* Make the IdChar function accessible from ctime.c */ |
+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS |
+SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); } |
+#endif |
+ |
+ |
+/* |
+** Return the length (in bytes) of the token that begins at z[0]. |
+** Store the token type in *tokenType before returning. |
+*/ |
+SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ |
+ int i, c; |
+ switch( aiClass[*z] ){ /* Switch on the character-class of the first byte |
+ ** of the token. See the comment on the CC_ defines |
+ ** above. */ |
+ case CC_SPACE: { |
+ testcase( z[0]==' ' ); |
+ testcase( z[0]=='\t' ); |
+ testcase( z[0]=='\n' ); |
+ testcase( z[0]=='\f' ); |
+ testcase( z[0]=='\r' ); |
+ for(i=1; sqlite3Isspace(z[i]); i++){} |
+ *tokenType = TK_SPACE; |
+ return i; |
+ } |
+ case CC_MINUS: { |
+ if( z[1]=='-' ){ |
+ for(i=2; (c=z[i])!=0 && c!='\n'; i++){} |
+ *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ |
+ return i; |
+ } |
+ *tokenType = TK_MINUS; |
+ return 1; |
+ } |
+ case CC_LP: { |
+ *tokenType = TK_LP; |
+ return 1; |
+ } |
+ case CC_RP: { |
+ *tokenType = TK_RP; |
+ return 1; |
+ } |
+ case CC_SEMI: { |
+ *tokenType = TK_SEMI; |
+ return 1; |
+ } |
+ case CC_PLUS: { |
+ *tokenType = TK_PLUS; |
+ return 1; |
+ } |
+ case CC_STAR: { |
+ *tokenType = TK_STAR; |
+ return 1; |
+ } |
+ case CC_SLASH: { |
+ if( z[1]!='*' || z[2]==0 ){ |
+ *tokenType = TK_SLASH; |
+ return 1; |
+ } |
+ for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){} |
+ if( c ) i++; |
+ *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ |
+ return i; |
+ } |
+ case CC_PERCENT: { |
+ *tokenType = TK_REM; |
+ return 1; |
+ } |
+ case CC_EQ: { |
+ *tokenType = TK_EQ; |
+ return 1 + (z[1]=='='); |
+ } |
+ case CC_LT: { |
+ if( (c=z[1])=='=' ){ |
+ *tokenType = TK_LE; |
+ return 2; |
+ }else if( c=='>' ){ |
+ *tokenType = TK_NE; |
+ return 2; |
+ }else if( c=='<' ){ |
+ *tokenType = TK_LSHIFT; |
+ return 2; |
+ }else{ |
+ *tokenType = TK_LT; |
+ return 1; |
+ } |
+ } |
+ case CC_GT: { |
+ if( (c=z[1])=='=' ){ |
+ *tokenType = TK_GE; |
+ return 2; |
+ }else if( c=='>' ){ |
+ *tokenType = TK_RSHIFT; |
+ return 2; |
+ }else{ |
+ *tokenType = TK_GT; |
+ return 1; |
+ } |
+ } |
+ case CC_BANG: { |
+ if( z[1]!='=' ){ |
+ *tokenType = TK_ILLEGAL; |
+ return 1; |
+ }else{ |
+ *tokenType = TK_NE; |
+ return 2; |
+ } |
+ } |
+ case CC_PIPE: { |
+ if( z[1]!='|' ){ |
+ *tokenType = TK_BITOR; |
+ return 1; |
+ }else{ |
+ *tokenType = TK_CONCAT; |
+ return 2; |
+ } |
+ } |
+ case CC_COMMA: { |
+ *tokenType = TK_COMMA; |
+ return 1; |
+ } |
+ case CC_AND: { |
+ *tokenType = TK_BITAND; |
+ return 1; |
+ } |
+ case CC_TILDA: { |
+ *tokenType = TK_BITNOT; |
+ return 1; |
+ } |
+ case CC_QUOTE: { |
+ int delim = z[0]; |
+ testcase( delim=='`' ); |
+ testcase( delim=='\'' ); |
+ testcase( delim=='"' ); |
+ for(i=1; (c=z[i])!=0; i++){ |
+ if( c==delim ){ |
+ if( z[i+1]==delim ){ |
+ i++; |
+ }else{ |
+ break; |
+ } |
+ } |
+ } |
+ if( c=='\'' ){ |
+ *tokenType = TK_STRING; |
+ return i+1; |
+ }else if( c!=0 ){ |
+ *tokenType = TK_ID; |
+ return i+1; |
+ }else{ |
+ *tokenType = TK_ILLEGAL; |
+ return i; |
+ } |
+ } |
+ case CC_DOT: { |
+#ifndef SQLITE_OMIT_FLOATING_POINT |
+ if( !sqlite3Isdigit(z[1]) ) |
+#endif |
+ { |
+ *tokenType = TK_DOT; |
+ return 1; |
+ } |
+ /* If the next character is a digit, this is a floating point |
+ ** number that begins with ".". Fall thru into the next case */ |
+ } |
+ case CC_DIGIT: { |
+ testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' ); |
+ testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' ); |
+ testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' ); |
+ testcase( z[0]=='9' ); |
+ *tokenType = TK_INTEGER; |
+#ifndef SQLITE_OMIT_HEX_INTEGER |
+ if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){ |
+ for(i=3; sqlite3Isxdigit(z[i]); i++){} |
+ return i; |
+ } |
+#endif |
+ for(i=0; sqlite3Isdigit(z[i]); i++){} |
+#ifndef SQLITE_OMIT_FLOATING_POINT |
+ if( z[i]=='.' ){ |
+ i++; |
+ while( sqlite3Isdigit(z[i]) ){ i++; } |
+ *tokenType = TK_FLOAT; |
+ } |
+ if( (z[i]=='e' || z[i]=='E') && |
+ ( sqlite3Isdigit(z[i+1]) |
+ || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2])) |
+ ) |
+ ){ |
+ i += 2; |
+ while( sqlite3Isdigit(z[i]) ){ i++; } |
+ *tokenType = TK_FLOAT; |
+ } |
+#endif |
+ while( IdChar(z[i]) ){ |
+ *tokenType = TK_ILLEGAL; |
+ i++; |
+ } |
+ return i; |
+ } |
+ case CC_QUOTE2: { |
+ for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){} |
+ *tokenType = c==']' ? TK_ID : TK_ILLEGAL; |
+ return i; |
+ } |
+ case CC_VARNUM: { |
+ *tokenType = TK_VARIABLE; |
+ for(i=1; sqlite3Isdigit(z[i]); i++){} |
+ return i; |
+ } |
+ case CC_DOLLAR: |
+ case CC_VARALPHA: { |
+ int n = 0; |
+ testcase( z[0]=='$' ); testcase( z[0]=='@' ); |
+ testcase( z[0]==':' ); testcase( z[0]=='#' ); |
+ *tokenType = TK_VARIABLE; |
+ for(i=1; (c=z[i])!=0; i++){ |
+ if( IdChar(c) ){ |
+ n++; |
+#ifndef SQLITE_OMIT_TCL_VARIABLE |
+ }else if( c=='(' && n>0 ){ |
+ do{ |
+ i++; |
+ }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' ); |
+ if( c==')' ){ |
+ i++; |
+ }else{ |
+ *tokenType = TK_ILLEGAL; |
+ } |
+ break; |
+ }else if( c==':' && z[i+1]==':' ){ |
+ i++; |
+#endif |
+ }else{ |
+ break; |
+ } |
+ } |
+ if( n==0 ) *tokenType = TK_ILLEGAL; |
+ return i; |
+ } |
+ case CC_KYWD: { |
+ for(i=1; aiClass[z[i]]<=CC_KYWD; i++){} |
+ if( IdChar(z[i]) ){ |
+ /* This token started out using characters that can appear in keywords, |
+ ** but z[i] is a character not allowed within keywords, so this must |
+ ** be an identifier instead */ |
+ i++; |
+ break; |
+ } |
+ *tokenType = TK_ID; |
+ return keywordCode((char*)z, i, tokenType); |
+ } |
+ case CC_X: { |
+#ifndef SQLITE_OMIT_BLOB_LITERAL |
+ testcase( z[0]=='x' ); testcase( z[0]=='X' ); |
+ if( z[1]=='\'' ){ |
+ *tokenType = TK_BLOB; |
+ for(i=2; sqlite3Isxdigit(z[i]); i++){} |
+ if( z[i]!='\'' || i%2 ){ |
+ *tokenType = TK_ILLEGAL; |
+ while( z[i] && z[i]!='\'' ){ i++; } |
+ } |
+ if( z[i] ) i++; |
+ return i; |
+ } |
+#endif |
+ /* If it is not a BLOB literal, then it must be an ID, since no |
+ ** SQL keywords start with the letter 'x'. Fall through */ |
+ } |
+ case CC_ID: { |
+ i = 1; |
+ break; |
+ } |
+ default: { |
+ *tokenType = TK_ILLEGAL; |
+ return 1; |
+ } |
+ } |
+ while( IdChar(z[i]) ){ i++; } |
+ *tokenType = TK_ID; |
+ return i; |
+} |
+ |
+/* |
+** Run the parser on the given SQL string. The parser structure is |
+** passed in. An SQLITE_ status code is returned. If an error occurs |
+** then an and attempt is made to write an error message into |
+** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that |
+** error message. |
+*/ |
+SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){ |
+ int nErr = 0; /* Number of errors encountered */ |
+ int i; /* Loop counter */ |
+ void *pEngine; /* The LEMON-generated LALR(1) parser */ |
+ int tokenType; /* type of the next token */ |
+ int lastTokenParsed = -1; /* type of the previous token */ |
+ sqlite3 *db = pParse->db; /* The database connection */ |
+ int mxSqlLen; /* Max length of an SQL string */ |
+#ifdef sqlite3Parser_ENGINEALWAYSONSTACK |
+ unsigned char zSpace[sizeof(yyParser)]; /* Space for parser engine object */ |
+#endif |
+ |
+ assert( zSql!=0 ); |
+ mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; |
+ if( db->nVdbeActive==0 ){ |
+ db->u1.isInterrupted = 0; |
+ } |
+ pParse->rc = SQLITE_OK; |
+ pParse->zTail = zSql; |
+ i = 0; |
+ assert( pzErrMsg!=0 ); |
+ /* sqlite3ParserTrace(stdout, "parser: "); */ |
+#ifdef sqlite3Parser_ENGINEALWAYSONSTACK |
+ pEngine = zSpace; |
+ sqlite3ParserInit(pEngine); |
+#else |
+ pEngine = sqlite3ParserAlloc(sqlite3Malloc); |
+ if( pEngine==0 ){ |
+ sqlite3OomFault(db); |
+ return SQLITE_NOMEM_BKPT; |
+ } |
+#endif |
+ assert( pParse->pNewTable==0 ); |
+ assert( pParse->pNewTrigger==0 ); |
+ assert( pParse->nVar==0 ); |
+ assert( pParse->pVList==0 ); |
+ while( 1 ){ |
+ assert( i>=0 ); |
+ if( zSql[i]!=0 ){ |
+ pParse->sLastToken.z = &zSql[i]; |
+ pParse->sLastToken.n = sqlite3GetToken((u8*)&zSql[i],&tokenType); |
+ i += pParse->sLastToken.n; |
+ if( i>mxSqlLen ){ |
+ pParse->rc = SQLITE_TOOBIG; |
+ break; |
+ } |
+ }else{ |
+ /* Upon reaching the end of input, call the parser two more times |
+ ** with tokens TK_SEMI and 0, in that order. */ |
+ if( lastTokenParsed==TK_SEMI ){ |
+ tokenType = 0; |
+ }else if( lastTokenParsed==0 ){ |
+ break; |
+ }else{ |
+ tokenType = TK_SEMI; |
+ } |
+ } |
+ if( tokenType>=TK_SPACE ){ |
+ assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL ); |
+ if( db->u1.isInterrupted ){ |
+ pParse->rc = SQLITE_INTERRUPT; |
+ break; |
+ } |
+ if( tokenType==TK_ILLEGAL ){ |
+ sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"", |
+ &pParse->sLastToken); |
+ break; |
+ } |
+ }else{ |
+ sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse); |
+ lastTokenParsed = tokenType; |
+ if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break; |
+ } |
+ } |
+ assert( nErr==0 ); |
+ pParse->zTail = &zSql[i]; |
+#ifdef YYTRACKMAXSTACKDEPTH |
+ sqlite3_mutex_enter(sqlite3MallocMutex()); |
+ sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK, |
+ sqlite3ParserStackPeak(pEngine) |
+ ); |
+ sqlite3_mutex_leave(sqlite3MallocMutex()); |
+#endif /* YYDEBUG */ |
+#ifdef sqlite3Parser_ENGINEALWAYSONSTACK |
+ sqlite3ParserFinalize(pEngine); |
+#else |
+ sqlite3ParserFree(pEngine, sqlite3_free); |
+#endif |
+ if( db->mallocFailed ){ |
+ pParse->rc = SQLITE_NOMEM_BKPT; |
+ } |
+ if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){ |
+ pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc)); |
+ } |
+ assert( pzErrMsg!=0 ); |
+ if( pParse->zErrMsg ){ |
+ *pzErrMsg = pParse->zErrMsg; |
+ sqlite3_log(pParse->rc, "%s", *pzErrMsg); |
+ pParse->zErrMsg = 0; |
+ nErr++; |
+ } |
+ if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){ |
+ sqlite3VdbeDelete(pParse->pVdbe); |
+ pParse->pVdbe = 0; |
+ } |
+#ifndef SQLITE_OMIT_SHARED_CACHE |
+ if( pParse->nested==0 ){ |
+ sqlite3DbFree(db, pParse->aTableLock); |
+ pParse->aTableLock = 0; |
+ pParse->nTableLock = 0; |
+ } |
+#endif |
+#ifndef SQLITE_OMIT_VIRTUALTABLE |
+ sqlite3_free(pParse->apVtabLock); |
+#endif |
+ |
+ if( !IN_DECLARE_VTAB ){ |
+ /* If the pParse->declareVtab flag is set, do not delete any table |
+ ** structure built up in pParse->pNewTable. The calling code (see vtab.c) |
+ ** will take responsibility for freeing the Table structure. |
+ */ |
+ sqlite3DeleteTable(db, pParse->pNewTable); |
+ } |
+ |
+ if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree); |
+ sqlite3DeleteTrigger(db, pParse->pNewTrigger); |
+ sqlite3DbFree(db, pParse->pVList); |
+ while( pParse->pAinc ){ |
+ AutoincInfo *p = pParse->pAinc; |
+ pParse->pAinc = p->pNext; |
+ sqlite3DbFree(db, p); |
+ } |
+ while( pParse->pZombieTab ){ |
+ Table *p = pParse->pZombieTab; |
+ pParse->pZombieTab = p->pNextZombie; |
+ sqlite3DeleteTable(db, p); |
+ } |
+ assert( nErr==0 || pParse->rc!=SQLITE_OK ); |
+ return nErr; |
+} |
+ |
+/************** End of tokenize.c ********************************************/ |
+/************** Begin file complete.c ****************************************/ |
+/* |
+** 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. |
+** |
+************************************************************************* |
+** An tokenizer for SQL |
+** |
+** This file contains C code that implements the sqlite3_complete() API. |
+** This code used to be part of the tokenizer.c source file. But by |
+** separating it out, the code will be automatically omitted from |
+** static links that do not use it. |
+*/ |
+/* #include "sqliteInt.h" */ |
+#ifndef SQLITE_OMIT_COMPLETE |
+ |
+/* |
+** This is defined in tokenize.c. We just have to import the definition. |
+*/ |
+#ifndef SQLITE_AMALGAMATION |
+#ifdef SQLITE_ASCII |
+#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) |
+#endif |
+#ifdef SQLITE_EBCDIC |
+SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[]; |
+#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) |
+#endif |
+#endif /* SQLITE_AMALGAMATION */ |
+ |
+ |
+/* |
+** Token types used by the sqlite3_complete() routine. See the header |
+** comments on that procedure for additional information. |
+*/ |
+#define tkSEMI 0 |
+#define tkWS 1 |
+#define tkOTHER 2 |
+#ifndef SQLITE_OMIT_TRIGGER |
+#define tkEXPLAIN 3 |
+#define tkCREATE 4 |
+#define tkTEMP 5 |
+#define tkTRIGGER 6 |
+#define tkEND 7 |
+#endif |
+ |
+/* |
+** Return TRUE if the given SQL string ends in a semicolon. |
+** |
+** Special handling is require for CREATE TRIGGER statements. |
+** Whenever the CREATE TRIGGER keywords are seen, the statement |
+** must end with ";END;". |
+** |
+** This implementation uses a state machine with 8 states: |
+** |
+** (0) INVALID We have not yet seen a non-whitespace character. |
+** |
+** (1) START At the beginning or end of an SQL statement. This routine |
+** returns 1 if it ends in the START state and 0 if it ends |
+** in any other state. |
+** |
+** (2) NORMAL We are in the middle of statement which ends with a single |
+** semicolon. |
+** |
+** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of |
+** a statement. |
+** |
+** (4) CREATE The keyword CREATE has been seen at the beginning of a |
+** statement, possibly preceded by EXPLAIN and/or followed by |
+** TEMP or TEMPORARY |
+** |
+** (5) TRIGGER We are in the middle of a trigger definition that must be |
+** ended by a semicolon, the keyword END, and another semicolon. |
+** |
+** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at |
+** the end of a trigger definition. |
+** |
+** (7) END We've seen the ";END" of the ";END;" that occurs at the end |
+** of a trigger definition. |
+** |
+** Transitions between states above are determined by tokens extracted |
+** from the input. The following tokens are significant: |
+** |
+** (0) tkSEMI A semicolon. |
+** (1) tkWS Whitespace. |
+** (2) tkOTHER Any other SQL token. |
+** (3) tkEXPLAIN The "explain" keyword. |
+** (4) tkCREATE The "create" keyword. |
+** (5) tkTEMP The "temp" or "temporary" keyword. |
+** (6) tkTRIGGER The "trigger" keyword. |
+** (7) tkEND The "end" keyword. |
+** |
+** Whitespace never causes a state transition and is always ignored. |
+** This means that a SQL string of all whitespace is invalid. |
+** |
+** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed |
+** to recognize the end of a trigger can be omitted. All we have to do |
+** is look for a semicolon that is not part of an string or comment. |
+*/ |
+SQLITE_API int sqlite3_complete(const char *zSql){ |
+ u8 state = 0; /* Current state, using numbers defined in header comment */ |
+ u8 token; /* Value of the next token */ |
+ |
+#ifndef SQLITE_OMIT_TRIGGER |
+ /* A complex statement machine used to detect the end of a CREATE TRIGGER |
+ ** statement. This is the normal case. |
+ */ |
+ static const u8 trans[8][8] = { |
+ /* Token: */ |
+ /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ |
+ /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, }, |
+ /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, }, |
+ /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, }, |
+ /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, }, |
+ /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, }, |
+ /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, }, |
+ /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, }, |
+ /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, }, |
+ }; |
+#else |
+ /* If triggers are not supported by this compile then the statement machine |
+ ** used to detect the end of a statement is much simpler |
+ */ |
+ static const u8 trans[3][3] = { |
+ /* Token: */ |
+ /* State: ** SEMI WS OTHER */ |
+ /* 0 INVALID: */ { 1, 0, 2, }, |
+ /* 1 START: */ { 1, 1, 2, }, |
+ /* 2 NORMAL: */ { 1, 2, 2, }, |
+ }; |
+#endif /* SQLITE_OMIT_TRIGGER */ |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( zSql==0 ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ |
+ while( *zSql ){ |
+ switch( *zSql ){ |
+ case ';': { /* A semicolon */ |
+ token = tkSEMI; |
+ break; |
+ } |
+ case ' ': |
+ case '\r': |
+ case '\t': |
+ case '\n': |
+ case '\f': { /* White space is ignored */ |
+ token = tkWS; |
+ break; |
+ } |
+ case '/': { /* C-style comments */ |
+ if( zSql[1]!='*' ){ |
+ token = tkOTHER; |
+ break; |
+ } |
+ zSql += 2; |
+ while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; } |
+ if( zSql[0]==0 ) return 0; |
+ zSql++; |
+ token = tkWS; |
+ break; |
+ } |
+ case '-': { /* SQL-style comments from "--" to end of line */ |
+ if( zSql[1]!='-' ){ |
+ token = tkOTHER; |
+ break; |
+ } |
+ while( *zSql && *zSql!='\n' ){ zSql++; } |
+ if( *zSql==0 ) return state==1; |
+ token = tkWS; |
+ break; |
+ } |
+ case '[': { /* Microsoft-style identifiers in [...] */ |
+ zSql++; |
+ while( *zSql && *zSql!=']' ){ zSql++; } |
+ if( *zSql==0 ) return 0; |
+ token = tkOTHER; |
+ break; |
+ } |
+ case '`': /* Grave-accent quoted symbols used by MySQL */ |
+ case '"': /* single- and double-quoted strings */ |
+ case '\'': { |
+ int c = *zSql; |
+ zSql++; |
+ while( *zSql && *zSql!=c ){ zSql++; } |
+ if( *zSql==0 ) return 0; |
+ token = tkOTHER; |
+ break; |
+ } |
+ default: { |
+#ifdef SQLITE_EBCDIC |
+ unsigned char c; |
+#endif |
+ if( IdChar((u8)*zSql) ){ |
+ /* Keywords and unquoted identifiers */ |
+ int nId; |
+ for(nId=1; IdChar(zSql[nId]); nId++){} |
+#ifdef SQLITE_OMIT_TRIGGER |
+ token = tkOTHER; |
+#else |
+ switch( *zSql ){ |
+ case 'c': case 'C': { |
+ if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){ |
+ token = tkCREATE; |
+ }else{ |
+ token = tkOTHER; |
+ } |
+ break; |
+ } |
+ case 't': case 'T': { |
+ if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){ |
+ token = tkTRIGGER; |
+ }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){ |
+ token = tkTEMP; |
+ }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){ |
+ token = tkTEMP; |
+ }else{ |
+ token = tkOTHER; |
+ } |
+ break; |
+ } |
+ case 'e': case 'E': { |
+ if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){ |
+ token = tkEND; |
+ }else |
+#ifndef SQLITE_OMIT_EXPLAIN |
+ if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){ |
+ token = tkEXPLAIN; |
+ }else |
+#endif |
+ { |
+ token = tkOTHER; |
+ } |
+ break; |
+ } |
+ default: { |
+ token = tkOTHER; |
+ break; |
+ } |
+ } |
+#endif /* SQLITE_OMIT_TRIGGER */ |
+ zSql += nId-1; |
+ }else{ |
+ /* Operators and special symbols */ |
+ token = tkOTHER; |
+ } |
+ break; |
+ } |
+ } |
+ state = trans[state][token]; |
+ zSql++; |
+ } |
+ return state==1; |
+} |
+ |
+#ifndef SQLITE_OMIT_UTF16 |
+/* |
+** This routine is the same as the sqlite3_complete() routine described |
+** above, except that the parameter is required to be UTF-16 encoded, not |
+** UTF-8. |
+*/ |
+SQLITE_API int sqlite3_complete16(const void *zSql){ |
+ sqlite3_value *pVal; |
+ char const *zSql8; |
+ int rc; |
+ |
+#ifndef SQLITE_OMIT_AUTOINIT |
+ rc = sqlite3_initialize(); |
+ if( rc ) return rc; |
+#endif |
+ pVal = sqlite3ValueNew(0); |
+ sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); |
+ zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); |
+ if( zSql8 ){ |
+ rc = sqlite3_complete(zSql8); |
+ }else{ |
+ rc = SQLITE_NOMEM_BKPT; |
+ } |
+ sqlite3ValueFree(pVal); |
+ return rc & 0xff; |
+} |
+#endif /* SQLITE_OMIT_UTF16 */ |
+#endif /* SQLITE_OMIT_COMPLETE */ |
+ |
+/************** End of complete.c ********************************************/ |
+/************** Begin file main.c ********************************************/ |
+/* |
+** 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. |
+** |
+************************************************************************* |
+** Main file for the SQLite library. The routines in this file |
+** implement the programmer interface to the library. Routines in |
+** other files are for internal use by SQLite and should not be |
+** accessed by users of the library. |
+*/ |
+/* #include "sqliteInt.h" */ |
+ |
+#ifdef SQLITE_ENABLE_FTS3 |
+/************** Include fts3.h in the middle of main.c ***********************/ |
+/************** Begin file fts3.h ********************************************/ |
+/* |
+** 2006 Oct 10 |
+** |
+** 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 header file is used by programs that want to link against the |
+** FTS3 library. All it does is declare the sqlite3Fts3Init() interface. |
+*/ |
+/* #include "sqlite3.h" */ |
+ |
+#if 0 |
+extern "C" { |
+#endif /* __cplusplus */ |
+ |
+SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db); |
+ |
+#if 0 |
+} /* extern "C" */ |
+#endif /* __cplusplus */ |
+ |
+/************** End of fts3.h ************************************************/ |
+/************** Continuing where we left off in main.c ***********************/ |
+#endif |
+#ifdef SQLITE_ENABLE_RTREE |
+/************** Include rtree.h in the middle of main.c **********************/ |
+/************** Begin file rtree.h *******************************************/ |
+/* |
+** 2008 May 26 |
+** |
+** 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 header file is used by programs that want to link against the |
+** RTREE library. All it does is declare the sqlite3RtreeInit() interface. |
+*/ |
+/* #include "sqlite3.h" */ |
+ |
+#if 0 |
+extern "C" { |
+#endif /* __cplusplus */ |
+ |
+SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db); |
+ |
+#if 0 |
+} /* extern "C" */ |
+#endif /* __cplusplus */ |
+ |
+/************** End of rtree.h ***********************************************/ |
+/************** Continuing where we left off in main.c ***********************/ |
+#endif |
+#ifdef SQLITE_ENABLE_ICU |
+/************** Include sqliteicu.h in the middle of main.c ******************/ |
+/************** Begin file sqliteicu.h ***************************************/ |
+/* |
+** 2008 May 26 |
+** |
+** 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 header file is used by programs that want to link against the |
+** ICU extension. All it does is declare the sqlite3IcuInit() interface. |
+*/ |
+/* #include "sqlite3.h" */ |
+ |
+#if 0 |
+extern "C" { |
+#endif /* __cplusplus */ |
+ |
+SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db); |
+ |
+#if 0 |
+} /* extern "C" */ |
+#endif /* __cplusplus */ |
+ |
+ |
+/************** End of sqliteicu.h *******************************************/ |
+/************** Continuing where we left off in main.c ***********************/ |
+#endif |
+#ifdef SQLITE_ENABLE_JSON1 |
+SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*); |
+#endif |
+#ifdef SQLITE_ENABLE_FTS5 |
+SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*); |
+#endif |
+ |
+#ifndef SQLITE_AMALGAMATION |
+/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant |
+** contains the text of SQLITE_VERSION macro. |
+*/ |
+SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; |
+#endif |
+ |
+/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns |
+** a pointer to the to the sqlite3_version[] string constant. |
+*/ |
+SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; } |
+ |
+/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a |
+** pointer to a string constant whose value is the same as the |
+** SQLITE_SOURCE_ID C preprocessor macro. |
+*/ |
+SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } |
+ |
+/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function |
+** returns an integer equal to SQLITE_VERSION_NUMBER. |
+*/ |
+SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; } |
+ |
+/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns |
+** zero if and only if SQLite was compiled with mutexing code omitted due to |
+** the SQLITE_THREADSAFE compile-time option being set to 0. |
+*/ |
+SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } |
+ |
+/* |
+** When compiling the test fixture or with debugging enabled (on Win32), |
+** this variable being set to non-zero will cause OSTRACE macros to emit |
+** extra diagnostic information. |
+*/ |
+#ifdef SQLITE_HAVE_OS_TRACE |
+# ifndef SQLITE_DEBUG_OS_TRACE |
+# define SQLITE_DEBUG_OS_TRACE 0 |
+# endif |
+ int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE; |
+#endif |
+ |
+#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) |
+/* |
+** If the following function pointer is not NULL and if |
+** SQLITE_ENABLE_IOTRACE is enabled, then messages describing |
+** I/O active are written using this function. These messages |
+** are intended for debugging activity only. |
+*/ |
+SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0; |
+#endif |
+ |
+/* |
+** If the following global variable points to a string which is the |
+** name of a directory, then that directory will be used to store |
+** temporary files. |
+** |
+** See also the "PRAGMA temp_store_directory" SQL command. |
+*/ |
+SQLITE_API char *sqlite3_temp_directory = 0; |
+ |
+/* |
+** If the following global variable points to a string which is the |
+** name of a directory, then that directory will be used to store |
+** all database files specified with a relative pathname. |
+** |
+** See also the "PRAGMA data_store_directory" SQL command. |
+*/ |
+SQLITE_API char *sqlite3_data_directory = 0; |
+ |
+/* |
+** Initialize SQLite. |
+** |
+** This routine must be called to initialize the memory allocation, |
+** VFS, and mutex subsystems prior to doing any serious work with |
+** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT |
+** this routine will be called automatically by key routines such as |
+** sqlite3_open(). |
+** |
+** This routine is a no-op except on its very first call for the process, |
+** or for the first call after a call to sqlite3_shutdown. |
+** |
+** The first thread to call this routine runs the initialization to |
+** completion. If subsequent threads call this routine before the first |
+** thread has finished the initialization process, then the subsequent |
+** threads must block until the first thread finishes with the initialization. |
+** |
+** The first thread might call this routine recursively. Recursive |
+** calls to this routine should not block, of course. Otherwise the |
+** initialization process would never complete. |
+** |
+** Let X be the first thread to enter this routine. Let Y be some other |
+** thread. Then while the initial invocation of this routine by X is |
+** incomplete, it is required that: |
+** |
+** * Calls to this routine from Y must block until the outer-most |
+** call by X completes. |
+** |
+** * Recursive calls to this routine from thread X return immediately |
+** without blocking. |
+*/ |
+SQLITE_API int sqlite3_initialize(void){ |
+ MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */ |
+ int rc; /* Result code */ |
+#ifdef SQLITE_EXTRA_INIT |
+ int bRunExtraInit = 0; /* Extra initialization needed */ |
+#endif |
+ |
+#ifdef SQLITE_OMIT_WSD |
+ rc = sqlite3_wsd_init(4096, 24); |
+ if( rc!=SQLITE_OK ){ |
+ return rc; |
+ } |
+#endif |
+ |
+ /* If the following assert() fails on some obscure processor/compiler |
+ ** combination, the work-around is to set the correct pointer |
+ ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */ |
+ assert( SQLITE_PTRSIZE==sizeof(char*) ); |
+ |
+ /* If SQLite is already completely initialized, then this call |
+ ** to sqlite3_initialize() should be a no-op. But the initialization |
+ ** must be complete. So isInit must not be set until the very end |
+ ** of this routine. |
+ */ |
+ if( sqlite3GlobalConfig.isInit ) return SQLITE_OK; |
+ |
+ /* Make sure the mutex subsystem is initialized. If unable to |
+ ** initialize the mutex subsystem, return early with the error. |
+ ** If the system is so sick that we are unable to allocate a mutex, |
+ ** there is not much SQLite is going to be able to do. |
+ ** |
+ ** The mutex subsystem must take care of serializing its own |
+ ** initialization. |
+ */ |
+ rc = sqlite3MutexInit(); |
+ if( rc ) return rc; |
+ |
+ /* Initialize the malloc() system and the recursive pInitMutex mutex. |
+ ** This operation is protected by the STATIC_MASTER mutex. Note that |
+ ** MutexAlloc() is called for a static mutex prior to initializing the |
+ ** malloc subsystem - this implies that the allocation of a static |
+ ** mutex must not require support from the malloc subsystem. |
+ */ |
+ MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) |
+ sqlite3_mutex_enter(pMaster); |
+ sqlite3GlobalConfig.isMutexInit = 1; |
+ if( !sqlite3GlobalConfig.isMallocInit ){ |
+ rc = sqlite3MallocInit(); |
+ } |
+ if( rc==SQLITE_OK ){ |
+ sqlite3GlobalConfig.isMallocInit = 1; |
+ if( !sqlite3GlobalConfig.pInitMutex ){ |
+ sqlite3GlobalConfig.pInitMutex = |
+ sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); |
+ if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){ |
+ rc = SQLITE_NOMEM_BKPT; |
+ } |
+ } |
+ } |
+ if( rc==SQLITE_OK ){ |
+ sqlite3GlobalConfig.nRefInitMutex++; |
+ } |
+ sqlite3_mutex_leave(pMaster); |
+ |
+ /* If rc is not SQLITE_OK at this point, then either the malloc |
+ ** subsystem could not be initialized or the system failed to allocate |
+ ** the pInitMutex mutex. Return an error in either case. */ |
+ if( rc!=SQLITE_OK ){ |
+ return rc; |
+ } |
+ |
+ /* Do the rest of the initialization under the recursive mutex so |
+ ** that we will be able to handle recursive calls into |
+ ** sqlite3_initialize(). The recursive calls normally come through |
+ ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other |
+ ** recursive calls might also be possible. |
+ ** |
+ ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls |
+ ** to the xInit method, so the xInit method need not be threadsafe. |
+ ** |
+ ** The following mutex is what serializes access to the appdef pcache xInit |
+ ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the |
+ ** call to sqlite3PcacheInitialize(). |
+ */ |
+ sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex); |
+ if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){ |
+ sqlite3GlobalConfig.inProgress = 1; |
+#ifdef SQLITE_ENABLE_SQLLOG |
+ { |
+ extern void sqlite3_init_sqllog(void); |
+ sqlite3_init_sqllog(); |
+ } |
+#endif |
+ memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions)); |
+ sqlite3RegisterBuiltinFunctions(); |
+ if( sqlite3GlobalConfig.isPCacheInit==0 ){ |
+ rc = sqlite3PcacheInitialize(); |
+ } |
+ if( rc==SQLITE_OK ){ |
+ sqlite3GlobalConfig.isPCacheInit = 1; |
+ rc = sqlite3OsInit(); |
+ } |
+ if( rc==SQLITE_OK ){ |
+ sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, |
+ sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); |
+ sqlite3GlobalConfig.isInit = 1; |
+#ifdef SQLITE_EXTRA_INIT |
+ bRunExtraInit = 1; |
+#endif |
+ } |
+ sqlite3GlobalConfig.inProgress = 0; |
+ } |
+ sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex); |
+ |
+ /* Go back under the static mutex and clean up the recursive |
+ ** mutex to prevent a resource leak. |
+ */ |
+ sqlite3_mutex_enter(pMaster); |
+ sqlite3GlobalConfig.nRefInitMutex--; |
+ if( sqlite3GlobalConfig.nRefInitMutex<=0 ){ |
+ assert( sqlite3GlobalConfig.nRefInitMutex==0 ); |
+ sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex); |
+ sqlite3GlobalConfig.pInitMutex = 0; |
+ } |
+ sqlite3_mutex_leave(pMaster); |
+ |
+ /* The following is just a sanity check to make sure SQLite has |
+ ** been compiled correctly. It is important to run this code, but |
+ ** we don't want to run it too often and soak up CPU cycles for no |
+ ** reason. So we run it once during initialization. |
+ */ |
+#ifndef NDEBUG |
+#ifndef SQLITE_OMIT_FLOATING_POINT |
+ /* This section of code's only "output" is via assert() statements. */ |
+ if ( rc==SQLITE_OK ){ |
+ u64 x = (((u64)1)<<63)-1; |
+ double y; |
+ assert(sizeof(x)==8); |
+ assert(sizeof(x)==sizeof(y)); |
+ memcpy(&y, &x, 8); |
+ assert( sqlite3IsNaN(y) ); |
+ } |
+#endif |
+#endif |
+ |
+ /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT |
+ ** compile-time option. |
+ */ |
+#ifdef SQLITE_EXTRA_INIT |
+ if( bRunExtraInit ){ |
+ int SQLITE_EXTRA_INIT(const char*); |
+ rc = SQLITE_EXTRA_INIT(0); |
+ } |
+#endif |
+ |
+ return rc; |
+} |
+ |
+/* |
+** Undo the effects of sqlite3_initialize(). Must not be called while |
+** there are outstanding database connections or memory allocations or |
+** while any part of SQLite is otherwise in use in any thread. This |
+** routine is not threadsafe. But it is safe to invoke this routine |
+** on when SQLite is already shut down. If SQLite is already shut down |
+** when this routine is invoked, then this routine is a harmless no-op. |
+*/ |
+SQLITE_API int sqlite3_shutdown(void){ |
+#ifdef SQLITE_OMIT_WSD |
+ int rc = sqlite3_wsd_init(4096, 24); |
+ if( rc!=SQLITE_OK ){ |
+ return rc; |
+ } |
+#endif |
+ |
+ if( sqlite3GlobalConfig.isInit ){ |
+#ifdef SQLITE_EXTRA_SHUTDOWN |
+ void SQLITE_EXTRA_SHUTDOWN(void); |
+ SQLITE_EXTRA_SHUTDOWN(); |
+#endif |
+ sqlite3_os_end(); |
+ sqlite3_reset_auto_extension(); |
+ sqlite3GlobalConfig.isInit = 0; |
+ } |
+ if( sqlite3GlobalConfig.isPCacheInit ){ |
+ sqlite3PcacheShutdown(); |
+ sqlite3GlobalConfig.isPCacheInit = 0; |
+ } |
+ if( sqlite3GlobalConfig.isMallocInit ){ |
+ sqlite3MallocEnd(); |
+ sqlite3GlobalConfig.isMallocInit = 0; |
+ |
+#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES |
+ /* The heap subsystem has now been shutdown and these values are supposed |
+ ** to be NULL or point to memory that was obtained from sqlite3_malloc(), |
+ ** which would rely on that heap subsystem; therefore, make sure these |
+ ** values cannot refer to heap memory that was just invalidated when the |
+ ** heap subsystem was shutdown. This is only done if the current call to |
+ ** this function resulted in the heap subsystem actually being shutdown. |
+ */ |
+ sqlite3_data_directory = 0; |
+ sqlite3_temp_directory = 0; |
+#endif |
+ } |
+ if( sqlite3GlobalConfig.isMutexInit ){ |
+ sqlite3MutexEnd(); |
+ sqlite3GlobalConfig.isMutexInit = 0; |
+ } |
+ |
+ return SQLITE_OK; |
+} |
+ |
+/* |
+** This API allows applications to modify the global configuration of |
+** the SQLite library at run-time. |
+** |
+** This routine should only be called when there are no outstanding |
+** database connections or memory allocations. This routine is not |
+** threadsafe. Failure to heed these warnings can lead to unpredictable |
+** behavior. |
+*/ |
+SQLITE_API int sqlite3_config(int op, ...){ |
+ va_list ap; |
+ int rc = SQLITE_OK; |
+ |
+ /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while |
+ ** the SQLite library is in use. */ |
+ if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT; |
+ |
+ va_start(ap, op); |
+ switch( op ){ |
+ |
+ /* Mutex configuration options are only available in a threadsafe |
+ ** compile. |
+ */ |
+#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */ |
+ case SQLITE_CONFIG_SINGLETHREAD: { |
+ /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to |
+ ** Single-thread. */ |
+ sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */ |
+ sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ |
+ break; |
+ } |
+#endif |
+#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */ |
+ case SQLITE_CONFIG_MULTITHREAD: { |
+ /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to |
+ ** Multi-thread. */ |
+ sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ |
+ sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ |
+ break; |
+ } |
+#endif |
+#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */ |
+ case SQLITE_CONFIG_SERIALIZED: { |
+ /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to |
+ ** Serialized. */ |
+ sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ |
+ sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */ |
+ break; |
+ } |
+#endif |
+#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */ |
+ case SQLITE_CONFIG_MUTEX: { |
+ /* Specify an alternative mutex implementation */ |
+ sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*); |
+ break; |
+ } |
+#endif |
+#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */ |
+ case SQLITE_CONFIG_GETMUTEX: { |
+ /* Retrieve the current mutex implementation */ |
+ *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; |
+ break; |
+ } |
+#endif |
+ |
+ case SQLITE_CONFIG_MALLOC: { |
+ /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a |
+ ** single argument which is a pointer to an instance of the |
+ ** sqlite3_mem_methods structure. The argument specifies alternative |
+ ** low-level memory allocation routines to be used in place of the memory |
+ ** allocation routines built into SQLite. */ |
+ sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*); |
+ break; |
+ } |
+ case SQLITE_CONFIG_GETMALLOC: { |
+ /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a |
+ ** single argument which is a pointer to an instance of the |
+ ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is |
+ ** filled with the currently defined memory allocation routines. */ |
+ if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault(); |
+ *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; |
+ break; |
+ } |
+ case SQLITE_CONFIG_MEMSTATUS: { |
+ /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes |
+ ** single argument of type int, interpreted as a boolean, which enables |
+ ** or disables the collection of memory allocation statistics. */ |
+ sqlite3GlobalConfig.bMemstat = va_arg(ap, int); |
+ break; |
+ } |
+ case SQLITE_CONFIG_SCRATCH: { |
+ /* EVIDENCE-OF: R-08404-60887 There are three arguments to |
+ ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from |
+ ** which the scratch allocations will be drawn, the size of each scratch |
+ ** allocation (sz), and the maximum number of scratch allocations (N). */ |
+ sqlite3GlobalConfig.pScratch = va_arg(ap, void*); |
+ sqlite3GlobalConfig.szScratch = va_arg(ap, int); |
+ sqlite3GlobalConfig.nScratch = va_arg(ap, int); |
+ break; |
+ } |
+ case SQLITE_CONFIG_PAGECACHE: { |
+ /* EVIDENCE-OF: R-18761-36601 There are three arguments to |
+ ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem), |
+ ** the size of each page cache line (sz), and the number of cache lines |
+ ** (N). */ |
+ sqlite3GlobalConfig.pPage = va_arg(ap, void*); |
+ sqlite3GlobalConfig.szPage = va_arg(ap, int); |
+ sqlite3GlobalConfig.nPage = va_arg(ap, int); |
+ break; |
+ } |
+ case SQLITE_CONFIG_PCACHE_HDRSZ: { |
+ /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes |
+ ** a single parameter which is a pointer to an integer and writes into |
+ ** that integer the number of extra bytes per page required for each page |
+ ** in SQLITE_CONFIG_PAGECACHE. */ |
+ *va_arg(ap, int*) = |
+ sqlite3HeaderSizeBtree() + |
+ sqlite3HeaderSizePcache() + |
+ sqlite3HeaderSizePcache1(); |
+ break; |
+ } |
+ |
+ case SQLITE_CONFIG_PCACHE: { |
+ /* no-op */ |
+ break; |
+ } |
+ case SQLITE_CONFIG_GETPCACHE: { |
+ /* now an error */ |
+ rc = SQLITE_ERROR; |
+ break; |
+ } |
+ |
+ case SQLITE_CONFIG_PCACHE2: { |
+ /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a |
+ ** single argument which is a pointer to an sqlite3_pcache_methods2 |
+ ** object. This object specifies the interface to a custom page cache |
+ ** implementation. */ |
+ sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*); |
+ break; |
+ } |
+ case SQLITE_CONFIG_GETPCACHE2: { |
+ /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a |
+ ** single argument which is a pointer to an sqlite3_pcache_methods2 |
+ ** object. SQLite copies of the current page cache implementation into |
+ ** that object. */ |
+ if( sqlite3GlobalConfig.pcache2.xInit==0 ){ |
+ sqlite3PCacheSetDefault(); |
+ } |
+ *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2; |
+ break; |
+ } |
+ |
+/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only |
+** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or |
+** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */ |
+#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) |
+ case SQLITE_CONFIG_HEAP: { |
+ /* EVIDENCE-OF: R-19854-42126 There are three arguments to |
+ ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the |
+ ** number of bytes in the memory buffer, and the minimum allocation size. |
+ */ |
+ sqlite3GlobalConfig.pHeap = va_arg(ap, void*); |
+ sqlite3GlobalConfig.nHeap = va_arg(ap, int); |
+ sqlite3GlobalConfig.mnReq = va_arg(ap, int); |
+ |
+ if( sqlite3GlobalConfig.mnReq<1 ){ |
+ sqlite3GlobalConfig.mnReq = 1; |
+ }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){ |
+ /* cap min request size at 2^12 */ |
+ sqlite3GlobalConfig.mnReq = (1<<12); |
+ } |
+ |
+ if( sqlite3GlobalConfig.pHeap==0 ){ |
+ /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer) |
+ ** is NULL, then SQLite reverts to using its default memory allocator |
+ ** (the system malloc() implementation), undoing any prior invocation of |
+ ** SQLITE_CONFIG_MALLOC. |
+ ** |
+ ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to |
+ ** revert to its default implementation when sqlite3_initialize() is run |
+ */ |
+ memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m)); |
+ }else{ |
+ /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the |
+ ** alternative memory allocator is engaged to handle all of SQLites |
+ ** memory allocation needs. */ |
+#ifdef SQLITE_ENABLE_MEMSYS3 |
+ sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3(); |
+#endif |
+#ifdef SQLITE_ENABLE_MEMSYS5 |
+ sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5(); |
+#endif |
+ } |
+ break; |
+ } |
+#endif |
+ |
+ case SQLITE_CONFIG_LOOKASIDE: { |
+ sqlite3GlobalConfig.szLookaside = va_arg(ap, int); |
+ sqlite3GlobalConfig.nLookaside = va_arg(ap, int); |
+ break; |
+ } |
+ |
+ /* Record a pointer to the logger function and its first argument. |
+ ** The default is NULL. Logging is disabled if the function pointer is |
+ ** NULL. |
+ */ |
+ case SQLITE_CONFIG_LOG: { |
+ /* MSVC is picky about pulling func ptrs from va lists. |
+ ** http://support.microsoft.com/kb/47961 |
+ ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*)); |
+ */ |
+ typedef void(*LOGFUNC_t)(void*,int,const char*); |
+ sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t); |
+ sqlite3GlobalConfig.pLogArg = va_arg(ap, void*); |
+ break; |
+ } |
+ |
+ /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames |
+ ** can be changed at start-time using the |
+ ** sqlite3_config(SQLITE_CONFIG_URI,1) or |
+ ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls. |
+ */ |
+ case SQLITE_CONFIG_URI: { |
+ /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single |
+ ** argument of type int. If non-zero, then URI handling is globally |
+ ** enabled. If the parameter is zero, then URI handling is globally |
+ ** disabled. */ |
+ sqlite3GlobalConfig.bOpenUri = va_arg(ap, int); |
+ break; |
+ } |
+ |
+ case SQLITE_CONFIG_COVERING_INDEX_SCAN: { |
+ /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN |
+ ** option takes a single integer argument which is interpreted as a |
+ ** boolean in order to enable or disable the use of covering indices for |
+ ** full table scans in the query optimizer. */ |
+ sqlite3GlobalConfig.bUseCis = va_arg(ap, int); |
+ break; |
+ } |
+ |
+#ifdef SQLITE_ENABLE_SQLLOG |
+ case SQLITE_CONFIG_SQLLOG: { |
+ typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int); |
+ sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t); |
+ sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *); |
+ break; |
+ } |
+#endif |
+ |
+ case SQLITE_CONFIG_MMAP_SIZE: { |
+ /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit |
+ ** integer (sqlite3_int64) values that are the default mmap size limit |
+ ** (the default setting for PRAGMA mmap_size) and the maximum allowed |
+ ** mmap size limit. */ |
+ sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64); |
+ sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64); |
+ /* EVIDENCE-OF: R-53367-43190 If either argument to this option is |
+ ** negative, then that argument is changed to its compile-time default. |
+ ** |
+ ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be |
+ ** silently truncated if necessary so that it does not exceed the |
+ ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE |
+ ** compile-time option. |
+ */ |
+ if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){ |
+ mxMmap = SQLITE_MAX_MMAP_SIZE; |
+ } |
+ if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE; |
+ if( szMmap>mxMmap) szMmap = mxMmap; |
+ sqlite3GlobalConfig.mxMmap = mxMmap; |
+ sqlite3GlobalConfig.szMmap = szMmap; |
+ break; |
+ } |
+ |
+#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */ |
+ case SQLITE_CONFIG_WIN32_HEAPSIZE: { |
+ /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit |
+ ** unsigned integer value that specifies the maximum size of the created |
+ ** heap. */ |
+ sqlite3GlobalConfig.nHeap = va_arg(ap, int); |
+ break; |
+ } |
+#endif |
+ |
+ case SQLITE_CONFIG_PMASZ: { |
+ sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int); |
+ break; |
+ } |
+ |
+ case SQLITE_CONFIG_STMTJRNL_SPILL: { |
+ sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int); |
+ break; |
+ } |
+ |
+ default: { |
+ rc = SQLITE_ERROR; |
+ break; |
+ } |
+ } |
+ va_end(ap); |
+ return rc; |
+} |
+ |
+/* |
+** Set up the lookaside buffers for a database connection. |
+** Return SQLITE_OK on success. |
+** If lookaside is already active, return SQLITE_BUSY. |
+** |
+** The sz parameter is the number of bytes in each lookaside slot. |
+** The cnt parameter is the number of slots. If pStart is NULL the |
+** space for the lookaside memory is obtained from sqlite3_malloc(). |
+** If pStart is not NULL then it is sz*cnt bytes of memory to use for |
+** the lookaside memory. |
+*/ |
+static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ |
+#ifndef SQLITE_OMIT_LOOKASIDE |
+ void *pStart; |
+ if( db->lookaside.nOut ){ |
+ return SQLITE_BUSY; |
+ } |
+ /* Free any existing lookaside buffer for this handle before |
+ ** allocating a new one so we don't have to have space for |
+ ** both at the same time. |
+ */ |
+ if( db->lookaside.bMalloced ){ |
+ sqlite3_free(db->lookaside.pStart); |
+ } |
+ /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger |
+ ** than a pointer to be useful. |
+ */ |
+ sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */ |
+ if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0; |
+ if( cnt<0 ) cnt = 0; |
+ if( sz==0 || cnt==0 ){ |
+ sz = 0; |
+ pStart = 0; |
+ }else if( pBuf==0 ){ |
+ sqlite3BeginBenignMalloc(); |
+ pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */ |
+ sqlite3EndBenignMalloc(); |
+ if( pStart ) cnt = sqlite3MallocSize(pStart)/sz; |
+ }else{ |
+ pStart = pBuf; |
+ } |
+ db->lookaside.pStart = pStart; |
+ db->lookaside.pFree = 0; |
+ db->lookaside.sz = (u16)sz; |
+ if( pStart ){ |
+ int i; |
+ LookasideSlot *p; |
+ assert( sz > (int)sizeof(LookasideSlot*) ); |
+ p = (LookasideSlot*)pStart; |
+ for(i=cnt-1; i>=0; i--){ |
+ p->pNext = db->lookaside.pFree; |
+ db->lookaside.pFree = p; |
+ p = (LookasideSlot*)&((u8*)p)[sz]; |
+ } |
+ db->lookaside.pEnd = p; |
+ db->lookaside.bDisable = 0; |
+ db->lookaside.bMalloced = pBuf==0 ?1:0; |
+ }else{ |
+ db->lookaside.pStart = db; |
+ db->lookaside.pEnd = db; |
+ db->lookaside.bDisable = 1; |
+ db->lookaside.bMalloced = 0; |
+ } |
+#endif /* SQLITE_OMIT_LOOKASIDE */ |
+ return SQLITE_OK; |
+} |
+ |
+/* |
+** Return the mutex associated with a database connection. |
+*/ |
+SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ return db->mutex; |
+} |
+ |
+/* |
+** Free up as much memory as we can from the given database |
+** connection. |
+*/ |
+SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){ |
+ int i; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ sqlite3BtreeEnterAll(db); |
+ for(i=0; i<db->nDb; i++){ |
+ Btree *pBt = db->aDb[i].pBt; |
+ if( pBt ){ |
+ Pager *pPager = sqlite3BtreePager(pBt); |
+ sqlite3PagerShrink(pPager); |
+ } |
+ } |
+ sqlite3BtreeLeaveAll(db); |
+ sqlite3_mutex_leave(db->mutex); |
+ return SQLITE_OK; |
+} |
+ |
+/* |
+** Flush any dirty pages in the pager-cache for any attached database |
+** to disk. |
+*/ |
+SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){ |
+ int i; |
+ int rc = SQLITE_OK; |
+ int bSeenBusy = 0; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ sqlite3BtreeEnterAll(db); |
+ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ |
+ Btree *pBt = db->aDb[i].pBt; |
+ if( pBt && sqlite3BtreeIsInTrans(pBt) ){ |
+ Pager *pPager = sqlite3BtreePager(pBt); |
+ rc = sqlite3PagerFlush(pPager); |
+ if( rc==SQLITE_BUSY ){ |
+ bSeenBusy = 1; |
+ rc = SQLITE_OK; |
+ } |
+ } |
+ } |
+ sqlite3BtreeLeaveAll(db); |
+ sqlite3_mutex_leave(db->mutex); |
+ return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc); |
+} |
+ |
+/* |
+** Configuration settings for an individual database connection |
+*/ |
+SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){ |
+ va_list ap; |
+ int rc; |
+ va_start(ap, op); |
+ switch( op ){ |
+ case SQLITE_DBCONFIG_MAINDBNAME: { |
+ db->aDb[0].zDbSName = va_arg(ap,char*); |
+ rc = SQLITE_OK; |
+ break; |
+ } |
+ case SQLITE_DBCONFIG_LOOKASIDE: { |
+ void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */ |
+ int sz = va_arg(ap, int); /* IMP: R-47871-25994 */ |
+ int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */ |
+ rc = setupLookaside(db, pBuf, sz, cnt); |
+ break; |
+ } |
+ default: { |
+ static const struct { |
+ int op; /* The opcode */ |
+ u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */ |
+ } aFlagOp[] = { |
+ { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys }, |
+ { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger }, |
+ { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer }, |
+ { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension }, |
+ { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose }, |
+ }; |
+ unsigned int i; |
+ rc = SQLITE_ERROR; /* IMP: R-42790-23372 */ |
+ for(i=0; i<ArraySize(aFlagOp); i++){ |
+ if( aFlagOp[i].op==op ){ |
+ int onoff = va_arg(ap, int); |
+ int *pRes = va_arg(ap, int*); |
+ int oldFlags = db->flags; |
+ if( onoff>0 ){ |
+ db->flags |= aFlagOp[i].mask; |
+ }else if( onoff==0 ){ |
+ db->flags &= ~aFlagOp[i].mask; |
+ } |
+ if( oldFlags!=db->flags ){ |
+ sqlite3ExpirePreparedStatements(db); |
+ } |
+ if( pRes ){ |
+ *pRes = (db->flags & aFlagOp[i].mask)!=0; |
+ } |
+ rc = SQLITE_OK; |
+ break; |
+ } |
+ } |
+ break; |
+ } |
+ } |
+ va_end(ap); |
+ return rc; |
+} |
+ |
+ |
+/* |
+** Return true if the buffer z[0..n-1] contains all spaces. |
+*/ |
+static int allSpaces(const char *z, int n){ |
+ while( n>0 && z[n-1]==' ' ){ n--; } |
+ return n==0; |
+} |
+ |
+/* |
+** This is the default collating function named "BINARY" which is always |
+** available. |
+** |
+** If the padFlag argument is not NULL then space padding at the end |
+** of strings is ignored. This implements the RTRIM collation. |
+*/ |
+static int binCollFunc( |
+ void *padFlag, |
+ int nKey1, const void *pKey1, |
+ int nKey2, const void *pKey2 |
+){ |
+ int rc, n; |
+ n = nKey1<nKey2 ? nKey1 : nKey2; |
+ /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares |
+ ** strings byte by byte using the memcmp() function from the standard C |
+ ** library. */ |
+ rc = memcmp(pKey1, pKey2, n); |
+ if( rc==0 ){ |
+ if( padFlag |
+ && allSpaces(((char*)pKey1)+n, nKey1-n) |
+ && allSpaces(((char*)pKey2)+n, nKey2-n) |
+ ){ |
+ /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra |
+ ** spaces at the end of either string do not change the result. In other |
+ ** words, strings will compare equal to one another as long as they |
+ ** differ only in the number of spaces at the end. |
+ */ |
+ }else{ |
+ rc = nKey1 - nKey2; |
+ } |
+ } |
+ return rc; |
+} |
+ |
+/* |
+** Another built-in collating sequence: NOCASE. |
+** |
+** This collating sequence is intended to be used for "case independent |
+** comparison". SQLite's knowledge of upper and lower case equivalents |
+** extends only to the 26 characters used in the English language. |
+** |
+** At the moment there is only a UTF-8 implementation. |
+*/ |
+static int nocaseCollatingFunc( |
+ void *NotUsed, |
+ int nKey1, const void *pKey1, |
+ int nKey2, const void *pKey2 |
+){ |
+ int r = sqlite3StrNICmp( |
+ (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2); |
+ UNUSED_PARAMETER(NotUsed); |
+ if( 0==r ){ |
+ r = nKey1-nKey2; |
+ } |
+ return r; |
+} |
+ |
+/* |
+** Return the ROWID of the most recent insert |
+*/ |
+SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ return db->lastRowid; |
+} |
+ |
+/* |
+** Return the number of changes in the most recent call to sqlite3_exec(). |
+*/ |
+SQLITE_API int sqlite3_changes(sqlite3 *db){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ return db->nChange; |
+} |
+ |
+/* |
+** Return the number of changes since the database handle was opened. |
+*/ |
+SQLITE_API int sqlite3_total_changes(sqlite3 *db){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ return db->nTotalChange; |
+} |
+ |
+/* |
+** Close all open savepoints. This function only manipulates fields of the |
+** database handle object, it does not close any savepoints that may be open |
+** at the b-tree/pager level. |
+*/ |
+SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){ |
+ while( db->pSavepoint ){ |
+ Savepoint *pTmp = db->pSavepoint; |
+ db->pSavepoint = pTmp->pNext; |
+ sqlite3DbFree(db, pTmp); |
+ } |
+ db->nSavepoint = 0; |
+ db->nStatement = 0; |
+ db->isTransactionSavepoint = 0; |
+} |
+ |
+/* |
+** Invoke the destructor function associated with FuncDef p, if any. Except, |
+** if this is not the last copy of the function, do not invoke it. Multiple |
+** copies of a single function are created when create_function() is called |
+** with SQLITE_ANY as the encoding. |
+*/ |
+static void functionDestroy(sqlite3 *db, FuncDef *p){ |
+ FuncDestructor *pDestructor = p->u.pDestructor; |
+ if( pDestructor ){ |
+ pDestructor->nRef--; |
+ if( pDestructor->nRef==0 ){ |
+ pDestructor->xDestroy(pDestructor->pUserData); |
+ sqlite3DbFree(db, pDestructor); |
+ } |
+ } |
+} |
+ |
+/* |
+** Disconnect all sqlite3_vtab objects that belong to database connection |
+** db. This is called when db is being closed. |
+*/ |
+static void disconnectAllVtab(sqlite3 *db){ |
+#ifndef SQLITE_OMIT_VIRTUALTABLE |
+ int i; |
+ HashElem *p; |
+ sqlite3BtreeEnterAll(db); |
+ for(i=0; i<db->nDb; i++){ |
+ Schema *pSchema = db->aDb[i].pSchema; |
+ if( db->aDb[i].pSchema ){ |
+ for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ |
+ Table *pTab = (Table *)sqliteHashData(p); |
+ if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab); |
+ } |
+ } |
+ } |
+ for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){ |
+ Module *pMod = (Module *)sqliteHashData(p); |
+ if( pMod->pEpoTab ){ |
+ sqlite3VtabDisconnect(db, pMod->pEpoTab); |
+ } |
+ } |
+ sqlite3VtabUnlockList(db); |
+ sqlite3BtreeLeaveAll(db); |
+#else |
+ UNUSED_PARAMETER(db); |
+#endif |
+} |
+ |
+/* |
+** Return TRUE if database connection db has unfinalized prepared |
+** statements or unfinished sqlite3_backup objects. |
+*/ |
+static int connectionIsBusy(sqlite3 *db){ |
+ int j; |
+ assert( sqlite3_mutex_held(db->mutex) ); |
+ if( db->pVdbe ) return 1; |
+ for(j=0; j<db->nDb; j++){ |
+ Btree *pBt = db->aDb[j].pBt; |
+ if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1; |
+ } |
+ return 0; |
+} |
+ |
+/* |
+** Close an existing SQLite database |
+*/ |
+static int sqlite3Close(sqlite3 *db, int forceZombie){ |
+ if( !db ){ |
+ /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or |
+ ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */ |
+ return SQLITE_OK; |
+ } |
+ if( !sqlite3SafetyCheckSickOrOk(db) ){ |
+ return SQLITE_MISUSE_BKPT; |
+ } |
+ sqlite3_mutex_enter(db->mutex); |
+ if( db->mTrace & SQLITE_TRACE_CLOSE ){ |
+ db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0); |
+ } |
+ |
+ /* Force xDisconnect calls on all virtual tables */ |
+ disconnectAllVtab(db); |
+ |
+ /* If a transaction is open, the disconnectAllVtab() call above |
+ ** will not have called the xDisconnect() method on any virtual |
+ ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback() |
+ ** call will do so. We need to do this before the check for active |
+ ** SQL statements below, as the v-table implementation may be storing |
+ ** some prepared statements internally. |
+ */ |
+ sqlite3VtabRollback(db); |
+ |
+ /* Legacy behavior (sqlite3_close() behavior) is to return |
+ ** SQLITE_BUSY if the connection can not be closed immediately. |
+ */ |
+ if( !forceZombie && connectionIsBusy(db) ){ |
+ sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized " |
+ "statements or unfinished backups"); |
+ sqlite3_mutex_leave(db->mutex); |
+ return SQLITE_BUSY; |
+ } |
+ |
+#ifdef SQLITE_ENABLE_SQLLOG |
+ if( sqlite3GlobalConfig.xSqllog ){ |
+ /* Closing the handle. Fourth parameter is passed the value 2. */ |
+ sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2); |
+ } |
+#endif |
+ |
+ /* Convert the connection into a zombie and then close it. |
+ */ |
+ db->magic = SQLITE_MAGIC_ZOMBIE; |
+ sqlite3LeaveMutexAndCloseZombie(db); |
+ return SQLITE_OK; |
+} |
+ |
+/* |
+** Two variations on the public interface for closing a database |
+** connection. The sqlite3_close() version returns SQLITE_BUSY and |
+** leaves the connection option if there are unfinalized prepared |
+** statements or unfinished sqlite3_backups. The sqlite3_close_v2() |
+** version forces the connection to become a zombie if there are |
+** unclosed resources, and arranges for deallocation when the last |
+** prepare statement or sqlite3_backup closes. |
+*/ |
+SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); } |
+SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); } |
+ |
+ |
+/* |
+** Close the mutex on database connection db. |
+** |
+** Furthermore, if database connection db is a zombie (meaning that there |
+** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and |
+** every sqlite3_stmt has now been finalized and every sqlite3_backup has |
+** finished, then free all resources. |
+*/ |
+SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ |
+ HashElem *i; /* Hash table iterator */ |
+ int j; |
+ |
+ /* If there are outstanding sqlite3_stmt or sqlite3_backup objects |
+ ** or if the connection has not yet been closed by sqlite3_close_v2(), |
+ ** then just leave the mutex and return. |
+ */ |
+ if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){ |
+ sqlite3_mutex_leave(db->mutex); |
+ return; |
+ } |
+ |
+ /* If we reach this point, it means that the database connection has |
+ ** closed all sqlite3_stmt and sqlite3_backup objects and has been |
+ ** passed to sqlite3_close (meaning that it is a zombie). Therefore, |
+ ** go ahead and free all resources. |
+ */ |
+ |
+ /* If a transaction is open, roll it back. This also ensures that if |
+ ** any database schemas have been modified by an uncommitted transaction |
+ ** they are reset. And that the required b-tree mutex is held to make |
+ ** the pager rollback and schema reset an atomic operation. */ |
+ sqlite3RollbackAll(db, SQLITE_OK); |
+ |
+ /* Free any outstanding Savepoint structures. */ |
+ sqlite3CloseSavepoints(db); |
+ |
+ /* Close all database connections */ |
+ for(j=0; j<db->nDb; j++){ |
+ struct Db *pDb = &db->aDb[j]; |
+ if( pDb->pBt ){ |
+ sqlite3BtreeClose(pDb->pBt); |
+ pDb->pBt = 0; |
+ if( j!=1 ){ |
+ pDb->pSchema = 0; |
+ } |
+ } |
+ } |
+ /* Clear the TEMP schema separately and last */ |
+ if( db->aDb[1].pSchema ){ |
+ sqlite3SchemaClear(db->aDb[1].pSchema); |
+ } |
+ sqlite3VtabUnlockList(db); |
+ |
+ /* Free up the array of auxiliary databases */ |
+ sqlite3CollapseDatabaseArray(db); |
+ assert( db->nDb<=2 ); |
+ assert( db->aDb==db->aDbStatic ); |
+ |
+ /* Tell the code in notify.c that the connection no longer holds any |
+ ** locks and does not require any further unlock-notify callbacks. |
+ */ |
+ sqlite3ConnectionClosed(db); |
+ |
+ for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){ |
+ FuncDef *pNext, *p; |
+ p = sqliteHashData(i); |
+ do{ |
+ functionDestroy(db, p); |
+ pNext = p->pNext; |
+ sqlite3DbFree(db, p); |
+ p = pNext; |
+ }while( p ); |
+ } |
+ sqlite3HashClear(&db->aFunc); |
+ for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){ |
+ CollSeq *pColl = (CollSeq *)sqliteHashData(i); |
+ /* Invoke any destructors registered for collation sequence user data. */ |
+ for(j=0; j<3; j++){ |
+ if( pColl[j].xDel ){ |
+ pColl[j].xDel(pColl[j].pUser); |
+ } |
+ } |
+ sqlite3DbFree(db, pColl); |
+ } |
+ sqlite3HashClear(&db->aCollSeq); |
+#ifndef SQLITE_OMIT_VIRTUALTABLE |
+ for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){ |
+ Module *pMod = (Module *)sqliteHashData(i); |
+ if( pMod->xDestroy ){ |
+ pMod->xDestroy(pMod->pAux); |
+ } |
+ sqlite3VtabEponymousTableClear(db, pMod); |
+ sqlite3DbFree(db, pMod); |
+ } |
+ sqlite3HashClear(&db->aModule); |
+#endif |
+ |
+ sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */ |
+ sqlite3ValueFree(db->pErr); |
+ sqlite3CloseExtensions(db); |
+#if SQLITE_USER_AUTHENTICATION |
+ sqlite3_free(db->auth.zAuthUser); |
+ sqlite3_free(db->auth.zAuthPW); |
+#endif |
+ |
+ db->magic = SQLITE_MAGIC_ERROR; |
+ |
+ /* The temp-database schema is allocated differently from the other schema |
+ ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). |
+ ** So it needs to be freed here. Todo: Why not roll the temp schema into |
+ ** the same sqliteMalloc() as the one that allocates the database |
+ ** structure? |
+ */ |
+ sqlite3DbFree(db, db->aDb[1].pSchema); |
+ sqlite3_mutex_leave(db->mutex); |
+ db->magic = SQLITE_MAGIC_CLOSED; |
+ sqlite3_mutex_free(db->mutex); |
+ assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */ |
+ if( db->lookaside.bMalloced ){ |
+ sqlite3_free(db->lookaside.pStart); |
+ } |
+ sqlite3_free(db); |
+} |
+ |
+/* |
+** Rollback all database files. If tripCode is not SQLITE_OK, then |
+** any write cursors are invalidated ("tripped" - as in "tripping a circuit |
+** breaker") and made to return tripCode if there are any further |
+** attempts to use that cursor. Read cursors remain open and valid |
+** but are "saved" in case the table pages are moved around. |
+*/ |
+SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){ |
+ int i; |
+ int inTrans = 0; |
+ int schemaChange; |
+ assert( sqlite3_mutex_held(db->mutex) ); |
+ sqlite3BeginBenignMalloc(); |
+ |
+ /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). |
+ ** This is important in case the transaction being rolled back has |
+ ** modified the database schema. If the b-tree mutexes are not taken |
+ ** here, then another shared-cache connection might sneak in between |
+ ** the database rollback and schema reset, which can cause false |
+ ** corruption reports in some cases. */ |
+ sqlite3BtreeEnterAll(db); |
+ schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0; |
+ |
+ for(i=0; i<db->nDb; i++){ |
+ Btree *p = db->aDb[i].pBt; |
+ if( p ){ |
+ if( sqlite3BtreeIsInTrans(p) ){ |
+ inTrans = 1; |
+ } |
+ sqlite3BtreeRollback(p, tripCode, !schemaChange); |
+ } |
+ } |
+ sqlite3VtabRollback(db); |
+ sqlite3EndBenignMalloc(); |
+ |
+ if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){ |
+ sqlite3ExpirePreparedStatements(db); |
+ sqlite3ResetAllSchemasOfConnection(db); |
+ } |
+ sqlite3BtreeLeaveAll(db); |
+ |
+ /* Any deferred constraint violations have now been resolved. */ |
+ db->nDeferredCons = 0; |
+ db->nDeferredImmCons = 0; |
+ db->flags &= ~SQLITE_DeferFKs; |
+ |
+ /* If one has been configured, invoke the rollback-hook callback */ |
+ if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){ |
+ db->xRollbackCallback(db->pRollbackArg); |
+ } |
+} |
+ |
+/* |
+** Return a static string containing the name corresponding to the error code |
+** specified in the argument. |
+*/ |
+#if defined(SQLITE_NEED_ERR_NAME) |
+SQLITE_PRIVATE const char *sqlite3ErrName(int rc){ |
+ const char *zName = 0; |
+ int i, origRc = rc; |
+ for(i=0; i<2 && zName==0; i++, rc &= 0xff){ |
+ switch( rc ){ |
+ case SQLITE_OK: zName = "SQLITE_OK"; break; |
+ case SQLITE_ERROR: zName = "SQLITE_ERROR"; break; |
+ case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break; |
+ case SQLITE_PERM: zName = "SQLITE_PERM"; break; |
+ case SQLITE_ABORT: zName = "SQLITE_ABORT"; break; |
+ case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break; |
+ case SQLITE_BUSY: zName = "SQLITE_BUSY"; break; |
+ case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break; |
+ case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break; |
+ case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break; |
+ case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break; |
+ case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break; |
+ case SQLITE_READONLY: zName = "SQLITE_READONLY"; break; |
+ case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break; |
+ case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break; |
+ case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break; |
+ case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break; |
+ case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break; |
+ case SQLITE_IOERR: zName = "SQLITE_IOERR"; break; |
+ case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break; |
+ case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break; |
+ case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break; |
+ case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break; |
+ case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break; |
+ case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break; |
+ case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break; |
+ case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break; |
+ case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break; |
+ case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break; |
+ case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break; |
+ case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break; |
+ case SQLITE_IOERR_CHECKRESERVEDLOCK: |
+ zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break; |
+ case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break; |
+ case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break; |
+ case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break; |
+ case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break; |
+ case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break; |
+ case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break; |
+ case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break; |
+ case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break; |
+ case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break; |
+ case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break; |
+ case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break; |
+ case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break; |
+ case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break; |
+ case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break; |
+ case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break; |
+ case SQLITE_FULL: zName = "SQLITE_FULL"; break; |
+ case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break; |
+ case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break; |
+ case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break; |
+ case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break; |
+ case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break; |
+ case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break; |
+ case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break; |
+ case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break; |
+ case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break; |
+ case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break; |
+ case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break; |
+ case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break; |
+ case SQLITE_CONSTRAINT_FOREIGNKEY: |
+ zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break; |
+ case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break; |
+ case SQLITE_CONSTRAINT_PRIMARYKEY: |
+ zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break; |
+ case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break; |
+ case SQLITE_CONSTRAINT_COMMITHOOK: |
+ zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break; |
+ case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break; |
+ case SQLITE_CONSTRAINT_FUNCTION: |
+ zName = "SQLITE_CONSTRAINT_FUNCTION"; break; |
+ case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break; |
+ case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break; |
+ case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break; |
+ case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break; |
+ case SQLITE_AUTH: zName = "SQLITE_AUTH"; break; |
+ case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break; |
+ case SQLITE_RANGE: zName = "SQLITE_RANGE"; break; |
+ case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break; |
+ case SQLITE_ROW: zName = "SQLITE_ROW"; break; |
+ case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break; |
+ case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break; |
+ case SQLITE_NOTICE_RECOVER_ROLLBACK: |
+ zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break; |
+ case SQLITE_WARNING: zName = "SQLITE_WARNING"; break; |
+ case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break; |
+ case SQLITE_DONE: zName = "SQLITE_DONE"; break; |
+ } |
+ } |
+ if( zName==0 ){ |
+ static char zBuf[50]; |
+ sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc); |
+ zName = zBuf; |
+ } |
+ return zName; |
+} |
+#endif |
+ |
+/* |
+** Return a static string that describes the kind of error specified in the |
+** argument. |
+*/ |
+SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){ |
+ static const char* const aMsg[] = { |
+ /* SQLITE_OK */ "not an error", |
+ /* SQLITE_ERROR */ "SQL logic error or missing database", |
+ /* SQLITE_INTERNAL */ 0, |
+ /* SQLITE_PERM */ "access permission denied", |
+ /* SQLITE_ABORT */ "callback requested query abort", |
+ /* SQLITE_BUSY */ "database is locked", |
+ /* SQLITE_LOCKED */ "database table is locked", |
+ /* SQLITE_NOMEM */ "out of memory", |
+ /* SQLITE_READONLY */ "attempt to write a readonly database", |
+ /* SQLITE_INTERRUPT */ "interrupted", |
+ /* SQLITE_IOERR */ "disk I/O error", |
+ /* SQLITE_CORRUPT */ "database disk image is malformed", |
+ /* SQLITE_NOTFOUND */ "unknown operation", |
+ /* SQLITE_FULL */ "database or disk is full", |
+ /* SQLITE_CANTOPEN */ "unable to open database file", |
+ /* SQLITE_PROTOCOL */ "locking protocol", |
+ /* SQLITE_EMPTY */ "table contains no data", |
+ /* SQLITE_SCHEMA */ "database schema has changed", |
+ /* SQLITE_TOOBIG */ "string or blob too big", |
+ /* SQLITE_CONSTRAINT */ "constraint failed", |
+ /* SQLITE_MISMATCH */ "datatype mismatch", |
+ /* SQLITE_MISUSE */ "library routine called out of sequence", |
+ /* SQLITE_NOLFS */ "large file support is disabled", |
+ /* SQLITE_AUTH */ "authorization denied", |
+ /* SQLITE_FORMAT */ "auxiliary database format error", |
+ /* SQLITE_RANGE */ "bind or column index out of range", |
+ /* SQLITE_NOTADB */ "file is encrypted or is not a database", |
+ }; |
+ const char *zErr = "unknown error"; |
+ switch( rc ){ |
+ case SQLITE_ABORT_ROLLBACK: { |
+ zErr = "abort due to ROLLBACK"; |
+ break; |
+ } |
+ default: { |
+ rc &= 0xff; |
+ if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){ |
+ zErr = aMsg[rc]; |
+ } |
+ break; |
+ } |
+ } |
+ return zErr; |
+} |
+ |
+/* |
+** This routine implements a busy callback that sleeps and tries |
+** again until a timeout value is reached. The timeout value is |
+** an integer number of milliseconds passed in as the first |
+** argument. |
+*/ |
+static int sqliteDefaultBusyCallback( |
+ void *ptr, /* Database connection */ |
+ int count /* Number of times table has been busy */ |
+){ |
+#if SQLITE_OS_WIN || HAVE_USLEEP |
+ static const u8 delays[] = |
+ { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 }; |
+ static const u8 totals[] = |
+ { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 }; |
+# define NDELAY ArraySize(delays) |
+ sqlite3 *db = (sqlite3 *)ptr; |
+ int timeout = db->busyTimeout; |
+ int delay, prior; |
+ |
+ assert( count>=0 ); |
+ if( count < NDELAY ){ |
+ delay = delays[count]; |
+ prior = totals[count]; |
+ }else{ |
+ delay = delays[NDELAY-1]; |
+ prior = totals[NDELAY-1] + delay*(count-(NDELAY-1)); |
+ } |
+ if( prior + delay > timeout ){ |
+ delay = timeout - prior; |
+ if( delay<=0 ) return 0; |
+ } |
+ sqlite3OsSleep(db->pVfs, delay*1000); |
+ return 1; |
+#else |
+ sqlite3 *db = (sqlite3 *)ptr; |
+ int timeout = ((sqlite3 *)ptr)->busyTimeout; |
+ if( (count+1)*1000 > timeout ){ |
+ return 0; |
+ } |
+ sqlite3OsSleep(db->pVfs, 1000000); |
+ return 1; |
+#endif |
+} |
+ |
+/* |
+** Invoke the given busy handler. |
+** |
+** This routine is called when an operation failed with a lock. |
+** If this routine returns non-zero, the lock is retried. If it |
+** returns 0, the operation aborts with an SQLITE_BUSY error. |
+*/ |
+SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){ |
+ int rc; |
+ if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0; |
+ rc = p->xFunc(p->pArg, p->nBusy); |
+ if( rc==0 ){ |
+ p->nBusy = -1; |
+ }else{ |
+ p->nBusy++; |
+ } |
+ return rc; |
+} |
+ |
+/* |
+** This routine sets the busy callback for an Sqlite database to the |
+** given callback function with the given argument. |
+*/ |
+SQLITE_API int sqlite3_busy_handler( |
+ sqlite3 *db, |
+ int (*xBusy)(void*,int), |
+ void *pArg |
+){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ db->busyHandler.xFunc = xBusy; |
+ db->busyHandler.pArg = pArg; |
+ db->busyHandler.nBusy = 0; |
+ db->busyTimeout = 0; |
+ sqlite3_mutex_leave(db->mutex); |
+ return SQLITE_OK; |
+} |
+ |
+#ifndef SQLITE_OMIT_PROGRESS_CALLBACK |
+/* |
+** This routine sets the progress callback for an Sqlite database to the |
+** given callback function with the given argument. The progress callback will |
+** be invoked every nOps opcodes. |
+*/ |
+SQLITE_API void sqlite3_progress_handler( |
+ sqlite3 *db, |
+ int nOps, |
+ int (*xProgress)(void*), |
+ void *pArg |
+){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return; |
+ } |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ if( nOps>0 ){ |
+ db->xProgress = xProgress; |
+ db->nProgressOps = (unsigned)nOps; |
+ db->pProgressArg = pArg; |
+ }else{ |
+ db->xProgress = 0; |
+ db->nProgressOps = 0; |
+ db->pProgressArg = 0; |
+ } |
+ sqlite3_mutex_leave(db->mutex); |
+} |
+#endif |
+ |
+ |
+/* |
+** This routine installs a default busy handler that waits for the |
+** specified number of milliseconds before returning 0. |
+*/ |
+SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ if( ms>0 ){ |
+ sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db); |
+ db->busyTimeout = ms; |
+ }else{ |
+ sqlite3_busy_handler(db, 0, 0); |
+ } |
+ return SQLITE_OK; |
+} |
+ |
+/* |
+** Cause any pending operation to stop at its earliest opportunity. |
+*/ |
+SQLITE_API void sqlite3_interrupt(sqlite3 *db){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return; |
+ } |
+#endif |
+ db->u1.isInterrupted = 1; |
+} |
+ |
+ |
+/* |
+** This function is exactly the same as sqlite3_create_function(), except |
+** that it is designed to be called by internal code. The difference is |
+** that if a malloc() fails in sqlite3_create_function(), an error code |
+** is returned and the mallocFailed flag cleared. |
+*/ |
+SQLITE_PRIVATE int sqlite3CreateFunc( |
+ sqlite3 *db, |
+ const char *zFunctionName, |
+ int nArg, |
+ int enc, |
+ void *pUserData, |
+ void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), |
+ void (*xStep)(sqlite3_context*,int,sqlite3_value **), |
+ void (*xFinal)(sqlite3_context*), |
+ FuncDestructor *pDestructor |
+){ |
+ FuncDef *p; |
+ int nName; |
+ int extraFlags; |
+ |
+ assert( sqlite3_mutex_held(db->mutex) ); |
+ if( zFunctionName==0 || |
+ (xSFunc && (xFinal || xStep)) || |
+ (!xSFunc && (xFinal && !xStep)) || |
+ (!xSFunc && (!xFinal && xStep)) || |
+ (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) || |
+ (255<(nName = sqlite3Strlen30( zFunctionName))) ){ |
+ return SQLITE_MISUSE_BKPT; |
+ } |
+ |
+ assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC ); |
+ extraFlags = enc & SQLITE_DETERMINISTIC; |
+ enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY); |
+ |
+#ifndef SQLITE_OMIT_UTF16 |
+ /* If SQLITE_UTF16 is specified as the encoding type, transform this |
+ ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the |
+ ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. |
+ ** |
+ ** If SQLITE_ANY is specified, add three versions of the function |
+ ** to the hash table. |
+ */ |
+ if( enc==SQLITE_UTF16 ){ |
+ enc = SQLITE_UTF16NATIVE; |
+ }else if( enc==SQLITE_ANY ){ |
+ int rc; |
+ rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags, |
+ pUserData, xSFunc, xStep, xFinal, pDestructor); |
+ if( rc==SQLITE_OK ){ |
+ rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags, |
+ pUserData, xSFunc, xStep, xFinal, pDestructor); |
+ } |
+ if( rc!=SQLITE_OK ){ |
+ return rc; |
+ } |
+ enc = SQLITE_UTF16BE; |
+ } |
+#else |
+ enc = SQLITE_UTF8; |
+#endif |
+ |
+ /* Check if an existing function is being overridden or deleted. If so, |
+ ** and there are active VMs, then return SQLITE_BUSY. If a function |
+ ** is being overridden/deleted but there are no active VMs, allow the |
+ ** operation to continue but invalidate all precompiled statements. |
+ */ |
+ p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0); |
+ if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){ |
+ if( db->nVdbeActive ){ |
+ sqlite3ErrorWithMsg(db, SQLITE_BUSY, |
+ "unable to delete/modify user-function due to active statements"); |
+ assert( !db->mallocFailed ); |
+ return SQLITE_BUSY; |
+ }else{ |
+ sqlite3ExpirePreparedStatements(db); |
+ } |
+ } |
+ |
+ p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1); |
+ assert(p || db->mallocFailed); |
+ if( !p ){ |
+ return SQLITE_NOMEM_BKPT; |
+ } |
+ |
+ /* If an older version of the function with a configured destructor is |
+ ** being replaced invoke the destructor function here. */ |
+ functionDestroy(db, p); |
+ |
+ if( pDestructor ){ |
+ pDestructor->nRef++; |
+ } |
+ p->u.pDestructor = pDestructor; |
+ p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags; |
+ testcase( p->funcFlags & SQLITE_DETERMINISTIC ); |
+ p->xSFunc = xSFunc ? xSFunc : xStep; |
+ p->xFinalize = xFinal; |
+ p->pUserData = pUserData; |
+ p->nArg = (u16)nArg; |
+ return SQLITE_OK; |
+} |
+ |
+/* |
+** Create new user functions. |
+*/ |
+SQLITE_API int sqlite3_create_function( |
+ sqlite3 *db, |
+ const char *zFunc, |
+ int nArg, |
+ int enc, |
+ void *p, |
+ void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), |
+ void (*xStep)(sqlite3_context*,int,sqlite3_value **), |
+ void (*xFinal)(sqlite3_context*) |
+){ |
+ return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep, |
+ xFinal, 0); |
+} |
+ |
+SQLITE_API int sqlite3_create_function_v2( |
+ sqlite3 *db, |
+ const char *zFunc, |
+ int nArg, |
+ int enc, |
+ void *p, |
+ void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), |
+ void (*xStep)(sqlite3_context*,int,sqlite3_value **), |
+ void (*xFinal)(sqlite3_context*), |
+ void (*xDestroy)(void *) |
+){ |
+ int rc = SQLITE_ERROR; |
+ FuncDestructor *pArg = 0; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ return SQLITE_MISUSE_BKPT; |
+ } |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ if( xDestroy ){ |
+ pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor)); |
+ if( !pArg ){ |
+ xDestroy(p); |
+ goto out; |
+ } |
+ pArg->xDestroy = xDestroy; |
+ pArg->pUserData = p; |
+ } |
+ rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg); |
+ if( pArg && pArg->nRef==0 ){ |
+ assert( rc!=SQLITE_OK ); |
+ xDestroy(p); |
+ sqlite3DbFree(db, pArg); |
+ } |
+ |
+ out: |
+ rc = sqlite3ApiExit(db, rc); |
+ sqlite3_mutex_leave(db->mutex); |
+ return rc; |
+} |
+ |
+#ifndef SQLITE_OMIT_UTF16 |
+SQLITE_API int sqlite3_create_function16( |
+ sqlite3 *db, |
+ const void *zFunctionName, |
+ int nArg, |
+ int eTextRep, |
+ void *p, |
+ void (*xSFunc)(sqlite3_context*,int,sqlite3_value**), |
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**), |
+ void (*xFinal)(sqlite3_context*) |
+){ |
+ int rc; |
+ char *zFunc8; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ assert( !db->mallocFailed ); |
+ zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE); |
+ rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0); |
+ sqlite3DbFree(db, zFunc8); |
+ rc = sqlite3ApiExit(db, rc); |
+ sqlite3_mutex_leave(db->mutex); |
+ return rc; |
+} |
+#endif |
+ |
+ |
+/* |
+** Declare that a function has been overloaded by a virtual table. |
+** |
+** If the function already exists as a regular global function, then |
+** this routine is a no-op. If the function does not exist, then create |
+** a new one that always throws a run-time error. |
+** |
+** When virtual tables intend to provide an overloaded function, they |
+** should call this routine to make sure the global function exists. |
+** A global function must exist in order for name resolution to work |
+** properly. |
+*/ |
+SQLITE_API int sqlite3_overload_function( |
+ sqlite3 *db, |
+ const char *zName, |
+ int nArg |
+){ |
+ int rc = SQLITE_OK; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){ |
+ return SQLITE_MISUSE_BKPT; |
+ } |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){ |
+ rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8, |
+ 0, sqlite3InvalidFunction, 0, 0, 0); |
+ } |
+ rc = sqlite3ApiExit(db, rc); |
+ sqlite3_mutex_leave(db->mutex); |
+ return rc; |
+} |
+ |
+#ifndef SQLITE_OMIT_TRACE |
+/* |
+** Register a trace function. The pArg from the previously registered trace |
+** is returned. |
+** |
+** A NULL trace function means that no tracing is executes. A non-NULL |
+** trace is a pointer to a function that is invoked at the start of each |
+** SQL statement. |
+*/ |
+#ifndef SQLITE_OMIT_DEPRECATED |
+SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){ |
+ void *pOld; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ pOld = db->pTraceArg; |
+ db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0; |
+ db->xTrace = (int(*)(u32,void*,void*,void*))xTrace; |
+ db->pTraceArg = pArg; |
+ sqlite3_mutex_leave(db->mutex); |
+ return pOld; |
+} |
+#endif /* SQLITE_OMIT_DEPRECATED */ |
+ |
+/* Register a trace callback using the version-2 interface. |
+*/ |
+SQLITE_API int sqlite3_trace_v2( |
+ sqlite3 *db, /* Trace this connection */ |
+ unsigned mTrace, /* Mask of events to be traced */ |
+ int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */ |
+ void *pArg /* Context */ |
+){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ return SQLITE_MISUSE_BKPT; |
+ } |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ if( mTrace==0 ) xTrace = 0; |
+ if( xTrace==0 ) mTrace = 0; |
+ db->mTrace = mTrace; |
+ db->xTrace = xTrace; |
+ db->pTraceArg = pArg; |
+ sqlite3_mutex_leave(db->mutex); |
+ return SQLITE_OK; |
+} |
+ |
+#ifndef SQLITE_OMIT_DEPRECATED |
+/* |
+** Register a profile function. The pArg from the previously registered |
+** profile function is returned. |
+** |
+** A NULL profile function means that no profiling is executes. A non-NULL |
+** profile is a pointer to a function that is invoked at the conclusion of |
+** each SQL statement that is run. |
+*/ |
+SQLITE_API void *sqlite3_profile( |
+ sqlite3 *db, |
+ void (*xProfile)(void*,const char*,sqlite_uint64), |
+ void *pArg |
+){ |
+ void *pOld; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ pOld = db->pProfileArg; |
+ db->xProfile = xProfile; |
+ db->pProfileArg = pArg; |
+ sqlite3_mutex_leave(db->mutex); |
+ return pOld; |
+} |
+#endif /* SQLITE_OMIT_DEPRECATED */ |
+#endif /* SQLITE_OMIT_TRACE */ |
+ |
+/* |
+** Register a function to be invoked when a transaction commits. |
+** If the invoked function returns non-zero, then the commit becomes a |
+** rollback. |
+*/ |
+SQLITE_API void *sqlite3_commit_hook( |
+ sqlite3 *db, /* Attach the hook to this database */ |
+ int (*xCallback)(void*), /* Function to invoke on each commit */ |
+ void *pArg /* Argument to the function */ |
+){ |
+ void *pOld; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ pOld = db->pCommitArg; |
+ db->xCommitCallback = xCallback; |
+ db->pCommitArg = pArg; |
+ sqlite3_mutex_leave(db->mutex); |
+ return pOld; |
+} |
+ |
+/* |
+** Register a callback to be invoked each time a row is updated, |
+** inserted or deleted using this database connection. |
+*/ |
+SQLITE_API void *sqlite3_update_hook( |
+ sqlite3 *db, /* Attach the hook to this database */ |
+ void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), |
+ void *pArg /* Argument to the function */ |
+){ |
+ void *pRet; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ pRet = db->pUpdateArg; |
+ db->xUpdateCallback = xCallback; |
+ db->pUpdateArg = pArg; |
+ sqlite3_mutex_leave(db->mutex); |
+ return pRet; |
+} |
+ |
+/* |
+** Register a callback to be invoked each time a transaction is rolled |
+** back by this database connection. |
+*/ |
+SQLITE_API void *sqlite3_rollback_hook( |
+ sqlite3 *db, /* Attach the hook to this database */ |
+ void (*xCallback)(void*), /* Callback function */ |
+ void *pArg /* Argument to the function */ |
+){ |
+ void *pRet; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ pRet = db->pRollbackArg; |
+ db->xRollbackCallback = xCallback; |
+ db->pRollbackArg = pArg; |
+ sqlite3_mutex_leave(db->mutex); |
+ return pRet; |
+} |
+ |
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK |
+/* |
+** Register a callback to be invoked each time a row is updated, |
+** inserted or deleted using this database connection. |
+*/ |
+SQLITE_API void *sqlite3_preupdate_hook( |
+ sqlite3 *db, /* Attach the hook to this database */ |
+ void(*xCallback)( /* Callback function */ |
+ void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64), |
+ void *pArg /* First callback argument */ |
+){ |
+ void *pRet; |
+ sqlite3_mutex_enter(db->mutex); |
+ pRet = db->pPreUpdateArg; |
+ db->xPreUpdateCallback = xCallback; |
+ db->pPreUpdateArg = pArg; |
+ sqlite3_mutex_leave(db->mutex); |
+ return pRet; |
+} |
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ |
+ |
+#ifndef SQLITE_OMIT_WAL |
+/* |
+** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint(). |
+** Invoke sqlite3_wal_checkpoint if the number of frames in the log file |
+** is greater than sqlite3.pWalArg cast to an integer (the value configured by |
+** wal_autocheckpoint()). |
+*/ |
+SQLITE_PRIVATE int sqlite3WalDefaultHook( |
+ void *pClientData, /* Argument */ |
+ sqlite3 *db, /* Connection */ |
+ const char *zDb, /* Database */ |
+ int nFrame /* Size of WAL */ |
+){ |
+ if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){ |
+ sqlite3BeginBenignMalloc(); |
+ sqlite3_wal_checkpoint(db, zDb); |
+ sqlite3EndBenignMalloc(); |
+ } |
+ return SQLITE_OK; |
+} |
+#endif /* SQLITE_OMIT_WAL */ |
+ |
+/* |
+** Configure an sqlite3_wal_hook() callback to automatically checkpoint |
+** a database after committing a transaction if there are nFrame or |
+** more frames in the log file. Passing zero or a negative value as the |
+** nFrame parameter disables automatic checkpoints entirely. |
+** |
+** The callback registered by this function replaces any existing callback |
+** registered using sqlite3_wal_hook(). Likewise, registering a callback |
+** using sqlite3_wal_hook() disables the automatic checkpoint mechanism |
+** configured by this function. |
+*/ |
+SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){ |
+#ifdef SQLITE_OMIT_WAL |
+ UNUSED_PARAMETER(db); |
+ UNUSED_PARAMETER(nFrame); |
+#else |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ if( nFrame>0 ){ |
+ sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); |
+ }else{ |
+ sqlite3_wal_hook(db, 0, 0); |
+ } |
+#endif |
+ return SQLITE_OK; |
+} |
+ |
+/* |
+** Register a callback to be invoked each time a transaction is written |
+** into the write-ahead-log by this database connection. |
+*/ |
+SQLITE_API void *sqlite3_wal_hook( |
+ sqlite3 *db, /* Attach the hook to this db handle */ |
+ int(*xCallback)(void *, sqlite3*, const char*, int), |
+ void *pArg /* First argument passed to xCallback() */ |
+){ |
+#ifndef SQLITE_OMIT_WAL |
+ void *pRet; |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ pRet = db->pWalArg; |
+ db->xWalCallback = xCallback; |
+ db->pWalArg = pArg; |
+ sqlite3_mutex_leave(db->mutex); |
+ return pRet; |
+#else |
+ return 0; |
+#endif |
+} |
+ |
+/* |
+** Checkpoint database zDb. |
+*/ |
+SQLITE_API int sqlite3_wal_checkpoint_v2( |
+ sqlite3 *db, /* Database handle */ |
+ const char *zDb, /* Name of attached database (or NULL) */ |
+ int eMode, /* SQLITE_CHECKPOINT_* value */ |
+ int *pnLog, /* OUT: Size of WAL log in frames */ |
+ int *pnCkpt /* OUT: Total number of frames checkpointed */ |
+){ |
+#ifdef SQLITE_OMIT_WAL |
+ return SQLITE_OK; |
+#else |
+ int rc; /* Return code */ |
+ int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */ |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ |
+ /* Initialize the output variables to -1 in case an error occurs. */ |
+ if( pnLog ) *pnLog = -1; |
+ if( pnCkpt ) *pnCkpt = -1; |
+ |
+ assert( SQLITE_CHECKPOINT_PASSIVE==0 ); |
+ assert( SQLITE_CHECKPOINT_FULL==1 ); |
+ assert( SQLITE_CHECKPOINT_RESTART==2 ); |
+ assert( SQLITE_CHECKPOINT_TRUNCATE==3 ); |
+ if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){ |
+ /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint |
+ ** mode: */ |
+ return SQLITE_MISUSE; |
+ } |
+ |
+ sqlite3_mutex_enter(db->mutex); |
+ if( zDb && zDb[0] ){ |
+ iDb = sqlite3FindDbName(db, zDb); |
+ } |
+ if( iDb<0 ){ |
+ rc = SQLITE_ERROR; |
+ sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb); |
+ }else{ |
+ db->busyHandler.nBusy = 0; |
+ rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); |
+ sqlite3Error(db, rc); |
+ } |
+ rc = sqlite3ApiExit(db, rc); |
+ |
+ /* If there are no active statements, clear the interrupt flag at this |
+ ** point. */ |
+ if( db->nVdbeActive==0 ){ |
+ db->u1.isInterrupted = 0; |
+ } |
+ |
+ sqlite3_mutex_leave(db->mutex); |
+ return rc; |
+#endif |
+} |
+ |
+ |
+/* |
+** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points |
+** to contains a zero-length string, all attached databases are |
+** checkpointed. |
+*/ |
+SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){ |
+ /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to |
+ ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */ |
+ return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0); |
+} |
+ |
+#ifndef SQLITE_OMIT_WAL |
+/* |
+** Run a checkpoint on database iDb. This is a no-op if database iDb is |
+** not currently open in WAL mode. |
+** |
+** If a transaction is open on the database being checkpointed, this |
+** function returns SQLITE_LOCKED and a checkpoint is not attempted. If |
+** an error occurs while running the checkpoint, an SQLite error code is |
+** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK. |
+** |
+** The mutex on database handle db should be held by the caller. The mutex |
+** associated with the specific b-tree being checkpointed is taken by |
+** this function while the checkpoint is running. |
+** |
+** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are |
+** checkpointed. If an error is encountered it is returned immediately - |
+** no attempt is made to checkpoint any remaining databases. |
+** |
+** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. |
+*/ |
+SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){ |
+ int rc = SQLITE_OK; /* Return code */ |
+ int i; /* Used to iterate through attached dbs */ |
+ int bBusy = 0; /* True if SQLITE_BUSY has been encountered */ |
+ |
+ assert( sqlite3_mutex_held(db->mutex) ); |
+ assert( !pnLog || *pnLog==-1 ); |
+ assert( !pnCkpt || *pnCkpt==-1 ); |
+ |
+ for(i=0; i<db->nDb && rc==SQLITE_OK; i++){ |
+ if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){ |
+ rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); |
+ pnLog = 0; |
+ pnCkpt = 0; |
+ if( rc==SQLITE_BUSY ){ |
+ bBusy = 1; |
+ rc = SQLITE_OK; |
+ } |
+ } |
+ } |
+ |
+ return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc; |
+} |
+#endif /* SQLITE_OMIT_WAL */ |
+ |
+/* |
+** This function returns true if main-memory should be used instead of |
+** a temporary file for transient pager files and statement journals. |
+** The value returned depends on the value of db->temp_store (runtime |
+** parameter) and the compile time value of SQLITE_TEMP_STORE. The |
+** following table describes the relationship between these two values |
+** and this functions return value. |
+** |
+** SQLITE_TEMP_STORE db->temp_store Location of temporary database |
+** ----------------- -------------- ------------------------------ |
+** 0 any file (return 0) |
+** 1 1 file (return 0) |
+** 1 2 memory (return 1) |
+** 1 0 file (return 0) |
+** 2 1 file (return 0) |
+** 2 2 memory (return 1) |
+** 2 0 memory (return 1) |
+** 3 any memory (return 1) |
+*/ |
+SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){ |
+#if SQLITE_TEMP_STORE==1 |
+ return ( db->temp_store==2 ); |
+#endif |
+#if SQLITE_TEMP_STORE==2 |
+ return ( db->temp_store!=1 ); |
+#endif |
+#if SQLITE_TEMP_STORE==3 |
+ UNUSED_PARAMETER(db); |
+ return 1; |
+#endif |
+#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 |
+ UNUSED_PARAMETER(db); |
+ return 0; |
+#endif |
+} |
+ |
+/* |
+** Return UTF-8 encoded English language explanation of the most recent |
+** error. |
+*/ |
+SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){ |
+ const char *z; |
+ if( !db ){ |
+ return sqlite3ErrStr(SQLITE_NOMEM_BKPT); |
+ } |
+ if( !sqlite3SafetyCheckSickOrOk(db) ){ |
+ return sqlite3ErrStr(SQLITE_MISUSE_BKPT); |
+ } |
+ sqlite3_mutex_enter(db->mutex); |
+ if( db->mallocFailed ){ |
+ z = sqlite3ErrStr(SQLITE_NOMEM_BKPT); |
+ }else{ |
+ testcase( db->pErr==0 ); |
+ z = (char*)sqlite3_value_text(db->pErr); |
+ assert( !db->mallocFailed ); |
+ if( z==0 ){ |
+ z = sqlite3ErrStr(db->errCode); |
+ } |
+ } |
+ sqlite3_mutex_leave(db->mutex); |
+ return z; |
+} |
+ |
+#ifndef SQLITE_OMIT_UTF16 |
+/* |
+** Return UTF-16 encoded English language explanation of the most recent |
+** error. |
+*/ |
+SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){ |
+ static const u16 outOfMem[] = { |
+ 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 |
+ }; |
+ static const u16 misuse[] = { |
+ 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', |
+ 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', |
+ 'c', 'a', 'l', 'l', 'e', 'd', ' ', |
+ 'o', 'u', 't', ' ', |
+ 'o', 'f', ' ', |
+ 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0 |
+ }; |
+ |
+ const void *z; |
+ if( !db ){ |
+ return (void *)outOfMem; |
+ } |
+ if( !sqlite3SafetyCheckSickOrOk(db) ){ |
+ return (void *)misuse; |
+ } |
+ sqlite3_mutex_enter(db->mutex); |
+ if( db->mallocFailed ){ |
+ z = (void *)outOfMem; |
+ }else{ |
+ z = sqlite3_value_text16(db->pErr); |
+ if( z==0 ){ |
+ sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode)); |
+ z = sqlite3_value_text16(db->pErr); |
+ } |
+ /* A malloc() may have failed within the call to sqlite3_value_text16() |
+ ** above. If this is the case, then the db->mallocFailed flag needs to |
+ ** be cleared before returning. Do this directly, instead of via |
+ ** sqlite3ApiExit(), to avoid setting the database handle error message. |
+ */ |
+ sqlite3OomClear(db); |
+ } |
+ sqlite3_mutex_leave(db->mutex); |
+ return z; |
+} |
+#endif /* SQLITE_OMIT_UTF16 */ |
+ |
+/* |
+** Return the most recent error code generated by an SQLite routine. If NULL is |
+** passed to this function, we assume a malloc() failed during sqlite3_open(). |
+*/ |
+SQLITE_API int sqlite3_errcode(sqlite3 *db){ |
+ if( db && !sqlite3SafetyCheckSickOrOk(db) ){ |
+ return SQLITE_MISUSE_BKPT; |
+ } |
+ if( !db || db->mallocFailed ){ |
+ return SQLITE_NOMEM_BKPT; |
+ } |
+ return db->errCode & db->errMask; |
+} |
+SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){ |
+ if( db && !sqlite3SafetyCheckSickOrOk(db) ){ |
+ return SQLITE_MISUSE_BKPT; |
+ } |
+ if( !db || db->mallocFailed ){ |
+ return SQLITE_NOMEM_BKPT; |
+ } |
+ return db->errCode; |
+} |
+SQLITE_API int sqlite3_system_errno(sqlite3 *db){ |
+ return db ? db->iSysErrno : 0; |
+} |
+ |
+/* |
+** Return a string that describes the kind of error specified in the |
+** argument. For now, this simply calls the internal sqlite3ErrStr() |
+** function. |
+*/ |
+SQLITE_API const char *sqlite3_errstr(int rc){ |
+ return sqlite3ErrStr(rc); |
+} |
+ |
+/* |
+** Create a new collating function for database "db". The name is zName |
+** and the encoding is enc. |
+*/ |
+static int createCollation( |
+ sqlite3* db, |
+ const char *zName, |
+ u8 enc, |
+ void* pCtx, |
+ int(*xCompare)(void*,int,const void*,int,const void*), |
+ void(*xDel)(void*) |
+){ |
+ CollSeq *pColl; |
+ int enc2; |
+ |
+ assert( sqlite3_mutex_held(db->mutex) ); |
+ |
+ /* If SQLITE_UTF16 is specified as the encoding type, transform this |
+ ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the |
+ ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. |
+ */ |
+ enc2 = enc; |
+ testcase( enc2==SQLITE_UTF16 ); |
+ testcase( enc2==SQLITE_UTF16_ALIGNED ); |
+ if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){ |
+ enc2 = SQLITE_UTF16NATIVE; |
+ } |
+ if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){ |
+ return SQLITE_MISUSE_BKPT; |
+ } |
+ |
+ /* Check if this call is removing or replacing an existing collation |
+ ** sequence. If so, and there are active VMs, return busy. If there |
+ ** are no active VMs, invalidate any pre-compiled statements. |
+ */ |
+ pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0); |
+ if( pColl && pColl->xCmp ){ |
+ if( db->nVdbeActive ){ |
+ sqlite3ErrorWithMsg(db, SQLITE_BUSY, |
+ "unable to delete/modify collation sequence due to active statements"); |
+ return SQLITE_BUSY; |
+ } |
+ sqlite3ExpirePreparedStatements(db); |
+ |
+ /* If collation sequence pColl was created directly by a call to |
+ ** sqlite3_create_collation, and not generated by synthCollSeq(), |
+ ** then any copies made by synthCollSeq() need to be invalidated. |
+ ** Also, collation destructor - CollSeq.xDel() - function may need |
+ ** to be called. |
+ */ |
+ if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ |
+ CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName); |
+ int j; |
+ for(j=0; j<3; j++){ |
+ CollSeq *p = &aColl[j]; |
+ if( p->enc==pColl->enc ){ |
+ if( p->xDel ){ |
+ p->xDel(p->pUser); |
+ } |
+ p->xCmp = 0; |
+ } |
+ } |
+ } |
+ } |
+ |
+ pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1); |
+ if( pColl==0 ) return SQLITE_NOMEM_BKPT; |
+ pColl->xCmp = xCompare; |
+ pColl->pUser = pCtx; |
+ pColl->xDel = xDel; |
+ pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED)); |
+ sqlite3Error(db, SQLITE_OK); |
+ return SQLITE_OK; |
+} |
+ |
+ |
+/* |
+** This array defines hard upper bounds on limit values. The |
+** initializer must be kept in sync with the SQLITE_LIMIT_* |
+** #defines in sqlite3.h. |
+*/ |
+static const int aHardLimit[] = { |
+ SQLITE_MAX_LENGTH, |
+ SQLITE_MAX_SQL_LENGTH, |
+ SQLITE_MAX_COLUMN, |
+ SQLITE_MAX_EXPR_DEPTH, |
+ SQLITE_MAX_COMPOUND_SELECT, |
+ SQLITE_MAX_VDBE_OP, |
+ SQLITE_MAX_FUNCTION_ARG, |
+ SQLITE_MAX_ATTACHED, |
+ SQLITE_MAX_LIKE_PATTERN_LENGTH, |
+ SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */ |
+ SQLITE_MAX_TRIGGER_DEPTH, |
+ SQLITE_MAX_WORKER_THREADS, |
+}; |
+ |
+/* |
+** Make sure the hard limits are set to reasonable values |
+*/ |
+#if SQLITE_MAX_LENGTH<100 |
+# error SQLITE_MAX_LENGTH must be at least 100 |
+#endif |
+#if SQLITE_MAX_SQL_LENGTH<100 |
+# error SQLITE_MAX_SQL_LENGTH must be at least 100 |
+#endif |
+#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH |
+# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH |
+#endif |
+#if SQLITE_MAX_COMPOUND_SELECT<2 |
+# error SQLITE_MAX_COMPOUND_SELECT must be at least 2 |
+#endif |
+#if SQLITE_MAX_VDBE_OP<40 |
+# error SQLITE_MAX_VDBE_OP must be at least 40 |
+#endif |
+#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127 |
+# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127 |
+#endif |
+#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125 |
+# error SQLITE_MAX_ATTACHED must be between 0 and 125 |
+#endif |
+#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 |
+# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 |
+#endif |
+#if SQLITE_MAX_COLUMN>32767 |
+# error SQLITE_MAX_COLUMN must not exceed 32767 |
+#endif |
+#if SQLITE_MAX_TRIGGER_DEPTH<1 |
+# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1 |
+#endif |
+#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50 |
+# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50 |
+#endif |
+ |
+ |
+/* |
+** Change the value of a limit. Report the old value. |
+** If an invalid limit index is supplied, report -1. |
+** Make no changes but still report the old value if the |
+** new limit is negative. |
+** |
+** A new lower limit does not shrink existing constructs. |
+** It merely prevents new constructs that exceed the limit |
+** from forming. |
+*/ |
+SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ |
+ int oldLimit; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return -1; |
+ } |
+#endif |
+ |
+ /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME |
+ ** there is a hard upper bound set at compile-time by a C preprocessor |
+ ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to |
+ ** "_MAX_".) |
+ */ |
+ assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH ); |
+ assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH ); |
+ assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN ); |
+ assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH ); |
+ assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT); |
+ assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP ); |
+ assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG ); |
+ assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED ); |
+ assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]== |
+ SQLITE_MAX_LIKE_PATTERN_LENGTH ); |
+ assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER); |
+ assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH ); |
+ assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS ); |
+ assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) ); |
+ |
+ |
+ if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ |
+ return -1; |
+ } |
+ oldLimit = db->aLimit[limitId]; |
+ if( newLimit>=0 ){ /* IMP: R-52476-28732 */ |
+ if( newLimit>aHardLimit[limitId] ){ |
+ newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */ |
+ } |
+ db->aLimit[limitId] = newLimit; |
+ } |
+ return oldLimit; /* IMP: R-53341-35419 */ |
+} |
+ |
+/* |
+** This function is used to parse both URIs and non-URI filenames passed by the |
+** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database |
+** URIs specified as part of ATTACH statements. |
+** |
+** The first argument to this function is the name of the VFS to use (or |
+** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx" |
+** query parameter. The second argument contains the URI (or non-URI filename) |
+** itself. When this function is called the *pFlags variable should contain |
+** the default flags to open the database handle with. The value stored in |
+** *pFlags may be updated before returning if the URI filename contains |
+** "cache=xxx" or "mode=xxx" query parameters. |
+** |
+** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to |
+** the VFS that should be used to open the database file. *pzFile is set to |
+** point to a buffer containing the name of the file to open. It is the |
+** responsibility of the caller to eventually call sqlite3_free() to release |
+** this buffer. |
+** |
+** If an error occurs, then an SQLite error code is returned and *pzErrMsg |
+** may be set to point to a buffer containing an English language error |
+** message. It is the responsibility of the caller to eventually release |
+** this buffer by calling sqlite3_free(). |
+*/ |
+SQLITE_PRIVATE int sqlite3ParseUri( |
+ const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */ |
+ const char *zUri, /* Nul-terminated URI to parse */ |
+ unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */ |
+ sqlite3_vfs **ppVfs, /* OUT: VFS to use */ |
+ char **pzFile, /* OUT: Filename component of URI */ |
+ char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */ |
+){ |
+ int rc = SQLITE_OK; |
+ unsigned int flags = *pFlags; |
+ const char *zVfs = zDefaultVfs; |
+ char *zFile; |
+ char c; |
+ int nUri = sqlite3Strlen30(zUri); |
+ |
+ assert( *pzErrMsg==0 ); |
+ |
+ if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */ |
+ || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */ |
+ && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */ |
+ ){ |
+ char *zOpt; |
+ int eState; /* Parser state when parsing URI */ |
+ int iIn; /* Input character index */ |
+ int iOut = 0; /* Output character index */ |
+ u64 nByte = nUri+2; /* Bytes of space to allocate */ |
+ |
+ /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen |
+ ** method that there may be extra parameters following the file-name. */ |
+ flags |= SQLITE_OPEN_URI; |
+ |
+ for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&'); |
+ zFile = sqlite3_malloc64(nByte); |
+ if( !zFile ) return SQLITE_NOMEM_BKPT; |
+ |
+ iIn = 5; |
+#ifdef SQLITE_ALLOW_URI_AUTHORITY |
+ if( strncmp(zUri+5, "///", 3)==0 ){ |
+ iIn = 7; |
+ /* The following condition causes URIs with five leading / characters |
+ ** like file://///host/path to be converted into UNCs like //host/path. |
+ ** The correct URI for that UNC has only two or four leading / characters |
+ ** file://host/path or file:////host/path. But 5 leading slashes is a |
+ ** common error, we are told, so we handle it as a special case. */ |
+ if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; } |
+ }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){ |
+ iIn = 16; |
+ } |
+#else |
+ /* Discard the scheme and authority segments of the URI. */ |
+ if( zUri[5]=='/' && zUri[6]=='/' ){ |
+ iIn = 7; |
+ while( zUri[iIn] && zUri[iIn]!='/' ) iIn++; |
+ if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){ |
+ *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", |
+ iIn-7, &zUri[7]); |
+ rc = SQLITE_ERROR; |
+ goto parse_uri_out; |
+ } |
+ } |
+#endif |
+ |
+ /* Copy the filename and any query parameters into the zFile buffer. |
+ ** Decode %HH escape codes along the way. |
+ ** |
+ ** Within this loop, variable eState may be set to 0, 1 or 2, depending |
+ ** on the parsing context. As follows: |
+ ** |
+ ** 0: Parsing file-name. |
+ ** 1: Parsing name section of a name=value query parameter. |
+ ** 2: Parsing value section of a name=value query parameter. |
+ */ |
+ eState = 0; |
+ while( (c = zUri[iIn])!=0 && c!='#' ){ |
+ iIn++; |
+ if( c=='%' |
+ && sqlite3Isxdigit(zUri[iIn]) |
+ && sqlite3Isxdigit(zUri[iIn+1]) |
+ ){ |
+ int octet = (sqlite3HexToInt(zUri[iIn++]) << 4); |
+ octet += sqlite3HexToInt(zUri[iIn++]); |
+ |
+ assert( octet>=0 && octet<256 ); |
+ if( octet==0 ){ |
+#ifndef SQLITE_ENABLE_URI_00_ERROR |
+ /* This branch is taken when "%00" appears within the URI. In this |
+ ** case we ignore all text in the remainder of the path, name or |
+ ** value currently being parsed. So ignore the current character |
+ ** and skip to the next "?", "=" or "&", as appropriate. */ |
+ while( (c = zUri[iIn])!=0 && c!='#' |
+ && (eState!=0 || c!='?') |
+ && (eState!=1 || (c!='=' && c!='&')) |
+ && (eState!=2 || c!='&') |
+ ){ |
+ iIn++; |
+ } |
+ continue; |
+#else |
+ /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */ |
+ *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri"); |
+ rc = SQLITE_ERROR; |
+ goto parse_uri_out; |
+#endif |
+ } |
+ c = octet; |
+ }else if( eState==1 && (c=='&' || c=='=') ){ |
+ if( zFile[iOut-1]==0 ){ |
+ /* An empty option name. Ignore this option altogether. */ |
+ while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++; |
+ continue; |
+ } |
+ if( c=='&' ){ |
+ zFile[iOut++] = '\0'; |
+ }else{ |
+ eState = 2; |
+ } |
+ c = 0; |
+ }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){ |
+ c = 0; |
+ eState = 1; |
+ } |
+ zFile[iOut++] = c; |
+ } |
+ if( eState==1 ) zFile[iOut++] = '\0'; |
+ zFile[iOut++] = '\0'; |
+ zFile[iOut++] = '\0'; |
+ |
+ /* Check if there were any options specified that should be interpreted |
+ ** here. Options that are interpreted here include "vfs" and those that |
+ ** correspond to flags that may be passed to the sqlite3_open_v2() |
+ ** method. */ |
+ zOpt = &zFile[sqlite3Strlen30(zFile)+1]; |
+ while( zOpt[0] ){ |
+ int nOpt = sqlite3Strlen30(zOpt); |
+ char *zVal = &zOpt[nOpt+1]; |
+ int nVal = sqlite3Strlen30(zVal); |
+ |
+ if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ |
+ zVfs = zVal; |
+ }else{ |
+ struct OpenMode { |
+ const char *z; |
+ int mode; |
+ } *aMode = 0; |
+ char *zModeType = 0; |
+ int mask = 0; |
+ int limit = 0; |
+ |
+ if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){ |
+ static struct OpenMode aCacheMode[] = { |
+ { "shared", SQLITE_OPEN_SHAREDCACHE }, |
+ { "private", SQLITE_OPEN_PRIVATECACHE }, |
+ { 0, 0 } |
+ }; |
+ |
+ mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE; |
+ aMode = aCacheMode; |
+ limit = mask; |
+ zModeType = "cache"; |
+ } |
+ if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){ |
+ static struct OpenMode aOpenMode[] = { |
+ { "ro", SQLITE_OPEN_READONLY }, |
+ { "rw", SQLITE_OPEN_READWRITE }, |
+ { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE }, |
+ { "memory", SQLITE_OPEN_MEMORY }, |
+ { 0, 0 } |
+ }; |
+ |
+ mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE |
+ | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY; |
+ aMode = aOpenMode; |
+ limit = mask & flags; |
+ zModeType = "access"; |
+ } |
+ |
+ if( aMode ){ |
+ int i; |
+ int mode = 0; |
+ for(i=0; aMode[i].z; i++){ |
+ const char *z = aMode[i].z; |
+ if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ |
+ mode = aMode[i].mode; |
+ break; |
+ } |
+ } |
+ if( mode==0 ){ |
+ *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal); |
+ rc = SQLITE_ERROR; |
+ goto parse_uri_out; |
+ } |
+ if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){ |
+ *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s", |
+ zModeType, zVal); |
+ rc = SQLITE_PERM; |
+ goto parse_uri_out; |
+ } |
+ flags = (flags & ~mask) | mode; |
+ } |
+ } |
+ |
+ zOpt = &zVal[nVal+1]; |
+ } |
+ |
+ }else{ |
+ zFile = sqlite3_malloc64(nUri+2); |
+ if( !zFile ) return SQLITE_NOMEM_BKPT; |
+ if( nUri ){ |
+ memcpy(zFile, zUri, nUri); |
+ } |
+ zFile[nUri] = '\0'; |
+ zFile[nUri+1] = '\0'; |
+ flags &= ~SQLITE_OPEN_URI; |
+ } |
+ |
+ *ppVfs = sqlite3_vfs_find(zVfs); |
+ if( *ppVfs==0 ){ |
+ *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); |
+ rc = SQLITE_ERROR; |
+ } |
+ parse_uri_out: |
+ if( rc!=SQLITE_OK ){ |
+ sqlite3_free(zFile); |
+ zFile = 0; |
+ } |
+ *pFlags = flags; |
+ *pzFile = zFile; |
+ return rc; |
+} |
+ |
+ |
+/* |
+** This routine does the work of opening a database on behalf of |
+** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" |
+** is UTF-8 encoded. |
+*/ |
+static int openDatabase( |
+ const char *zFilename, /* Database filename UTF-8 encoded */ |
+ sqlite3 **ppDb, /* OUT: Returned database handle */ |
+ unsigned int flags, /* Operational flags */ |
+ const char *zVfs /* Name of the VFS to use */ |
+){ |
+ sqlite3 *db; /* Store allocated handle here */ |
+ int rc; /* Return code */ |
+ int isThreadsafe; /* True for threadsafe connections */ |
+ char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */ |
+ char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */ |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( ppDb==0 ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ *ppDb = 0; |
+#ifndef SQLITE_OMIT_AUTOINIT |
+ rc = sqlite3_initialize(); |
+ if( rc ) return rc; |
+#endif |
+ |
+ /* Only allow sensible combinations of bits in the flags argument. |
+ ** Throw an error if any non-sense combination is used. If we |
+ ** do not block illegal combinations here, it could trigger |
+ ** assert() statements in deeper layers. Sensible combinations |
+ ** are: |
+ ** |
+ ** 1: SQLITE_OPEN_READONLY |
+ ** 2: SQLITE_OPEN_READWRITE |
+ ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
+ */ |
+ assert( SQLITE_OPEN_READONLY == 0x01 ); |
+ assert( SQLITE_OPEN_READWRITE == 0x02 ); |
+ assert( SQLITE_OPEN_CREATE == 0x04 ); |
+ testcase( (1<<(flags&7))==0x02 ); /* READONLY */ |
+ testcase( (1<<(flags&7))==0x04 ); /* READWRITE */ |
+ testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */ |
+ if( ((1<<(flags&7)) & 0x46)==0 ){ |
+ return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */ |
+ } |
+ |
+ if( sqlite3GlobalConfig.bCoreMutex==0 ){ |
+ isThreadsafe = 0; |
+ }else if( flags & SQLITE_OPEN_NOMUTEX ){ |
+ isThreadsafe = 0; |
+ }else if( flags & SQLITE_OPEN_FULLMUTEX ){ |
+ isThreadsafe = 1; |
+ }else{ |
+ isThreadsafe = sqlite3GlobalConfig.bFullMutex; |
+ } |
+ if( flags & SQLITE_OPEN_PRIVATECACHE ){ |
+ flags &= ~SQLITE_OPEN_SHAREDCACHE; |
+ }else if( sqlite3GlobalConfig.sharedCacheEnabled ){ |
+ flags |= SQLITE_OPEN_SHAREDCACHE; |
+ } |
+ |
+ /* Remove harmful bits from the flags parameter |
+ ** |
+ ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were |
+ ** dealt with in the previous code block. Besides these, the only |
+ ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, |
+ ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE, |
+ ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask |
+ ** off all other flags. |
+ */ |
+ flags &= ~( SQLITE_OPEN_DELETEONCLOSE | |
+ SQLITE_OPEN_EXCLUSIVE | |
+ SQLITE_OPEN_MAIN_DB | |
+ SQLITE_OPEN_TEMP_DB | |
+ SQLITE_OPEN_TRANSIENT_DB | |
+ SQLITE_OPEN_MAIN_JOURNAL | |
+ SQLITE_OPEN_TEMP_JOURNAL | |
+ SQLITE_OPEN_SUBJOURNAL | |
+ SQLITE_OPEN_MASTER_JOURNAL | |
+ SQLITE_OPEN_NOMUTEX | |
+ SQLITE_OPEN_FULLMUTEX | |
+ SQLITE_OPEN_WAL |
+ ); |
+ |
+ /* Allocate the sqlite data structure */ |
+ db = sqlite3MallocZero( sizeof(sqlite3) ); |
+ if( db==0 ) goto opendb_out; |
+ if( isThreadsafe ){ |
+ db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); |
+ if( db->mutex==0 ){ |
+ sqlite3_free(db); |
+ db = 0; |
+ goto opendb_out; |
+ } |
+ } |
+ sqlite3_mutex_enter(db->mutex); |
+ db->errMask = 0xff; |
+ db->nDb = 2; |
+ db->magic = SQLITE_MAGIC_BUSY; |
+ db->aDb = db->aDbStatic; |
+ |
+ assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); |
+ memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); |
+ db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS; |
+ db->autoCommit = 1; |
+ db->nextAutovac = -1; |
+ db->szMmap = sqlite3GlobalConfig.szMmap; |
+ db->nextPagesize = 0; |
+ db->nMaxSorterMmap = 0x7FFFFFFF; |
+ db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill |
+#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX |
+ | SQLITE_AutoIndex |
+#endif |
+#if SQLITE_DEFAULT_CKPTFULLFSYNC |
+ | SQLITE_CkptFullFSync |
+#endif |
+#if SQLITE_DEFAULT_FILE_FORMAT<4 |
+ | SQLITE_LegacyFileFmt |
+#endif |
+#ifdef SQLITE_ENABLE_LOAD_EXTENSION |
+ | SQLITE_LoadExtension |
+#endif |
+#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS |
+ | SQLITE_RecTriggers |
+#endif |
+#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS |
+ | SQLITE_ForeignKeys |
+#endif |
+#if defined(SQLITE_REVERSE_UNORDERED_SELECTS) |
+ | SQLITE_ReverseOrder |
+#endif |
+#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK) |
+ | SQLITE_CellSizeCk |
+#endif |
+#if defined(SQLITE_ENABLE_FTS3_TOKENIZER) |
+ | SQLITE_Fts3Tokenizer |
+#endif |
+ ; |
+ sqlite3HashInit(&db->aCollSeq); |
+#ifndef SQLITE_OMIT_VIRTUALTABLE |
+ sqlite3HashInit(&db->aModule); |
+#endif |
+ |
+ /* Add the default collation sequence BINARY. BINARY works for both UTF-8 |
+ ** and UTF-16, so add a version for each to avoid any unnecessary |
+ ** conversions. The only error that can occur here is a malloc() failure. |
+ ** |
+ ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating |
+ ** functions: |
+ */ |
+ createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0); |
+ createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0); |
+ createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0); |
+ createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); |
+ createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0); |
+ if( db->mallocFailed ){ |
+ goto opendb_out; |
+ } |
+ /* EVIDENCE-OF: R-08308-17224 The default collating function for all |
+ ** strings is BINARY. |
+ */ |
+ db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0); |
+ assert( db->pDfltColl!=0 ); |
+ |
+ /* Parse the filename/URI argument. */ |
+ db->openFlags = flags; |
+ rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg); |
+ if( rc!=SQLITE_OK ){ |
+ if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); |
+ sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg); |
+ sqlite3_free(zErrMsg); |
+ goto opendb_out; |
+ } |
+ |
+ /* Open the backend database driver */ |
+ rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0, |
+ flags | SQLITE_OPEN_MAIN_DB); |
+ if( rc!=SQLITE_OK ){ |
+ if( rc==SQLITE_IOERR_NOMEM ){ |
+ rc = SQLITE_NOMEM_BKPT; |
+ } |
+ sqlite3Error(db, rc); |
+ goto opendb_out; |
+ } |
+ sqlite3BtreeEnter(db->aDb[0].pBt); |
+ db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); |
+ if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db); |
+ sqlite3BtreeLeave(db->aDb[0].pBt); |
+ db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); |
+ |
+ /* The default safety_level for the main database is FULL; for the temp |
+ ** database it is OFF. This matches the pager layer defaults. |
+ */ |
+ db->aDb[0].zDbSName = "main"; |
+ db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1; |
+ db->aDb[1].zDbSName = "temp"; |
+ db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF; |
+ |
+ db->magic = SQLITE_MAGIC_OPEN; |
+ if( db->mallocFailed ){ |
+ goto opendb_out; |
+ } |
+ |
+ /* Register all built-in functions, but do not attempt to read the |
+ ** database schema yet. This is delayed until the first time the database |
+ ** is accessed. |
+ */ |
+ sqlite3Error(db, SQLITE_OK); |
+ sqlite3RegisterPerConnectionBuiltinFunctions(db); |
+ rc = sqlite3_errcode(db); |
+ |
+#ifdef SQLITE_ENABLE_FTS5 |
+ /* Register any built-in FTS5 module before loading the automatic |
+ ** extensions. This allows automatic extensions to register FTS5 |
+ ** tokenizers and auxiliary functions. */ |
+ if( !db->mallocFailed && rc==SQLITE_OK ){ |
+ rc = sqlite3Fts5Init(db); |
+ } |
+#endif |
+ |
+ /* Load automatic extensions - extensions that have been registered |
+ ** using the sqlite3_automatic_extension() API. |
+ */ |
+ if( rc==SQLITE_OK ){ |
+ sqlite3AutoLoadExtensions(db); |
+ rc = sqlite3_errcode(db); |
+ if( rc!=SQLITE_OK ){ |
+ goto opendb_out; |
+ } |
+ } |
+ |
+#ifdef SQLITE_ENABLE_FTS1 |
+ if( !db->mallocFailed ){ |
+ extern int sqlite3Fts1Init(sqlite3*); |
+ rc = sqlite3Fts1Init(db); |
+ } |
+#endif |
+ |
+#ifdef SQLITE_ENABLE_FTS2 |
+ if( !db->mallocFailed && rc==SQLITE_OK ){ |
+ extern int sqlite3Fts2Init(sqlite3*); |
+ rc = sqlite3Fts2Init(db); |
+ } |
+#endif |
+ |
+#ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */ |
+ if( !db->mallocFailed && rc==SQLITE_OK ){ |
+ rc = sqlite3Fts3Init(db); |
+ } |
+#endif |
+ |
+#ifdef DEFAULT_ENABLE_RECOVER |
+ /* Initialize recover virtual table for testing. */ |
+ extern int recoverVtableInit(sqlite3 *db); |
+ if( !db->mallocFailed && rc==SQLITE_OK ){ |
+ rc = recoverVtableInit(db); |
+ } |
+#endif |
+ |
+#ifdef SQLITE_ENABLE_ICU |
+ if( !db->mallocFailed && rc==SQLITE_OK ){ |
+ rc = sqlite3IcuInit(db); |
+ } |
+#endif |
+ |
+#ifdef SQLITE_ENABLE_RTREE |
+ if( !db->mallocFailed && rc==SQLITE_OK){ |
+ rc = sqlite3RtreeInit(db); |
+ } |
+#endif |
+ |
+#ifdef SQLITE_ENABLE_DBSTAT_VTAB |
+ if( !db->mallocFailed && rc==SQLITE_OK){ |
+ rc = sqlite3DbstatRegister(db); |
+ } |
+#endif |
+ |
+#ifdef SQLITE_ENABLE_JSON1 |
+ if( !db->mallocFailed && rc==SQLITE_OK){ |
+ rc = sqlite3Json1Init(db); |
+ } |
+#endif |
+ |
+ /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking |
+ ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking |
+ ** mode. Doing nothing at all also makes NORMAL the default. |
+ */ |
+#ifdef SQLITE_DEFAULT_LOCKING_MODE |
+ db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; |
+ sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt), |
+ SQLITE_DEFAULT_LOCKING_MODE); |
+#endif |
+ |
+ if( rc ) sqlite3Error(db, rc); |
+ |
+ /* Enable the lookaside-malloc subsystem */ |
+ setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, |
+ sqlite3GlobalConfig.nLookaside); |
+ |
+ sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT); |
+ |
+opendb_out: |
+ if( db ){ |
+ assert( db->mutex!=0 || isThreadsafe==0 |
+ || sqlite3GlobalConfig.bFullMutex==0 ); |
+ sqlite3_mutex_leave(db->mutex); |
+ } |
+ rc = sqlite3_errcode(db); |
+ assert( db!=0 || rc==SQLITE_NOMEM ); |
+ if( rc==SQLITE_NOMEM ){ |
+ sqlite3_close(db); |
+ db = 0; |
+ }else if( rc!=SQLITE_OK ){ |
+ db->magic = SQLITE_MAGIC_SICK; |
+ } |
+ *ppDb = db; |
+#ifdef SQLITE_ENABLE_SQLLOG |
+ if( sqlite3GlobalConfig.xSqllog ){ |
+ /* Opening a db handle. Fourth parameter is passed 0. */ |
+ void *pArg = sqlite3GlobalConfig.pSqllogArg; |
+ sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0); |
+ } |
+#endif |
+#if defined(SQLITE_HAS_CODEC) |
+ if( rc==SQLITE_OK ){ |
+ const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey"); |
+ if( zHexKey && zHexKey[0] ){ |
+ u8 iByte; |
+ int i; |
+ char zKey[40]; |
+ for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){ |
+ iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]); |
+ if( (i&1)!=0 ) zKey[i/2] = iByte; |
+ } |
+ sqlite3_key_v2(db, 0, zKey, i/2); |
+ } |
+ } |
+#endif |
+ sqlite3_free(zOpen); |
+ return rc & 0xff; |
+} |
+ |
+/* |
+** Open a new database handle. |
+*/ |
+SQLITE_API int sqlite3_open( |
+ const char *zFilename, |
+ sqlite3 **ppDb |
+){ |
+ return openDatabase(zFilename, ppDb, |
+ SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); |
+} |
+SQLITE_API int sqlite3_open_v2( |
+ const char *filename, /* Database filename (UTF-8) */ |
+ sqlite3 **ppDb, /* OUT: SQLite db handle */ |
+ int flags, /* Flags */ |
+ const char *zVfs /* Name of VFS module to use */ |
+){ |
+ return openDatabase(filename, ppDb, (unsigned int)flags, zVfs); |
+} |
+ |
+#ifndef SQLITE_OMIT_UTF16 |
+/* |
+** Open a new database handle. |
+*/ |
+SQLITE_API int sqlite3_open16( |
+ const void *zFilename, |
+ sqlite3 **ppDb |
+){ |
+ char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ |
+ sqlite3_value *pVal; |
+ int rc; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( ppDb==0 ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ *ppDb = 0; |
+#ifndef SQLITE_OMIT_AUTOINIT |
+ rc = sqlite3_initialize(); |
+ if( rc ) return rc; |
+#endif |
+ if( zFilename==0 ) zFilename = "\000\000"; |
+ pVal = sqlite3ValueNew(0); |
+ sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); |
+ zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); |
+ if( zFilename8 ){ |
+ rc = openDatabase(zFilename8, ppDb, |
+ SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); |
+ assert( *ppDb || rc==SQLITE_NOMEM ); |
+ if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ |
+ SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE; |
+ } |
+ }else{ |
+ rc = SQLITE_NOMEM_BKPT; |
+ } |
+ sqlite3ValueFree(pVal); |
+ |
+ return rc & 0xff; |
+} |
+#endif /* SQLITE_OMIT_UTF16 */ |
+ |
+/* |
+** Register a new collation sequence with the database handle db. |
+*/ |
+SQLITE_API int sqlite3_create_collation( |
+ sqlite3* db, |
+ const char *zName, |
+ int enc, |
+ void* pCtx, |
+ int(*xCompare)(void*,int,const void*,int,const void*) |
+){ |
+ return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0); |
+} |
+ |
+/* |
+** Register a new collation sequence with the database handle db. |
+*/ |
+SQLITE_API int sqlite3_create_collation_v2( |
+ sqlite3* db, |
+ const char *zName, |
+ int enc, |
+ void* pCtx, |
+ int(*xCompare)(void*,int,const void*,int,const void*), |
+ void(*xDel)(void*) |
+){ |
+ int rc; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ assert( !db->mallocFailed ); |
+ rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel); |
+ rc = sqlite3ApiExit(db, rc); |
+ sqlite3_mutex_leave(db->mutex); |
+ return rc; |
+} |
+ |
+#ifndef SQLITE_OMIT_UTF16 |
+/* |
+** Register a new collation sequence with the database handle db. |
+*/ |
+SQLITE_API int sqlite3_create_collation16( |
+ sqlite3* db, |
+ const void *zName, |
+ int enc, |
+ void* pCtx, |
+ int(*xCompare)(void*,int,const void*,int,const void*) |
+){ |
+ int rc = SQLITE_OK; |
+ char *zName8; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ assert( !db->mallocFailed ); |
+ zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); |
+ if( zName8 ){ |
+ rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0); |
+ sqlite3DbFree(db, zName8); |
+ } |
+ rc = sqlite3ApiExit(db, rc); |
+ sqlite3_mutex_leave(db->mutex); |
+ return rc; |
+} |
+#endif /* SQLITE_OMIT_UTF16 */ |
+ |
+/* |
+** Register a collation sequence factory callback with the database handle |
+** db. Replace any previously installed collation sequence factory. |
+*/ |
+SQLITE_API int sqlite3_collation_needed( |
+ sqlite3 *db, |
+ void *pCollNeededArg, |
+ void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) |
+){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ db->xCollNeeded = xCollNeeded; |
+ db->xCollNeeded16 = 0; |
+ db->pCollNeededArg = pCollNeededArg; |
+ sqlite3_mutex_leave(db->mutex); |
+ return SQLITE_OK; |
+} |
+ |
+#ifndef SQLITE_OMIT_UTF16 |
+/* |
+** Register a collation sequence factory callback with the database handle |
+** db. Replace any previously installed collation sequence factory. |
+*/ |
+SQLITE_API int sqlite3_collation_needed16( |
+ sqlite3 *db, |
+ void *pCollNeededArg, |
+ void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) |
+){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ db->xCollNeeded = 0; |
+ db->xCollNeeded16 = xCollNeeded16; |
+ db->pCollNeededArg = pCollNeededArg; |
+ sqlite3_mutex_leave(db->mutex); |
+ return SQLITE_OK; |
+} |
+#endif /* SQLITE_OMIT_UTF16 */ |
+ |
+#ifndef SQLITE_OMIT_DEPRECATED |
+/* |
+** This function is now an anachronism. It used to be used to recover from a |
+** malloc() failure, but SQLite now does this automatically. |
+*/ |
+SQLITE_API int sqlite3_global_recover(void){ |
+ return SQLITE_OK; |
+} |
+#endif |
+ |
+/* |
+** Test to see whether or not the database connection is in autocommit |
+** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on |
+** by default. Autocommit is disabled by a BEGIN statement and reenabled |
+** by the next COMMIT or ROLLBACK. |
+*/ |
+SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ return db->autoCommit; |
+} |
+ |
+/* |
+** The following routines are substitutes for constants SQLITE_CORRUPT, |
+** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error |
+** constants. They serve two purposes: |
+** |
+** 1. Serve as a convenient place to set a breakpoint in a debugger |
+** to detect when version error conditions occurs. |
+** |
+** 2. Invoke sqlite3_log() to provide the source code location where |
+** a low-level error is first detected. |
+*/ |
+static int reportError(int iErr, int lineno, const char *zType){ |
+ sqlite3_log(iErr, "%s at line %d of [%.10s]", |
+ zType, lineno, 20+sqlite3_sourceid()); |
+ return iErr; |
+} |
+SQLITE_PRIVATE int sqlite3CorruptError(int lineno){ |
+ testcase( sqlite3GlobalConfig.xLog!=0 ); |
+ return reportError(SQLITE_CORRUPT, lineno, "database corruption"); |
+} |
+SQLITE_PRIVATE int sqlite3MisuseError(int lineno){ |
+ testcase( sqlite3GlobalConfig.xLog!=0 ); |
+ return reportError(SQLITE_MISUSE, lineno, "misuse"); |
+} |
+SQLITE_PRIVATE int sqlite3CantopenError(int lineno){ |
+ testcase( sqlite3GlobalConfig.xLog!=0 ); |
+ return reportError(SQLITE_CANTOPEN, lineno, "cannot open file"); |
+} |
+#ifdef SQLITE_DEBUG |
+SQLITE_PRIVATE int sqlite3NomemError(int lineno){ |
+ testcase( sqlite3GlobalConfig.xLog!=0 ); |
+ return reportError(SQLITE_NOMEM, lineno, "OOM"); |
+} |
+SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){ |
+ testcase( sqlite3GlobalConfig.xLog!=0 ); |
+ return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error"); |
+} |
+#endif |
+ |
+#ifndef SQLITE_OMIT_DEPRECATED |
+/* |
+** This is a convenience routine that makes sure that all thread-specific |
+** data for this thread has been deallocated. |
+** |
+** SQLite no longer uses thread-specific data so this routine is now a |
+** no-op. It is retained for historical compatibility. |
+*/ |
+SQLITE_API void sqlite3_thread_cleanup(void){ |
+} |
+#endif |
+ |
+/* |
+** Return meta information about a specific column of a database table. |
+** See comment in sqlite3.h (sqlite.h.in) for details. |
+*/ |
+SQLITE_API int sqlite3_table_column_metadata( |
+ sqlite3 *db, /* Connection handle */ |
+ const char *zDbName, /* Database name or NULL */ |
+ const char *zTableName, /* Table name */ |
+ const char *zColumnName, /* Column name */ |
+ char const **pzDataType, /* OUTPUT: Declared data type */ |
+ char const **pzCollSeq, /* OUTPUT: Collation sequence name */ |
+ int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ |
+ int *pPrimaryKey, /* OUTPUT: True if column part of PK */ |
+ int *pAutoinc /* OUTPUT: True if column is auto-increment */ |
+){ |
+ int rc; |
+ char *zErrMsg = 0; |
+ Table *pTab = 0; |
+ Column *pCol = 0; |
+ int iCol = 0; |
+ char const *zDataType = 0; |
+ char const *zCollSeq = 0; |
+ int notnull = 0; |
+ int primarykey = 0; |
+ int autoinc = 0; |
+ |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){ |
+ return SQLITE_MISUSE_BKPT; |
+ } |
+#endif |
+ |
+ /* Ensure the database schema has been loaded */ |
+ sqlite3_mutex_enter(db->mutex); |
+ sqlite3BtreeEnterAll(db); |
+ rc = sqlite3Init(db, &zErrMsg); |
+ if( SQLITE_OK!=rc ){ |
+ goto error_out; |
+ } |
+ |
+ /* Locate the table in question */ |
+ pTab = sqlite3FindTable(db, zTableName, zDbName); |
+ if( !pTab || pTab->pSelect ){ |
+ pTab = 0; |
+ goto error_out; |
+ } |
+ |
+ /* Find the column for which info is requested */ |
+ if( zColumnName==0 ){ |
+ /* Query for existance of table only */ |
+ }else{ |
+ for(iCol=0; iCol<pTab->nCol; iCol++){ |
+ pCol = &pTab->aCol[iCol]; |
+ if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){ |
+ break; |
+ } |
+ } |
+ if( iCol==pTab->nCol ){ |
+ if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){ |
+ iCol = pTab->iPKey; |
+ pCol = iCol>=0 ? &pTab->aCol[iCol] : 0; |
+ }else{ |
+ pTab = 0; |
+ goto error_out; |
+ } |
+ } |
+ } |
+ |
+ /* The following block stores the meta information that will be returned |
+ ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey |
+ ** and autoinc. At this point there are two possibilities: |
+ ** |
+ ** 1. The specified column name was rowid", "oid" or "_rowid_" |
+ ** and there is no explicitly declared IPK column. |
+ ** |
+ ** 2. The table is not a view and the column name identified an |
+ ** explicitly declared column. Copy meta information from *pCol. |
+ */ |
+ if( pCol ){ |
+ zDataType = sqlite3ColumnType(pCol,0); |
+ zCollSeq = pCol->zColl; |
+ notnull = pCol->notNull!=0; |
+ primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0; |
+ autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0; |
+ }else{ |
+ zDataType = "INTEGER"; |
+ primarykey = 1; |
+ } |
+ if( !zCollSeq ){ |
+ zCollSeq = sqlite3StrBINARY; |
+ } |
+ |
+error_out: |
+ sqlite3BtreeLeaveAll(db); |
+ |
+ /* Whether the function call succeeded or failed, set the output parameters |
+ ** to whatever their local counterparts contain. If an error did occur, |
+ ** this has the effect of zeroing all output parameters. |
+ */ |
+ if( pzDataType ) *pzDataType = zDataType; |
+ if( pzCollSeq ) *pzCollSeq = zCollSeq; |
+ if( pNotNull ) *pNotNull = notnull; |
+ if( pPrimaryKey ) *pPrimaryKey = primarykey; |
+ if( pAutoinc ) *pAutoinc = autoinc; |
+ |
+ if( SQLITE_OK==rc && !pTab ){ |
+ sqlite3DbFree(db, zErrMsg); |
+ zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, |
+ zColumnName); |
+ rc = SQLITE_ERROR; |
+ } |
+ sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg); |
+ sqlite3DbFree(db, zErrMsg); |
+ rc = sqlite3ApiExit(db, rc); |
+ sqlite3_mutex_leave(db->mutex); |
+ return rc; |
+} |
+ |
+/* |
+** Sleep for a little while. Return the amount of time slept. |
+*/ |
+SQLITE_API int sqlite3_sleep(int ms){ |
+ sqlite3_vfs *pVfs; |
+ int rc; |
+ pVfs = sqlite3_vfs_find(0); |
+ if( pVfs==0 ) return 0; |
+ |
+ /* This function works in milliseconds, but the underlying OsSleep() |
+ ** API uses microseconds. Hence the 1000's. |
+ */ |
+ rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000); |
+ return rc; |
+} |
+ |
+/* |
+** Enable or disable the extended result codes. |
+*/ |
+SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ db->errMask = onoff ? 0xffffffff : 0xff; |
+ sqlite3_mutex_leave(db->mutex); |
+ return SQLITE_OK; |
+} |
+ |
+/* |
+** Invoke the xFileControl method on a particular database. |
+*/ |
+SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){ |
+ int rc = SQLITE_ERROR; |
+ Btree *pBtree; |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ pBtree = sqlite3DbNameToBtree(db, zDbName); |
+ if( pBtree ){ |
+ Pager *pPager; |
+ sqlite3_file *fd; |
+ sqlite3BtreeEnter(pBtree); |
+ pPager = sqlite3BtreePager(pBtree); |
+ assert( pPager!=0 ); |
+ fd = sqlite3PagerFile(pPager); |
+ assert( fd!=0 ); |
+ if( op==SQLITE_FCNTL_FILE_POINTER ){ |
+ *(sqlite3_file**)pArg = fd; |
+ rc = SQLITE_OK; |
+ }else if( op==SQLITE_FCNTL_VFS_POINTER ){ |
+ *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager); |
+ rc = SQLITE_OK; |
+ }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){ |
+ *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager); |
+ rc = SQLITE_OK; |
+ }else if( fd->pMethods ){ |
+ rc = sqlite3OsFileControl(fd, op, pArg); |
+ }else{ |
+ rc = SQLITE_NOTFOUND; |
+ } |
+ sqlite3BtreeLeave(pBtree); |
+ } |
+ sqlite3_mutex_leave(db->mutex); |
+ return rc; |
+} |
+ |
+/* |
+** Interface to the testing logic. |
+*/ |
+SQLITE_API int sqlite3_test_control(int op, ...){ |
+ int rc = 0; |
+#ifdef SQLITE_UNTESTABLE |
+ UNUSED_PARAMETER(op); |
+#else |
+ va_list ap; |
+ va_start(ap, op); |
+ switch( op ){ |
+ |
+ /* |
+ ** Save the current state of the PRNG. |
+ */ |
+ case SQLITE_TESTCTRL_PRNG_SAVE: { |
+ sqlite3PrngSaveState(); |
+ break; |
+ } |
+ |
+ /* |
+ ** Restore the state of the PRNG to the last state saved using |
+ ** PRNG_SAVE. If PRNG_SAVE has never before been called, then |
+ ** this verb acts like PRNG_RESET. |
+ */ |
+ case SQLITE_TESTCTRL_PRNG_RESTORE: { |
+ sqlite3PrngRestoreState(); |
+ break; |
+ } |
+ |
+ /* |
+ ** Reset the PRNG back to its uninitialized state. The next call |
+ ** to sqlite3_randomness() will reseed the PRNG using a single call |
+ ** to the xRandomness method of the default VFS. |
+ */ |
+ case SQLITE_TESTCTRL_PRNG_RESET: { |
+ sqlite3_randomness(0,0); |
+ break; |
+ } |
+ |
+ /* |
+ ** sqlite3_test_control(BITVEC_TEST, size, program) |
+ ** |
+ ** Run a test against a Bitvec object of size. The program argument |
+ ** is an array of integers that defines the test. Return -1 on a |
+ ** memory allocation error, 0 on success, or non-zero for an error. |
+ ** See the sqlite3BitvecBuiltinTest() for additional information. |
+ */ |
+ case SQLITE_TESTCTRL_BITVEC_TEST: { |
+ int sz = va_arg(ap, int); |
+ int *aProg = va_arg(ap, int*); |
+ rc = sqlite3BitvecBuiltinTest(sz, aProg); |
+ break; |
+ } |
+ |
+ /* |
+ ** sqlite3_test_control(FAULT_INSTALL, xCallback) |
+ ** |
+ ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called, |
+ ** if xCallback is not NULL. |
+ ** |
+ ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0) |
+ ** is called immediately after installing the new callback and the return |
+ ** value from sqlite3FaultSim(0) becomes the return from |
+ ** sqlite3_test_control(). |
+ */ |
+ case SQLITE_TESTCTRL_FAULT_INSTALL: { |
+ /* MSVC is picky about pulling func ptrs from va lists. |
+ ** http://support.microsoft.com/kb/47961 |
+ ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int)); |
+ */ |
+ typedef int(*TESTCALLBACKFUNC_t)(int); |
+ sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t); |
+ rc = sqlite3FaultSim(0); |
+ break; |
+ } |
+ |
+ /* |
+ ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) |
+ ** |
+ ** Register hooks to call to indicate which malloc() failures |
+ ** are benign. |
+ */ |
+ case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { |
+ typedef void (*void_function)(void); |
+ void_function xBenignBegin; |
+ void_function xBenignEnd; |
+ xBenignBegin = va_arg(ap, void_function); |
+ xBenignEnd = va_arg(ap, void_function); |
+ sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); |
+ break; |
+ } |
+ |
+ /* |
+ ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) |
+ ** |
+ ** Set the PENDING byte to the value in the argument, if X>0. |
+ ** Make no changes if X==0. Return the value of the pending byte |
+ ** as it existing before this routine was called. |
+ ** |
+ ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in |
+ ** an incompatible database file format. Changing the PENDING byte |
+ ** while any database connection is open results in undefined and |
+ ** deleterious behavior. |
+ */ |
+ case SQLITE_TESTCTRL_PENDING_BYTE: { |
+ rc = PENDING_BYTE; |
+#ifndef SQLITE_OMIT_WSD |
+ { |
+ unsigned int newVal = va_arg(ap, unsigned int); |
+ if( newVal ) sqlite3PendingByte = newVal; |
+ } |
+#endif |
+ break; |
+ } |
+ |
+ /* |
+ ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) |
+ ** |
+ ** This action provides a run-time test to see whether or not |
+ ** assert() was enabled at compile-time. If X is true and assert() |
+ ** is enabled, then the return value is true. If X is true and |
+ ** assert() is disabled, then the return value is zero. If X is |
+ ** false and assert() is enabled, then the assertion fires and the |
+ ** process aborts. If X is false and assert() is disabled, then the |
+ ** return value is zero. |
+ */ |
+ case SQLITE_TESTCTRL_ASSERT: { |
+ volatile int x = 0; |
+ assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 ); |
+ rc = x; |
+ break; |
+ } |
+ |
+ |
+ /* |
+ ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) |
+ ** |
+ ** This action provides a run-time test to see how the ALWAYS and |
+ ** NEVER macros were defined at compile-time. |
+ ** |
+ ** The return value is ALWAYS(X). |
+ ** |
+ ** The recommended test is X==2. If the return value is 2, that means |
+ ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the |
+ ** default setting. If the return value is 1, then ALWAYS() is either |
+ ** hard-coded to true or else it asserts if its argument is false. |
+ ** The first behavior (hard-coded to true) is the case if |
+ ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second |
+ ** behavior (assert if the argument to ALWAYS() is false) is the case if |
+ ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. |
+ ** |
+ ** The run-time test procedure might look something like this: |
+ ** |
+ ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ |
+ ** // ALWAYS() and NEVER() are no-op pass-through macros |
+ ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ |
+ ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. |
+ ** }else{ |
+ ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. |
+ ** } |
+ */ |
+ case SQLITE_TESTCTRL_ALWAYS: { |
+ int x = va_arg(ap,int); |
+ rc = ALWAYS(x); |
+ break; |
+ } |
+ |
+ /* |
+ ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER); |
+ ** |
+ ** The integer returned reveals the byte-order of the computer on which |
+ ** SQLite is running: |
+ ** |
+ ** 1 big-endian, determined at run-time |
+ ** 10 little-endian, determined at run-time |
+ ** 432101 big-endian, determined at compile-time |
+ ** 123410 little-endian, determined at compile-time |
+ */ |
+ case SQLITE_TESTCTRL_BYTEORDER: { |
+ rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN; |
+ break; |
+ } |
+ |
+ /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) |
+ ** |
+ ** Set the nReserve size to N for the main database on the database |
+ ** connection db. |
+ */ |
+ case SQLITE_TESTCTRL_RESERVE: { |
+ sqlite3 *db = va_arg(ap, sqlite3*); |
+ int x = va_arg(ap,int); |
+ sqlite3_mutex_enter(db->mutex); |
+ sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); |
+ sqlite3_mutex_leave(db->mutex); |
+ break; |
+ } |
+ |
+ /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N) |
+ ** |
+ ** Enable or disable various optimizations for testing purposes. The |
+ ** argument N is a bitmask of optimizations to be disabled. For normal |
+ ** operation N should be 0. The idea is that a test program (like the |
+ ** SQL Logic Test or SLT test module) can run the same SQL multiple times |
+ ** with various optimizations disabled to verify that the same answer |
+ ** is obtained in every case. |
+ */ |
+ case SQLITE_TESTCTRL_OPTIMIZATIONS: { |
+ sqlite3 *db = va_arg(ap, sqlite3*); |
+ db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff); |
+ break; |
+ } |
+ |
+#ifdef SQLITE_N_KEYWORD |
+ /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord) |
+ ** |
+ ** If zWord is a keyword recognized by the parser, then return the |
+ ** number of keywords. Or if zWord is not a keyword, return 0. |
+ ** |
+ ** This test feature is only available in the amalgamation since |
+ ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite |
+ ** is built using separate source files. |
+ */ |
+ case SQLITE_TESTCTRL_ISKEYWORD: { |
+ const char *zWord = va_arg(ap, const char*); |
+ int n = sqlite3Strlen30(zWord); |
+ rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0; |
+ break; |
+ } |
+#endif |
+ |
+ /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree); |
+ ** |
+ ** Pass pFree into sqlite3ScratchFree(). |
+ ** If sz>0 then allocate a scratch buffer into pNew. |
+ */ |
+ case SQLITE_TESTCTRL_SCRATCHMALLOC: { |
+ void *pFree, **ppNew; |
+ int sz; |
+ sz = va_arg(ap, int); |
+ ppNew = va_arg(ap, void**); |
+ pFree = va_arg(ap, void*); |
+ if( sz ) *ppNew = sqlite3ScratchMalloc(sz); |
+ sqlite3ScratchFree(pFree); |
+ break; |
+ } |
+ |
+ /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); |
+ ** |
+ ** If parameter onoff is non-zero, configure the wrappers so that all |
+ ** subsequent calls to localtime() and variants fail. If onoff is zero, |
+ ** undo this setting. |
+ */ |
+ case SQLITE_TESTCTRL_LOCALTIME_FAULT: { |
+ sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); |
+ break; |
+ } |
+ |
+ /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int); |
+ ** |
+ ** Set or clear a flag that indicates that the database file is always well- |
+ ** formed and never corrupt. This flag is clear by default, indicating that |
+ ** database files might have arbitrary corruption. Setting the flag during |
+ ** testing causes certain assert() statements in the code to be activated |
+ ** that demonstrat invariants on well-formed database files. |
+ */ |
+ case SQLITE_TESTCTRL_NEVER_CORRUPT: { |
+ sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int); |
+ break; |
+ } |
+ |
+ /* Set the threshold at which OP_Once counters reset back to zero. |
+ ** By default this is 0x7ffffffe (over 2 billion), but that value is |
+ ** too big to test in a reasonable amount of time, so this control is |
+ ** provided to set a small and easily reachable reset value. |
+ */ |
+ case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: { |
+ sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int); |
+ break; |
+ } |
+ |
+ /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr); |
+ ** |
+ ** Set the VDBE coverage callback function to xCallback with context |
+ ** pointer ptr. |
+ */ |
+ case SQLITE_TESTCTRL_VDBE_COVERAGE: { |
+#ifdef SQLITE_VDBE_COVERAGE |
+ typedef void (*branch_callback)(void*,int,u8,u8); |
+ sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback); |
+ sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*); |
+#endif |
+ break; |
+ } |
+ |
+ /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */ |
+ case SQLITE_TESTCTRL_SORTER_MMAP: { |
+ sqlite3 *db = va_arg(ap, sqlite3*); |
+ db->nMaxSorterMmap = va_arg(ap, int); |
+ break; |
+ } |
+ |
+ /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT); |
+ ** |
+ ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if |
+ ** not. |
+ */ |
+ case SQLITE_TESTCTRL_ISINIT: { |
+ if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR; |
+ break; |
+ } |
+ |
+ /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum); |
+ ** |
+ ** This test control is used to create imposter tables. "db" is a pointer |
+ ** to the database connection. dbName is the database name (ex: "main" or |
+ ** "temp") which will receive the imposter. "onOff" turns imposter mode on |
+ ** or off. "tnum" is the root page of the b-tree to which the imposter |
+ ** table should connect. |
+ ** |
+ ** Enable imposter mode only when the schema has already been parsed. Then |
+ ** run a single CREATE TABLE statement to construct the imposter table in |
+ ** the parsed schema. Then turn imposter mode back off again. |
+ ** |
+ ** If onOff==0 and tnum>0 then reset the schema for all databases, causing |
+ ** the schema to be reparsed the next time it is needed. This has the |
+ ** effect of erasing all imposter tables. |
+ */ |
+ case SQLITE_TESTCTRL_IMPOSTER: { |
+ sqlite3 *db = va_arg(ap, sqlite3*); |
+ sqlite3_mutex_enter(db->mutex); |
+ db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*)); |
+ db->init.busy = db->init.imposterTable = va_arg(ap,int); |
+ db->init.newTnum = va_arg(ap,int); |
+ if( db->init.busy==0 && db->init.newTnum>0 ){ |
+ sqlite3ResetAllSchemasOfConnection(db); |
+ } |
+ sqlite3_mutex_leave(db->mutex); |
+ break; |
+ } |
+ } |
+ va_end(ap); |
+#endif /* SQLITE_UNTESTABLE */ |
+ return rc; |
+} |
+ |
+/* |
+** This is a utility routine, useful to VFS implementations, that checks |
+** to see if a database file was a URI that contained a specific query |
+** parameter, and if so obtains the value of the query parameter. |
+** |
+** The zFilename argument is the filename pointer passed into the xOpen() |
+** method of a VFS implementation. The zParam argument is the name of the |
+** query parameter we seek. This routine returns the value of the zParam |
+** parameter if it exists. If the parameter does not exist, this routine |
+** returns a NULL pointer. |
+*/ |
+SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){ |
+ if( zFilename==0 || zParam==0 ) return 0; |
+ zFilename += sqlite3Strlen30(zFilename) + 1; |
+ while( zFilename[0] ){ |
+ int x = strcmp(zFilename, zParam); |
+ zFilename += sqlite3Strlen30(zFilename) + 1; |
+ if( x==0 ) return zFilename; |
+ zFilename += sqlite3Strlen30(zFilename) + 1; |
+ } |
+ return 0; |
+} |
+ |
+/* |
+** Return a boolean value for a query parameter. |
+*/ |
+SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){ |
+ const char *z = sqlite3_uri_parameter(zFilename, zParam); |
+ bDflt = bDflt!=0; |
+ return z ? sqlite3GetBoolean(z, bDflt) : bDflt; |
+} |
+ |
+/* |
+** Return a 64-bit integer value for a query parameter. |
+*/ |
+SQLITE_API sqlite3_int64 sqlite3_uri_int64( |
+ const char *zFilename, /* Filename as passed to xOpen */ |
+ const char *zParam, /* URI parameter sought */ |
+ sqlite3_int64 bDflt /* return if parameter is missing */ |
+){ |
+ const char *z = sqlite3_uri_parameter(zFilename, zParam); |
+ sqlite3_int64 v; |
+ if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){ |
+ bDflt = v; |
+ } |
+ return bDflt; |
+} |
+ |
+/* |
+** Return the Btree pointer identified by zDbName. Return NULL if not found. |
+*/ |
+SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){ |
+ int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0; |
+ return iDb<0 ? 0 : db->aDb[iDb].pBt; |
+} |
+ |
+/* |
+** Return the filename of the database associated with a database |
+** connection. |
+*/ |
+SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){ |
+ Btree *pBt; |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return 0; |
+ } |
+#endif |
+ pBt = sqlite3DbNameToBtree(db, zDbName); |
+ return pBt ? sqlite3BtreeGetFilename(pBt) : 0; |
+} |
+ |
+/* |
+** Return 1 if database is read-only or 0 if read/write. Return -1 if |
+** no such database exists. |
+*/ |
+SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){ |
+ Btree *pBt; |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ (void)SQLITE_MISUSE_BKPT; |
+ return -1; |
+ } |
+#endif |
+ pBt = sqlite3DbNameToBtree(db, zDbName); |
+ return pBt ? sqlite3BtreeIsReadonly(pBt) : -1; |
+} |
+ |
+#ifdef SQLITE_ENABLE_SNAPSHOT |
+/* |
+** Obtain a snapshot handle for the snapshot of database zDb currently |
+** being read by handle db. |
+*/ |
+SQLITE_API int sqlite3_snapshot_get( |
+ sqlite3 *db, |
+ const char *zDb, |
+ sqlite3_snapshot **ppSnapshot |
+){ |
+ int rc = SQLITE_ERROR; |
+#ifndef SQLITE_OMIT_WAL |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ return SQLITE_MISUSE_BKPT; |
+ } |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ |
+ if( db->autoCommit==0 ){ |
+ int iDb = sqlite3FindDbName(db, zDb); |
+ if( iDb==0 || iDb>1 ){ |
+ Btree *pBt = db->aDb[iDb].pBt; |
+ if( 0==sqlite3BtreeIsInTrans(pBt) ){ |
+ rc = sqlite3BtreeBeginTrans(pBt, 0); |
+ if( rc==SQLITE_OK ){ |
+ rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot); |
+ } |
+ } |
+ } |
+ } |
+ |
+ sqlite3_mutex_leave(db->mutex); |
+#endif /* SQLITE_OMIT_WAL */ |
+ return rc; |
+} |
+ |
+/* |
+** Open a read-transaction on the snapshot idendified by pSnapshot. |
+*/ |
+SQLITE_API int sqlite3_snapshot_open( |
+ sqlite3 *db, |
+ const char *zDb, |
+ sqlite3_snapshot *pSnapshot |
+){ |
+ int rc = SQLITE_ERROR; |
+#ifndef SQLITE_OMIT_WAL |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ return SQLITE_MISUSE_BKPT; |
+ } |
+#endif |
+ sqlite3_mutex_enter(db->mutex); |
+ if( db->autoCommit==0 ){ |
+ int iDb; |
+ iDb = sqlite3FindDbName(db, zDb); |
+ if( iDb==0 || iDb>1 ){ |
+ Btree *pBt = db->aDb[iDb].pBt; |
+ if( 0==sqlite3BtreeIsInReadTrans(pBt) ){ |
+ rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot); |
+ if( rc==SQLITE_OK ){ |
+ rc = sqlite3BtreeBeginTrans(pBt, 0); |
+ sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0); |
+ } |
+ } |
+ } |
+ } |
+ |
+ sqlite3_mutex_leave(db->mutex); |
+#endif /* SQLITE_OMIT_WAL */ |
+ return rc; |
+} |
+ |
+/* |
+** Recover as many snapshots as possible from the wal file associated with |
+** schema zDb of database db. |
+*/ |
+SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){ |
+ int rc = SQLITE_ERROR; |
+ int iDb; |
+#ifndef SQLITE_OMIT_WAL |
+ |
+#ifdef SQLITE_ENABLE_API_ARMOR |
+ if( !sqlite3SafetyCheckOk(db) ){ |
+ return SQLITE_MISUSE_BKPT; |
+ } |
+#endif |
+ |
+ sqlite3_mutex_enter(db->mutex); |
+ iDb = sqlite3FindDbName(db, zDb); |
+ if( iDb==0 || iDb>1 ){ |
+ Btree *pBt = db->aDb[iDb].pBt; |
+ if( 0==sqlite3BtreeIsInReadTrans(pBt) ){ |
+ rc = sqlite3BtreeBeginTrans(pBt, 0); |
+ if( rc==SQLITE_OK ){ |
+ rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt)); |
+ sqlite3BtreeCommit(pBt); |
+ } |
+ } |
+ } |
+ sqlite3_mutex_leave(db->mutex); |
+#endif /* SQLITE_OMIT_WAL */ |
+ return rc; |
+} |
+ |
+/* |
+** Free a snapshot handle obtained from sqlite3_snapshot_get(). |
+*/ |
+SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){ |
+ sqlite3_free(pSnapshot); |
+} |
+#endif /* SQLITE_ENABLE_SNAPSHOT */ |
+ |
+/************** End of main.c ************************************************/ |
+/************** Begin file notify.c ******************************************/ |
+/* |
+** 2009 March 3 |
+** |
+** 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 file contains the implementation of the sqlite3_unlock_notify() |
+** API method and its associated functionality. |
+*/ |
+/* #include "sqliteInt.h" */ |
+/* #include "btreeInt.h" */ |
+ |
+/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */ |
+#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY |
+ |
+/* |
+** Public interfaces: |
+** |
+** sqlite3ConnectionBlocked() |
+** sqlite3ConnectionUnlocked() |
+** sqlite3ConnectionClosed() |
+** sqlite3_unlock_notify() |
+*/ |
+ |
+#define assertMutexHeld() \ |
+ assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ) |
+ |
+/* |
+** Head of a linked list of all sqlite3 objects created by this process |
+** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection |
+** is not NULL. This variable may only accessed while the STATIC_MASTER |
+** mutex is held. |
+*/ |
+static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0; |
+ |
+#ifndef NDEBUG |
+/* |
+** This function is a complex assert() that verifies the following |
+** properties of the blocked connections list: |
+** |
+** 1) Each entry in the list has a non-NULL value for either |
+** pUnlockConnection or pBlockingConnection, or both. |
+** |
+** 2) All entries in the list that share a common value for |
+** xUnlockNotify are grouped together. |
+** |
+** 3) If the argument db is not NULL, then none of the entries in the |
+** blocked connections list have pUnlockConnection or pBlockingConnection |
+** set to db. This is used when closing connection db. |
+*/ |
+static void checkListProperties(sqlite3 *db){ |
+ sqlite3 *p; |
+ for(p=sqlite3BlockedList; p; p=p->pNextBlocked){ |
+ int seen = 0; |
+ sqlite3 *p2; |
+ |
+ /* Verify property (1) */ |
+ assert( p->pUnlockConnection || p->pBlockingConnection ); |
+ |
+ /* Verify property (2) */ |
+ for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){ |
+ if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1; |
+ assert( p2->xUnlockNotify==p->xUnlockNotify || !seen ); |
+ assert( db==0 || p->pUnlockConnection!=db ); |
+ assert( db==0 || p->pBlockingConnection!=db ); |
+ } |
+ } |
+} |
+#else |
+# define checkListProperties(x) |
+#endif |
+ |
+/* |
+** Remove connection db from the blocked connections list. If connection |
+** db is not currently a part of the list, this function is a no-op. |
+*/ |
+static void removeFromBlockedList(sqlite3 *db){ |
+ sqlite3 **pp; |
+ assertMutexHeld(); |
+ for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){ |
+ if( *pp==db ){ |
+ *pp = (*pp)->pNextBlocked; |
+ break; |
+ } |
+ } |
+} |
+ |
+/* |
+** Add connection db to the blocked connections list. It is assumed |
+** that it is not already a part of the list. |
+*/ |
+static void addToBlockedList(sqlite3 *db){ |
+ sqlite3 **pp; |
+ assertMutexHeld(); |
+ for( |
+ pp=&sqlite3BlockedList; |
+ *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; |
+ pp=&(*pp)->pNextBlocked |
+ ); |
+ db->pNextBlocked = *pp; |
+ *pp = db; |
+} |
+ |
+/* |
+** Obtain the STATIC_MASTER mutex. |
+*/ |
+static void enterMutex(void){ |
+ sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); |
+ checkListProperties(0); |
+} |
+ |
+/* |
+** Release the STATIC_MASTER mutex. |
+*/ |
+static void leaveMutex(void){ |
+ assertMutexHeld(); |
+ checkListProperties(0); |
+ sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); |
+} |
+ |
+/* |
+** Register an unlock-notify callback. |
+** |
+** This is called after connection "db" has attempted some operation |
+** but has received an SQLITE_LOCKED error because another connection |
+** (call it pOther) in the same process was busy using the same shared |
+** cache. pOther is found by looking at db->pBlockingConnection. |
+** |
+** If there is no blocking connection, the callback is invoked immediately, |
+** before this routine returns. |
+** |
+** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate |
+** a deadlock. |
+** |
+** Otherwise, make arrangements to invoke xNotify when pOther drops |
+** its locks. |
+** |
+** Each call to this routine overrides any prior callbacks registered |
+** on the same "db". If xNotify==0 then any prior callbacks are immediately |
+** cancelled. |
+*/ |
+SQLITE_API int sqlite3_unlock_notify( |
+ sqlite3 *db, |
+ void (*xNotify)(void **, int), |
+ void *pArg |
+){ |
+ int rc = SQLITE_OK; |
+ |
+ sqlite3_mutex_enter(db->mutex); |
+ enterMutex(); |
+ |
+ if( xNotify==0 ){ |
+ removeFromBlockedList(db); |
+ db->pBlockingConnection = 0; |
+ db->pUnlockConnection = 0; |
+ db->xUnlockNotify = 0; |
+ db->pUnlockArg = 0; |
+ }else if( 0==db->pBlockingConnection ){ |
+ /* The blocking transaction has been concluded. Or there never was a |
+ ** blocking transaction. In either case, invoke the notify callback |
+ ** immediately. |
+ */ |
+ xNotify(&pArg, 1); |
+ }else{ |
+ sqlite3 *p; |
+ |
+ for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){} |
+ if( p ){ |
+ rc = SQLITE_LOCKED; /* Deadlock detected. */ |
+ }else{ |
+ db->pUnlockConnection = db->pBlockingConnection; |
+ db->xUnlockNotify = xNotify; |
+ db->pUnlockArg = pArg; |
+ removeFromBlockedList(db); |
+ addToBlockedList(db); |
+ } |
+ } |
+ |
+ leaveMutex(); |
+ assert( !db->mallocFailed ); |
+ sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0)); |
+ sqlite3_mutex_leave(db->mutex); |
+ return rc; |
+} |
+ |
+/* |
+** This function is called while stepping or preparing a statement |
+** associated with connection db. The operation will return SQLITE_LOCKED |
+** to the user because it requires a lock that will not be available |
+** until connection pBlocker concludes its current transaction. |
+*/ |
+SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){ |
+ enterMutex(); |
+ if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){ |
+ addToBlockedList(db); |
+ } |
+ db->pBlockingConnection = pBlocker; |
+ leaveMutex(); |
+} |
+ |
+/* |
+** This function is called when |
+** the transaction opened by database db has just finished. Locks held |
+** by database connection db have been released. |
+** |
+** This function loops through each entry in the blocked connections |
+** list and does the following: |
+** |
+** 1) If the sqlite3.pBlockingConnection member of a list entry is |
+** set to db, then set pBlockingConnection=0. |
+** |
+** 2) If the sqlite3.pUnlockConnection member of a list entry is |
+** set to db, then invoke the configured unlock-notify callback and |
+** set pUnlockConnection=0. |
+** |
+** 3) If the two steps above mean that pBlockingConnection==0 and |
+** pUnlockConnection==0, remove the entry from the blocked connections |
+** list. |
+*/ |
+SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){ |
+ void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */ |
+ int nArg = 0; /* Number of entries in aArg[] */ |
+ sqlite3 **pp; /* Iterator variable */ |
+ void **aArg; /* Arguments to the unlock callback */ |
+ void **aDyn = 0; /* Dynamically allocated space for aArg[] */ |
+ void *aStatic[16]; /* Starter space for aArg[]. No malloc required */ |
+ |
+ aArg = aStatic; |
+ enterMutex(); /* Enter STATIC_MASTER mutex */ |
+ |
+ /* This loop runs once for each entry in the blocked-connections list. */ |
+ for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){ |
+ sqlite3 *p = *pp; |
+ |
+ /* Step 1. */ |
+ if( p->pBlockingConnection==db ){ |
+ p->pBlockingConnection = 0; |
+ } |
+ |
+ /* Step 2. */ |
+ if( p->pUnlockConnection==db ){ |
+ assert( p->xUnlockNotify ); |
+ if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){ |
+ xUnlockNotify(aArg, nArg); |
+ nArg = 0; |
+ } |
+ |
+ sqlite3BeginBenignMalloc(); |
+ assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) ); |
+ assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn ); |
+ if( (!aDyn && nArg==(int)ArraySize(aStatic)) |
+ || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*))) |
+ ){ |
+ /* The aArg[] array needs to grow. */ |
+ void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2); |
+ if( pNew ){ |
+ memcpy(pNew, aArg, nArg*sizeof(void *)); |
+ sqlite3_free(aDyn); |
+ aDyn = aArg = pNew; |
+ }else{ |
+ /* This occurs when the array of context pointers that need to |
+ ** be passed to the unlock-notify callback is larger than the |
+ ** aStatic[] array allocated on the stack and the attempt to |
+ ** allocate a larger array from the heap has failed. |
+ ** |
+ ** This is a difficult situation to handle. Returning an error |
+ ** code to the caller is insufficient, as even if an error code |
+ ** is returned the transaction on connection db will still be |
+ ** closed and the unlock-notify callbacks on blocked connections |
+ ** will go unissued. This might cause the application to wait |
+ ** indefinitely for an unlock-notify callback that will never |
+ ** arrive. |
+ ** |
+ ** Instead, invoke the unlock-notify callback with the context |
+ ** array already accumulated. We can then clear the array and |
+ ** begin accumulating any further context pointers without |
+ ** requiring any dynamic allocation. This is sub-optimal because |
+ ** it means that instead of one callback with a large array of |
+ ** context pointers the application will receive two or more |
+ ** callbacks with smaller arrays of context pointers, which will |
+ ** reduce the applications ability to prioritize multiple |
+ ** connections. But it is the best that can be done under the |
+ ** circumstances. |
+ */ |
+ xUnlockNotify(aArg, nArg); |
+ nArg = 0; |
+ } |
+ } |
+ sqlite3EndBenignMalloc(); |
+ |
+ aArg[nArg++] = p->pUnlockArg; |
+ xUnlockNotify = p->xUnlockNotify; |
+ p->pUnlockConnection = 0; |
+ p->xUnlockNotify = 0; |
+ p->pUnlockArg = 0; |
+ } |
+ |
+ /* Step 3. */ |
+ if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){ |
+ /* Remove connection p from the blocked connections list. */ |
+ *pp = p->pNextBlocked; |
+ p->pNextBlocked = 0; |
+ }else{ |
+ pp = &p->pNextBlocked; |
+ } |
+ } |
+ |
+ if( nArg!=0 ){ |
+ xUnlockNotify(aArg, nArg); |
+ } |
+ sqlite3_free(aDyn); |
+ leaveMutex(); /* Leave STATIC_MASTER mutex */ |
+} |
+ |
+/* |
+** This is called when the database connection passed as an argument is |
+** being closed. The connection is removed from the blocked list. |
+*/ |
+SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){ |
+ sqlite3ConnectionUnlocked(db); |
+ enterMutex(); |
+ removeFromBlockedList(db); |
+ checkListProperties(db); |
+ leaveMutex(); |
+} |
+#endif |
+ |
+/************** End of notify.c **********************************************/ |
+ |
+/* Chain include. */ |
+#include "sqlite3.07.c" |