/Community.CsharpSqlite/src/where_c.cs
C# | 5843 lines | 3727 code | 271 blank | 1845 comment | 1241 complexity | a17d6f46b8cab672bc870d075d46415f MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- using System;
- using System.Diagnostics;
- using System.Text;
- using Bitmask = System.UInt64;
- using i16 = System.Int16;
- using u8 = System.Byte;
- using u16 = System.UInt16;
- using u32 = System.UInt32;
- using sqlite3_int64 = System.Int64;
- namespace Community.CsharpSqlite
- {
- using sqlite3_value = Sqlite3.Mem;
- public partial class Sqlite3
- {
- /*
- ** 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".
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908ecd7
- **
- *************************************************************************
- */
- //#include "sqliteInt.h"
- /*
- ** Trace output macros
- */
- #if (SQLITE_TEST) || (SQLITE_DEBUG)
- static bool sqlite3WhereTrace = false;
- #endif
- #if (SQLITE_TEST) && (SQLITE_DEBUG) && TRACE
- //# define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
- static void WHERETRACE( string X, params object[] ap ) { if ( sqlite3WhereTrace ) sqlite3DebugPrintf( X, ap ); }
- #else
- //# define WHERETRACE(X)
- static void WHERETRACE( string X, params object[] ap )
- {
- }
- #endif
- /* Forward reference
- */
- //typedef struct WhereClause WhereClause;
- //typedef struct WhereMaskSet WhereMaskSet;
- //typedef struct WhereOrInfo WhereOrInfo;
- //typedef struct WhereAndInfo WhereAndInfo;
- //typedef struct WhereCost WhereCost;
- /*
- ** The query generator uses an array of instances of this structure to
- ** help it analyze the subexpressions of the WHERE clause. Each WHERE
- ** clause subexpression is separated from the others by AND operators,
- ** 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 as the TERM_ORINFO set and eOperator==WO_OR
- ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
- ** is collected about the
- **
- ** If a term in the WHERE clause does not match either of the two previous
- ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
- ** to the original subexpression content and wtFlags is set up appropriately
- ** but no other fields in the WhereTerm object are meaningful.
- **
- ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
- ** but they do so indirectly. A single WhereMaskSet structure translates
- ** cursor number into bits and the translated bit is stored in the prereq
- ** fields. The translation is used in order to maximize the number of
- ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
- ** spread out over the non-negative integers. For example, the cursor
- ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
- ** translates these sparse cursor numbers into consecutive integers
- ** beginning with 0 in order to make the best possible use of the available
- ** bits in the Bitmask. So, in the example above, the cursor numbers
- ** would be mapped into integers 0 through 7.
- **
- ** The number of terms in a join is limited by the number of bits
- ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
- ** is only able to process joins with 64 or fewer tables.
- */
- //typedef struct WhereTerm WhereTerm;
- public class WhereTerm
- {
- public Expr pExpr; /* Pointer to the subexpression that is this term */
- public int iParent; /* Disable pWC.a[iParent] when this term disabled */
- public int leftCursor; /* Cursor number of X in "X <op> <expr>" */
- public class _u
- {
- public int leftColumn; /* Column number of X in "X <op> <expr>" */
- public WhereOrInfo pOrInfo; /* Extra information if eOperator==WO_OR */
- public WhereAndInfo pAndInfo; /* Extra information if eOperator==WO_AND */
- }
- public _u u = new _u();
- public u16 eOperator; /* A WO_xx value describing <op> */
- public u8 wtFlags; /* TERM_xxx bit flags. See below */
- public u8 nChild; /* Number of children that must disable us */
- public WhereClause pWC; /* The clause this term is part of */
- public Bitmask prereqRight; /* Bitmask of tables used by pExpr.pRight */
- public Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
- };
- /*
- ** Allowed values of WhereTerm.wtFlags
- */
- //#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, ref 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 */
- #if SQLITE_ENABLE_STAT2
- //# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
- #else
- //# define TERM_VNULL 0x00 /* Disabled if not using stat2 */
- #endif
- const int TERM_DYNAMIC = 0x01; /* Need to call sqlite3ExprDelete(db, ref pExpr) */
- const int TERM_VIRTUAL = 0x02; /* Added by the optimizer. Do not code */
- const int TERM_CODED = 0x04; /* This term is already coded */
- const int TERM_COPIED = 0x08; /* Has a child */
- const int TERM_ORINFO = 0x10; /* Need to free the WhereTerm.u.pOrInfo object */
- const int TERM_ANDINFO = 0x20; /* Need to free the WhereTerm.u.pAndInfo obj */
- const int TERM_OR_OK = 0x40; /* Used during OR-clause processing */
- #if SQLITE_ENABLE_STAT2
- const int TERM_VNULL = 0x80; /* Manufactured x>NULL or x<=NULL term */
- #else
- const int TERM_VNULL = 0x00; /* Disabled if not using stat2 */
- #endif
- /*
- ** An instance of the following structure holds all information about a
- ** WHERE clause. Mostly this is a container for one or more WhereTerms.
- */
- public class WhereClause
- {
- public Parse pParse; /* The parser context */
- public WhereMaskSet pMaskSet; /* Mapping of table cursor numbers to bitmasks */
- public Bitmask vmask; /* Bitmask identifying virtual table cursors */
- public u8 op; /* Split operator. TK_AND or TK_OR */
- public int nTerm; /* Number of terms */
- public int nSlot; /* Number of entries in a[] */
- public WhereTerm[] a; /* Each a[] describes a term of the WHERE cluase */
- #if (SQLITE_SMALL_STACK)
- public WhereTerm[] aStatic = new WhereTerm[1]; /* Initial static space for a[] */
- #else
- public WhereTerm[] aStatic = new WhereTerm[8]; /* Initial static space for a[] */
- #endif
- public void CopyTo( WhereClause wc )
- {
- wc.pParse = this.pParse;
- wc.pMaskSet = new WhereMaskSet();
- this.pMaskSet.CopyTo( wc.pMaskSet );
- wc.op = this.op;
- wc.nTerm = this.nTerm;
- wc.nSlot = this.nSlot;
- wc.a = (WhereTerm[])this.a.Clone();
- wc.aStatic = (WhereTerm[])this.aStatic.Clone();
- }
- };
- /*
- ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
- ** a dynamically allocated instance of the following structure.
- */
- public class WhereOrInfo
- {
- public WhereClause wc = new WhereClause();/* Decomposition into subterms */
- public 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.
- */
- public class WhereAndInfo
- {
- public WhereClause wc = new WhereClause(); /* 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.
- */
- public class WhereMaskSet
- {
- public int n; /* Number of Debug.Assigned cursor values */
- public int[] ix = new int[BMS]; /* Cursor Debug.Assigned to each bit */
- public void CopyTo( WhereMaskSet wms )
- {
- wms.n = this.n;
- wms.ix = (int[])this.ix.Clone();
- }
- }
- /*
- ** A WhereCost object records a lookup strategy and the estimated
- ** cost of pursuing that strategy.
- */
- public class WhereCost
- {
- public WherePlan plan = new WherePlan();/* The lookup strategy */
- public double rCost; /* Overall cost of pursuing this search strategy */
- public Bitmask used; /* Bitmask of cursors used by this plan */
- public void Clear()
- {
- plan.Clear();
- rCost = 0;
- used = 0;
- }
- };
- /*
- ** Bitmasks for the operators that indices are able to exploit. An
- ** OR-ed combination of these values can be used when searching for
- ** terms in the where clause.
- */
- //#define WO_IN 0x001
- //#define WO_EQ 0x002
- //#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
- //#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
- //#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
- //#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
- //#define WO_MATCH 0x040
- //#define WO_ISNULL 0x080
- //#define WO_OR 0x100 /* Two or more OR-connected terms */
- //#define WO_AND 0x200 /* Two or more AND-connected terms */
- //#define WO_NOOP 0x800 /* This term does not restrict search space */
- //#define WO_ALL 0xfff /* Mask of all possible WO_* values */
- //#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
- const int WO_IN = 0x001;
- const int WO_EQ = 0x002;
- const int WO_LT = ( WO_EQ << ( TK_LT - TK_EQ ) );
- const int WO_LE = ( WO_EQ << ( TK_LE - TK_EQ ) );
- const int WO_GT = ( WO_EQ << ( TK_GT - TK_EQ ) );
- const int WO_GE = ( WO_EQ << ( TK_GE - TK_EQ ) );
- const int WO_MATCH = 0x040;
- const int WO_ISNULL = 0x080;
- const int WO_OR = 0x100; /* Two or more OR-connected terms */
- const int WO_AND = 0x200; /* Two or more AND-connected terms */
- const int WO_NOOP = 0x800; /* This term does not restrict search space */
- const int WO_ALL = 0xfff; /* Mask of all possible WO_* values */
- const int WO_SINGLE = 0x0ff; /* Mask of all non-compound WO_* values */
- /*
- ** Value for wsFlags returned by bestIndex() and stored in
- ** WhereLevel.wsFlags. These flags determine which search
- ** strategies are appropriate.
- **
- ** The least significant 12 bits is reserved as a mask for WO_ values above.
- ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
- ** But if the table is the right table of a left join, WhereLevel.wsFlags
- ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
- ** the "op" parameter to findTerm when we are resolving equality constraints.
- ** ISNULL constraints will then not be used on the right table of a left
- ** join. Tickets #2177 and #2189.
- */
- //#define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
- //#define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
- //#define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
- //#define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
- //#define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
- //#define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
- //#define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
- //#define WHERE_IN_ABLE 0x000f1000 /* Able to support an IN operator */
- //#define WHERE_NOT_FULLSCAN 0x100f3000 /* Does not do a full table scan */
- //#define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
- //#define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
- //#define WHERE_BOTH_LIMIT 0x00300000 /* Both x>EXPR and x<EXPR */
- //#define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
- //#define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
- //#define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
- //#define WHERE_UNIQUE 0x04000000 /* Selects no more than one row */
- //#define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
- //#define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
- //#define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
- const int WHERE_ROWID_EQ = 0x00001000;
- const int WHERE_ROWID_RANGE = 0x00002000;
- const int WHERE_COLUMN_EQ = 0x00010000;
- const int WHERE_COLUMN_RANGE = 0x00020000;
- const int WHERE_COLUMN_IN = 0x00040000;
- const int WHERE_COLUMN_NULL = 0x00080000;
- const int WHERE_INDEXED = 0x000f0000;
- const int WHERE_IN_ABLE = 0x000f1000;
- const int WHERE_NOT_FULLSCAN = 0x100f3000;
- const int WHERE_TOP_LIMIT = 0x00100000;
- const int WHERE_BTM_LIMIT = 0x00200000;
- const int WHERE_BOTH_LIMIT = 0x00300000;
- const int WHERE_IDX_ONLY = 0x00800000;
- const int WHERE_ORDERBY = 0x01000000;
- const int WHERE_REVERSE = 0x02000000;
- const int WHERE_UNIQUE = 0x04000000;
- const int WHERE_VIRTUALTABLE = 0x08000000;
- const int WHERE_MULTI_OR = 0x10000000;
- const int WHERE_TEMP_INDEX = 0x20000000;
- /*
- ** Initialize a preallocated WhereClause structure.
- */
- static void whereClauseInit(
- WhereClause pWC, /* The WhereClause to be initialized */
- Parse pParse, /* The parsing context */
- WhereMaskSet pMaskSet /* Mapping from table cursor numbers to bitmasks */
- )
- {
- pWC.pParse = pParse;
- pWC.pMaskSet = pMaskSet;
- pWC.nTerm = 0;
- pWC.nSlot = ArraySize( pWC.aStatic ) - 1;
- pWC.a = pWC.aStatic;
- pWC.vmask = 0;
- }
- /* Forward reference */
- //static void whereClauseClear(WhereClause);
- /*
- ** Deallocate all memory Debug.Associated with a WhereOrInfo object.
- */
- static void whereOrInfoDelete( sqlite3 db, WhereOrInfo p )
- {
- whereClauseClear( p.wc );
- sqlite3DbFree( db, ref p );
- }
- /*
- ** Deallocate all memory Debug.Associated with a WhereAndInfo object.
- */
- static void whereAndInfoDelete( sqlite3 db, WhereAndInfo p )
- {
- whereClauseClear( p.wc );
- sqlite3DbFree( db, ref p );
- }
- /*
- ** Deallocate a WhereClause structure. The WhereClause structure
- ** itself is not freed. This routine is the inverse of whereClauseInit().
- */
- static void whereClauseClear( WhereClause pWC )
- {
- int i;
- WhereTerm a;
- sqlite3 db = pWC.pParse.db;
- for ( i = pWC.nTerm - 1; i >= 0; i-- )//, a++)
- {
- a = pWC.a[i];
- if ( ( a.wtFlags & TERM_DYNAMIC ) != 0 )
- {
- sqlite3ExprDelete( db, ref a.pExpr );
- }
- if ( ( a.wtFlags & TERM_ORINFO ) != 0 )
- {
- whereOrInfoDelete( db, a.u.pOrInfo );
- }
- else if ( ( a.wtFlags & TERM_ANDINFO ) != 0 )
- {
- whereAndInfoDelete( db, a.u.pAndInfo );
- }
- }
- if ( pWC.a != pWC.aStatic )
- {
- sqlite3DbFree( db, ref pWC.a );
- }
- }
- /*
- ** Add a single new WhereTerm entry to the WhereClause object pWC.
- ** The new WhereTerm object is constructed from Expr p and with wtFlags.
- ** The index in pWC.a[] of the new WhereTerm is returned on success.
- ** 0 is returned if the new WhereTerm could not be added due to a memory
- ** allocation error. The memory allocation failure will be recorded in
- ** the db.mallocFailed flag so that higher-level functions can detect it.
- **
- ** This routine will increase the size of the pWC.a[] array as necessary.
- **
- ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
- ** for freeing the expression p is Debug.Assumed by the WhereClause object pWC.
- ** This is true even if this routine fails to allocate a new WhereTerm.
- **
- ** WARNING: This routine might reallocate the space used to store
- ** WhereTerms. All pointers to WhereTerms should be invalidated after
- ** calling this routine. Such pointers may be reinitialized by referencing
- ** the pWC.a[] array.
- */
- static int whereClauseInsert( WhereClause pWC, Expr p, u8 wtFlags )
- {
- WhereTerm pTerm;
- int idx;
- testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
- if ( pWC.nTerm >= pWC.nSlot )
- {
- //WhereTerm pOld = pWC.a;
- //sqlite3 db = pWC.pParse.db;
- Array.Resize( ref pWC.a, pWC.nSlot * 2 );
- //pWC.a = sqlite3DbMallocRaw(db, sizeof(pWC.a[0])*pWC.nSlot*2 );
- //if( pWC.a==null ){
- // if( wtFlags & TERM_DYNAMIC ){
- // sqlite3ExprDelete(db, ref p);
- // }
- // pWC.a = pOld;
- // return 0;
- //}
- //memcpy(pWC.a, pOld, sizeof(pWC.a[0])*pWC.nTerm);
- //if( pOld!=pWC.aStatic ){
- // sqlite3DbFree(db, ref pOld);
- //}
- //pWC.nSlot = sqlite3DbMallocSize(db, pWC.a)/sizeof(pWC.a[0]);
- pWC.nSlot = pWC.a.Length - 1;
- }
- pWC.a[idx = pWC.nTerm++] = new WhereTerm();
- pTerm = pWC.a[idx];
- pTerm.pExpr = p;
- pTerm.wtFlags = wtFlags;
- pTerm.pWC = pWC;
- pTerm.iParent = -1;
- return idx;
- }
- /*
- ** This routine identifies subexpressions in the WHERE clause where
- ** each subexpression is separated by the AND operator or some other
- ** operator specified in the op parameter. The WhereClause structure
- ** is filled with pointers to subexpressions. For example:
- **
- ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
- ** \________/ \_______________/ \________________/
- ** slot[0] slot[1] slot[2]
- **
- ** The original WHERE clause in pExpr is unaltered. All this routine
- ** does is make slot[] entries point to substructure within pExpr.
- **
- ** In the previous sentence and in the diagram, "slot[]" refers to
- ** the WhereClause.a[] array. The slot[] array grows as needed to contain
- ** all terms of the WHERE clause.
- */
- static void whereSplit( WhereClause pWC, Expr pExpr, int op )
- {
- pWC.op = (u8)op;
- if ( pExpr == null )
- return;
- if ( pExpr.op != op )
- {
- whereClauseInsert( pWC, pExpr, 0 );
- }
- else
- {
- whereSplit( pWC, pExpr.pLeft, op );
- whereSplit( pWC, pExpr.pRight, op );
- }
- }
- /*
- ** Initialize an expression mask set (a WhereMaskSet object)
- */
- //#define initMaskSet(P) memset(P, 0, sizeof(*P))
- /*
- ** Return the bitmask for the given cursor number. Return 0 if
- ** iCursor is not in the set.
- */
- static Bitmask getMask( WhereMaskSet pMaskSet, int iCursor )
- {
- int i;
- Debug.Assert( pMaskSet.n <= (int)sizeof( Bitmask ) * 8 );
- for ( i = 0; i < pMaskSet.n; i++ )
- {
- if ( pMaskSet.ix[i] == iCursor )
- {
- return ( (Bitmask)1 ) << 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 )
- {
- Debug.Assert( pMaskSet.n < ArraySize( pMaskSet.ix ) );
- pMaskSet.ix[pMaskSet.n++] = iCursor;
- }
- /*
- ** This routine walks (recursively) an expression tree and generates
- ** a bitmask indicating which tables are used in that expression
- ** tree.
- **
- ** In order for this routine to work, the calling function must have
- ** previously invoked sqlite3ResolveExprNames() on the expression. See
- ** the header comment on that routine for additional information.
- ** The sqlite3ResolveExprNames() routines looks for column names and
- ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
- ** the VDBE cursor number of the table. This routine just has to
- ** translate the cursor numbers into bitmask values and OR all
- ** the bitmasks together.
- */
- //static Bitmask exprListTableUsage(WhereMaskSet*, ExprList);
- //static Bitmask exprSelectTableUsage(WhereMaskSet*, Select);
- static Bitmask exprTableUsage( WhereMaskSet pMaskSet, Expr p )
- {
- Bitmask mask = 0;
- if ( p == null )
- return 0;
- if ( p.op == TK_COLUMN )
- {
- mask = getMask( pMaskSet, p.iTable );
- return mask;
- }
- mask = exprTableUsage( pMaskSet, p.pRight );
- mask |= exprTableUsage( pMaskSet, p.pLeft );
- if ( ExprHasProperty( p, EP_xIsSelect ) )
- {
- mask |= exprSelectTableUsage( pMaskSet, p.x.pSelect );
- }
- else
- {
- mask |= exprListTableUsage( pMaskSet, p.x.pList );
- }
- return mask;
- }
- static Bitmask exprListTableUsage( WhereMaskSet pMaskSet, ExprList pList )
- {
- int i;
- Bitmask mask = 0;
- if ( pList != null )
- {
- for ( i = 0; i < pList.nExpr; i++ )
- {
- mask |= exprTableUsage( pMaskSet, pList.a[i].pExpr );
- }
- }
- return mask;
- }
- static Bitmask exprSelectTableUsage( WhereMaskSet pMaskSet, Select pS )
- {
- Bitmask mask = 0;
- while ( pS != null )
- {
- mask |= exprListTableUsage( pMaskSet, pS.pEList );
- mask |= exprListTableUsage( pMaskSet, pS.pGroupBy );
- mask |= exprListTableUsage( pMaskSet, pS.pOrderBy );
- mask |= exprTableUsage( pMaskSet, pS.pWhere );
- mask |= exprTableUsage( pMaskSet, pS.pHaving );
- pS = pS.pPrior;
- }
- return mask;
- }
- /*
- ** Return TRUE if the given operator is one of the operators that is
- ** allowed for an indexable WHERE clause term. The allowed operators are
- ** "=", "<", ">", "<=", ">=", and "IN".
- **
- ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
- ** of one of the following forms: column = expression column > expression
- ** column >= expression column < expression column <= expression
- ** expression = column expression > column expression >= column
- ** expression < column expression <= column column IN
- ** (expression-list) column IN (subquery) column IS NULL
- */
- static bool allowedOp( int op )
- {
- Debug.Assert( TK_GT > TK_EQ && TK_GT < TK_GE );
- Debug.Assert( TK_LT > TK_EQ && TK_LT < TK_GE );
- Debug.Assert( TK_LE > TK_EQ && TK_LE < TK_GE );
- Debug.Assert( TK_GE == TK_EQ + 4 );
- return op == TK_IN || ( op >= TK_EQ && op <= TK_GE ) || op == TK_ISNULL;
- }
- /*
- ** Swap two objects of type TYPE.
- */
- //#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
- /*
- ** Commute a comparison operator. Expressions of the form "X op Y"
- ** are converted into "Y op X".
- **
- ** If a collation sequence is Debug.Associated with either the left or right
- ** side of the comparison, it remains Debug.Associated with the same side after
- ** the commutation. So "Y collate NOCASE op X" becomes
- ** "X collate NOCASE op Y". This is 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_ExpCollate flag
- ** is not commuted.
- */
- static void exprCommute( Parse pParse, Expr pExpr )
- {
- u16 expRight = (u16)( pExpr.pRight.flags & EP_ExpCollate );
- u16 expLeft = (u16)( pExpr.pLeft.flags & EP_ExpCollate );
- Debug.Assert( allowedOp( pExpr.op ) && pExpr.op != TK_IN );
- pExpr.pRight.pColl = sqlite3ExprCollSeq( pParse, pExpr.pRight );
- pExpr.pLeft.pColl = sqlite3ExprCollSeq( pParse, pExpr.pLeft );
- SWAP( ref pExpr.pRight.pColl, ref pExpr.pLeft.pColl );
- pExpr.pRight.flags = (u16)( ( pExpr.pRight.flags & ~EP_ExpCollate ) | expLeft );
- pExpr.pLeft.flags = (u16)( ( pExpr.pLeft.flags & ~EP_ExpCollate ) | expRight );
- SWAP( ref pExpr.pRight, ref pExpr.pLeft );
- if ( pExpr.op >= TK_GT )
- {
- Debug.Assert( TK_LT == TK_GT + 2 );
- Debug.Assert( TK_GE == TK_LE + 2 );
- Debug.Assert( TK_GT > TK_EQ );
- Debug.Assert( TK_GT < TK_LE );
- Debug.Assert( pExpr.op >= TK_GT && pExpr.op <= TK_GE );
- pExpr.op = (u8)( ( ( pExpr.op - TK_GT ) ^ 2 ) + TK_GT );
- }
- }
- /*
- ** Translate from TK_xx operator to WO_xx bitmask.
- */
- static u16 operatorMask( int op )
- {
- u16 c;
- Debug.Assert( allowedOp( op ) );
- if ( op == TK_IN )
- {
- c = WO_IN;
- }
- else if ( op == TK_ISNULL )
- {
- c = WO_ISNULL;
- }
- else
- {
- Debug.Assert( ( WO_EQ << ( op - TK_EQ ) ) < 0x7fff );
- c = (u16)( WO_EQ << ( op - TK_EQ ) );
- }
- Debug.Assert( op != TK_ISNULL || c == WO_ISNULL );
- Debug.Assert( op != TK_IN || c == WO_IN );
- Debug.Assert( op != TK_EQ || c == WO_EQ );
- Debug.Assert( op != TK_LT || c == WO_LT );
- Debug.Assert( op != TK_LE || c == WO_LE );
- Debug.Assert( op != TK_GT || c == WO_GT );
- Debug.Assert( op != TK_GE || c == WO_GE );
- return c;
- }
- /*
- ** 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 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.
- */
- static WhereTerm findTerm(
- 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 pTerm;
- int k;
- Debug.Assert( iCur >= 0 );
- op &= WO_ALL;
- for ( k = pWC.nTerm; k != 0; k-- )//, pTerm++)
- {
- pTerm = pWC.a[pWC.nTerm - k];
- if ( pTerm.leftCursor == iCur
- && ( pTerm.prereqRight & notReady ) == 0
- && pTerm.u.leftColumn == iColumn
- && ( pTerm.eOperator & op ) != 0
- )
- {
- if ( pIdx != null && pTerm.eOperator != WO_ISNULL )
- {
- Expr pX = pTerm.pExpr;
- CollSeq pColl;
- char idxaff;
- int j;
- Parse pParse = pWC.pParse;
- idxaff = pIdx.pTable.aCol[iColumn].affinity;
- if ( !sqlite3IndexAffinityOk( pX, idxaff ) )
- continue;
- /* Figure out the collation sequence required from an index for
- ** it to be useful for optimising expression pX. Store this
- ** value in variable pColl.
- */
- Debug.Assert( pX.pLeft != null );
- pColl = sqlite3BinaryCompareCollSeq( pParse, pX.pLeft, pX.pRight );
- Debug.Assert( pColl != null || pParse.nErr != 0 );
- for ( j = 0; pIdx.aiColumn[j] != iColumn; j++ )
- {
- if ( NEVER( j >= pIdx.nColumn ) )
- return null;
- }
- if ( pColl != null && !pColl.zName.Equals( pIdx.azColl[j], StringComparison.OrdinalIgnoreCase ) )
- continue;
- }
- return pTerm;
- }
- }
- return null;
- }
- /* Forward reference */
- //static void exprAnalyze(SrcList*, WhereClause*, int);
- /*
- ** Call exprAnalyze on all terms in a WHERE clause.
- **
- **
- */
- static void exprAnalyzeAll(
- 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 );
- }
- }
- #if !SQLITE_OMIT_LIKE_OPTIMIZATION
- /*
- ** Check to see if the given expression is a LIKE or GLOB operator that
- ** can be optimized using inequality constraints. Return TRUE if it is
- ** so and false if not.
- **
- ** In order for the operator to be optimizible, the RHS must be a string
- ** literal that does not begin with a wildcard.
- */
- static int isLikeOrGlob(
- Parse pParse, /* Parsing and code generating context */
- Expr pExpr, /* Test this expression */
- ref Expr ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
- ref bool pisComplete, /* True if the only wildcard is % in the last character */
- ref bool pnoCase /* True if uppercase is equivalent to lowercase */
- )
- {
- string z = null; /* 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 = 0; /* One character in z[] */
- int cnt; /* Number of non-wildcard prefix characters */
- char[] wc = new char[3]; /* Wildcard characters */
- sqlite3 db = pParse.db; /* Data_base connection */
- sqlite3_value pVal = null;
- int op; /* Opcode of pRight */
- if ( !sqlite3IsLikeFunction( db, pExpr, ref pnoCase, wc ) )
- {
- return 0;
- }
- //#if 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 )
- {
- /* 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;
- }
- Debug.Assert( pLeft.iColumn != ( -1 ) ); /* Because IPK never has AFF_TEXT */
- pRight = pList.a[0].pExpr;
- op = pRight.op;
- if ( op == TK_REGISTER )
- {
- op = pRight.op2;
- }
- if ( op == TK_VARIABLE )
- {
- Vdbe pReprepare = pParse.pReprepare;
- int iCol = pRight.iColumn;
- pVal = sqlite3VdbeGetValue( pReprepare, iCol, (byte)SQLITE_AFF_NONE );
- if ( pVal != null && sqlite3_value_type( pVal ) == SQLITE_TEXT )
- {
- z = sqlite3_value_text( pVal );
- }
- sqlite3VdbeSetVarmask( pParse.pVdbe, iCol ); /* IMP: R-23257-02778 */
- Debug.Assert( pRight.op == TK_VARIABLE || pRight.op == TK_REGISTER );
- }
- else if ( op == TK_STRING )
- {
- z = pRight.u.zToken;
- }
- if ( !String.IsNullOrEmpty( z ) )
- {
- cnt = 0;
- while ( cnt < z.Length && ( 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] && cnt == z.Length - 1;
- pPrefix = sqlite3Expr( db, TK_STRING, z );
- if ( pPrefix != null )
- pPrefix.u.zToken = pPrefix.u.zToken.Substring( 0, cnt );
- ppPrefix = pPrefix;
- if ( op == TK_VARIABLE )
- {
- Vdbe v = pParse.pVdbe;
- sqlite3VdbeSetVarmask( v, pRight.iColumn ); /* IMP: R-23257-02778 */
- if ( pisComplete && pRight.u.zToken.Length > 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 workaround 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 = null;
- }
- }
- sqlite3ValueFree( ref pVal );
- return ( z != null ) ? 1 : 0;
- }
- #endif //* SQLITE_OMIT_LIKE_OPTIMIZATION */
- #if !SQLITE_OMIT_VIRTUALTABLE
- /*
- ** Check to see if the given expression is of the form
- **
- ** column MATCH expr
- **
- ** If it is then return TRUE. If not, return FALSE.
- */
- static int isMatchOfColumn(
- Expr pExpr /* Test this expression */
- ){
- ExprList pList;
- if( pExpr.op!=TK_FUNCTION ){
- return 0;
- }
- if( !pExpr.u.zToken.Equals("match", StringComparison.OrdinalIgnoreCase ) ){
- return 0;
- }
- pList = pExpr.x.pList;
- if( pList.nExpr!=2 ){
- return 0;
- }
- if( pList.a[1].pExpr.op != TK_COLUMN ){
- return 0;
- }
- return 1;
- }
- #endif //* SQLITE_OMIT_VIRTUALTABLE */
- /*
- ** 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 )
- {
- pDerived.flags = (u16)( pDerived.flags | pBase.flags & EP_FromJoin );
- pDerived.iRightJoinTable = pBase.iRightJoinTable;
- }
- #if !(SQLITE_OMIT_OR_OPTIMIZATION) && !(SQLITE_OMIT_SUBQUERY)
- /*
- ** Analyze a term that consists of two or more OR-connected
- ** subterms. So in:
- **
- ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
- ** ^^^^^^^^^^^^^^^^^^^^
- **
- ** This routine analyzes terms such as the middle term in the above example.
- ** A WhereOrTerm object is computed and attached to the term under
- ** analysis, regardless of the outcome of the analysis. Hence:
- **
- ** WhereTerm.wtFlags |= TERM_ORINFO
- ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
- **
- ** The term being analyzed must have two or more of OR-connected subterms.
- ** A single subterm might be a set of AND-connected sub-subterms.
- ** Examples of terms under analysis:
- **
- ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
- ** (B) x=expr1 OR expr2=x OR x=expr3
- ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
- ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
- ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
- **
- ** CASE 1:
- **
- ** If all subterms are of the form T.C=expr for some single column of C
- ** a single table T (as shown in example B above) then create a new virtual
- ** term that is an equivalent IN expression. In other words, if the term
- ** being analyzed is:
- **
- ** x = expr1 OR expr2 = x OR x = expr3
- **
- ** then create a new virtual term like this:
- **
- ** x IN (expr1,expr2,expr3)
- **
- ** CASE 2:
- **
- ** If all subterms are indexable by a single table T, then set
- **
- ** WhereTerm.eOperator = WO_OR
- ** WhereTerm.u.pOrInfo.indexable |= the cursor number for table T
- **
- ** A subterm is "indexable" if it is of the form
- ** "T.C <op> <expr>" where C is any column of table T and
- ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
- ** A subterm is also indexable if it is an AND of two or more
- ** subsubterms at least one of which is indexable. Indexable AND
- ** subterms have their eOperator set to WO_AND and they have
- ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
- **
- ** From another point of view, "indexable" means that the subterm could
- ** potentially be used with an index if an appropriate index exists.
- ** This analysis does not consider whether or not the index exists; that
- ** is something the bestIndex() routine will determine. This analysis
- ** only looks at whether subterms appropriate for indexing exist.
- **
- ** All examples A through E above all satisfy case 2. But if a term
- ** also statisfies case 1 (such as B) we know that the optimizer will
- ** always prefer case 1, so in that case we pretend that case 2 is not
- ** satisfied.
- **
- ** It might be the case that multiple tables are indexable. For example,
- ** (E) above is indexable on tables P, Q, and R.
- **
- ** Terms that satisfy case 2 are candidates for lookup by using
- ** separate indices to find rowids for each subterm and composing
- ** the union of all rowids using a RowSet object. This is similar
- ** to "bitmap indices" in other data_base engines.
- **
- ** OTHERWISE:
- **
- ** If neither case 1 nor case 2 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 */
- )
- {
- Parse pParse = pWC.pParse; /* Parser context */
- sqlite3 db = pParse.db; /* Data_base connection */
- WhereTerm pTerm = pWC.a[idxTerm]; /* The term to be analyzed */
- Expr pExpr = pTerm.pExpr; /* The expression of the term */
- WhereMaskSet pMaskSet = pWC.pMaskSet; /* Table use masks */
- int i; /* Loop counters */
- WhereClause pOrWc; /* Breakup of pTerm into subterms */
- WhereTerm pOrTerm; /* A Sub-term within the pOrWc */
- WhereOrInfo pOrInfo; /* Additional information Debug.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.
- */
- Debug.Assert( ( pTerm.wtFlags & ( TERM_DYNAMIC | TERM_ORINFO | TERM_ANDINFO ) ) == 0 );
- Debug.Assert( pExpr.op == TK_OR );
- pTerm.u.pOrInfo = pOrInfo = new WhereOrInfo();//sqlite3DbMallocZero(db, sizeof(*pOrInfo));
- if ( pOrInfo == null )
- return;
- pTerm.wtFlags |= TERM_ORINFO;
- pOrWc = pOrInfo.wc;
- whereClauseInit( pOrWc, pWC.pParse, pMaskSet );
- whereSplit( pOrWc, pExpr, TK_OR );
- exprAnalyzeAll( pSrc, pOrWc );
- // if ( db.mallocFailed != 0 ) return;
- Debug.Assert( pOrWc.nTerm >= 2 );
- /*
- ** Compute the set of tables that might satisfy cases 1 or 2.
- */
- indexable = ~(Bitmask)0;
- chngToIN = ~( pWC.vmask );
- for ( i = pOrWc.nTerm - 1; i >= 0 && indexable != 0; i-- )//, pOrTerm++ )
- {
- pOrTerm = pOrWc.a[i];
- if ( ( pOrTerm.eOperator & WO_SINGLE ) == 0 )
- {
- WhereAndInfo pAndInfo;
- Debug.Assert( pOrTerm.eOperator == 0 );
- Debug.Assert( ( pOrTerm.wtFlags & ( TERM_ANDINFO | TERM_ORINFO ) ) == 0 );
- chngToIN = 0;
- pAndInfo = new WhereAndInfo();//sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
- if ( pAndInfo != null )
- {
- WhereClause pAndWC;
- WhereTerm pAndTerm;
- int j;
- Bitmask b = 0;
- pOrTerm.u.pAndInfo = pAndInfo;
- pOrTerm.wtFlags |= TERM_ANDINFO;
- pOrTerm.eOperator = WO_AND;
- pAndWC = pAndInfo.wc;
- whereClauseInit( pAndWC, pWC.pParse, pMaskSet );
- whereSplit( pAndWC, pOrTerm.pExpr, TK_AND );
- exprAnalyzeAll( pSrc, pAndWC );
- //testcase( db.mallocFailed );
- ////if ( 0 == db.mallocFailed )
- {
- for ( j = 0; j < pAndWC.nTerm; j++ )//, pAndTerm++ )
- {
- pAndTerm = pAndWC.a[j];
- Debug.Assert( pAndTerm.pExpr != null );
- if ( allowedOp( pAndTerm.pExpr.op ) )
- {
- b |= getMask( pMaskSet, pAndTerm.leftCursor );
- }
- }
- }
- indexable &= b;
- }
- }
- else if ( ( pOrTerm.wtFlags & TERM_COPIED ) != 0 )
- {
- /* Skip this term for now. We revisit it when we process the
- ** corresponding TERM_VIRTUAL term */
- }
- else
- {
- Bitmask b;
- b = getMask( pMaskSet, pOrTerm.leftCursor );
- if ( ( pOrTerm.wtFlags & TERM_VIRTUAL ) != 0 )
- {
- WhereTerm pOther = pOrWc.a[pOrTerm.iParent];
- b |= getMask( pMaskSet, pOther.leftCursor );
- }
- indexable &= b;
- if ( pOrTerm.eOperator != WO_EQ )
- {
- chngToIN = 0;
- }
- else
- {
- chngToIN &= b;
- }
- }
- }
- /*
- ** Record the set of tables that satisfy case 2. The set might be
- ** empty.
- */
- pOrInfo.indexable = indexable;
- pTerm.eOperator = (u16)( indexable == 0 ? 0 : WO_OR );
- /*
- ** chngToIN holds a set of tables that *might* satisfy case 1. But
- ** we have to do some additional checking to see if case 1 really
- ** is satisfied.
- **
- ** 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 != 0 )
- {
- 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 && 0 == okToChngToIN; j++ )
- {
- //pOrTerm = pOrWc.a;
- for ( i = pOrWc.nTerm - 1; i >= 0; i-- )//, pOrTerm++)
- {
- pOrTerm = pOrWc.a[pOrWc.nTerm - 1 - i];
- Debug.Assert( pOrTerm.eOperator == WO_EQ );
- pOrTerm.wtFlags = (u8)( 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. */
- Debug.Assert( j == 1 );
- continue;
- }
- if ( ( chngToIN & getMask( pMaskSet, 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 preceeded
- ** 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 );
- Debug.Assert( ( pOrTerm.wtFlags & ( TERM_COPIED | TERM_VIRTUAL ) ) != 0 );
- 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 */
- Debug.Assert( j == 1 );
- Debug.Assert( ( chngToIN & ( chngToIN - 1 ) ) == 0 );
- Debug.Assert( chngToIN == getMask( pMaskSet, 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 != 0; i-- )//, pOrTerm++)
- {
- pOrTerm = pOrWc.a[pOrWc.nTerm - 1 - i];
- Debug.Assert( pOrTerm.eOperator == WO_EQ );
- if ( pOrTerm.leftCursor != iCursor )
- {
- pOrTerm.wtFlags = (u8)( 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.
- **
- ** EV: R-00211-15100
- */
- if ( okToChngToIN != 0 )
- {
- Expr pDup; /* A transient duplicate expression */
- ExprList pList = null; /* The RHS of the IN operator */
- Expr pLeft = null; /* The LHS of the IN operator */
- Expr pNew; /* The complete IN operator */
- for ( i = pOrWc.nTerm - 1; i >= 0; i-- )//, pOrTerm++)
- {
- pOrTerm = pOrWc.a[pOrWc.nTerm - 1 - i];
- if ( ( pOrTerm.wtFlags & TERM_OR_OK ) == 0 )
- continue;
- Debug.Assert( pOrTerm.eOperator == WO_EQ );
- Debug.Assert( pOrTerm.leftCursor == iCursor );
- Debug.Assert( pOrTerm.u.leftColumn ==…
Large files files are truncated, but you can click here to view the full file