#define SQLITE_MAX_EXPR_DEPTH using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using Bitmask = System.UInt64; using i16 = System.Int16; using i64 = System.Int64; using sqlite3_int64 = System.Int64; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; using u64 = System.UInt64; using unsigned = System.UInt64; using Pgno = System.UInt32; #if !SQLITE_MAX_VARIABLE_NUMBER using ynVar = System.Int16; #else using ynVar = System.Int32; #endif 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. ** ************************************************************************* ** Internal interface definitions for SQLite. ** ************************************************************************* ** 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: 2010-03-09 19:31:43 4ae453ea7be69018d8c16eb8dabe05617397dc4d ** ** $Header$ ************************************************************************* */ //#if !_SQLITEINT_H_ //#define _SQLITEINT_H_ /* ** These #defines should enable >2GB file support on POSIX if the ** underlying operating system supports it. If the OS lacks ** large file support, or if the OS is windows, these should be no-ops. ** ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any ** system #includes. Hence, this block of code must be the very first ** code in all source files. ** ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch ** on the compiler command line. This is necessary if you are compiling ** on a recent machine (ex: Red Hat 7.2) but you want your code to work ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 ** without this option, LFS is enable. But LFS does not exist in the kernel ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary ** portability you should omit LFS. ** ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. */ //#if !SQLITE_DISABLE_LFS //# define _LARGE_FILE 1 //# ifndef _FILE_OFFSET_BITS //# define _FILE_OFFSET_BITS 64 //# endif //# define _LARGEFILE_SOURCE 1 //#endif /* ** Include the configuration header output by 'configure' if we're using the ** autoconf-based build */ #if _HAVE_SQLITE_CONFIG_H //#include "config.h" #endif //#include "sqliteLimit.h" /* Disable nuisance warnings on Borland compilers */ //#if defined(__BORLANDC__) //#pragma warn -rch /* unreachable code */ //#pragma warn -ccc /* Condition is always true or false */ //#pragma warn -aus /* Assigned value is never used */ //#pragma warn -csu /* Comparing signed and unsigned */ //#pragma warn -spa /* Suspicious pointer arithmetic */ //#endif /* Needed for various definitions... */ //#if !_GNU_SOURCE //#define _GNU_SOURCE //#endif /* ** Include standard header files as necessary */ #if HAVE_STDINT_H //#include #endif #if HAVE_INTTYPES_H //#include #endif /* ** The number of samples of an index that SQLite takes in order to ** construct a histogram of the table content when running ANALYZE ** and with SQLITE_ENABLE_STAT2 */ //#define SQLITE_INDEX_SAMPLES 10 public const int SQLITE_INDEX_SAMPLES = 10; /* ** The following macros are used to cast pointers to integers and ** integers to pointers. The way you do this varies from one compiler ** to the next, so we have developed the following set of #if statements ** to generate appropriate macros for a wide range of compilers. ** ** The correct "ANSI" way to do this is to use the intptr_t type. ** Unfortunately, that typedef is not available on all compilers, or ** if it is available, it requires an #include of specific headers ** that very from one machine to the next. ** ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). ** So we have to define the macros in different ways depending on the ** compiler. */ //#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ //# define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) //# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) //#elif !defined(__GNUC__) /* Works for compilers other than LLVM */ //# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) //# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) //#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ //# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) //# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) //#else /* Generates a warning - but it always works */ //# define SQLITE_INT_TO_PTR(X) ((void*)(X)) //# define SQLITE_PTR_TO_INT(X) ((int)(X)) //#endif /* ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1. ** Older versions of SQLite used an optional THREADSAFE macro. ** We support that for legacy */ #if !SQLITE_THREADSAFE #if THREADSAFE //# define SQLITE_THREADSAFE THREADSAFE #else //# define SQLITE_THREADSAFE 1 const int SQLITE_THREADSAFE = 1; #endif #else const int SQLITE_THREADSAFE = 1; #endif /* ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1. ** It determines whether or not the features related to ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can ** be overridden at runtime using the sqlite3_config() API. */ #if !(SQLITE_DEFAULT_MEMSTATUS) //# define SQLITE_DEFAULT_MEMSTATUS 1 const int SQLITE_DEFAULT_MEMSTATUS = 0; #else const int SQLITE_DEFAULT_MEMSTATUS = 1; #endif /* ** Exactly one of the following macros must be defined in order to ** specify which memory allocation subsystem to use. ** ** SQLITE_SYSTEM_MALLOC // Use normal system malloc() ** SQLITE_MEMDEBUG // Debugging version of system malloc() ** ** (Historical note: There used to be several other options, but we've ** pared it down to just these two.) ** ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as ** the default. */ //#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ //# error "At most one of the following compile-time configuration options\ // is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG" //#endif //#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ //# define SQLITE_SYSTEM_MALLOC 1 //#endif /* ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the ** sizes of memory allocations below this value where possible. */ #if !(SQLITE_MALLOC_SOFT_LIMIT) const int SQLITE_MALLOC_SOFT_LIMIT = 1024; #endif /* ** We need to define _XOPEN_SOURCE as follows in order to enable ** recursive mutexes on most Unix systems. But Mac OS X is different. ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told, ** so it is omitted there. See ticket #2673. ** ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly ** implemented on some systems. So we avoid defining it at all ** if it is already defined or if it is unneeded because we are ** not doing a threadsafe build. Ticket #2681. ** ** See also ticket #2741. */ #if !_XOPEN_SOURCE && !__DARWIN__ && !__APPLE__ && SQLITE_THREADSAFE const int _XOPEN_SOURCE = 500;//#define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */ #endif /* ** The TCL headers are only needed when compiling the TCL bindings. */ #if SQLITE_TCL || TCLSH //# include #endif /* ** Many people are failing to set -DNDEBUG=1 when compiling SQLite. ** Setting NDEBUG makes the code smaller and run faster. So the following ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1 ** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out ** feature. */ #if !NDEBUG && !SQLITE_DEBUG const int NDEBUG = 1;//# define NDEBUG 1 #endif /* ** The testcase() macro is used to aid in coverage testing. When ** doing coverage testing, the condition inside the argument to ** testcase() must be evaluated both true and false in order to ** get full branch coverage. The testcase() macro is inserted ** to help ensure adequate test coverage in places where simple ** condition/decision coverage is inadequate. For example, testcase() ** can be used to make sure boundary values are tested. For ** bitmask tests, testcase() can be used to make sure each bit ** is significant and used at least once. On switch statements ** where multiple cases go to the same block of code, testcase() ** can insure that all cases are evaluated. ** */ #if SQLITE_COVERAGE_TEST void sqlite3Coverage(int); //# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } #else //# define testcase(X) static void testcase(T X) { } #endif /* ** The TESTONLY macro is used to enclose variable declarations or ** other bits of code that are needed to support the arguments ** within testcase() and assert() macros. */ #if !NDEBUG || SQLITE_COVERAGE_TEST //# define TESTONLY(X) X // -- Need workaround for C#, since inline macros don't exist #else //# define TESTONLY(X) #endif /* ** Sometimes we need a small amount of code such as a variable initialization ** to setup for a later assert() statement. We do not want this code to ** appear when assert() is disabled. The following macro is therefore ** used to contain that setup code. The "VVA" acronym stands for ** "Verification, Validation, and Accreditation". In other words, the ** code within VVA_ONLY() will only run during verification processes. */ #if !NDEBUG //# define VVA_ONLY(X) X #else //# define VVA_ONLY(X) #endif /* ** The ALWAYS and NEVER macros surround boolean expressions which ** are intended to always be true or false, respectively. Such ** expressions could be omitted from the code completely. But they ** are included in a few cases in order to enhance the resilience ** of SQLite to unexpected behavior - to make the code "self-healing" ** or "ductile" rather than being "brittle" and crashing at the first ** hint of unplanned behavior. ** ** In other words, ALWAYS and NEVER are added for defensive code. ** ** When doing coverage testing ALWAYS and NEVER are hard-coded to ** be true and false so that the unreachable code then specify will ** not be counted as untested code. */ #if SQLITE_COVERAGE_TEST //# define ALWAYS(X) (1) //# define NEVER(X) (0) #elif !NDEBUG //# define ALWAYS(X) ((X)?1:(assert(0),0)) static bool ALWAYS(bool X) { if (X != true) Debug.Assert(false); return true; } static int ALWAYS(int X) { if (X == 0) Debug.Assert(false); return 1; } static bool ALWAYS(T X) { if (X == null) Debug.Assert(false); return true; } //# define NEVER(X) ((X)?(assert(0),1):0) static bool NEVER(bool X) { if (X == true) Debug.Assert(false); return false; } static byte NEVER(byte X) { if (X != 0) Debug.Assert(false); return 0; } static int NEVER(int X) { if (X != 0) Debug.Assert(false); return 0; } static bool NEVER(T X) { if (X != null) Debug.Assert(false); return false; } #else //# define ALWAYS(X) (X) static bool ALWAYS(bool X) { return X; } static byte ALWAYS(byte X) { return X; } static int ALWAYS(int X) { return X; } static bool ALWAYS( T X ) { return true; } //# define NEVER(X) (X) static bool NEVER(bool X) { return X; } static byte NEVER(byte X) { return X; } static int NEVER(int X) { return X; } static bool NEVER(T X) { return false; } #endif /* ** The macro unlikely() is a hint that surrounds a boolean ** expression that is usually false. Macro likely() surrounds ** a boolean expression that is usually true. GCC is able to ** use these hints to generate better code, sometimes. */ #if (__GNUC__) && FALSE //# define likely(X) __builtin_expect((X),1) //# define unlikely(X) __builtin_expect((X),0) #else //# define likely(X) !!(X) static bool likely(bool X) { return !!X; } //# define unlikely(X) !!(X) static bool unlikely(bool X) { return !!X; } #endif //#include "sqlite3.h" //#include "hash.h" //#include "parse.h" //#include //#include //#include //#include //#include /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point */ #if SQLITE_OMIT_FLOATING_POINT //# define double sqlite_int64 //# define LONGDOUBLE_TYPE sqlite_int64 //#if !SQLITE_BIG_DBL //# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) //# endif //# define SQLITE_OMIT_DATETIME_FUNCS 1 //# define SQLITE_OMIT_TRACE 1 //# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT //# undef SQLITE_HAVE_ISNAN #endif #if !SQLITE_BIG_DBL const double SQLITE_BIG_DBL = (((sqlite3_int64)1) << 60);//# define SQLITE_BIG_DBL (1e99) #endif /* ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 ** afterward. Having this macro allows us to cause the C compiler ** to omit code used by TEMP tables without messy #if !statements. */ #if SQLITE_OMIT_TEMPDB //#define OMIT_TEMPDB 1 #else static int OMIT_TEMPDB = 0; #endif /* ** The "file format" number is an integer that is incremented whenever ** the VDBE-level file format changes. The following macros define the ** the default file format for new databases and the maximum file format ** that the library can read. */ static public int SQLITE_MAX_FILE_FORMAT = 4;//#define SQLITE_MAX_FILE_FORMAT 4 //#if !SQLITE_DEFAULT_FILE_FORMAT static int SQLITE_DEFAULT_FILE_FORMAT = 1;//# define SQLITE_DEFAULT_FILE_FORMAT 1 //#endif /* ** Determine whether triggers are recursive by default. This can be ** changed at run-time using a pragma. */ #if !SQLITE_DEFAULT_RECURSIVE_TRIGGERS //# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 static public bool SQLITE_DEFAULT_RECURSIVE_TRIGGERS = false; #else static public bool SQLITE_DEFAULT_RECURSIVE_TRIGGERS = true; #endif /* ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified ** on the command-line */ #if !SQLITE_TEMP_STORE static int SQLITE_TEMP_STORE = 1;//#define SQLITE_TEMP_STORE 1 #endif /* ** GCC does not define the offsetof() macro so we'll have to do it ** ourselves. */ #if !offsetof //#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) #endif /* ** Check to see if this machine uses EBCDIC. (Yes, believe it or ** not, there are still machines out there that use EBCDIC.) */ #if FALSE //'A' == '\301' //# define SQLITE_EBCDIC 1 #else const int SQLITE_ASCII = 1;//#define SQLITE_ASCII 1 #endif /* ** Integers of known sizes. These typedefs might change for architectures ** where the sizes very. Preprocessor macros are available so that the ** types can be conveniently redefined at compile-type. Like this: ** ** cc '-Du32PTR_TYPE=long long int' ... */ //#if !u32_TYPE //# ifdef HAVE_u32_T //# define u32_TYPE u32_t //# else //# define u32_TYPE unsigned int //# endif //#endif //#if !u3216_TYPE //# ifdef HAVE_u3216_T //# define u3216_TYPE u3216_t //# else //# define u3216_TYPE unsigned short int //# endif //#endif //#if !INT16_TYPE //# ifdef HAVE_INT16_T //# define INT16_TYPE int16_t //# else //# define INT16_TYPE short int //# endif //#endif //#if !u328_TYPE //# ifdef HAVE_u328_T //# define u328_TYPE u328_t //# else //# define u328_TYPE unsigned char //# endif //#endif //#if !INT8_TYPE //# ifdef HAVE_INT8_T //# define INT8_TYPE int8_t //# else //# define INT8_TYPE signed char //# endif //#endif //#if !LONGDOUBLE_TYPE //# define LONGDOUBLE_TYPE long double //#endif //typedef sqlite_int64 i64; /* 8-byte signed integer */ //typedef sqlite_u3264 u64; /* 8-byte unsigned integer */ //typedef u32_TYPE u32; /* 4-byte unsigned integer */ //typedef u3216_TYPE u16; /* 2-byte unsigned integer */ //typedef INT16_TYPE i16; /* 2-byte signed integer */ //typedef u328_TYPE u8; /* 1-byte unsigned integer */ //typedef INT8_TYPE i8; /* 1-byte signed integer */ /* ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value ** that can be stored in a u32 without loss of data. The value ** is 0x00000000ffffffff. But because of quirks of some compilers, we ** have to specify the value in the less intuitive manner shown: */ //#define SQLITE_MAX_U32 ((((u64)1)<<32)-1) const u32 SQLITE_MAX_U32 = (u32)((((u64)1) << 32) - 1); /* ** Macros to determine whether the machine is big or little endian, ** evaluated at runtime. */ #if SQLITE_AMALGAMATION //const int sqlite3one = 1; #else const bool sqlite3one = true; #endif #if i386 || __i386__ || _M_IX86 const int ;//#define SQLITE_BIGENDIAN 0 const int ;//#define SQLITE_LITTLEENDIAN 1 const int ;//#define SQLITE_UTF16NATIVE SQLITE_UTF16LE #else static u8 SQLITE_BIGENDIAN = 0;//#define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) static u8 SQLITE_LITTLEENDIAN = 1;//#define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) static u8 SQLITE_UTF16NATIVE = (SQLITE_BIGENDIAN != 0 ? SQLITE_UTF16BE : SQLITE_UTF16LE);//#define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) #endif /* ** Constants for the largest and smallest possible 64-bit signed integers. ** These macros are designed to work correctly on both 32-bit and 64-bit ** compilers. */ //#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) //#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) const i64 LARGEST_INT64 = i64.MaxValue;//( 0xffffffff | ( ( (i64)0x7fffffff ) << 32 ) ); const i64 SMALLEST_INT64 = i64.MinValue;//( ( ( i64 ) - 1 ) - LARGEST_INT64 ); /* ** Round up a number to the next larger multiple of 8. This is used ** to force 8-byte alignment on 64-bit architectures. */ //#define ROUND8(x) (((x)+7)&~7) static int ROUND8(int x) { return (x + 7) & ~7; } /* ** Round down to the nearest multiple of 8 */ //#define ROUNDDOWN8(x) ((x)&~7) static int ROUNDDOWN8(int x) { return x & ~7; } /* ** Assert that the pointer X is aligned to an 8-byte boundary. This ** macro is used only within assert() to verify that the code gets ** all alignment restrictions correct. ** ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the ** underlying malloc() implemention might return us 4-byte aligned ** pointers. In that case, only verify 4-byte alignment. */ //#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC //# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0) //#else //# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) //#endif /* ** An instance of the following structure is used to store the busy-handler ** callback for a given sqlite handle. ** ** The sqlite.busyHandler member of the sqlite struct contains the busy ** callback for the database handle. Each pager opened via the sqlite ** handle is passed a pointer to sqlite.busyHandler. The busy-handler ** callback is currently invoked only from within pager.c. */ //typedef struct BusyHandler BusyHandler; public class BusyHandler { public dxBusy xFunc;//)(void *,int); /* The busy callback */ public object pArg; /* First arg to busy callback */ public int nBusy; /* Incremented with each busy call */ }; /* ** Name of the master database table. The master database table ** is a special table that holds the names and attributes of all ** user tables and indices. */ const string MASTER_NAME = "sqlite_master";//#define MASTER_NAME "sqlite_master" const string TEMP_MASTER_NAME = "sqlite_temp_master";//#define TEMP_MASTER_NAME "sqlite_temp_master" /* ** The root-page of the master database table. */ const int MASTER_ROOT = 1;//#define MASTER_ROOT 1 /* ** The name of the schema table. */ static string SCHEMA_TABLE(int x) //#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) { return ((OMIT_TEMPDB == 0) && (x == 1) ? TEMP_MASTER_NAME : MASTER_NAME); } /* ** A convenience macro that returns the number of elements in ** an array. */ //#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) static int ArraySize(T[] x) { return x.Length; } /* ** The following value as a destructor means to use sqlite3DbFree(). ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT. */ //#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree) static dxDel SQLITE_DYNAMIC; /* ** When SQLITE_OMIT_WSD is defined, it means that the target platform does ** not support Writable Static Data (WSD) such as global and static variables. ** All variables must either be on the stack or dynamically allocated from ** the heap. When WSD is unsupported, the variable declarations scattered ** throughout the SQLite code must become constants instead. The SQLITE_WSD ** macro is used for this purpose. And instead of referencing the variable ** directly, we use its constant as a key to lookup the run-time allocated ** buffer that holds real variable. The constant is also the initializer ** for the run-time allocated buffer. ** ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL ** macros become no-ops and have zero performance impact. */ #if SQLITE_OMIT_WSD //#define SQLITE_WSD const //#define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) //#define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) int sqlite3_wsd_init(int N, int J); void *sqlite3_wsd_find(void *K, int L); #else //#define SQLITE_WSD //#define GLOBAL(t,v) v //#define sqlite3GlobalConfig sqlite3Config static Sqlite3Config sqlite3GlobalConfig; #endif /* ** The following macros are used to suppress compiler warnings and to ** make it clear to human readers when a function parameter is deliberately ** left unused within the body of a function. This usually happens when ** a function is called via a function pointer. For example the ** implementation of an SQL aggregate step callback may not use the ** parameter indicating the number of arguments passed to the aggregate, ** if it knows that this is enforced elsewhere. ** ** When a function parameter is not used at all within the body of a function, ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. ** However, these macros may also be used to suppress warnings related to ** parameters that may or may not be used depending on compilation options. ** For example those parameters only used in assert() statements. In these ** cases the parameters are named as per the usual conventions. */ //#define UNUSED_PARAMETER(x) (void)(x) static void UNUSED_PARAMETER(T x) { } //#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) static void UNUSED_PARAMETER2(T1 x, T2 y) { UNUSED_PARAMETER(x); UNUSED_PARAMETER(y); } /* ** Forward references to structures */ //typedef struct AggInfo AggInfo; //typedef struct AuthContext AuthContext; //typedef struct AutoincInfo AutoincInfo; //typedef struct Bitvec Bitvec; //typedef struct CollSeq CollSeq; //typedef struct Column Column; //typedef struct Db Db; //typedef struct Schema Schema; //typedef struct Expr Expr; //typedef struct ExprList ExprList; //typedef struct ExprSpan ExprSpan; //typedef struct FKey FKey; //typedef struct FuncDef FuncDef; //typedef struct IdList IdList; //typedef struct Index Index; //typedef struct IndexSample IndexSample; //typedef struct KeyClass KeyClass; //typedef struct KeyInfo KeyInfo; //typedef struct Lookaside Lookaside; //typedef struct LookasideSlot LookasideSlot; //typedef struct Module Module; //typedef struct NameContext NameContext; //typedef struct Parse Parse; //typedef struct RowSet RowSet; //typedef struct Savepoint Savepoint; //typedef struct Select Select; //typedef struct SrcList SrcList; //typedef struct StrAccum StrAccum; //typedef struct Table Table; //typedef struct TableLock TableLock; //typedef struct Token Token; //typedef struct Trigger Trigger; //typedef struct TriggerPrg TriggerPrg; //typedef struct TriggerStep TriggerStep; //typedef struct UnpackedRecord UnpackedRecord; //typedef struct VTable VTable; //typedef struct Walker Walker; //typedef struct WherePlan WherePlan; //typedef struct WhereInfo WhereInfo; //typedef struct WhereLevel WhereLevel; /* ** Defer sourcing vdbe.h and btree.h until after the "u8" and ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque ** pointer types (i.e. FuncDef) defined above. */ //#include "btree.h" //#include "vdbe.h" //#include "pager.h" //#include "pcache_g.h" //#include "os.h" //#include "mutex.h" /* ** Each database file to be accessed by the system is an instance ** of the following structure. There are normally two of these structures ** in the sqlite.aDb[] array. aDb[0] is the main database file and ** aDb[1] is the database file used to hold temporary tables. Additional ** databases may be attached. */ public class Db { public string zName; /* Name of this database */ public Btree pBt; /* The B Tree structure for this database file */ public u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */ public u8 safety_level; /* How aggressive at syncing data to disk */ public Schema pSchema; /* Pointer to database schema (possibly shared) */ }; /* ** An instance of the following structure stores a database schema. ** ** If there are no virtual tables configured in this schema, the ** Schema.db variable is set to NULL. After the first virtual table ** has been added, it is set to point to the database connection ** used to create the connection. Once a virtual table has been ** added to the Schema structure and the Schema.db variable populated, ** only that database connection may use the Schema to prepare ** statements. */ public class Schema { public int schema_cookie; /* Database schema version number for this file */ public Hash tblHash = new Hash(); /* All tables indexed by name */ public Hash idxHash = new Hash(); /* All (named) indices indexed by name */ public Hash trigHash = new Hash();/* All triggers indexed by name */ public Hash fkeyHash = new Hash();/* All foreign keys by referenced table name */ public Table pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ public u8 file_format; /* Schema format version for this file */ public u8 enc; /* Text encoding used by this database */ public u16 flags; /* Flags associated with this schema */ public int cache_size; /* Number of pages to use in the cache */ #if !SQLITE_OMIT_VIRTUALTABLE public sqlite3 db; /* "Owner" connection. See comment above */ #endif public Schema Copy() { if (this == null) return null; else { Schema cp = (Schema)MemberwiseClone(); return cp; } } }; /* ** These macros can be used to test, set, or clear bits in the ** Db.pSchema->flags field. */ //#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P)) static bool DbHasProperty(sqlite3 D, int I, ushort P) { return (D.aDb[I].pSchema.flags & P) == P; } //#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0) //#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P) static void DbSetProperty(sqlite3 D, int I, ushort P) { D.aDb[I].pSchema.flags = (u16)(D.aDb[I].pSchema.flags | P); } //#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P) static void DbClearProperty(sqlite3 D, int I, ushort P) { D.aDb[I].pSchema.flags = (u16)(D.aDb[I].pSchema.flags & ~P); } /* ** Allowed values for the DB.pSchema->flags field. ** ** The DB_SchemaLoaded flag is set after the database schema has been ** read into internal hash tables. ** ** DB_UnresetViews means that one or more views have column names that ** have been filled out. If the schema changes, these column names might ** changes and so the view will need to be reset. */ //#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ //#define DB_UnresetViews 0x0002 /* Some views have defined column names */ //#define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ const u16 DB_SchemaLoaded = 0x0001; const u16 DB_UnresetViews = 0x0002; const u16 DB_Empty = 0x0004; /* ** The number of different kinds of things that can be limited ** using the sqlite3_limit() interface. */ //#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1) const int SQLITE_N_LIMIT = SQLITE_LIMIT_TRIGGER_DEPTH + 1; /* ** Lookaside malloc is a set of fixed-size buffers that can be used ** to satisfy small transient memory allocation requests for objects ** associated with a particular database connection. The use of ** lookaside malloc provides a significant performance enhancement ** (approx 10%) by avoiding numerous malloc/free requests while parsing ** SQL statements. ** ** The Lookaside structure holds configuration information about the ** lookaside malloc subsystem. Each available memory allocation in ** the lookaside subsystem is stored on a linked list of LookasideSlot ** objects. ** ** Lookaside allocations are only allowed for objects that are associated ** with a particular database connection. Hence, schema information cannot ** be stored in lookaside because in shared cache mode the schema information ** is shared by multiple database connections. Therefore, while parsing ** schema information, the Lookaside.bEnabled flag is cleared so that ** lookaside allocations are not used to construct the schema objects. */ public class Lookaside { public int sz; /* Size of each buffer in bytes */ public u8 bEnabled; /* False to disable new lookaside allocations */ public bool bMalloced; /* True if pStart obtained from sqlite3_malloc() */ public int nOut; /* Number of buffers currently checked out */ public int mxOut; /* Highwater mark for nOut */ public LookasideSlot pFree; /* List of available buffers */ public int pStart; /* First byte of available memory space */ public int pEnd; /* First byte past end of available space */ }; public class LookasideSlot { public LookasideSlot pNext; /* Next buffer in the list of free buffers */ }; /* ** A hash table for function definitions. ** ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. ** Collisions are on the FuncDef.pHash chain. */ public class FuncDefHash { public FuncDef[] a = new FuncDef[23]; /* Hash table for functions */ }; /* ** Each database connection is an instance of the following structure. ** ** The sqlite.lastRowid records the last insert rowid generated by an ** insert statement. Inserts on views do not affect its value. Each ** trigger has its own context, so that lastRowid can be updated inside ** triggers as usual. The previous value will be restored once the trigger ** exits. Upon entering a before or instead of trigger, lastRowid is no ** longer (since after version 2.8.12) reset to -1. ** ** The sqlite.nChange does not count changes within triggers and keeps no ** context. It is reset at start of sqlite3_exec. ** The sqlite.lsChange represents the number of changes made by the last ** insert, update, or delete statement. It remains constant throughout the ** length of a statement and is then updated by OP_SetCounts. It keeps a ** context stack just like lastRowid so that the count of changes ** within a trigger is not seen outside the trigger. Changes to views do not ** affect the value of lsChange. ** The sqlite.csChange keeps track of the number of current changes (since ** the last statement) and is used to update sqlite_lsChange. ** ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16 ** store the most recent error code and, if applicable, string. The ** internal function sqlite3Error() is used to set these variables ** consistently. */ public class sqlite3 { public sqlite3_vfs pVfs; /* OS Interface */ public int nDb; /* Number of backends currently in use */ public Db[] aDb = new Db[SQLITE_MAX_ATTACHED]; /* All backends */ public int flags; /* Miscellaneous flags. See below */ public int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ public int errCode; /* Most recent error code (SQLITE_*) */ public int errMask; /* & result codes with this before returning */ public u8 autoCommit; /* The auto-commit flag. */ public u8 temp_store; /* 1: file 2: memory 0: default */ // Cannot happen under C# // public u8 mallocFailed; /* True if we have seen a malloc failure */ public u8 dfltLockMode; /* Default locking-mode for attached dbs */ public u8 dfltJournalMode; /* Default journal mode for attached dbs */ public int nextAutovac; /* Autovac setting after VACUUM if >=0 */ public u8 suppressErr; /* Do not issue error messages if true */ public int nextPagesize; /* Pagesize after VACUUM if >0 */ public int nTable; /* Number of tables in the database */ public CollSeq pDfltColl; /* The default collating sequence (BINARY) */ public i64 lastRowid; /* ROWID of most recent insert (see above) */ public u32 magic; /* Magic number for detect library misuse */ public int nChange; /* Value returned by sqlite3_changes() */ public int nTotalChange; /* Value returned by sqlite3_total_changes() */ public sqlite3_mutex mutex; /* Connection mutex */ public int[] aLimit = new int[SQLITE_N_LIMIT]; /* Limits */ public class sqlite3InitInfo { /* Information used during initialization */ public int iDb; /* When back is being initialized */ public int newTnum; /* Rootpage of table being initialized */ public u8 busy; /* TRUE if currently initializing */ public u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ }; public sqlite3InitInfo init = new sqlite3InitInfo(); public int nExtension; /* Number of loaded extensions */ public object[] aExtension; /* Array of shared library handles */ public Vdbe pVdbe; /* List of active virtual machines */ public int activeVdbeCnt; /* Number of VDBEs currently executing */ public int writeVdbeCnt; /* Number of active VDBEs that are writing */ public dxTrace xTrace;//)(void*,const char*); /* Trace function */ public object pTraceArg; /* Argument to the trace function */ public dxProfile xProfile;//)(void*,const char*,u64); /* Profiling function */ public object pProfileArg; /* Argument to profile function */ public object pCommitArg; /* Argument to xCommitCallback() */ public dxCommitCallback xCommitCallback;//)(void*); /* Invoked at every commit. */ public object pRollbackArg; /* Argument to xRollbackCallback() */ public dxRollbackCallback xRollbackCallback;//)(void*); /* Invoked at every commit. */ public object pUpdateArg; public dxUpdateCallback xUpdateCallback;//)(void*,int, const char*,const char*,sqlite_int64); public dxCollNeeded xCollNeeded;//)(void*,sqlite3*,int eTextRep,const char*); public dxCollNeeded xCollNeeded16;//)(void*,sqlite3*,int eTextRep,const void*); public object pCollNeededArg; public sqlite3_value pErr; /* Most recent error message */ public string zErrMsg; /* Most recent error message (UTF-8 encoded) */ public string zErrMsg16; /* Most recent error message (UTF-16 encoded) */ public struct _u1 { public bool isInterrupted; /* True if sqlite3_interrupt has been called */ public double notUsed1; /* Spacer */ } public _u1 u1; public Lookaside lookaside = new Lookaside(); /* Lookaside malloc configuration */ #if !SQLITE_OMIT_AUTHORIZATION public dxAuth xAuth;//)(void*,int,const char*,const char*,const char*,const char*); /* Access authorization function */ public object pAuthArg; /* 1st argument to the access auth function */ #endif #if !SQLITE_OMIT_PROGRESS_CALLBACK public dxProgress xProgress;//)(void *); /* The progress callback */ public object pProgressArg; /* Argument to the progress callback */ public int nProgressOps; /* Number of opcodes for progress callback */ #endif #if !SQLITE_OMIT_VIRTUALTABLE public Hash aModule; /* populated by sqlite3_create_module() */ public Table pVTab; /* vtab with active Connect/Create method */ public VTable aVTrans; /* Virtual tables with open transactions */ public int nVTrans; /* Allocated size of aVTrans */ public VTable pDisconnect; /* Disconnect these in next sqlite3_prepare() */ #endif public FuncDefHash aFunc = new FuncDefHash(); /* Hash table of connection functions */ public Hash aCollSeq = new Hash(); /* All collating sequences */ public BusyHandler busyHandler = new BusyHandler(); /* Busy callback */ public int busyTimeout; /* Busy handler timeout, in msec */ public Db[] aDbStatic = new Db[] { new Db(), new Db() }; /* Static space for the 2 default backends */ public Savepoint pSavepoint; /* List of active savepoints */ public int nSavepoint; /* Number of non-transaction savepoints */ public int nStatement; /* Number of nested statement-transactions */ public u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ public i64 nDeferredCons; /* Net deferred constraints this transaction. */ #if SQLITE_ENABLE_UNLOCK_NOTIFY /* The following variables are all protected by the STATIC_MASTER ** mutex, not by sqlite3.mutex. They are used by code in notify.c. ** ** When X.pUnlockConnection==Y, that means that X is waiting for Y to ** unlock so that it can proceed. ** ** When X.pBlockingConnection==Y, that means that something that X tried ** tried to do recently failed with an SQLITE_LOCKED error due to locks ** held by Y. */ sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ void *pUnlockArg; /* Argument to xUnlockNotify */ void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ #endif }; /* ** A macro to discover the encoding of a database. */ //#define ENC(db) ((db)->aDb[0].pSchema->enc) static u8 ENC(sqlite3 db) { return db.aDb[0].pSchema.enc; } /* ** Possible values for the sqlite3.flags. */ //#define SQLITE_VdbeTrace 0x00000100 /* True to trace VDBE execution */ //#define SQLITE_InternChanges 0x00000200 /* Uncommitted Hash table changes */ //#define SQLITE_FullColNames 0x00000400 /* Show full column names on SELECT */ //#define SQLITE_ShortColNames 0x00000800 /* Show short columns names */ //#define SQLITE_CountRows 0x00001000 /* Count rows changed by INSERT, */ // /* DELETE, or UPDATE and return */ // /* the count using a callback. */ //#define SQLITE_NullCallback 0x00002000 /* Invoke the callback once if the */ // /* result set is empty */ //#define SQLITE_SqlTrace 0x00004000 /* Debug print SQL as it executes */ //#define SQLITE_VdbeListing 0x00008000 /* Debug listings of VDBE programs */ //#define SQLITE_WriteSchema 0x00010000 /* OK to update SQLITE_MASTER */ //#define SQLITE_NoReadlock 0x00020000 /* Readlocks are omitted when // ** accessing read-only databases */ //#define SQLITE_IgnoreChecks 0x00040000 /* Do not enforce check constraints */ //#define SQLITE_ReadUncommitted 0x0080000 /* For shared-cache mode */ //#define SQLITE_LegacyFileFmt 0x00100000 /* Create new databases in format 1 */ //#define SQLITE_FullFSync 0x00200000 /* Use full fsync on the backend */ //#define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */ //#define SQLITE_RecoveryMode 0x00800000 /* Ignore schema errors */ //#define SQLITE_ReverseOrder 0x01000000 /* Reverse unordered SELECTs */ //#define SQLITE_RecTriggers 0x02000000 /* Enable recursive triggers */ //#define SQLITE_ForeignKeys 0x04000000 /* Enforce foreign key constraints */ const int SQLITE_VdbeTrace = 0x00000100; /* True to trace VDBE execution */ const int SQLITE_InternChanges = 0x00000200; /* Uncommitted Hash table changes */ const int SQLITE_FullColNames = 0x00000400; /* Show full column names on SELECT */ const int SQLITE_ShortColNames = 0x00000800; /* Show short columns names */ const int SQLITE_CountRows = 0x00001000; /* Count rows changed by INSERT, */ /* DELETE, or UPDATE and return */ /* the count using a callback. */ const int SQLITE_NullCallback = 0x00002000; /* Invoke the callback once if the */ /* result set is empty */ const int SQLITE_SqlTrace = 0x00004000; /* Debug print SQL as it executes */ const int SQLITE_VdbeListing = 0x00008000; /* Debug listings of VDBE programs */ const int SQLITE_WriteSchema = 0x00010000; /* OK to update SQLITE_MASTER */ const int SQLITE_NoReadlock = 0x00020000; /* Readlocks are omitted when ** accessing read-only databases */ const int SQLITE_IgnoreChecks = 0x00040000; /* Do not enforce check constraints */ const int SQLITE_ReadUncommitted = 0x0080000; /* For shared-cache mode */ const int SQLITE_LegacyFileFmt = 0x00100000; /* Create new databases in format 1 */ const int SQLITE_FullFSync = 0x00200000; /* Use full fsync on the backend */ const int SQLITE_LoadExtension = 0x00400000; /* Enable load_extension */ const int SQLITE_RecoveryMode = 0x00800000; /* Ignore schema errors */ const int SQLITE_ReverseOrder = 0x01000000; /* Reverse unordered SELECTs */ const int SQLITE_RecTriggers = 0x02000000; /* Enable recursive triggers */ const int SQLITE_ForeignKeys = 0x04000000; /* Enforce foreign key constraints */ /* ** Bits of the sqlite3.flags field that are used by the ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface. ** These must be the low-order bits of the flags field. */ //#define SQLITE_QueryFlattener 0x01 /* Disable query flattening */ //#define SQLITE_ColumnCache 0x02 /* Disable the column cache */ //#define SQLITE_IndexSort 0x04 /* Disable indexes for sorting */ //#define SQLITE_IndexSearch 0x08 /* Disable indexes for searching */ //#define SQLITE_IndexCover 0x10 /* Disable index covering table */ //#define SQLITE_OptMask 0x1f /* Mask of all disablable opts */ const int SQLITE_QueryFlattener = 0x01; /* Disable query flattening */ const int SQLITE_ColumnCache = 0x02; /* Disable the column cache */ const int SQLITE_IndexSort = 0x04; /* Disable indexes for sorting */ const int SQLITE_IndexSearch = 0x08; /* Disable indexes for searching */ const int SQLITE_IndexCover = 0x10; /* Disable index covering table */ const int SQLITE_OptMask = 0x1f; /* Mask of all disablable opts */ /* ** Possible values for the sqlite.magic field. ** The numbers are obtained at random and have no special meaning, other ** than being distinct from one another. */ const int SQLITE_MAGIC_OPEN = 0x1029a697; //#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ const int SQLITE_MAGIC_CLOSED = 0x2f3c2d33; //#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ const int SQLITE_MAGIC_SICK = 0x3b771290; //#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ const int SQLITE_MAGIC_BUSY = 0x403b7906; //#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ const int SQLITE_MAGIC_ERROR = 0x55357930; //#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ /* ** Each SQL function is defined by an instance of the following ** structure. A pointer to this structure is stored in the sqlite.aFunc ** hash table. When multiple functions have the same name, the hash table ** points to a linked list of these structures. */ public class FuncDef { public i16 nArg; /* Number of arguments. -1 means unlimited */ public u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */ public u8 flags; /* Some combination of SQLITE_FUNC_* */ public object pUserData; /* User data parameter */ public FuncDef pNext; /* Next function with same name */ public dxFunc xFunc;//)(sqlite3_context*,int,sqlite3_value**); /* Regular function */ public dxStep xStep;//)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */ public dxFinal xFinalize;//)(sqlite3_context*); /* Aggregate finalizer */ public string zName; /* SQL name of the function. */ public FuncDef pHash; /* Next with a different name but the same hash */ public FuncDef() { } public FuncDef(i16 nArg, u8 iPrefEnc, u8 iflags, object pUserData, FuncDef pNext, dxFunc xFunc, dxStep xStep, dxFinal xFinalize, string zName, FuncDef pHash) { this.nArg = nArg; this.iPrefEnc = iPrefEnc; this.flags = iflags; this.pUserData = pUserData; this.pNext = pNext; this.xFunc = xFunc; this.xStep = xStep; this.xFinalize = xFinalize; this.zName = zName; this.pHash = pHash; } public FuncDef(string zName, u8 iPrefEnc, i16 nArg, int iArg, u8 iflags, dxFunc xFunc) { this.nArg = nArg; this.iPrefEnc = iPrefEnc; this.flags = iflags; this.pUserData = iArg; this.pNext = null; this.xFunc = xFunc; this.xStep = null; this.xFinalize = null; this.zName = zName; } public FuncDef(string zName, u8 iPrefEnc, i16 nArg, int iArg, u8 iflags, dxStep xStep, dxFinal xFinal) { this.nArg = nArg; this.iPrefEnc = iPrefEnc; this.flags = iflags; this.pUserData = iArg; this.pNext = null; this.xFunc = null; this.xStep = xStep; this.xFinalize = xFinal; this.zName = zName; } public FuncDef(string zName, u8 iPrefEnc, i16 nArg, object arg, dxFunc xFunc, u8 flags) { this.nArg = nArg; this.iPrefEnc = iPrefEnc; this.flags = flags; this.pUserData = arg; this.pNext = null; this.xFunc = xFunc; this.xStep = null; this.xFinalize = null; this.zName = zName; } }; /* ** Possible values for FuncDef.flags */ //#define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */ //#define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */ //#define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */ //#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */ //#define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */ //#define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */ //#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */ const int SQLITE_FUNC_LIKE = 0x01; /* Candidate for the LIKE optimization */ const int SQLITE_FUNC_CASE = 0x02; /* Case-sensitive LIKE-type function */ const int SQLITE_FUNC_EPHEM = 0x04; /* Ephermeral. Delete with VDBE */ const int SQLITE_FUNC_NEEDCOLL = 0x08;/* sqlite3GetFuncCollSeq() might be called */ const int SQLITE_FUNC_PRIVATE = 0x10; /* Allowed for internal use only */ const int SQLITE_FUNC_COUNT = 0x20; /* Built-in count(*) aggregate */ const int SQLITE_FUNC_COALESCE = 0x40;/* Built-in coalesce() or ifnull() function */ /* ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are ** used to create the initializers for the FuncDef structures. ** ** FUNCTION(zName, nArg, iArg, bNC, xFunc) ** Used to create a scalar function definition of a function zName ** implemented by C function xFunc that accepts nArg arguments. The ** value passed as iArg is cast to a (void*) and made available ** as the user-data (sqlite3_user_data()) for the function. If ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. ** ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) ** Used to create an aggregate function definition implemented by ** the C functions xStep and xFinal. The first four parameters ** are interpreted in the same way as the first 4 parameters to ** FUNCTION(). ** ** LIKEFUNC(zName, nArg, pArg, flags) ** Used to create a scalar function definition of a function zName ** that accepts nArg arguments and is implemented by a call to C ** function likeFunc. Argument pArg is cast to a (void *) and made ** available as the function user-data (sqlite3_user_data()). The ** FuncDef.flags variable is set to the value passed as the flags ** parameter. */ //#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ // {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ //SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0} static FuncDef FUNCTION(string zName, i16 nArg, int iArg, u8 bNC, dxFunc xFunc) { return new FuncDef(zName, SQLITE_UTF8, nArg, iArg, (u8)(bNC * SQLITE_FUNC_NEEDCOLL), xFunc); } //#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ // {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ //pArg, 0, xFunc, 0, 0, #zName, 0} //#define LIKEFUNC(zName, nArg, arg, flags) \ // {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0} static FuncDef LIKEFUNC(string zName, i16 nArg, object arg, u8 flags) { return new FuncDef(zName, SQLITE_UTF8, nArg, arg, likeFunc, flags); } //#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ // {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \ //SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0} static FuncDef AGGREGATE(string zName, i16 nArg, int arg, u8 nc, dxStep xStep, dxFinal xFinal) { return new FuncDef(zName, SQLITE_UTF8, nArg, arg, (u8)(nc * SQLITE_FUNC_NEEDCOLL), xStep, xFinal); } /* ** All current savepoints are stored in a linked list starting at ** sqlite3.pSavepoint. The first element in the list is the most recently ** opened savepoint. Savepoints are added to the list by the vdbe ** OP_Savepoint instruction. */ //struct Savepoint { // char *zName; /* Savepoint name (nul-terminated) */ // i64 nDeferredCons; /* Number of deferred fk violations */ // Savepoint *pNext; /* Parent savepoint (if any) */ //}; public class Savepoint { public string zName; /* Savepoint name (nul-terminated) */ public i64 nDeferredCons; /* Number of deferred fk violations */ public Savepoint pNext; /* Parent savepoint (if any) */ }; /* ** The following are used as the second parameter to sqlite3Savepoint(), ** and as the P1 argument to the OP_Savepoint instruction. */ const int SAVEPOINT_BEGIN = 0; //#define SAVEPOINT_BEGIN 0 const int SAVEPOINT_RELEASE = 1; //#define SAVEPOINT_RELEASE 1 const int SAVEPOINT_ROLLBACK = 2; //#define SAVEPOINT_ROLLBACK 2 /* ** Each SQLite module (virtual table definition) is defined by an ** instance of the following structure, stored in the sqlite3.aModule ** hash table. */ public class Module { public sqlite3_module pModule; /* Callback pointers */ public string zName; /* Name passed to create_module() */ public object pAux; /* pAux passed to create_module() */ public dxDestroy xDestroy;//)(void *); /* Module destructor function */ }; /* ** information about each column of an SQL table is held in an instance ** of this structure. */ public class Column { public string zName; /* Name of this column */ public Expr pDflt; /* Default value of this column */ public string zDflt; /* Original text of the default value */ public string zType; /* Data type for this column */ public string zColl; /* Collating sequence. If NULL, use the default */ public u8 notNull; /* True if there is a NOT NULL constraint */ public u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */ public char affinity; /* One of the SQLITE_AFF_... values */ #if !SQLITE_OMIT_VIRTUALTABLE public u8 isHidden; /* True if this column is 'hidden' */ #endif public Column Copy() { Column cp = (Column)MemberwiseClone(); if (cp.pDflt != null) cp.pDflt = pDflt.Copy(); return cp; } }; /* ** A "Collating Sequence" is defined by an instance of the following ** structure. Conceptually, a collating sequence consists of a name and ** a comparison routine that defines the order of that sequence. ** ** There may two separate implementations of the collation function, one ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine ** native byte order. When a collation sequence is invoked, SQLite selects ** the version that will require the least expensive encoding ** translations, if any. ** ** The CollSeq.pUser member variable is an extra parameter that passed in ** as the first argument to the UTF-8 comparison function, xCmp. ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function, ** xCmp16. ** ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the ** collating sequence is undefined. Indices built on an undefined ** collating sequence may not be read or written. */ public class CollSeq { public string zName; /* Name of the collating sequence, UTF-8 encoded */ public u8 enc; /* Text encoding handled by xCmp() */ public u8 type; /* One of the SQLITE_COLL_... values below */ public object pUser; /* First argument to xCmp() */ public dxCompare xCmp;//)(void*,int, const void*, int, const void*); public dxDelCollSeq xDel;//)(void*); /* Destructor for pUser */ public CollSeq Copy() { if (this == null) return null; else { CollSeq cp = (CollSeq)MemberwiseClone(); return cp; } } }; /* ** Allowed values of CollSeq.type: */ const int SQLITE_COLL_BINARY = 1;//#define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */ const int SQLITE_COLL_NOCASE = 2;//#define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */ const int SQLITE_COLL_REVERSE = 3;//#define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */ const int SQLITE_COLL_USER = 0;//#define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */ /* ** A sort order can be either ASC or DESC. */ const int SQLITE_SO_ASC = 0;//#define SQLITE_SO_ASC 0 /* Sort in ascending order */ const int SQLITE_SO_DESC = 1;//#define SQLITE_SO_DESC 1 /* Sort in ascending order */ /* ** Column affinity types. ** ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve ** the speed a little by numbering the values consecutively. ** ** But rather than start with 0 or 1, we begin with 'a'. That way, ** when multiple affinity types are concatenated into a string and ** used as the P4 operand, they will be more readable. ** ** Note also that the numeric types are grouped together so that testing ** for a numeric type is a single comparison. */ const char SQLITE_AFF_TEXT = 'a';//#define SQLITE_AFF_TEXT 'a' const char SQLITE_AFF_NONE = 'b';//#define SQLITE_AFF_NONE 'b' const char SQLITE_AFF_NUMERIC = 'c';//#define SQLITE_AFF_NUMERIC 'c' const char SQLITE_AFF_INTEGER = 'd';//#define SQLITE_AFF_INTEGER 'd' const char SQLITE_AFF_REAL = 'e';//#define SQLITE_AFF_REAL 'e' //#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) /* ** The SQLITE_AFF_MASK values masks off the significant bits of an ** affinity value. */ const int SQLITE_AFF_MASK = 0x67;//#define SQLITE_AFF_MASK 0x67 /* ** Additional bit values that can be ORed with an affinity without ** changing the affinity. */ const int SQLITE_JUMPIFNULL = 0x08; //#define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */ const int SQLITE_STOREP2 = 0x10; //#define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */ const int SQLITE_NULLEQ = 0x80; //#define SQLITE_NULLEQ 0x80 /* NULL=NULL */ /* ** An object of this type is created for each virtual table present in ** the database schema. ** ** If the database schema is shared, then there is one instance of this ** structure for each database connection (sqlite3*) that uses the shared ** schema. This is because each database connection requires its own unique ** instance of the sqlite3_vtab* handle used to access the virtual table ** implementation. sqlite3_vtab* handles can not be shared between ** database connections, even when the rest of the in-memory database ** schema is shared, as the implementation often stores the database ** connection handle passed to it via the xConnect() or xCreate() method ** during initialization internally. This database connection handle may ** then used by the virtual table implementation to access real tables ** within the database. So that they appear as part of the callers ** transaction, these accesses need to be made via the same database ** connection as that used to execute SQL operations on the virtual table. ** ** All VTable objects that correspond to a single table in a shared ** database schema are initially stored in a linked-list pointed to by ** the Table.pVTable member variable of the corresponding Table object. ** When an sqlite3_prepare() operation is required to access the virtual ** table, it searches the list for the VTable that corresponds to the ** database connection doing the preparing so as to use the correct ** sqlite3_vtab* handle in the compiled query. ** ** When an in-memory Table object is deleted (for example when the ** schema is being reloaded for some reason), the VTable objects are not ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed ** immediately. Instead, they are moved from the Table.pVTable list to ** another linked list headed by the sqlite3.pDisconnect member of the ** corresponding sqlite3 structure. They are then deleted/xDisconnected ** next time a statement is prepared using said sqlite3*. This is done ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. ** Refer to comments above function sqlite3VtabUnlockList() for an ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect ** list without holding the corresponding sqlite3.mutex mutex. ** ** The memory for objects of this type is always allocated by ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as ** the first argument. */ public class VTable { public sqlite3 db; /* Database connection associated with this table */ public Module pMod; /* Pointer to module implementation */ public sqlite3_vtab pVtab; /* Pointer to vtab instance */ public int nRef; /* Number of pointers to this structure */ public VTable pNext; /* Next in linked list (see above) */ }; /* ** Each SQL table is represented in memory by an instance of the ** following structure. ** ** Table.zName is the name of the table. The case of the original ** CREATE TABLE statement is stored, but case is not significant for ** comparisons. ** ** Table.nCol is the number of columns in this table. Table.aCol is a ** pointer to an array of Column structures, one for each column. ** ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of ** the column that is that key. Otherwise Table.iPKey is negative. Note ** that the datatype of the PRIMARY KEY must be INTEGER for this field to ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid ** is generated for each row of the table. TF_HasPrimaryKey is set if ** the table has any PRIMARY KEY, INTEGER or otherwise. ** ** Table.tnum is the page number for the root BTree page of the table in the ** database file. If Table.iDb is the index of the database table backend ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that ** holds temporary tables and indices. If TF_Ephemeral is set ** then the table is stored in a file that is automatically deleted ** when the VDBE cursor to the table is closed. In this case Table.tnum ** refers VDBE cursor number that holds the table open, not to the root ** page number. Transient tables are used to hold the results of a ** sub-query that appears instead of a real table name in the FROM clause ** of a SELECT statement. */ public class Table { public sqlite3 dbMem; /* DB connection used for lookaside allocations. */ public string zName; /* Name of the table or view */ public int iPKey; /* If not negative, use aCol[iPKey] as the primary key */ public int nCol; /* Number of columns in this table */ public Column[] aCol; /* Information about each column */ public Index pIndex; /* List of SQL indexes on this table. */ public int tnum; /* Root BTree node for this table (see note above) */ public Select pSelect; /* NULL for tables. Points to definition if a view. */ public u16 nRef; /* Number of pointers to this Table */ public u8 tabFlags; /* Mask of TF_* values */ public u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ public FKey pFKey; /* Linked list of all foreign keys in this table */ public string zColAff; /* String defining the affinity of each column */ #if !SQLITE_OMIT_CHECK public Expr pCheck; /* The AND of all CHECK constraints */ #endif #if !SQLITE_OMIT_ALTERTABLE public int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ #endif #if !SQLITE_OMIT_VIRTUALTABLE public VTable pVTable; /* List of VTable objects. */ public int nModuleArg; /* Number of arguments to the module */ public string[] azModuleArg;/* Text of all module args. [0] is module name */ #endif public Trigger pTrigger; /* List of SQL triggers on this table */ public Schema pSchema; /* Schema that contains this table */ public Table pNextZombie; /* Next on the Parse.pZombieTab list */ public Table Copy() { if (this == null) return null; else { Table cp = (Table)MemberwiseClone(); if (pIndex != null) cp.pIndex = pIndex.Copy(); if (pSelect != null) cp.pSelect = pSelect.Copy(); if (pTrigger != null) cp.pTrigger = pTrigger.Copy(); if (pFKey != null) cp.pFKey = pFKey.Copy(); #if !SQLITE_OMIT_CHECK // Don't Clone Checks, only copy reference via Memberwise Clone above -- //if ( pCheck != null ) cp.pCheck = pCheck.Copy(); #endif #if !SQLITE_OMIT_VIRTUALTABLE if ( pMod != null ) cp.pMod =pMod.Copy(); if ( pVtab != null ) cp.pVtab =pVtab.Copy(); #endif // Don't Clone Schema, only copy reference via Memberwise Clone above -- // if ( pSchema != null ) cp.pSchema=pSchema.Copy(); // Don't Clone pNextZombie, only copy reference via Memberwise Clone above -- // if ( pNextZombie != null ) cp.pNextZombie=pNextZombie.Copy(); return cp; } } }; /* ** Allowed values for Tabe.tabFlags. */ //#define TF_Readonly 0x01 /* Read-only system table */ //#define TF_Ephemeral 0x02 /* An ephemeral table */ //#define TF_HasPrimaryKey 0x04 /* Table has a primary key */ //#define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ //#define TF_Virtual 0x10 /* Is a virtual table */ //#define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */ /* ** Allowed values for Tabe.tabFlags. */ const int TF_Readonly = 0x01; /* Read-only system table */ const int TF_Ephemeral = 0x02; /* An ephemeral table */ const int TF_HasPrimaryKey = 0x04; /* Table has a primary key */ const int TF_Autoincrement = 0x08; /* Integer primary key is autoincrement */ const int TF_Virtual = 0x10; /* Is a virtual table */ const int TF_NeedMetadata = 0x20; /* aCol[].zType and aCol[].pColl missing */ /* ** Test to see whether or not a table is a virtual table. This is ** done as a macro so that it will be optimized out when virtual ** table support is omitted from the build. */ #if !SQLITE_OMIT_VIRTUALTABLE //# define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) static bool IsVirtual( Table X) { return (X.tabFlags & TF_Virtual)!=0;} //# define IsHiddenColumn(X) ((X)->isHidden) static bool IsVirtual( Column X) { return X.isHidden!=0;} #else //# define IsVirtual(X) 0 static bool IsVirtual(Table T) { return false; } //# define IsHiddenColumn(X) 0 static bool IsHiddenColumn(Column C) { return false; } #endif /* ** Each foreign key constraint is an instance of the following structure. ** ** A foreign key is associated with two tables. The "from" table is ** the table that contains the REFERENCES clause that creates the foreign ** key. The "to" table is the table that is named in the REFERENCES clause. ** Consider this example: ** ** CREATE TABLE ex1( ** a INTEGER PRIMARY KEY, ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) ** ); ** ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". ** ** Each REFERENCES clause generates an instance of the following structure ** which is attached to the from-table. The to-table need not exist when ** the from-table is created. The existence of the to-table is not checked. */ public class FKey { public Table pFrom; /* Table containing the REFERENCES clause (aka: Child) */ public FKey pNextFrom; /* Next foreign key in pFrom */ public string zTo; /* Name of table that the key points to (aka: Parent) */ public FKey pNextTo; /* Next foreign key on table named zTo */ public FKey pPrevTo; /* Previous foreign key on table named zTo */ public int nCol; /* Number of columns in this key */ /* EV: R-30323-21917 */ public u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ public u8[] aAction = new u8[2]; /* ON DELETE and ON UPDATE actions, respectively */ public Trigger[] apTrigger = new Trigger[2];/* Triggers for aAction[] actions */ public class sColMap { /* Mapping of columns in pFrom to columns in zTo */ public int iFrom; /* Index of column in pFrom */ public string zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */ }; public sColMap[] aCol; /* One entry for each of nCol column s */ public FKey Copy() { if (this == null) return null; else { FKey cp = (FKey)MemberwiseClone(); return cp; } } }; /* ** SQLite supports many different ways to resolve a constraint ** error. ROLLBACK processing means that a constraint violation ** causes the operation in process to fail and for the current transaction ** to be rolled back. ABORT processing means the operation in process ** fails and any prior changes from that one operation are backed out, ** but the transaction is not rolled back. FAIL processing means that ** the operation in progress stops and returns an error code. But prior ** changes due to the same operation are not backed out and no rollback ** occurs. IGNORE means that the particular row that caused the constraint ** error is not inserted or updated. Processing continues and no error ** is returned. REPLACE means that preexisting database rows that caused ** a UNIQUE constraint violation are removed so that the new insert or ** update can proceed. Processing continues and no error is reported. ** ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the ** referenced table row is propagated into the row that holds the ** foreign key. ** ** The following symbolic values are used to record which type ** of action to take. */ const int OE_None = 0;//#define OE_None 0 /* There is no constraint to check */ const int OE_Rollback = 1;//#define OE_Rollback 1 /* Fail the operation and rollback the transaction */ const int OE_Abort = 2;//#define OE_Abort 2 /* Back out changes but do no rollback transaction */ const int OE_Fail = 3;//#define OE_Fail 3 /* Stop the operation but leave all prior changes */ const int OE_Ignore = 4;//#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ const int OE_Replace = 5;//#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ const int OE_Restrict = 6;//#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ const int OE_SetNull = 7;//#define OE_SetNull 7 /* Set the foreign key value to NULL */ const int OE_SetDflt = 8;//#define OE_SetDflt 8 /* Set the foreign key value to its default */ const int OE_Cascade = 9;//#define OE_Cascade 9 /* Cascade the changes */ const int OE_Default = 99;//#define OE_Default 99 /* Do whatever the default action is */ /* ** An instance of the following structure is passed as the first ** argument to sqlite3VdbeKeyCompare and is used to control the ** comparison of the two index keys. */ public class KeyInfo { public sqlite3 db; /* The database connection */ public u8 enc; /* Text encoding - one of the TEXT_Utf* values */ public u16 nField; /* Number of entries in aColl[] */ public u8[] aSortOrder; /* If defined an aSortOrder[i] is true, sort DESC */ public CollSeq[] aColl = new CollSeq[1]; /* Collating sequence for each term of the key */ public KeyInfo Copy() { return (KeyInfo)MemberwiseClone(); } }; /* ** An instance of the following structure holds information about a ** single index record that has already been parsed out into individual ** values. ** ** A record is an object that contains one or more fields of data. ** Records are used to store the content of a table row and to store ** the key of an index. A blob encoding of a record is created by ** the OP_MakeRecord opcode of the VDBE and is disassembled by the ** OP_Column opcode. ** ** This structure holds a record that has already been disassembled ** into its constituent fields. */ public class UnpackedRecord { public KeyInfo pKeyInfo; /* Collation and sort-order information */ public u16 nField; /* Number of entries in apMem[] */ public u16 flags; /* Boolean settings. UNPACKED_... below */ public i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */ public Mem[] aMem; /* Values */ }; /* ** Allowed values of UnpackedRecord.flags */ //#define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */ //#define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */ //#define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */ //#define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */ //#define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */ //#define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */ const int UNPACKED_NEED_FREE = 0x0001; /* Memory is from sqlite3Malloc() */ const int UNPACKED_NEED_DESTROY = 0x0002; /* apMem[]s should all be destroyed */ const int UNPACKED_IGNORE_ROWID = 0x0004; /* Ignore trailing rowid on key1 */ const int UNPACKED_INCRKEY = 0x0008; /* Make this key an epsilon larger */ const int UNPACKED_PREFIX_MATCH = 0x0010; /* A prefix match is considered OK */ const int UNPACKED_PREFIX_SEARCH = 0x0020; /* A prefix match is considered OK */ /* ** Each SQL index is represented in memory by an ** instance of the following structure. ** ** The columns of the table that are to be indexed are described ** by the aiColumn[] field of this structure. For example, suppose ** we have the following table and index: ** ** CREATE TABLE Ex1(c1 int, c2 int, c3 text); ** CREATE INDEX Ex2 ON Ex1(c3,c1); ** ** In the Table structure describing Ex1, nCol==3 because there are ** three columns in the table. In the Index structure describing ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. ** The second column to be indexed (c1) has an index of 0 in ** Ex1.aCol[], hence Ex2.aiColumn[1]==0. ** ** The Index.onError field determines whether or not the indexed columns ** must be unique and what to do if they are not. When Index.onError=OE_None, ** it means this is not a unique index. Otherwise it is a unique index ** and the value of Index.onError indicate the which conflict resolution ** algorithm to employ whenever an attempt is made to insert a non-unique ** element. */ public class Index { public string zName; /* Name of this index */ public int nColumn; /* Number of columns in the table used by this index */ public int[] aiColumn; /* Which columns are used by this index. 1st is 0 */ public int[] aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */ public Table pTable; /* The SQL table being indexed */ public int tnum; /* Page containing root of this index in database file */ public u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ public u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */ public string zColAff; /* String defining the affinity of each column */ public Index pNext; /* The next index associated with the same table */ public Schema pSchema; /* Schema containing this index */ public u8[] aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */ public string[] azColl; /* Array of collation sequence names for index */ public IndexSample[] aSample; /* Array of SQLITE_INDEX_SAMPLES samples */ public Index Copy() { if (this == null) return null; else { Index cp = (Index)MemberwiseClone(); return cp; } } }; /* ** Each sample stored in the sqlite_stat2 table is represented in memory ** using a structure of this type. */ public struct IndexSample { public struct _u { //union { public string z; /* Value if eType is SQLITE_TEXT */ public byte[] zBLOB; /* Value if eType is SQLITE_BLOB */ public double r; /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */ } public _u u; public u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */ public u8 nByte; /* Size in byte of text or blob. */ }; /* ** Each token coming out of the lexer is an instance of ** this structure. Tokens are also used as part of an expression. ** ** Note if Token.z==0 then Token.dyn and Token.n are undefined and ** may contain random values. Do not make any assumptions about Token.dyn ** and Token.n when Token.z==0. */ public class Token { #if DEBUG_CLASS_TOKEN || DEBUG_CLASS_ALL public string _z; /* Text of the token. Not NULL-terminated! */ public bool dyn;// : 1; /* True for malloced memory, false for static */ public Int32 _n;// : 31; /* Number of characters in this token */ public string z { get { return _z; } set { _z = value; } } public Int32 n { get { return _n; } set { _n = value; } } #else public string z; /* Text of the token. Not NULL-terminated! */ public Int32 n; /* Number of characters in this token */ #endif public Token() { this.z = null; this.n = 0; } public Token(string z, Int32 n) { this.z = z; this.n = n; } public Token Copy() { if (this == null) return null; else { Token cp = (Token)MemberwiseClone(); if (z == null || z.Length == 0) cp.n = 0; else if (n > z.Length) cp.n = z.Length; return cp; } } } /* ** An instance of this structure contains information needed to generate ** code for a SELECT that contains aggregate functions. ** ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a ** pointer to this structure. The Expr.iColumn field is the index in ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate ** code for that node. ** ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the ** original Select structure that describes the SELECT statement. These ** fields do not need to be freed when deallocating the AggInfo structure. */ public class AggInfo_col { /* For each column used in source tables */ public Table pTab; /* Source table */ public int iTable; /* VdbeCursor number of the source table */ public int iColumn; /* Column number within the source table */ public int iSorterColumn; /* Column number in the sorting index */ public int iMem; /* Memory location that acts as accumulator */ public Expr pExpr; /* The original expression */ }; public class AggInfo_func { /* For each aggregate function */ public Expr pExpr; /* Expression encoding the function */ public FuncDef pFunc; /* The aggregate function implementation */ public int iMem; /* Memory location that acts as accumulator */ public int iDistinct; /* Ephemeral table used to enforce DISTINCT */ } public class AggInfo { public u8 directMode; /* Direct rendering mode means take data directly ** from source tables rather than from accumulators */ public u8 useSortingIdx; /* In direct mode, reference the sorting index rather ** than the source table */ public int sortingIdx; /* VdbeCursor number of the sorting index */ public ExprList pGroupBy; /* The group by clause */ public int nSortingColumn; /* Number of columns in the sorting index */ public AggInfo_col[] aCol; public int nColumn; /* Number of used entries in aCol[] */ public int nColumnAlloc; /* Number of slots allocated for aCol[] */ public int nAccumulator; /* Number of columns that show through to the output. ** Additional columns are used only as parameters to ** aggregate functions */ public AggInfo_func[] aFunc; public int nFunc; /* Number of entries in aFunc[] */ public int nFuncAlloc; /* Number of slots allocated for aFunc[] */ public AggInfo Copy() { if (this == null) return null; else { AggInfo cp = (AggInfo)MemberwiseClone(); if (pGroupBy != null) cp.pGroupBy = pGroupBy.Copy(); return cp; } } }; /* ** The datatype ynVar is a signed integer, either 16-bit or 32-bit. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater ** than 32767 we have to make it 32-bit. 16-bit is preferred because ** it uses less memory in the Expr object, which is a big memory user ** in systems with lots of prepared statements. And few applications ** need more than about 10 or 20 variables. But some extreme users want ** to have prepared statements with over 32767 variables, and for them ** the option is available (at compile-time). */ //#if SQLITE_MAX_VARIABLE_NUMBER<=32767 //typedef i16 ynVar; //#else //typedef int ynVar; //#endif /* ** Each node of an expression in the parse tree is an instance ** of this structure. ** ** Expr.op is the opcode. The integer parser token codes are reused ** as opcodes here. For example, the parser defines TK_GE to be an integer ** code representing the ">=" operator. This same integer code is reused ** to represent the greater-than-or-equal-to operator in the expression ** tree. ** ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, ** or TK_STRING), then Expr.token contains the text of the SQL literal. If ** the expression is a variable (TK_VARIABLE), then Expr.token contains the ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), ** then Expr.token contains the name of the function. ** ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a ** binary operator. Either or both may be NULL. ** ** Expr.x.pList is a list of arguments if the expression is an SQL function, ** a CASE expression or an IN expression of the form " IN (, ...)". ** Expr.x.pSelect is used if the expression is a sub-select or an expression of ** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is ** valid. ** ** An expression of the form ID or ID.ID refers to a column in a table. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is ** the integer cursor number of a VDBE cursor pointing to that table and ** Expr.iColumn is the column number for the specific column. If the ** expression is used as a result in an aggregate SELECT, then the ** value is also stored in the Expr.iAgg column in the aggregate so that ** it can be accessed after all aggregates are computed. ** ** If the expression is an unbound variable marker (a question mark ** character '?' in the original SQL) then the Expr.iTable holds the index ** number for that variable. ** ** If the expression is a subquery then Expr.iColumn holds an integer ** register number containing the result of the subquery. If the ** subquery gives a constant result, then iTable is -1. If the subquery ** gives a different answer at different times during statement processing ** then iTable is the address of a subroutine that computes the subquery. ** ** If the Expr is of type OP_Column, and the table it is selecting from ** is a disk table or the "old.*" pseudo-table, then pTab points to the ** corresponding table definition. ** ** ALLOCATION NOTES: ** ** Expr objects can use a lot of memory space in database schema. To ** help reduce memory requirements, sometimes an Expr object will be ** truncated. And to reduce the number of memory allocations, sometimes ** two or more Expr objects will be stored in a single memory allocation, ** together with Expr.zToken strings. ** ** If the EP_Reduced and EP_TokenOnly flags are set when ** an Expr object is truncated. When EP_Reduced is set, then all ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees ** are contained within the same memory allocation. Note, however, that ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately ** allocated, regardless of whether or not EP_Reduced is set. */ public class Expr { #if DEBUG_CLASS_EXPR || DEBUG_CLASS_ALL public u8 _op; /* Operation performed by this node */ public u8 op { get { return _op; } set { _op = value; } } #else public u8 op; /* Operation performed by this node */ #endif public char affinity; /* The affinity of the column or 0 if not a column */ #if DEBUG_CLASS_EXPR || DEBUG_CLASS_ALL public u16 _flags; /* Various flags. EP_* See below */ public u16 flags { get { return _flags; } set { _flags = value; } } public struct _u { public string _zToken; /* Token value. Zero terminated and dequoted */ public string zToken { get { return _zToken; } set { _zToken = value; } } public int iValue; /* Integer value if EP_IntValue */ } #else public struct _u { public string zToken; /* Token value. Zero terminated and dequoted */ public int iValue; /* Integer value if EP_IntValue */ } public u16 flags; /* Various flags. EP_* See below */ #endif public _u u; /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no ** space is allocated for the fields below this point. An attempt to ** access them will result in a segfault or malfunction. *********************************************************************/ public Expr pLeft; /* Left subnode */ public Expr pRight; /* Right subnode */ public struct _x { public ExprList pList; /* Function arguments or in " IN ( IN (