sqliteInt.h

Go to the documentation of this file.
00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** Internal interface definitions for SQLite.
00013 **
00014 ** @(#) $Id: sqliteInt.h,v 1.790 2008/11/11 18:29:00 drh Exp $
00015 */
00016 #ifndef _SQLITEINT_H_
00017 #define _SQLITEINT_H_
00018 
00019 /*
00020 ** Include the configuration header output by 'configure' if we're using the
00021 ** autoconf-based build
00022 */
00023 #include "sqlite3_config.h"
00024 
00025 #include "sqliteLimit.h"
00026 
00027 /* Disable nuisance warnings on Borland compilers */
00028 #if defined(__BORLANDC__)
00029 #pragma warn -rch /* unreachable code */
00030 #pragma warn -ccc /* Condition is always true or false */
00031 #pragma warn -aus /* Assigned value is never used */
00032 #pragma warn -csu /* Comparing signed and unsigned */
00033 #pragma warn -spa /* Suspicous pointer arithmetic */
00034 #endif
00035 
00036 /* Needed for various definitions... */
00037 #ifndef _GNU_SOURCE
00038 # define _GNU_SOURCE
00039 #endif
00040 
00041 /*
00042 ** Include standard header files as necessary
00043 */
00044 #ifdef HAVE_STDINT_H
00045 #include <stdint.h>
00046 #endif
00047 #ifdef HAVE_INTTYPES_H
00048 #include <inttypes.h>
00049 #endif
00050 
00051 /*
00052 ** A macro used to aid in coverage testing.  When doing coverage
00053 ** testing, the condition inside the argument must be evaluated 
00054 ** both true and false in order to get full branch coverage.
00055 ** This macro can be inserted to ensure adequate test coverage
00056 ** in places where simple condition/decision coverage is inadequate.
00057 */
00058 #ifdef SQLITE_COVERAGE_TEST
00059   void sqlite3Coverage(int);
00060 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
00061 #else
00062 # define testcase(X)
00063 #endif
00064 
00065 /*
00066 ** The ALWAYS and NEVER macros surround boolean expressions which 
00067 ** are intended to always be true or false, respectively.  Such
00068 ** expressions could be omitted from the code completely.  But they
00069 ** are included in a few cases in order to enhance the resilience
00070 ** of SQLite to unexpected behavior - to make the code "self-healing"
00071 ** or "ductile" rather than being "brittle" and crashing at the first
00072 ** hint of unplanned behavior.
00073 **
00074 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
00075 ** be true and false so that the unreachable code then specify will
00076 ** not be counted as untested code.
00077 */
00078 #ifdef SQLITE_COVERAGE_TEST
00079 # define ALWAYS(X)      (1)
00080 # define NEVER(X)       (0)
00081 #else
00082 # define ALWAYS(X)      (X)
00083 # define NEVER(X)       (X)
00084 #endif
00085 
00086 /*
00087 ** The macro unlikely() is a hint that surrounds a boolean
00088 ** expression that is usually false.  Macro likely() surrounds
00089 ** a boolean expression that is usually true.  GCC is able to
00090 ** use these hints to generate better code, sometimes.
00091 */
00092 #if defined(__GNUC__) && 0
00093 # define likely(X)    __builtin_expect((X),1)
00094 # define unlikely(X)  __builtin_expect((X),0)
00095 #else
00096 # define likely(X)    !!(X)
00097 # define unlikely(X)  !!(X)
00098 #endif
00099 
00100 /*
00101  * This macro is used to "hide" some ugliness in casting an int
00102  * value to a ptr value under the MSVC 64-bit compiler.   Casting
00103  * non 64-bit values to ptr types results in a "hard" error with 
00104  * the MSVC 64-bit compiler which this attempts to avoid.  
00105  *
00106  * A simple compiler pragma or casting sequence could not be found
00107  * to correct this in all situations, so this macro was introduced.
00108  *
00109  * It could be argued that the intptr_t type could be used in this
00110  * case, but that type is not available on all compilers, or 
00111  * requires the #include of specific headers which differs between
00112  * platforms.
00113  */
00114 #define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
00115 #define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
00116 
00117 /*
00118 ** These #defines should enable >2GB file support on Posix if the
00119 ** underlying operating system supports it.  If the OS lacks
00120 ** large file support, or if the OS is windows, these should be no-ops.
00121 **
00122 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
00123 ** system #includes.  Hence, this block of code must be the very first
00124 ** code in all source files.
00125 **
00126 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
00127 ** on the compiler command line.  This is necessary if you are compiling
00128 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
00129 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
00130 ** without this option, LFS is enable.  But LFS does not exist in the kernel
00131 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
00132 ** portability you should omit LFS.
00133 **
00134 ** Similar is true for MacOS.  LFS is only supported on MacOS 9 and later.
00135 */
00136 #ifndef SQLITE_DISABLE_LFS
00137 # define _LARGE_FILE       1
00138 # ifndef _FILE_OFFSET_BITS
00139 #   define _FILE_OFFSET_BITS 64
00140 # endif
00141 # define _LARGEFILE_SOURCE 1
00142 #endif
00143 
00144 
00145 /*
00146 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
00147 ** Older versions of SQLite used an optional THREADSAFE macro.
00148 ** We support that for legacy
00149 */
00150 #if !defined(SQLITE_THREADSAFE)
00151 #if defined(THREADSAFE)
00152 # define SQLITE_THREADSAFE THREADSAFE
00153 #else
00154 # define SQLITE_THREADSAFE 1
00155 #endif
00156 #endif
00157 
00158 /*
00159 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
00160 ** It determines whether or not the features related to 
00161 ** SQLITE_CONFIG_MEMSTATUS are availabe by default or not. This value can
00162 ** be overridden at runtime using the sqlite3_config() API.
00163 */
00164 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
00165 # define SQLITE_DEFAULT_MEMSTATUS 1
00166 #endif
00167 
00168 /*
00169 ** Exactly one of the following macros must be defined in order to
00170 ** specify which memory allocation subsystem to use.
00171 **
00172 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
00173 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
00174 **     SQLITE_MEMORY_SIZE            // internal allocator #1
00175 **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
00176 **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
00177 **
00178 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
00179 ** the default.
00180 */
00181 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
00182     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
00183     defined(SQLITE_POW2_MEMORY_SIZE)>1
00184 # error "At most one of the following compile-time configuration options\
00185  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
00186  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
00187 #endif
00188 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
00189     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
00190     defined(SQLITE_POW2_MEMORY_SIZE)==0
00191 # define SQLITE_SYSTEM_MALLOC 1
00192 #endif
00193 
00194 /*
00195 ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
00196 ** sizes of memory allocations below this value where possible.
00197 */
00198 #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
00199 # define SQLITE_MALLOC_SOFT_LIMIT 1024
00200 #endif
00201 
00202 /*
00203 ** We need to define _XOPEN_SOURCE as follows in order to enable
00204 ** recursive mutexes on most unix systems.  But Mac OS X is different.
00205 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
00206 ** so it is omitted there.  See ticket #2673.
00207 **
00208 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
00209 ** implemented on some systems.  So we avoid defining it at all
00210 ** if it is already defined or if it is unneeded because we are
00211 ** not doing a threadsafe build.  Ticket #2681.
00212 **
00213 ** See also ticket #2741.
00214 */
00215 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
00216 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
00217 #endif
00218 
00219 /*
00220 ** The TCL headers are only needed when compiling the TCL bindings.
00221 */
00222 #if defined(SQLITE_TCL) || defined(TCLSH)
00223 # include <tcl.h>
00224 #endif
00225 
00226 /*
00227 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
00228 ** Setting NDEBUG makes the code smaller and run faster.  So the following
00229 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
00230 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
00231 ** feature.
00232 */
00233 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
00234 # define NDEBUG 1
00235 #endif
00236 
00237 #include "sqlite3.h"
00238 #include "hash.h"
00239 #include "parse.h"
00240 #include <stdio.h>
00241 #include <stdlib.h>
00242 #include <string.h>
00243 #include <assert.h>
00244 #include <stddef.h>
00245 
00246 /*
00247 ** If compiling for a processor that lacks floating point support,
00248 ** substitute integer for floating-point
00249 */
00250 #ifdef SQLITE_OMIT_FLOATING_POINT
00251 # define double sqlite_int64
00252 # define LONGDOUBLE_TYPE sqlite_int64
00253 # ifndef SQLITE_BIG_DBL
00254 #   define SQLITE_BIG_DBL (0x7fffffffffffffff)
00255 # endif
00256 # define SQLITE_OMIT_DATETIME_FUNCS 1
00257 # define SQLITE_OMIT_TRACE 1
00258 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
00259 #endif
00260 #ifndef SQLITE_BIG_DBL
00261 # define SQLITE_BIG_DBL (1e99)
00262 #endif
00263 
00264 /*
00265 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
00266 ** afterward. Having this macro allows us to cause the C compiler 
00267 ** to omit code used by TEMP tables without messy #ifndef statements.
00268 */
00269 #ifdef SQLITE_OMIT_TEMPDB
00270 #define OMIT_TEMPDB 1
00271 #else
00272 #define OMIT_TEMPDB 0
00273 #endif
00274 
00275 /*
00276 ** If the following macro is set to 1, then NULL values are considered
00277 ** distinct when determining whether or not two entries are the same
00278 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
00279 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
00280 ** is the way things are suppose to work.
00281 **
00282 ** If the following macro is set to 0, the NULLs are indistinct for
00283 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
00284 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
00285 ** work.
00286 */
00287 #define NULL_DISTINCT_FOR_UNIQUE 1
00288 
00289 /*
00290 ** The "file format" number is an integer that is incremented whenever
00291 ** the VDBE-level file format changes.  The following macros define the
00292 ** the default file format for new databases and the maximum file format
00293 ** that the library can read.
00294 */
00295 #define SQLITE_MAX_FILE_FORMAT 4
00296 #ifndef SQLITE_DEFAULT_FILE_FORMAT
00297 # define SQLITE_DEFAULT_FILE_FORMAT 1
00298 #endif
00299 
00300 /*
00301 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
00302 ** on the command-line
00303 */
00304 #ifndef SQLITE_TEMP_STORE
00305 # define SQLITE_TEMP_STORE 1
00306 #endif
00307 
00308 /*
00309 ** GCC does not define the offsetof() macro so we'll have to do it
00310 ** ourselves.
00311 */
00312 #ifndef offsetof
00313 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
00314 #endif
00315 
00316 /*
00317 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
00318 ** not, there are still machines out there that use EBCDIC.)
00319 */
00320 #if 'A' == '\301'
00321 # define SQLITE_EBCDIC 1
00322 #else
00323 # define SQLITE_ASCII 1
00324 #endif
00325 
00326 /*
00327 ** Integers of known sizes.  These typedefs might change for architectures
00328 ** where the sizes very.  Preprocessor macros are available so that the
00329 ** types can be conveniently redefined at compile-type.  Like this:
00330 **
00331 **         cc '-DUINTPTR_TYPE=long long int' ...
00332 */
00333 #ifndef UINT32_TYPE
00334 # ifdef HAVE_UINT32_T
00335 #  define UINT32_TYPE uint32_t
00336 # else
00337 #  define UINT32_TYPE unsigned int
00338 # endif
00339 #endif
00340 #ifndef UINT16_TYPE
00341 # ifdef HAVE_UINT16_T
00342 #  define UINT16_TYPE uint16_t
00343 # else
00344 #  define UINT16_TYPE unsigned short int
00345 # endif
00346 #endif
00347 #ifndef INT16_TYPE
00348 # ifdef HAVE_INT16_T
00349 #  define INT16_TYPE int16_t
00350 # else
00351 #  define INT16_TYPE short int
00352 # endif
00353 #endif
00354 #ifndef UINT8_TYPE
00355 # ifdef HAVE_UINT8_T
00356 #  define UINT8_TYPE uint8_t
00357 # else
00358 #  define UINT8_TYPE unsigned char
00359 # endif
00360 #endif
00361 #ifndef INT8_TYPE
00362 # ifdef HAVE_INT8_T
00363 #  define INT8_TYPE int8_t
00364 # else
00365 #  define INT8_TYPE signed char
00366 # endif
00367 #endif
00368 #ifndef LONGDOUBLE_TYPE
00369 # define LONGDOUBLE_TYPE long double
00370 #endif
00371 typedef sqlite_int64 i64;          /* 8-byte signed integer */
00372 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
00373 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
00374 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
00375 typedef INT16_TYPE i16;            /* 2-byte signed integer */
00376 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
00377 typedef INT8_TYPE i8;              /* 1-byte signed integer */
00378 
00379 /*
00380 ** Macros to determine whether the machine is big or little endian,
00381 ** evaluated at runtime.
00382 */
00383 #ifdef SQLITE_AMALGAMATION
00384 const int sqlite3one;
00385 #else
00386 extern const int sqlite3one;
00387 #endif
00388 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
00389                              || defined(__x86_64) || defined(__x86_64__)
00390 # define SQLITE_BIGENDIAN    0
00391 # define SQLITE_LITTLEENDIAN 1
00392 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
00393 #else
00394 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
00395 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
00396 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
00397 #endif
00398 
00399 /*
00400 ** Constants for the largest and smallest possible 64-bit signed integers.
00401 ** These macros are designed to work correctly on both 32-bit and 64-bit
00402 ** compilers.
00403 */
00404 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
00405 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
00406 
00407 /*
00408 ** An instance of the following structure is used to store the busy-handler
00409 ** callback for a given sqlite handle. 
00410 **
00411 ** The sqlite.busyHandler member of the sqlite struct contains the busy
00412 ** callback for the database handle. Each pager opened via the sqlite
00413 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
00414 ** callback is currently invoked only from within pager.c.
00415 */
00416 typedef struct BusyHandler BusyHandler;
00417 struct BusyHandler {
00418   int (*xFunc)(void *,int);  /* The busy callback */
00419   void *pArg;                /* First arg to busy callback */
00420   int nBusy;                 /* Incremented with each busy call */
00421 };
00422 
00423 /*
00424 ** Name of the master database table.  The master database table
00425 ** is a special table that holds the names and attributes of all
00426 ** user tables and indices.
00427 */
00428 #define MASTER_NAME       "sqlite_master"
00429 #define TEMP_MASTER_NAME  "sqlite_temp_master"
00430 
00431 /*
00432 ** The root-page of the master database table.
00433 */
00434 #define MASTER_ROOT       1
00435 
00436 /*
00437 ** The name of the schema table.
00438 */
00439 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
00440 
00441 /*
00442 ** A convenience macro that returns the number of elements in
00443 ** an array.
00444 */
00445 #define ArraySize(X)    (sizeof(X)/sizeof(X[0]))
00446 
00447 /*
00448 ** The following value as a destructor means to use sqlite3DbFree().
00449 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
00450 */
00451 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
00452 
00453 /*
00454 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
00455 ** not support Writable Static Data (WSD) such as global and static variables.
00456 ** All variables must either be on the stack or dynamically allocated from
00457 ** the heap.  When WSD is unsupported, the variable declarations scattered
00458 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
00459 ** macro is used for this purpose.  And instead of referencing the variable
00460 ** directly, we use its constant as a key to lookup the run-time allocated
00461 ** buffer that holds real variable.  The constant is also the initializer
00462 ** for the run-time allocated buffer.
00463 **
00464 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
00465 ** macros become no-ops and have zero performance impact.
00466 */
00467 #ifdef SQLITE_OMIT_WSD
00468   #define SQLITE_WSD const
00469   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
00470   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
00471   int sqlite3_wsd_init(int N, int J);
00472   void *sqlite3_wsd_find(void *K, int L);
00473 #else
00474   #define SQLITE_WSD 
00475   #define GLOBAL(t,v) v
00476   #define sqlite3GlobalConfig sqlite3Config
00477 #endif
00478 
00479 /*
00480 ** Forward references to structures
00481 */
00482 typedef struct AggInfo AggInfo;
00483 typedef struct AuthContext AuthContext;
00484 typedef struct Bitvec Bitvec;
00485 typedef struct CollSeq CollSeq;
00486 typedef struct Column Column;
00487 typedef struct Db Db;
00488 typedef struct Schema Schema;
00489 typedef struct Expr Expr;
00490 typedef struct ExprList ExprList;
00491 typedef struct FKey FKey;
00492 typedef struct FuncDef FuncDef;
00493 typedef struct FuncDefHash FuncDefHash;
00494 typedef struct IdList IdList;
00495 typedef struct Index Index;
00496 typedef struct KeyClass KeyClass;
00497 typedef struct KeyInfo KeyInfo;
00498 typedef struct Lookaside Lookaside;
00499 typedef struct LookasideSlot LookasideSlot;
00500 typedef struct Module Module;
00501 typedef struct NameContext NameContext;
00502 typedef struct Parse Parse;
00503 typedef struct Select Select;
00504 typedef struct SrcList SrcList;
00505 typedef struct StrAccum StrAccum;
00506 typedef struct Table Table;
00507 typedef struct TableLock TableLock;
00508 typedef struct Token Token;
00509 typedef struct TriggerStack TriggerStack;
00510 typedef struct TriggerStep TriggerStep;
00511 typedef struct Trigger Trigger;
00512 typedef struct UnpackedRecord UnpackedRecord;
00513 typedef struct Walker Walker;
00514 typedef struct WhereInfo WhereInfo;
00515 typedef struct WhereLevel WhereLevel;
00516 
00517 /*
00518 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
00519 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
00520 ** pointer types (i.e. FuncDef) defined above.
00521 */
00522 #include "btree.h"
00523 #include "vdbe.h"
00524 #include "pager.h"
00525 #include "pcache.h"
00526 
00527 #include "os.h"
00528 #include "mutex.h"
00529 
00530 
00531 /*
00532 ** Each database file to be accessed by the system is an instance
00533 ** of the following structure.  There are normally two of these structures
00534 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
00535 ** aDb[1] is the database file used to hold temporary tables.  Additional
00536 ** databases may be attached.
00537 */
00538 struct Db {
00539   char *zName;         /* Name of this database */
00540   Btree *pBt;          /* The B*Tree structure for this database file */
00541   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
00542   u8 safety_level;     /* How aggressive at synching data to disk */
00543   void *pAux;               /* Auxiliary data.  Usually NULL */
00544   void (*xFreeAux)(void*);  /* Routine to free pAux */
00545   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
00546 };
00547 
00548 /*
00549 ** An instance of the following structure stores a database schema.
00550 **
00551 ** If there are no virtual tables configured in this schema, the
00552 ** Schema.db variable is set to NULL. After the first virtual table
00553 ** has been added, it is set to point to the database connection 
00554 ** used to create the connection. Once a virtual table has been
00555 ** added to the Schema structure and the Schema.db variable populated, 
00556 ** only that database connection may use the Schema to prepare 
00557 ** statements.
00558 */
00559 struct Schema {
00560   int schema_cookie;   /* Database schema version number for this file */
00561   Hash tblHash;        /* All tables indexed by name */
00562   Hash idxHash;        /* All (named) indices indexed by name */
00563   Hash trigHash;       /* All triggers indexed by name */
00564   Hash aFKey;          /* Foreign keys indexed by to-table */
00565   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
00566   u8 file_format;      /* Schema format version for this file */
00567   u8 enc;              /* Text encoding used by this database */
00568   u16 flags;           /* Flags associated with this schema */
00569   int cache_size;      /* Number of pages to use in the cache */
00570 #ifndef SQLITE_OMIT_VIRTUALTABLE
00571   sqlite3 *db;         /* "Owner" connection. See comment above */
00572 #endif
00573 };
00574 
00575 /*
00576 ** These macros can be used to test, set, or clear bits in the 
00577 ** Db.flags field.
00578 */
00579 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
00580 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
00581 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
00582 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
00583 
00584 /*
00585 ** Allowed values for the DB.flags field.
00586 **
00587 ** The DB_SchemaLoaded flag is set after the database schema has been
00588 ** read into internal hash tables.
00589 **
00590 ** DB_UnresetViews means that one or more views have column names that
00591 ** have been filled out.  If the schema changes, these column names might
00592 ** changes and so the view will need to be reset.
00593 */
00594 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
00595 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
00596 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
00597 
00598 /*
00599 ** The number of different kinds of things that can be limited
00600 ** using the sqlite3_limit() interface.
00601 */
00602 #define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1)
00603 
00604 /*
00605 ** Lookaside malloc is a set of fixed-size buffers that can be used
00606 ** to satisify small transient memory allocation requests for objects
00607 ** associated with a particular database connection.  The use of
00608 ** lookaside malloc provides a significant performance enhancement
00609 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
00610 ** SQL statements.
00611 **
00612 ** The Lookaside structure holds configuration information about the
00613 ** lookaside malloc subsystem.  Each available memory allocation in
00614 ** the lookaside subsystem is stored on a linked list of LookasideSlot
00615 ** objects.
00616 */
00617 struct Lookaside {
00618   u16 sz;                 /* Size of each buffer in bytes */
00619   u8 bEnabled;            /* True if use lookaside.  False to ignore it */
00620   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
00621   int nOut;               /* Number of buffers currently checked out */
00622   int mxOut;              /* Highwater mark for nOut */
00623   LookasideSlot *pFree;   /* List of available buffers */
00624   void *pStart;           /* First byte of available memory space */
00625   void *pEnd;             /* First byte past end of available space */
00626 };
00627 struct LookasideSlot {
00628   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
00629 };
00630 
00631 /*
00632 ** A hash table for function definitions.
00633 **
00634 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
00635 ** Collisions are on the FuncDef.pHash chain.
00636 */
00637 struct FuncDefHash {
00638   FuncDef *a[23];       /* Hash table for functions */
00639 };
00640 
00641 /*
00642 ** Each database is an instance of the following structure.
00643 **
00644 ** The sqlite.lastRowid records the last insert rowid generated by an
00645 ** insert statement.  Inserts on views do not affect its value.  Each
00646 ** trigger has its own context, so that lastRowid can be updated inside
00647 ** triggers as usual.  The previous value will be restored once the trigger
00648 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
00649 ** longer (since after version 2.8.12) reset to -1.
00650 **
00651 ** The sqlite.nChange does not count changes within triggers and keeps no
00652 ** context.  It is reset at start of sqlite3_exec.
00653 ** The sqlite.lsChange represents the number of changes made by the last
00654 ** insert, update, or delete statement.  It remains constant throughout the
00655 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
00656 ** context stack just like lastRowid so that the count of changes
00657 ** within a trigger is not seen outside the trigger.  Changes to views do not
00658 ** affect the value of lsChange.
00659 ** The sqlite.csChange keeps track of the number of current changes (since
00660 ** the last statement) and is used to update sqlite_lsChange.
00661 **
00662 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
00663 ** store the most recent error code and, if applicable, string. The
00664 ** internal function sqlite3Error() is used to set these variables
00665 ** consistently.
00666 */
00667 struct sqlite3 {
00668   sqlite3_vfs *pVfs;            /* OS Interface */
00669   int nDb;                      /* Number of backends currently in use */
00670   Db *aDb;                      /* All backends */
00671   int flags;                    /* Miscellanous flags. See below */
00672   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
00673   int errCode;                  /* Most recent error code (SQLITE_*) */
00674   int errMask;                  /* & result codes with this before returning */
00675   u8 autoCommit;                /* The auto-commit flag. */
00676   u8 temp_store;                /* 1: file 2: memory 0: default */
00677   u8 mallocFailed;              /* True if we have seen a malloc failure */
00678   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
00679   u8 dfltJournalMode;           /* Default journal mode for attached dbs */
00680   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
00681   int nextPagesize;             /* Pagesize after VACUUM if >0 */
00682   int nTable;                   /* Number of tables in the database */
00683   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
00684   i64 lastRowid;                /* ROWID of most recent insert (see above) */
00685   i64 priorNewRowid;            /* Last randomly generated ROWID */
00686   int magic;                    /* Magic number for detect library misuse */
00687   int nChange;                  /* Value returned by sqlite3_changes() */
00688   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
00689   sqlite3_mutex *mutex;         /* Connection mutex */
00690   int aLimit[SQLITE_N_LIMIT];   /* Limits */
00691   struct sqlite3InitInfo {      /* Information used during initialization */
00692     int iDb;                    /* When back is being initialized */
00693     int newTnum;                /* Rootpage of table being initialized */
00694     u8 busy;                    /* TRUE if currently initializing */
00695   } init;
00696   int nExtension;               /* Number of loaded extensions */
00697   void **aExtension;            /* Array of shared libraray handles */
00698   struct Vdbe *pVdbe;           /* List of active virtual machines */
00699   int activeVdbeCnt;            /* Number of vdbes currently executing */
00700   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
00701   void (*xTrace)(void*,const char*);        /* Trace function */
00702   void *pTraceArg;                          /* Argument to the trace function */
00703   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
00704   void *pProfileArg;                        /* Argument to profile function */
00705   void *pCommitArg;                 /* Argument to xCommitCallback() */   
00706   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
00707   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
00708   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
00709   void *pUpdateArg;
00710   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
00711   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
00712   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
00713   void *pCollNeededArg;
00714   sqlite3_value *pErr;          /* Most recent error message */
00715   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
00716   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
00717   union {
00718     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
00719     double notUsed1;            /* Spacer */
00720   } u1;
00721   Lookaside lookaside;          /* Lookaside malloc configuration */
00722 #ifndef SQLITE_OMIT_AUTHORIZATION
00723   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
00724                                 /* Access authorization function */
00725   void *pAuthArg;               /* 1st argument to the access auth function */
00726 #endif
00727 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
00728   int (*xProgress)(void *);     /* The progress callback */
00729   void *pProgressArg;           /* Argument to the progress callback */
00730   int nProgressOps;             /* Number of opcodes for progress callback */
00731 #endif
00732 #ifndef SQLITE_OMIT_VIRTUALTABLE
00733   Hash aModule;                 /* populated by sqlite3_create_module() */
00734   Table *pVTab;                 /* vtab with active Connect/Create method */
00735   sqlite3_vtab **aVTrans;       /* Virtual tables with open transactions */
00736   int nVTrans;                  /* Allocated size of aVTrans */
00737 #endif
00738   FuncDefHash aFunc;            /* Hash table of connection functions */
00739   Hash aCollSeq;                /* All collating sequences */
00740   BusyHandler busyHandler;      /* Busy callback */
00741   int busyTimeout;              /* Busy handler timeout, in msec */
00742   Db aDbStatic[2];              /* Static space for the 2 default backends */
00743 #ifdef SQLITE_SSE
00744   sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
00745 #endif
00746 };
00747 
00748 /*
00749 ** A macro to discover the encoding of a database.
00750 */
00751 #define ENC(db) ((db)->aDb[0].pSchema->enc)
00752 
00753 /*
00754 ** Possible values for the sqlite.flags and or Db.flags fields.
00755 **
00756 ** On sqlite.flags, the SQLITE_InTrans value means that we have
00757 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
00758 ** transaction is active on that particular database file.
00759 */
00760 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
00761 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
00762 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
00763 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
00764 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
00765 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
00766                                           /*   DELETE, or UPDATE and return */
00767                                           /*   the count using a callback. */
00768 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
00769                                           /*   result set is empty */
00770 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
00771 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
00772 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
00773 #define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
00774                                           ** accessing read-only databases */
00775 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
00776 #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
00777 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
00778 #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
00779 #define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */
00780 
00781 #define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
00782 #define SQLITE_SharedCache    0x00080000  /* Cache sharing is enabled */
00783 #define SQLITE_Vtab           0x00100000  /* There exists a virtual table */
00784 
00785 /*
00786 ** Possible values for the sqlite.magic field.
00787 ** The numbers are obtained at random and have no special meaning, other
00788 ** than being distinct from one another.
00789 */
00790 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
00791 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
00792 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
00793 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
00794 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
00795 
00796 /*
00797 ** Each SQL function is defined by an instance of the following
00798 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
00799 ** hash table.  When multiple functions have the same name, the hash table
00800 ** points to a linked list of these structures.
00801 */
00802 struct FuncDef {
00803   i16 nArg;            /* Number of arguments.  -1 means unlimited */
00804   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
00805   u8 flags;            /* Some combination of SQLITE_FUNC_* */
00806   void *pUserData;     /* User data parameter */
00807   FuncDef *pNext;      /* Next function with same name */
00808   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
00809   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
00810   void (*xFinalize)(sqlite3_context*);                /* Aggregate finializer */
00811   char *zName;         /* SQL name of the function. */
00812   FuncDef *pHash;      /* Next with a different name but the same hash */
00813 };
00814 
00815 /*
00816 ** Possible values for FuncDef.flags
00817 */
00818 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
00819 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
00820 #define SQLITE_FUNC_EPHEM    0x04 /* Ephermeral.  Delete with VDBE */
00821 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
00822 
00823 /*
00824 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
00825 ** used to create the initializers for the FuncDef structures.
00826 **
00827 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
00828 **     Used to create a scalar function definition of a function zName 
00829 **     implemented by C function xFunc that accepts nArg arguments. The
00830 **     value passed as iArg is cast to a (void*) and made available
00831 **     as the user-data (sqlite3_user_data()) for the function. If 
00832 **     argument bNC is true, then the FuncDef.needCollate flag is set.
00833 **
00834 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
00835 **     Used to create an aggregate function definition implemented by
00836 **     the C functions xStep and xFinal. The first four parameters
00837 **     are interpreted in the same way as the first 4 parameters to
00838 **     FUNCTION().
00839 **
00840 **   LIKEFUNC(zName, nArg, pArg, flags)
00841 **     Used to create a scalar function definition of a function zName 
00842 **     that accepts nArg arguments and is implemented by a call to C 
00843 **     function likeFunc. Argument pArg is cast to a (void *) and made
00844 **     available as the function user-data (sqlite3_user_data()). The
00845 **     FuncDef.flags variable is set to the value passed as the flags
00846 **     parameter.
00847 */
00848 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
00849   {nArg, SQLITE_UTF8, bNC*8, SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName}
00850 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
00851   {nArg, SQLITE_UTF8, bNC*8, pArg, 0, xFunc, 0, 0, #zName}
00852 #define LIKEFUNC(zName, nArg, arg, flags) \
00853   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName}
00854 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
00855   {nArg, SQLITE_UTF8, nc*8, SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal, #zName}
00856 
00857 
00858 /*
00859 ** Each SQLite module (virtual table definition) is defined by an
00860 ** instance of the following structure, stored in the sqlite3.aModule
00861 ** hash table.
00862 */
00863 struct Module {
00864   const sqlite3_module *pModule;       /* Callback pointers */
00865   const char *zName;                   /* Name passed to create_module() */
00866   void *pAux;                          /* pAux passed to create_module() */
00867   void (*xDestroy)(void *);            /* Module destructor function */
00868 };
00869 
00870 /*
00871 ** information about each column of an SQL table is held in an instance
00872 ** of this structure.
00873 */
00874 struct Column {
00875   char *zName;     /* Name of this column */
00876   Expr *pDflt;     /* Default value of this column */
00877   char *zType;     /* Data type for this column */
00878   char *zColl;     /* Collating sequence.  If NULL, use the default */
00879   u8 notNull;      /* True if there is a NOT NULL constraint */
00880   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
00881   char affinity;   /* One of the SQLITE_AFF_... values */
00882 #ifndef SQLITE_OMIT_VIRTUALTABLE
00883   u8 isHidden;     /* True if this column is 'hidden' */
00884 #endif
00885 };
00886 
00887 /*
00888 ** A "Collating Sequence" is defined by an instance of the following
00889 ** structure. Conceptually, a collating sequence consists of a name and
00890 ** a comparison routine that defines the order of that sequence.
00891 **
00892 ** There may two seperate implementations of the collation function, one
00893 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
00894 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
00895 ** native byte order. When a collation sequence is invoked, SQLite selects
00896 ** the version that will require the least expensive encoding
00897 ** translations, if any.
00898 **
00899 ** The CollSeq.pUser member variable is an extra parameter that passed in
00900 ** as the first argument to the UTF-8 comparison function, xCmp.
00901 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
00902 ** xCmp16.
00903 **
00904 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
00905 ** collating sequence is undefined.  Indices built on an undefined
00906 ** collating sequence may not be read or written.
00907 */
00908 struct CollSeq {
00909   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
00910   u8 enc;               /* Text encoding handled by xCmp() */
00911   u8 type;              /* One of the SQLITE_COLL_... values below */
00912   void *pUser;          /* First argument to xCmp() */
00913   int (*xCmp)(void*,int, const void*, int, const void*);
00914   void (*xDel)(void*);  /* Destructor for pUser */
00915 };
00916 
00917 /*
00918 ** Allowed values of CollSeq.type:
00919 */
00920 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
00921 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
00922 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
00923 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
00924 
00925 /*
00926 ** A sort order can be either ASC or DESC.
00927 */
00928 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
00929 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
00930 
00931 /*
00932 ** Column affinity types.
00933 **
00934 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
00935 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
00936 ** the speed a little by numbering the values consecutively.  
00937 **
00938 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
00939 ** when multiple affinity types are concatenated into a string and
00940 ** used as the P4 operand, they will be more readable.
00941 **
00942 ** Note also that the numeric types are grouped together so that testing
00943 ** for a numeric type is a single comparison.
00944 */
00945 #define SQLITE_AFF_TEXT     'a'
00946 #define SQLITE_AFF_NONE     'b'
00947 #define SQLITE_AFF_NUMERIC  'c'
00948 #define SQLITE_AFF_INTEGER  'd'
00949 #define SQLITE_AFF_REAL     'e'
00950 
00951 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
00952 
00953 /*
00954 ** The SQLITE_AFF_MASK values masks off the significant bits of an
00955 ** affinity value. 
00956 */
00957 #define SQLITE_AFF_MASK     0x67
00958 
00959 /*
00960 ** Additional bit values that can be ORed with an affinity without
00961 ** changing the affinity.
00962 */
00963 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
00964 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
00965 
00966 /*
00967 ** Each SQL table is represented in memory by an instance of the
00968 ** following structure.
00969 **
00970 ** Table.zName is the name of the table.  The case of the original
00971 ** CREATE TABLE statement is stored, but case is not significant for
00972 ** comparisons.
00973 **
00974 ** Table.nCol is the number of columns in this table.  Table.aCol is a
00975 ** pointer to an array of Column structures, one for each column.
00976 **
00977 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
00978 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
00979 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
00980 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
00981 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
00982 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
00983 ** the table has any PRIMARY KEY, INTEGER or otherwise.
00984 **
00985 ** Table.tnum is the page number for the root BTree page of the table in the
00986 ** database file.  If Table.iDb is the index of the database table backend
00987 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
00988 ** holds temporary tables and indices.  If TF_Ephemeral is set
00989 ** then the table is stored in a file that is automatically deleted
00990 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
00991 ** refers VDBE cursor number that holds the table open, not to the root
00992 ** page number.  Transient tables are used to hold the results of a
00993 ** sub-query that appears instead of a real table name in the FROM clause 
00994 ** of a SELECT statement.
00995 */
00996 struct Table {
00997   sqlite3 *db;         /* Associated database connection.  Might be NULL. */
00998   char *zName;         /* Name of the table or view */
00999   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
01000   int nCol;            /* Number of columns in this table */
01001   Column *aCol;        /* Information about each column */
01002   Index *pIndex;       /* List of SQL indexes on this table. */
01003   int tnum;            /* Root BTree node for this table (see note above) */
01004   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
01005   u16 nRef;            /* Number of pointers to this Table */
01006   u8 tabFlags;         /* Mask of TF_* values */
01007   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
01008   Trigger *pTrigger;   /* List of SQL triggers on this table */
01009   FKey *pFKey;         /* Linked list of all foreign keys in this table */
01010   char *zColAff;       /* String defining the affinity of each column */
01011 #ifndef SQLITE_OMIT_CHECK
01012   Expr *pCheck;        /* The AND of all CHECK constraints */
01013 #endif
01014 #ifndef SQLITE_OMIT_ALTERTABLE
01015   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
01016 #endif
01017 #ifndef SQLITE_OMIT_VIRTUALTABLE
01018   Module *pMod;        /* Pointer to the implementation of the module */
01019   sqlite3_vtab *pVtab; /* Pointer to the module instance */
01020   int nModuleArg;      /* Number of arguments to the module */
01021   char **azModuleArg;  /* Text of all module args. [0] is module name */
01022 #endif
01023   Schema *pSchema;     /* Schema that contains this table */
01024   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
01025 };
01026 
01027 /*
01028 ** Allowed values for Tabe.tabFlags.
01029 */
01030 #define TF_Readonly        0x01    /* Read-only system table */
01031 #define TF_Ephemeral       0x02    /* An emphermal table */
01032 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
01033 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
01034 #define TF_Virtual         0x10    /* Is a virtual table */
01035 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
01036 
01037 
01038 
01039 /*
01040 ** Test to see whether or not a table is a virtual table.  This is
01041 ** done as a macro so that it will be optimized out when virtual
01042 ** table support is omitted from the build.
01043 */
01044 #ifndef SQLITE_OMIT_VIRTUALTABLE
01045 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
01046 #  define IsHiddenColumn(X) ((X)->isHidden)
01047 #else
01048 #  define IsVirtual(X)      0
01049 #  define IsHiddenColumn(X) 0
01050 #endif
01051 
01052 /*
01053 ** Each foreign key constraint is an instance of the following structure.
01054 **
01055 ** A foreign key is associated with two tables.  The "from" table is
01056 ** the table that contains the REFERENCES clause that creates the foreign
01057 ** key.  The "to" table is the table that is named in the REFERENCES clause.
01058 ** Consider this example:
01059 **
01060 **     CREATE TABLE ex1(
01061 **       a INTEGER PRIMARY KEY,
01062 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
01063 **     );
01064 **
01065 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
01066 **
01067 ** Each REFERENCES clause generates an instance of the following structure
01068 ** which is attached to the from-table.  The to-table need not exist when
01069 ** the from-table is created.  The existance of the to-table is not checked
01070 ** until an attempt is made to insert data into the from-table.
01071 **
01072 ** The sqlite.aFKey hash table stores pointers to this structure
01073 ** given the name of a to-table.  For each to-table, all foreign keys
01074 ** associated with that table are on a linked list using the FKey.pNextTo
01075 ** field.
01076 */
01077 struct FKey {
01078   Table *pFrom;     /* The table that constains the REFERENCES clause */
01079   FKey *pNextFrom;  /* Next foreign key in pFrom */
01080   char *zTo;        /* Name of table that the key points to */
01081   FKey *pNextTo;    /* Next foreign key that points to zTo */
01082   int nCol;         /* Number of columns in this key */
01083   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
01084     int iFrom;         /* Index of column in pFrom */
01085     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
01086   } *aCol;          /* One entry for each of nCol column s */
01087   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
01088   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
01089   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
01090   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
01091 };
01092 
01093 /*
01094 ** SQLite supports many different ways to resolve a constraint
01095 ** error.  ROLLBACK processing means that a constraint violation
01096 ** causes the operation in process to fail and for the current transaction
01097 ** to be rolled back.  ABORT processing means the operation in process
01098 ** fails and any prior changes from that one operation are backed out,
01099 ** but the transaction is not rolled back.  FAIL processing means that
01100 ** the operation in progress stops and returns an error code.  But prior
01101 ** changes due to the same operation are not backed out and no rollback
01102 ** occurs.  IGNORE means that the particular row that caused the constraint
01103 ** error is not inserted or updated.  Processing continues and no error
01104 ** is returned.  REPLACE means that preexisting database rows that caused
01105 ** a UNIQUE constraint violation are removed so that the new insert or
01106 ** update can proceed.  Processing continues and no error is reported.
01107 **
01108 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
01109 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
01110 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
01111 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
01112 ** referenced table row is propagated into the row that holds the
01113 ** foreign key.
01114 ** 
01115 ** The following symbolic values are used to record which type
01116 ** of action to take.
01117 */
01118 #define OE_None     0   /* There is no constraint to check */
01119 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
01120 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
01121 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
01122 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
01123 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
01124 
01125 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
01126 #define OE_SetNull  7   /* Set the foreign key value to NULL */
01127 #define OE_SetDflt  8   /* Set the foreign key value to its default */
01128 #define OE_Cascade  9   /* Cascade the changes */
01129 
01130 #define OE_Default  99  /* Do whatever the default action is */
01131 
01132 
01133 /*
01134 ** An instance of the following structure is passed as the first
01135 ** argument to sqlite3VdbeKeyCompare and is used to control the 
01136 ** comparison of the two index keys.
01137 */
01138 struct KeyInfo {
01139   sqlite3 *db;        /* The database connection */
01140   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
01141   u16 nField;         /* Number of entries in aColl[] */
01142   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
01143   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
01144 };
01145 
01146 /*
01147 ** An instance of the following structure holds information about a
01148 ** single index record that has already been parsed out into individual
01149 ** values.
01150 **
01151 ** A record is an object that contains one or more fields of data.
01152 ** Records are used to store the content of a table row and to store
01153 ** the key of an index.  A blob encoding of a record is created by
01154 ** the OP_MakeRecord opcode of the VDBE and is disassemblied by the
01155 ** OP_Column opcode.
01156 **
01157 ** This structure holds a record that has already been disassembled
01158 ** into its constitutent fields.
01159 */
01160 struct UnpackedRecord {
01161   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
01162   u16 nField;         /* Number of entries in apMem[] */
01163   u16 flags;          /* Boolean settings.  UNPACKED_... below */
01164   Mem *aMem;          /* Values */
01165 };
01166 
01167 /*
01168 ** Allowed values of UnpackedRecord.flags
01169 */
01170 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
01171 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
01172 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
01173 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
01174 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
01175 
01176 /*
01177 ** Each SQL index is represented in memory by an
01178 ** instance of the following structure.
01179 **
01180 ** The columns of the table that are to be indexed are described
01181 ** by the aiColumn[] field of this structure.  For example, suppose
01182 ** we have the following table and index:
01183 **
01184 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
01185 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
01186 **
01187 ** In the Table structure describing Ex1, nCol==3 because there are
01188 ** three columns in the table.  In the Index structure describing
01189 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
01190 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
01191 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
01192 ** The second column to be indexed (c1) has an index of 0 in
01193 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
01194 **
01195 ** The Index.onError field determines whether or not the indexed columns
01196 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
01197 ** it means this is not a unique index.  Otherwise it is a unique index
01198 ** and the value of Index.onError indicate the which conflict resolution 
01199 ** algorithm to employ whenever an attempt is made to insert a non-unique
01200 ** element.
01201 */
01202 struct Index {
01203   char *zName;     /* Name of this index */
01204   int nColumn;     /* Number of columns in the table used by this index */
01205   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
01206   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
01207   Table *pTable;   /* The SQL table being indexed */
01208   int tnum;        /* Page containing root of this index in database file */
01209   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
01210   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
01211   char *zColAff;   /* String defining the affinity of each column */
01212   Index *pNext;    /* The next index associated with the same table */
01213   Schema *pSchema; /* Schema containing this index */
01214   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
01215   char **azColl;   /* Array of collation sequence names for index */
01216 };
01217 
01218 /*
01219 ** Each token coming out of the lexer is an instance of
01220 ** this structure.  Tokens are also used as part of an expression.
01221 **
01222 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
01223 ** may contain random values.  Do not make any assuptions about Token.dyn
01224 ** and Token.n when Token.z==0.
01225 */
01226 struct Token {
01227   const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
01228   unsigned dyn  : 1;      /* True for malloced memory, false for static */
01229   unsigned n    : 31;     /* Number of characters in this token */
01230 };
01231 
01232 /*
01233 ** An instance of this structure contains information needed to generate
01234 ** code for a SELECT that contains aggregate functions.
01235 **
01236 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
01237 ** pointer to this structure.  The Expr.iColumn field is the index in
01238 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
01239 ** code for that node.
01240 **
01241 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
01242 ** original Select structure that describes the SELECT statement.  These
01243 ** fields do not need to be freed when deallocating the AggInfo structure.
01244 */
01245 struct AggInfo {
01246   u8 directMode;          /* Direct rendering mode means take data directly
01247                           ** from source tables rather than from accumulators */
01248   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
01249                           ** than the source table */
01250   int sortingIdx;         /* Cursor number of the sorting index */
01251   ExprList *pGroupBy;     /* The group by clause */
01252   int nSortingColumn;     /* Number of columns in the sorting index */
01253   struct AggInfo_col {    /* For each column used in source tables */
01254     Table *pTab;             /* Source table */
01255     int iTable;              /* Cursor number of the source table */
01256     int iColumn;             /* Column number within the source table */
01257     int iSorterColumn;       /* Column number in the sorting index */
01258     int iMem;                /* Memory location that acts as accumulator */
01259     Expr *pExpr;             /* The original expression */
01260   } *aCol;
01261   int nColumn;            /* Number of used entries in aCol[] */
01262   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
01263   int nAccumulator;       /* Number of columns that show through to the output.
01264                           ** Additional columns are used only as parameters to
01265                           ** aggregate functions */
01266   struct AggInfo_func {   /* For each aggregate function */
01267     Expr *pExpr;             /* Expression encoding the function */
01268     FuncDef *pFunc;          /* The aggregate function implementation */
01269     int iMem;                /* Memory location that acts as accumulator */
01270     int iDistinct;           /* Ephermeral table used to enforce DISTINCT */
01271   } *aFunc;
01272   int nFunc;              /* Number of entries in aFunc[] */
01273   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
01274 };
01275 
01276 /*
01277 ** Each node of an expression in the parse tree is an instance
01278 ** of this structure.
01279 **
01280 ** Expr.op is the opcode.  The integer parser token codes are reused
01281 ** as opcodes here.  For example, the parser defines TK_GE to be an integer
01282 ** code representing the ">=" operator.  This same integer code is reused
01283 ** to represent the greater-than-or-equal-to operator in the expression
01284 ** tree.
01285 **
01286 ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
01287 ** of argument if the expression is a function.
01288 **
01289 ** Expr.token is the operator token for this node.  For some expressions
01290 ** that have subexpressions, Expr.token can be the complete text that gave
01291 ** rise to the Expr.  In the latter case, the token is marked as being
01292 ** a compound token.
01293 **
01294 ** An expression of the form ID or ID.ID refers to a column in a table.
01295 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
01296 ** the integer cursor number of a VDBE cursor pointing to that table and
01297 ** Expr.iColumn is the column number for the specific column.  If the
01298 ** expression is used as a result in an aggregate SELECT, then the
01299 ** value is also stored in the Expr.iAgg column in the aggregate so that
01300 ** it can be accessed after all aggregates are computed.
01301 **
01302 ** If the expression is a function, the Expr.iTable is an integer code
01303 ** representing which function.  If the expression is an unbound variable
01304 ** marker (a question mark character '?' in the original SQL) then the
01305 ** Expr.iTable holds the index number for that variable.
01306 **
01307 ** If the expression is a subquery then Expr.iColumn holds an integer
01308 ** register number containing the result of the subquery.  If the
01309 ** subquery gives a constant result, then iTable is -1.  If the subquery
01310 ** gives a different answer at different times during statement processing
01311 ** then iTable is the address of a subroutine that computes the subquery.
01312 **
01313 ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
01314 ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
01315 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
01316 ** operand.
01317 **
01318 ** If the Expr is of type OP_Column, and the table it is selecting from
01319 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
01320 ** corresponding table definition.
01321 */
01322 struct Expr {
01323   u8 op;                 /* Operation performed by this node */
01324   char affinity;         /* The affinity of the column or 0 if not a column */
01325   u16 flags;             /* Various flags.  See below */
01326   CollSeq *pColl;        /* The collation type of the column or 0 */
01327   Expr *pLeft, *pRight;  /* Left and right subnodes */
01328   ExprList *pList;       /* A list of expressions used as function arguments
01329                          ** or in "<expr> IN (<expr-list)" */
01330   Token token;           /* An operand token */
01331   Token span;            /* Complete text of the expression */
01332   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
01333                          ** iColumn-th field of the iTable-th table. */
01334   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
01335   int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
01336   int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
01337   Select *pSelect;       /* When the expression is a sub-select.  Also the
01338                          ** right side of "<expr> IN (<select>)" */
01339   Table *pTab;           /* Table for TK_COLUMN expressions. */
01340 #if SQLITE_MAX_EXPR_DEPTH>0
01341   int nHeight;           /* Height of the tree headed by this node */
01342 #endif
01343 };
01344 
01345 /*
01346 ** The following are the meanings of bits in the Expr.flags field.
01347 */
01348 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
01349 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
01350 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
01351 #define EP_Error      0x0008  /* Expression contains one or more errors */
01352 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
01353 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
01354 #define EP_Dequoted   0x0040  /* True if the string has been dequoted */
01355 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
01356 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
01357 #define EP_AnyAff     0x0200  /* Can take a cached column of any affinity */
01358 #define EP_FixedDest  0x0400  /* Result needed in a specific register */
01359 #define EP_IntValue   0x0800  /* Integer value contained in iTable */
01360 /*
01361 ** These macros can be used to test, set, or clear bits in the 
01362 ** Expr.flags field.
01363 */
01364 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
01365 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
01366 #define ExprSetProperty(E,P)     (E)->flags|=(P)
01367 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
01368 
01369 /*
01370 ** A list of expressions.  Each expression may optionally have a
01371 ** name.  An expr/name combination can be used in several ways, such
01372 ** as the list of "expr AS ID" fields following a "SELECT" or in the
01373 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
01374 ** also be used as the argument to a function, in which case the a.zName
01375 ** field is not used.
01376 */
01377 struct ExprList {
01378   int nExpr;             /* Number of expressions on the list */
01379   int nAlloc;            /* Number of entries allocated below */
01380   int iECursor;          /* VDBE Cursor associated with this ExprList */
01381   struct ExprList_item {
01382     Expr *pExpr;           /* The list of expressions */
01383     char *zName;           /* Token associated with this expression */
01384     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
01385     u8 done;               /* A flag to indicate when processing is finished */
01386     u16 iCol;              /* For ORDER BY, column number in result set */
01387     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
01388   } *a;                  /* One entry for each expression */
01389 };
01390 
01391 /*
01392 ** An instance of this structure can hold a simple list of identifiers,
01393 ** such as the list "a,b,c" in the following statements:
01394 **
01395 **      INSERT INTO t(a,b,c) VALUES ...;
01396 **      CREATE INDEX idx ON t(a,b,c);
01397 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
01398 **
01399 ** The IdList.a.idx field is used when the IdList represents the list of
01400 ** column names after a table name in an INSERT statement.  In the statement
01401 **
01402 **     INSERT INTO t(a,b,c) ...
01403 **
01404 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
01405 */
01406 struct IdList {
01407   struct IdList_item {
01408     char *zName;      /* Name of the identifier */
01409     int idx;          /* Index in some Table.aCol[] of a column named zName */
01410   } *a;
01411   int nId;         /* Number of identifiers on the list */
01412   int nAlloc;      /* Number of entries allocated for a[] below */
01413 };
01414 
01415 /*
01416 ** The bitmask datatype defined below is used for various optimizations.
01417 **
01418 ** Changing this from a 64-bit to a 32-bit type limits the number of
01419 ** tables in a join to 32 instead of 64.  But it also reduces the size
01420 ** of the library by 738 bytes on ix86.
01421 */
01422 typedef u64 Bitmask;
01423 
01424 /*
01425 ** The following structure describes the FROM clause of a SELECT statement.
01426 ** Each table or subquery in the FROM clause is a separate element of
01427 ** the SrcList.a[] array.
01428 **
01429 ** With the addition of multiple database support, the following structure
01430 ** can also be used to describe a particular table such as the table that
01431 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
01432 ** such a table must be a simple name: ID.  But in SQLite, the table can
01433 ** now be identified by a database name, a dot, then the table name: ID.ID.
01434 **
01435 ** The jointype starts out showing the join type between the current table
01436 ** and the next table on the list.  The parser builds the list this way.
01437 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
01438 ** jointype expresses the join between the table and the previous table.
01439 */
01440 struct SrcList {
01441   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
01442   i16 nAlloc;      /* Number of entries allocated in a[] below */
01443   struct SrcList_item {
01444     char *zDatabase;  /* Name of database holding this table */
01445     char *zName;      /* Name of the table */
01446     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
01447     Table *pTab;      /* An SQL table corresponding to zName */
01448     Select *pSelect;  /* A SELECT statement used in place of a table name */
01449     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
01450     u8 jointype;      /* Type of join between this able and the previous */
01451     int iCursor;      /* The VDBE cursor number used to access this table */
01452     Expr *pOn;        /* The ON clause of a join */
01453     IdList *pUsing;   /* The USING clause of a join */
01454     Bitmask colUsed;  /* Bit N (1<<N) set if column N or pTab is used */
01455     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
01456     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
01457     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
01458   } a[1];             /* One entry for each identifier on the list */
01459 };
01460 
01461 /*
01462 ** Permitted values of the SrcList.a.jointype field
01463 */
01464 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
01465 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
01466 #define JT_NATURAL   0x0004    /* True for a "natural" join */
01467 #define JT_LEFT      0x0008    /* Left outer join */
01468 #define JT_RIGHT     0x0010    /* Right outer join */
01469 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
01470 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
01471 
01472 /*
01473 ** For each nested loop in a WHERE clause implementation, the WhereInfo
01474 ** structure contains a single instance of this structure.  This structure
01475 ** is intended to be private the the where.c module and should not be
01476 ** access or modified by other modules.
01477 **
01478 ** The pIdxInfo and pBestIdx fields are used to help pick the best
01479 ** index on a virtual table.  The pIdxInfo pointer contains indexing
01480 ** information for the i-th table in the FROM clause before reordering.
01481 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
01482 ** The pBestIdx pointer is a copy of pIdxInfo for the i-th table after
01483 ** FROM clause ordering.  This is a little confusing so I will repeat
01484 ** it in different words.  WhereInfo.a[i].pIdxInfo is index information 
01485 ** for WhereInfo.pTabList.a[i].  WhereInfo.a[i].pBestInfo is the
01486 ** index information for the i-th loop of the join.  pBestInfo is always
01487 ** either NULL or a copy of some pIdxInfo.  So for cleanup it is 
01488 ** sufficient to free all of the pIdxInfo pointers.
01489 ** 
01490 */
01491 struct WhereLevel {
01492   int iFrom;            /* Which entry in the FROM clause */
01493   int flags;            /* Flags associated with this level */
01494   int iMem;             /* First memory cell used by this level */
01495   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
01496   Index *pIdx;          /* Index used.  NULL if no index */
01497   int iTabCur;          /* The VDBE cursor used to access the table */
01498   int iIdxCur;          /* The VDBE cursor used to acesss pIdx */
01499   int brk;              /* Jump here to break out of the loop */
01500   int nxt;              /* Jump here to start the next IN combination */
01501   int cont;             /* Jump here to continue with the next loop cycle */
01502   int top;              /* First instruction of interior of the loop */
01503   int op, p1, p2, p5;   /* Opcode used to terminate the loop */
01504   int nEq;              /* Number of == or IN constraints on this loop */
01505   int nIn;              /* Number of IN operators constraining this loop */
01506   struct InLoop {
01507     int iCur;              /* The VDBE cursor used by this IN operator */
01508     int topAddr;           /* Top of the IN loop */
01509   } *aInLoop;           /* Information about each nested IN operator */
01510   sqlite3_index_info *pBestIdx;  /* Index information for this level */
01511 
01512   /* The following field is really not part of the current level.  But
01513   ** we need a place to cache index information for each table in the
01514   ** FROM clause and the WhereLevel structure is a convenient place.
01515   */
01516   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
01517 };
01518 
01519 /*
01520 ** Flags appropriate for the wflags parameter of sqlite3WhereBegin().
01521 */
01522 #define WHERE_ORDERBY_NORMAL     0   /* No-op */
01523 #define WHERE_ORDERBY_MIN        1   /* ORDER BY processing for min() func */
01524 #define WHERE_ORDERBY_MAX        2   /* ORDER BY processing for max() func */
01525 #define WHERE_ONEPASS_DESIRED    4   /* Want to do one-pass UPDATE/DELETE */
01526 
01527 /*
01528 ** The WHERE clause processing routine has two halves.  The
01529 ** first part does the start of the WHERE loop and the second
01530 ** half does the tail of the WHERE loop.  An instance of
01531 ** this structure is returned by the first half and passed
01532 ** into the second half to give some continuity.
01533 */
01534 struct WhereInfo {
01535   Parse *pParse;       /* Parsing and code generating context */
01536   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
01537   SrcList *pTabList;   /* List of tables in the join */
01538   int iTop;            /* The very beginning of the WHERE loop */
01539   int iContinue;       /* Jump here to continue with next record */
01540   int iBreak;          /* Jump here to break out of the loop */
01541   int nLevel;          /* Number of nested loop */
01542   sqlite3_index_info **apInfo;  /* Array of pointers to index info structures */
01543   WhereLevel a[1];     /* Information about each nest loop in the WHERE */
01544 };
01545 
01546 /*
01547 ** A NameContext defines a context in which to resolve table and column
01548 ** names.  The context consists of a list of tables (the pSrcList) field and
01549 ** a list of named expression (pEList).  The named expression list may
01550 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
01551 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
01552 ** pEList corresponds to the result set of a SELECT and is NULL for
01553 ** other statements.
01554 **
01555 ** NameContexts can be nested.  When resolving names, the inner-most 
01556 ** context is searched first.  If no match is found, the next outer
01557 ** context is checked.  If there is still no match, the next context
01558 ** is checked.  This process continues until either a match is found
01559 ** or all contexts are check.  When a match is found, the nRef member of
01560 ** the context containing the match is incremented. 
01561 **
01562 ** Each subquery gets a new NameContext.  The pNext field points to the
01563 ** NameContext in the parent query.  Thus the process of scanning the
01564 ** NameContext list corresponds to searching through successively outer
01565 ** subqueries looking for a match.
01566 */
01567 struct NameContext {
01568   Parse *pParse;       /* The parser */
01569   SrcList *pSrcList;   /* One or more tables used to resolve names */
01570   ExprList *pEList;    /* Optional list of named expressions */
01571   int nRef;            /* Number of names resolved by this context */
01572   int nErr;            /* Number of errors encountered while resolving names */
01573   u8 allowAgg;         /* Aggregate functions allowed here */
01574   u8 hasAgg;           /* True if aggregates are seen */
01575   u8 isCheck;          /* True if resolving names in a CHECK constraint */
01576   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
01577   AggInfo *pAggInfo;   /* Information about aggregates at this level */
01578   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
01579 };
01580 
01581 /*
01582 ** An instance of the following structure contains all information
01583 ** needed to generate code for a single SELECT statement.
01584 **
01585 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
01586 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
01587 ** limit and nOffset to the value of the offset (or 0 if there is not
01588 ** offset).  But later on, nLimit and nOffset become the memory locations
01589 ** in the VDBE that record the limit and offset counters.
01590 **
01591 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
01592 ** These addresses must be stored so that we can go back and fill in
01593 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
01594 ** the number of columns in P2 can be computed at the same time
01595 ** as the OP_OpenEphm instruction is coded because not
01596 ** enough information about the compound query is known at that point.
01597 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
01598 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
01599 ** sequences for the ORDER BY clause.
01600 */
01601 struct Select {
01602   ExprList *pEList;      /* The fields of the result */
01603   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
01604   char affinity;         /* MakeRecord with this affinity for SRT_Set */
01605   u16 selFlags;          /* Various SF_* values */
01606   SrcList *pSrc;         /* The FROM clause */
01607   Expr *pWhere;          /* The WHERE clause */
01608   ExprList *pGroupBy;    /* The GROUP BY clause */
01609   Expr *pHaving;         /* The HAVING clause */
01610   ExprList *pOrderBy;    /* The ORDER BY clause */
01611   Select *pPrior;        /* Prior select in a compound select statement */
01612   Select *pNext;         /* Next select to the left in a compound */
01613   Select *pRightmost;    /* Right-most select in a compound select statement */
01614   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
01615   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
01616   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
01617   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
01618 };
01619 
01620 /*
01621 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
01622 ** "Select Flag".
01623 */
01624 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
01625 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
01626 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
01627 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
01628 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
01629 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
01630 
01631 
01632 /*
01633 ** The results of a select can be distributed in several ways.  The
01634 ** "SRT" prefix means "SELECT Result Type".
01635 */
01636 #define SRT_Union        1  /* Store result as keys in an index */
01637 #define SRT_Except       2  /* Remove result from a UNION index */
01638 #define SRT_Exists       3  /* Store 1 if the result is not empty */
01639 #define SRT_Discard      4  /* Do not save the results anywhere */
01640 
01641 /* The ORDER BY clause is ignored for all of the above */
01642 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
01643 
01644 #define SRT_Output       5  /* Output each row of result */
01645 #define SRT_Mem          6  /* Store result in a memory cell */
01646 #define SRT_Set          7  /* Store results as keys in an index */
01647 #define SRT_Table        8  /* Store result as data with an automatic rowid */
01648 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
01649 #define SRT_Coroutine   10  /* Generate a single row of result */
01650 
01651 /*
01652 ** A structure used to customize the behaviour of sqlite3Select(). See
01653 ** comments above sqlite3Select() for details.
01654 */
01655 typedef struct SelectDest SelectDest;
01656 struct SelectDest {
01657   u8 eDest;         /* How to dispose of the results */
01658   u8 affinity;      /* Affinity used when eDest==SRT_Set */
01659   int iParm;        /* A parameter used by the eDest disposal method */
01660   int iMem;         /* Base register where results are written */
01661   int nMem;         /* Number of registers allocated */
01662 };
01663 
01664 /*
01665 ** An SQL parser context.  A copy of this structure is passed through
01666 ** the parser and down into all the parser action routine in order to
01667 ** carry around information that is global to the entire parse.
01668 **
01669 ** The structure is divided into two parts.  When the parser and code
01670 ** generate call themselves recursively, the first part of the structure
01671 ** is constant but the second part is reset at the beginning and end of
01672 ** each recursion.
01673 **
01674 ** The nTableLock and aTableLock variables are only used if the shared-cache 
01675 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
01676 ** used to store the set of table-locks required by the statement being
01677 ** compiled. Function sqlite3TableLock() is used to add entries to the
01678 ** list.
01679 */
01680 struct Parse {
01681   sqlite3 *db;         /* The main database structure */
01682   int rc;              /* Return code from execution */
01683   char *zErrMsg;       /* An error message */
01684   Vdbe *pVdbe;         /* An engine for executing database bytecode */
01685   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
01686   u8 nameClash;        /* A permanent table name clashes with temp table name */
01687   u8 checkSchema;      /* Causes schema cookie check after an error */
01688   u8 nested;           /* Number of nested calls to the parser/code generator */
01689   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
01690   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
01691   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
01692   int aTempReg[8];     /* Holding area for temporary registers */
01693   int nRangeReg;       /* Size of the temporary register block */
01694   int iRangeReg;       /* First register in temporary register block */
01695   int nErr;            /* Number of errors seen */
01696   int nTab;            /* Number of previously allocated VDBE cursors */
01697   int nMem;            /* Number of memory cells used so far */
01698   int nSet;            /* Number of sets used so far */
01699   int ckBase;          /* Base register of data during check constraints */
01700   int disableColCache; /* True to disable adding to column cache */
01701   int nColCache;       /* Number of entries in the column cache */
01702   int iColCache;       /* Next entry of the cache to replace */
01703   struct yColCache {
01704     int iTable;           /* Table cursor number */
01705     int iColumn;          /* Table column number */
01706     char affChange;       /* True if this register has had an affinity change */
01707     int iReg;             /* Register holding value of this column */
01708   } aColCache[10];     /* One for each valid column cache entry */
01709   u32 writeMask;       /* Start a write transaction on these databases */
01710   u32 cookieMask;      /* Bitmask of schema verified databases */
01711   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
01712   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
01713 #ifndef SQLITE_OMIT_SHARED_CACHE
01714   int nTableLock;        /* Number of locks in aTableLock */
01715   TableLock *aTableLock; /* Required table locks for shared-cache mode */
01716 #endif
01717   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
01718   int regRoot;         /* Register holding root page number for new objects */
01719 
01720   /* Above is constant between recursions.  Below is reset before and after
01721   ** each recursion */
01722 
01723   int nVar;            /* Number of '?' variables seen in the SQL so far */
01724   int nVarExpr;        /* Number of used slots in apVarExpr[] */
01725   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
01726   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
01727   int nAlias;          /* Number of aliased result set columns */
01728   int *aAlias;         /* Register used to hold aliased result */
01729   u8 explain;          /* True if the EXPLAIN flag is found on the query */
01730   Token sErrToken;     /* The token at which the error occurred */
01731   Token sNameToken;    /* Token with unqualified schema object name */
01732   Token sLastToken;    /* The last token parsed */
01733   const char *zSql;    /* All SQL text */
01734   const char *zTail;   /* All SQL text past the last semicolon parsed */
01735   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
01736   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
01737   TriggerStack *trigStack;  /* Trigger actions being coded */
01738   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
01739 #ifndef SQLITE_OMIT_VIRTUALTABLE
01740   Token sArg;                /* Complete text of a module argument */
01741   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
01742   int nVtabLock;             /* Number of virtual tables to lock */
01743   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
01744 #endif
01745   int nHeight;            /* Expression tree height of current sub-select */
01746   Table *pZombieTab;      /* List of Table objects to delete after code gen */
01747 };
01748 
01749 #ifdef SQLITE_OMIT_VIRTUALTABLE
01750   #define IN_DECLARE_VTAB 0
01751 #else
01752   #define IN_DECLARE_VTAB (pParse->declareVtab)
01753 #endif
01754 
01755 /*
01756 ** An instance of the following structure can be declared on a stack and used
01757 ** to save the Parse.zAuthContext value so that it can be restored later.
01758 */
01759 struct AuthContext {
01760   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
01761   Parse *pParse;              /* The Parse structure */
01762 };
01763 
01764 /*
01765 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
01766 */
01767 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
01768 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
01769 #define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
01770 #define OPFLAG_APPEND    8    /* This is likely to be an append */
01771 
01772 /*
01773  * Each trigger present in the database schema is stored as an instance of
01774  * struct Trigger. 
01775  *
01776  * Pointers to instances of struct Trigger are stored in two ways.
01777  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
01778  *    database). This allows Trigger structures to be retrieved by name.
01779  * 2. All triggers associated with a single table form a linked list, using the
01780  *    pNext member of struct Trigger. A pointer to the first element of the
01781  *    linked list is stored as the "pTrigger" member of the associated
01782  *    struct Table.
01783  *
01784  * The "step_list" member points to the first element of a linked list
01785  * containing the SQL statements specified as the trigger program.
01786  */
01787 struct Trigger {
01788   char *name;             /* The name of the trigger                        */
01789   char *table;            /* The table or view to which the trigger applies */
01790   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
01791   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
01792   Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
01793   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
01794                              the <column-list> is stored here */
01795   Token nameToken;        /* Token containing zName. Use during parsing only */
01796   Schema *pSchema;        /* Schema containing the trigger */
01797   Schema *pTabSchema;     /* Schema containing the table */
01798   TriggerStep *step_list; /* Link list of trigger program steps             */
01799   Trigger *pNext;         /* Next trigger associated with the table */
01800 };
01801 
01802 /*
01803 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
01804 ** determine which. 
01805 **
01806 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
01807 ** In that cases, the constants below can be ORed together.
01808 */
01809 #define TRIGGER_BEFORE  1
01810 #define TRIGGER_AFTER   2
01811 
01812 /*
01813  * An instance of struct TriggerStep is used to store a single SQL statement
01814  * that is a part of a trigger-program. 
01815  *
01816  * Instances of struct TriggerStep are stored in a singly linked list (linked
01817  * using the "pNext" member) referenced by the "step_list" member of the 
01818  * associated struct Trigger instance. The first element of the linked list is
01819  * the first step of the trigger-program.
01820  * 
01821  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
01822  * "SELECT" statement. The meanings of the other members is determined by the 
01823  * value of "op" as follows:
01824  *
01825  * (op == TK_INSERT)
01826  * orconf    -> stores the ON CONFLICT algorithm
01827  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
01828  *              this stores a pointer to the SELECT statement. Otherwise NULL.
01829  * target    -> A token holding the name of the table to insert into.
01830  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
01831  *              this stores values to be inserted. Otherwise NULL.
01832  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
01833  *              statement, then this stores the column-names to be
01834  *              inserted into.
01835  *
01836  * (op == TK_DELETE)
01837  * target    -> A token holding the name of the table to delete from.
01838  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
01839  *              Otherwise NULL.
01840  * 
01841  * (op == TK_UPDATE)
01842  * target    -> A token holding the name of the table to update rows of.
01843  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
01844  *              Otherwise NULL.
01845  * pExprList -> A list of the columns to update and the expressions to update
01846  *              them to. See sqlite3Update() documentation of "pChanges"
01847  *              argument.
01848  * 
01849  */
01850 struct TriggerStep {
01851   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
01852   int orconf;          /* OE_Rollback etc. */
01853   Trigger *pTrig;      /* The trigger that this step is a part of */
01854 
01855   Select *pSelect;     /* Valid for SELECT and sometimes 
01856                           INSERT steps (when pExprList == 0) */
01857   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
01858   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
01859   ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
01860                            INSERT steps (when pSelect == 0)         */
01861   IdList *pIdList;     /* Valid for INSERT statements only */
01862   TriggerStep *pNext;  /* Next in the link-list */
01863   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
01864 };
01865 
01866 /*
01867  * An instance of struct TriggerStack stores information required during code
01868  * generation of a single trigger program. While the trigger program is being
01869  * coded, its associated TriggerStack instance is pointed to by the
01870  * "pTriggerStack" member of the Parse structure.
01871  *
01872  * The pTab member points to the table that triggers are being coded on. The 
01873  * newIdx member contains the index of the vdbe cursor that points at the temp
01874  * table that stores the new.* references. If new.* references are not valid
01875  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
01876  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
01877  *
01878  * The ON CONFLICT policy to be used for the trigger program steps is stored 
01879  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
01880  * specified for individual triggers steps is used.
01881  *
01882  * struct TriggerStack has a "pNext" member, to allow linked lists to be
01883  * constructed. When coding nested triggers (triggers fired by other triggers)
01884  * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
01885  * pointer. Once the nested trigger has been coded, the pNext value is restored
01886  * to the pTriggerStack member of the Parse stucture and coding of the parent
01887  * trigger continues.
01888  *
01889  * Before a nested trigger is coded, the linked list pointed to by the 
01890  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
01891  * recursively. If this condition is detected, the nested trigger is not coded.
01892  */
01893 struct TriggerStack {
01894   Table *pTab;         /* Table that triggers are currently being coded on */
01895   int newIdx;          /* Index of vdbe cursor to "new" temp table */
01896   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
01897   u32 newColMask;
01898   u32 oldColMask;
01899   int orconf;          /* Current orconf policy */
01900   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
01901   Trigger *pTrigger;   /* The trigger currently being coded */
01902   TriggerStack *pNext; /* Next trigger down on the trigger stack */
01903 };
01904 
01905 /*
01906 ** The following structure contains information used by the sqliteFix...
01907 ** routines as they walk the parse tree to make database references
01908 ** explicit.  
01909 */
01910 typedef struct DbFixer DbFixer;
01911 struct DbFixer {
01912   Parse *pParse;      /* The parsing context.  Error messages written here */
01913   const char *zDb;    /* Make sure all objects are contained in this database */
01914   const char *zType;  /* Type of the container - used for error messages */
01915   const Token *pName; /* Name of the container - used for error messages */
01916 };
01917 
01918 /*
01919 ** An objected used to accumulate the text of a string where we
01920 ** do not necessarily know how big the string will be in the end.
01921 */
01922 struct StrAccum {
01923   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
01924   char *zBase;         /* A base allocation.  Not from malloc. */
01925   char *zText;         /* The string collected so far */
01926   int  nChar;          /* Length of the string so far */
01927   int  nAlloc;         /* Amount of space allocated in zText */
01928   int  mxAlloc;        /* Maximum allowed string length */
01929   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
01930   u8   useMalloc;      /* True if zText is enlargable using realloc */
01931   u8   tooBig;         /* Becomes true if string size exceeds limits */
01932 };
01933 
01934 /*
01935 ** A pointer to this structure is used to communicate information
01936 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
01937 */
01938 typedef struct {
01939   sqlite3 *db;        /* The database being initialized */
01940   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
01941   char **pzErrMsg;    /* Error message stored here */
01942   int rc;             /* Result code stored here */
01943 } InitData;
01944 
01945 /*
01946 ** Structure containing global configuration data for the SQLite library.
01947 **
01948 ** This structure also contains some state information.
01949 */
01950 struct Sqlite3Config {
01951   int bMemstat;                     /* True to enable memory status */
01952   int bCoreMutex;                   /* True to enable core mutexing */
01953   int bFullMutex;                   /* True to enable full mutexing */
01954   int mxStrlen;                     /* Maximum string length */
01955   int szLookaside;                  /* Default lookaside buffer size */
01956   int nLookaside;                   /* Default lookaside buffer count */
01957   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
01958   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
01959   void *pHeap;                      /* Heap storage space */
01960   int nHeap;                        /* Size of pHeap[] */
01961   int mnReq, mxReq;                 /* Min and max heap requests sizes */
01962   void *pScratch;                   /* Scratch memory */
01963   int szScratch;                    /* Size of each scratch buffer */
01964   int nScratch;                     /* Number of scratch buffers */
01965   void *pPage;                      /* Page cache memory */
01966   int szPage;                       /* Size of each page in pPage[] */
01967   int nPage;                        /* Number of pages in pPage[] */
01968   int isInit;                       /* True after initialization has finished */
01969   int inProgress;                   /* True while initialization in progress */
01970   int isMallocInit;                 /* True after malloc is initialized */
01971   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
01972   int nRefInitMutex;                /* Number of users of pInitMutex */
01973   int mxParserStack;                /* maximum depth of the parser stack */
01974   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
01975 };
01976 
01977 /*
01978 ** Context pointer passed down through the tree-walk.
01979 */
01980 struct Walker {
01981   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
01982   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
01983   Parse *pParse;                            /* Parser context.  */
01984   union {                                   /* Extra data for callback */
01985     NameContext *pNC;                          /* Naming context */
01986     int i;                                     /* Integer value */
01987   } u;
01988 };
01989 
01990 /* Forward declarations */
01991 int sqlite3WalkExpr(Walker*, Expr*);
01992 int sqlite3WalkExprList(Walker*, ExprList*);
01993 int sqlite3WalkSelect(Walker*, Select*);
01994 int sqlite3WalkSelectExpr(Walker*, Select*);
01995 int sqlite3WalkSelectFrom(Walker*, Select*);
01996 
01997 /*
01998 ** Return code from the parse-tree walking primitives and their
01999 ** callbacks.
02000 */
02001 #define WRC_Continue    0
02002 #define WRC_Prune       1
02003 #define WRC_Abort       2
02004 
02005 /*
02006 ** Assuming zIn points to the first byte of a UTF-8 character,
02007 ** advance zIn to point to the first byte of the next UTF-8 character.
02008 */
02009 #define SQLITE_SKIP_UTF8(zIn) {                        \
02010   if( (*(zIn++))>=0xc0 ){                              \
02011     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
02012   }                                                    \
02013 }
02014 
02015 /*
02016 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
02017 ** builds) or a function call (for debugging).  If it is a function call,
02018 ** it allows the operator to set a breakpoint at the spot where database
02019 ** corruption is first detected.
02020 */
02021 #ifdef SQLITE_DEBUG
02022   int sqlite3Corrupt(void);
02023 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
02024 #else
02025 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
02026 #endif
02027 
02028 /*
02029 ** Internal function prototypes
02030 */
02031 int sqlite3StrICmp(const char *, const char *);
02032 int sqlite3StrNICmp(const char *, const char *, int);
02033 int sqlite3IsNumber(const char*, int*, u8);
02034 int sqlite3Strlen(sqlite3*, const char*);
02035 
02036 int sqlite3MallocInit(void);
02037 void sqlite3MallocEnd(void);
02038 void *sqlite3Malloc(int);
02039 void *sqlite3MallocZero(int);
02040 void *sqlite3DbMallocZero(sqlite3*, int);
02041 void *sqlite3DbMallocRaw(sqlite3*, int);
02042 char *sqlite3DbStrDup(sqlite3*,const char*);
02043 char *sqlite3DbStrNDup(sqlite3*,const char*, int);
02044 void *sqlite3Realloc(void*, int);
02045 void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
02046 void *sqlite3DbRealloc(sqlite3 *, void *, int);
02047 void sqlite3DbFree(sqlite3*, void*);
02048 int sqlite3MallocSize(void*);
02049 int sqlite3DbMallocSize(sqlite3*, void*);
02050 void *sqlite3ScratchMalloc(int);
02051 void sqlite3ScratchFree(void*);
02052 void *sqlite3PageMalloc(int);
02053 void sqlite3PageFree(void*);
02054 void sqlite3MemSetDefault(void);
02055 const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
02056 const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
02057 void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
02058 int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
02059 
02060 #ifndef SQLITE_MUTEX_OMIT
02061   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
02062   sqlite3_mutex *sqlite3MutexAlloc(int);
02063   int sqlite3MutexInit(void);
02064   int sqlite3MutexEnd(void);
02065 #endif
02066 
02067 int sqlite3StatusValue(int);
02068 void sqlite3StatusAdd(int, int);
02069 void sqlite3StatusSet(int, int);
02070 
02071 int sqlite3IsNaN(double);
02072 
02073 void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
02074 char *sqlite3MPrintf(sqlite3*,const char*, ...);
02075 char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
02076 char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
02077 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
02078   void sqlite3DebugPrintf(const char*, ...);
02079 #endif
02080 #if defined(SQLITE_TEST)
02081   void *sqlite3TestTextToPtr(const char*);
02082 #endif
02083 void sqlite3SetString(char **, sqlite3*, const char*, ...);
02084 void sqlite3ErrorMsg(Parse*, const char*, ...);
02085 void sqlite3ErrorClear(Parse*);
02086 void sqlite3Dequote(char*);
02087 void sqlite3DequoteExpr(sqlite3*, Expr*);
02088 int sqlite3KeywordCode(const unsigned char*, int);
02089 int sqlite3RunParser(Parse*, const char*, char **);
02090 void sqlite3FinishCoding(Parse*);
02091 int sqlite3GetTempReg(Parse*);
02092 void sqlite3ReleaseTempReg(Parse*,int);
02093 int sqlite3GetTempRange(Parse*,int);
02094 void sqlite3ReleaseTempRange(Parse*,int,int);
02095 Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
02096 Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
02097 Expr *sqlite3RegisterExpr(Parse*,Token*);
02098 Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
02099 void sqlite3ExprSpan(Expr*,Token*,Token*);
02100 Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
02101 void sqlite3ExprAssignVarNumber(Parse*, Expr*);
02102 void sqlite3ExprClear(sqlite3*, Expr*);
02103 void sqlite3ExprDelete(sqlite3*, Expr*);
02104 ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
02105 void sqlite3ExprListDelete(sqlite3*, ExprList*);
02106 int sqlite3Init(sqlite3*, char**);
02107 int sqlite3InitCallback(void*, int, char**, char**);
02108 void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
02109 void sqlite3ResetInternalSchema(sqlite3*, int);
02110 void sqlite3BeginParse(Parse*,int);
02111 void sqlite3CommitInternalChanges(sqlite3*);
02112 Table *sqlite3ResultSetOfSelect(Parse*,Select*);
02113 void sqlite3OpenMasterTable(Parse *, int);
02114 void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
02115 void sqlite3AddColumn(Parse*,Token*);
02116 void sqlite3AddNotNull(Parse*, int);
02117 void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
02118 void sqlite3AddCheckConstraint(Parse*, Expr*);
02119 void sqlite3AddColumnType(Parse*,Token*);
02120 void sqlite3AddDefaultValue(Parse*,Expr*);
02121 void sqlite3AddCollateType(Parse*, Token*);
02122 void sqlite3EndTable(Parse*,Token*,Token*,Select*);
02123 
02124 Bitvec *sqlite3BitvecCreate(u32);
02125 int sqlite3BitvecTest(Bitvec*, u32);
02126 int sqlite3BitvecSet(Bitvec*, u32);
02127 void sqlite3BitvecClear(Bitvec*, u32);
02128 void sqlite3BitvecDestroy(Bitvec*);
02129 int sqlite3BitvecBuiltinTest(int,int*);
02130 
02131 void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
02132 
02133 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
02134   int sqlite3ViewGetColumnNames(Parse*,Table*);
02135 #else
02136 # define sqlite3ViewGetColumnNames(A,B) 0
02137 #endif
02138 
02139 void sqlite3DropTable(Parse*, SrcList*, int, int);
02140 void sqlite3DeleteTable(Table*);
02141 void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
02142 void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
02143 IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
02144 int sqlite3IdListIndex(IdList*,const char*);
02145 SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
02146 SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
02147 SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
02148                                       Token*, Select*, Expr*, IdList*);
02149 void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
02150 int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
02151 void sqlite3SrcListShiftJoinType(SrcList*);
02152 void sqlite3SrcListAssignCursors(Parse*, SrcList*);
02153 void sqlite3IdListDelete(sqlite3*, IdList*);
02154 void sqlite3SrcListDelete(sqlite3*, SrcList*);
02155 void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
02156                         Token*, int, int);
02157 void sqlite3DropIndex(Parse*, SrcList*, int);
02158 int sqlite3Select(Parse*, Select*, SelectDest*);
02159 Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
02160                          Expr*,ExprList*,int,Expr*,Expr*);
02161 void sqlite3SelectDelete(sqlite3*, Select*);
02162 Table *sqlite3SrcListLookup(Parse*, SrcList*);
02163 int sqlite3IsReadOnly(Parse*, Table*, int);
02164 void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
02165 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
02166 Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
02167 #endif
02168 void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
02169 void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
02170 WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8);
02171 void sqlite3WhereEnd(WhereInfo*);
02172 int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
02173 void sqlite3ExprCodeMove(Parse*, int, int, int);
02174 void sqlite3ExprCodeCopy(Parse*, int, int, int);
02175 void sqlite3ExprClearColumnCache(Parse*, int);
02176 void sqlite3ExprCacheAffinityChange(Parse*, int, int);
02177 int sqlite3ExprWritableRegister(Parse*,int,int);
02178 void sqlite3ExprHardCopy(Parse*,int,int);
02179 int sqlite3ExprCode(Parse*, Expr*, int);
02180 int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
02181 int sqlite3ExprCodeTarget(Parse*, Expr*, int);
02182 int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
02183 void sqlite3ExprCodeConstants(Parse*, Expr*);
02184 int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
02185 void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
02186 void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
02187 Table *sqlite3FindTable(sqlite3*,const char*, const char*);
02188 Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
02189 Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
02190 void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
02191 void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
02192 void sqlite3Vacuum(Parse*);
02193 int sqlite3RunVacuum(char**, sqlite3*);
02194 char *sqlite3NameFromToken(sqlite3*, Token*);
02195 int sqlite3ExprCompare(Expr*, Expr*);
02196 void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
02197 void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
02198 Vdbe *sqlite3GetVdbe(Parse*);
02199 Expr *sqlite3CreateIdExpr(Parse *, const char*);
02200 void sqlite3PrngSaveState(void);
02201 void sqlite3PrngRestoreState(void);
02202 void sqlite3PrngResetState(void);
02203 void sqlite3RollbackAll(sqlite3*);
02204 void sqlite3CodeVerifySchema(Parse*, int);
02205 void sqlite3BeginTransaction(Parse*, int);
02206 void sqlite3CommitTransaction(Parse*);
02207 void sqlite3RollbackTransaction(Parse*);
02208 int sqlite3ExprIsConstant(Expr*);
02209 int sqlite3ExprIsConstantNotJoin(Expr*);
02210 int sqlite3ExprIsConstantOrFunction(Expr*);
02211 int sqlite3ExprIsInteger(Expr*, int*);
02212 int sqlite3IsRowid(const char*);
02213 void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
02214 void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
02215 int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
02216 void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
02217                                      int*,int,int,int,int);
02218 void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*,int,int,int,int);
02219 int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
02220 void sqlite3BeginWriteOperation(Parse*, int, int);
02221 Expr *sqlite3ExprDup(sqlite3*,Expr*);
02222 void sqlite3TokenCopy(sqlite3*,Token*, Token*);
02223 ExprList *sqlite3ExprListDup(sqlite3*,ExprList*);
02224 SrcList *sqlite3SrcListDup(sqlite3*,SrcList*);
02225 IdList *sqlite3IdListDup(sqlite3*,IdList*);
02226 Select *sqlite3SelectDup(sqlite3*,Select*);
02227 void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
02228 FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
02229 void sqlite3RegisterBuiltinFunctions(sqlite3*);
02230 void sqlite3RegisterDateTimeFunctions(void);
02231 void sqlite3RegisterGlobalFunctions(void);
02232 int sqlite3GetBuiltinFunction(const char *, int, FuncDef **);
02233 #ifdef SQLITE_DEBUG
02234   int sqlite3SafetyOn(sqlite3*);
02235   int sqlite3SafetyOff(sqlite3*);
02236 #else
02237 # define sqlite3SafetyOn(A) 0
02238 # define sqlite3SafetyOff(A) 0
02239 #endif
02240 int sqlite3SafetyCheckOk(sqlite3*);
02241 int sqlite3SafetyCheckSickOrOk(sqlite3*);
02242 void sqlite3ChangeCookie(Parse*, int);
02243 
02244 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
02245 void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
02246 #endif
02247 
02248 #ifndef SQLITE_OMIT_TRIGGER
02249   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
02250                            Expr*,int, int);
02251   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
02252   void sqlite3DropTrigger(Parse*, SrcList*, int);
02253   void sqlite3DropTriggerPtr(Parse*, Trigger*);
02254   int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
02255   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
02256                            int, int, u32*, u32*);
02257   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
02258   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
02259   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
02260   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
02261                                         ExprList*,Select*,int);
02262   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
02263   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
02264   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
02265   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
02266 #else
02267 # define sqlite3TriggersExist(A,B,C,D,E,F) 0
02268 # define sqlite3DeleteTrigger(A,B)
02269 # define sqlite3DropTriggerPtr(A,B)
02270 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
02271 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K) 0
02272 #endif
02273 
02274 int sqlite3JoinType(Parse*, Token*, Token*, Token*);
02275 void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
02276 void sqlite3DeferForeignKey(Parse*, int);
02277 #ifndef SQLITE_OMIT_AUTHORIZATION
02278   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
02279   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
02280   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
02281   void sqlite3AuthContextPop(AuthContext*);
02282 #else
02283 # define sqlite3AuthRead(a,b,c,d)
02284 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
02285 # define sqlite3AuthContextPush(a,b,c)
02286 # define sqlite3AuthContextPop(a)  ((void)(a))
02287 #endif
02288 void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
02289 void sqlite3Detach(Parse*, Expr*);
02290 int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
02291                        int omitJournal, int nCache, int flags, Btree **ppBtree);
02292 int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
02293 int sqlite3FixSrcList(DbFixer*, SrcList*);
02294 int sqlite3FixSelect(DbFixer*, Select*);
02295 int sqlite3FixExpr(DbFixer*, Expr*);
02296 int sqlite3FixExprList(DbFixer*, ExprList*);
02297 int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
02298 int sqlite3AtoF(const char *z, double*);
02299 int sqlite3GetInt32(const char *, int*);
02300 int sqlite3FitsIn64Bits(const char *, int);
02301 int sqlite3Utf16ByteLen(const void *pData, int nChar);
02302 int sqlite3Utf8CharLen(const char *pData, int nByte);
02303 int sqlite3Utf8Read(const u8*, const u8*, const u8**);
02304 
02305 /*
02306 ** Routines to read and write variable-length integers.  These used to
02307 ** be defined locally, but now we use the varint routines in the util.c
02308 ** file.  Code should use the MACRO forms below, as the Varint32 versions
02309 ** are coded to assume the single byte case is already handled (which 
02310 ** the MACRO form does).
02311 */
02312 int sqlite3PutVarint(unsigned char*, u64);
02313 int sqlite3PutVarint32(unsigned char*, u32);
02314 int sqlite3GetVarint(const unsigned char *, u64 *);
02315 int sqlite3GetVarint32(const unsigned char *, u32 *);
02316 int sqlite3VarintLen(u64 v);
02317 
02318 /*
02319 ** The header of a record consists of a sequence variable-length integers.
02320 ** These integers are almost always small and are encoded as a single byte.
02321 ** The following macros take advantage this fact to provide a fast encode
02322 ** and decode of the integers in a record header.  It is faster for the common
02323 ** case where the integer is a single byte.  It is a little slower when the
02324 ** integer is two or more bytes.  But overall it is faster.
02325 **
02326 ** The following expressions are equivalent:
02327 **
02328 **     x = sqlite3GetVarint32( A, &B );
02329 **     x = sqlite3PutVarint32( A, B );
02330 **
02331 **     x = getVarint32( A, B );
02332 **     x = putVarint32( A, B );
02333 **
02334 */
02335 #define getVarint32(A,B)  ((*(A)<(unsigned char)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), &(B)))
02336 #define putVarint32(A,B)  (((B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
02337 #define getVarint    sqlite3GetVarint
02338 #define putVarint    sqlite3PutVarint
02339 
02340 
02341 void sqlite3IndexAffinityStr(Vdbe *, Index *);
02342 void sqlite3TableAffinityStr(Vdbe *, Table *);
02343 char sqlite3CompareAffinity(Expr *pExpr, char aff2);
02344 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
02345 char sqlite3ExprAffinity(Expr *pExpr);
02346 int sqlite3Atoi64(const char*, i64*);
02347 void sqlite3Error(sqlite3*, int, const char*,...);
02348 void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
02349 int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
02350 const char *sqlite3ErrStr(int);
02351 int sqlite3ReadSchema(Parse *pParse);
02352 CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
02353 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
02354 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
02355 Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
02356 int sqlite3CheckCollSeq(Parse *, CollSeq *);
02357 int sqlite3CheckObjectName(Parse *, const char *);
02358 void sqlite3VdbeSetChanges(sqlite3 *, int);
02359 
02360 const void *sqlite3ValueText(sqlite3_value*, u8);
02361 int sqlite3ValueBytes(sqlite3_value*, u8);
02362 void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
02363                         void(*)(void*));
02364 void sqlite3ValueFree(sqlite3_value*);
02365 sqlite3_value *sqlite3ValueNew(sqlite3 *);
02366 char *sqlite3Utf16to8(sqlite3 *, const void*, int);
02367 int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
02368 void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
02369 #ifndef SQLITE_AMALGAMATION
02370 extern const unsigned char sqlite3UpperToLower[];
02371 extern SQLITE_WSD struct Sqlite3Config sqlite3Config;
02372 extern SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
02373 #endif
02374 void sqlite3RootPageMoved(Db*, int, int);
02375 void sqlite3Reindex(Parse*, Token*, Token*);
02376 void sqlite3AlterFunctions(sqlite3*);
02377 void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
02378 int sqlite3GetToken(const unsigned char *, int *);
02379 void sqlite3NestedParse(Parse*, const char*, ...);
02380 void sqlite3ExpirePreparedStatements(sqlite3*);
02381 void sqlite3CodeSubselect(Parse *, Expr *, int, int);
02382 void sqlite3SelectPrep(Parse*, Select*, NameContext*);
02383 int sqlite3ResolveExprNames(NameContext*, Expr*);
02384 void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
02385 int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
02386 void sqlite3ColumnDefault(Vdbe *, Table *, int);
02387 void sqlite3AlterFinishAddColumn(Parse *, Token *);
02388 void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
02389 CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
02390 char sqlite3AffinityType(const Token*);
02391 void sqlite3Analyze(Parse*, Token*, Token*);
02392 int sqlite3InvokeBusyHandler(BusyHandler*);
02393 int sqlite3FindDb(sqlite3*, Token*);
02394 int sqlite3AnalysisLoad(sqlite3*,int iDB);
02395 void sqlite3DefaultRowEst(Index*);
02396 void sqlite3RegisterLikeFunctions(sqlite3*, int);
02397 int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
02398 void sqlite3MinimumFileFormat(Parse*, int, int);
02399 void sqlite3SchemaFree(void *);
02400 Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
02401 int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
02402 KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
02403 int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
02404   void (*)(sqlite3_context*,int,sqlite3_value **),
02405   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
02406 int sqlite3ApiExit(sqlite3 *db, int);
02407 int sqlite3OpenTempDatabase(Parse *);
02408 
02409 void sqlite3StrAccumInit(StrAccum*, char*, int, int);
02410 void sqlite3StrAccumAppend(StrAccum*,const char*,int);
02411 char *sqlite3StrAccumFinish(StrAccum*);
02412 void sqlite3StrAccumReset(StrAccum*);
02413 void sqlite3SelectDestInit(SelectDest*,int,int);
02414 
02415 /*
02416 ** The interface to the LEMON-generated parser
02417 */
02418 void *sqlite3ParserAlloc(void*(*)(size_t));
02419 void sqlite3ParserFree(void*, void(*)(void*));
02420 void sqlite3Parser(void*, int, Token, Parse*);
02421 #ifdef YYTRACKMAXSTACKDEPTH
02422   int sqlite3ParserStackPeak(void*);
02423 #endif
02424 
02425 int sqlite3AutoLoadExtensions(sqlite3*);
02426 #ifndef SQLITE_OMIT_LOAD_EXTENSION
02427   void sqlite3CloseExtensions(sqlite3*);
02428 #else
02429 # define sqlite3CloseExtensions(X)
02430 #endif
02431 
02432 #ifndef SQLITE_OMIT_SHARED_CACHE
02433   void sqlite3TableLock(Parse *, int, int, u8, const char *);
02434 #else
02435   #define sqlite3TableLock(v,w,x,y,z)
02436 #endif
02437 
02438 #ifdef SQLITE_TEST
02439   int sqlite3Utf8To8(unsigned char*);
02440 #endif
02441 
02442 #ifdef SQLITE_OMIT_VIRTUALTABLE
02443 #  define sqlite3VtabClear(X)
02444 #  define sqlite3VtabSync(X,Y) SQLITE_OK
02445 #  define sqlite3VtabRollback(X)
02446 #  define sqlite3VtabCommit(X)
02447 #else
02448    void sqlite3VtabClear(Table*);
02449    int sqlite3VtabSync(sqlite3 *db, char **);
02450    int sqlite3VtabRollback(sqlite3 *db);
02451    int sqlite3VtabCommit(sqlite3 *db);
02452 #endif
02453 void sqlite3VtabMakeWritable(Parse*,Table*);
02454 void sqlite3VtabLock(sqlite3_vtab*);
02455 void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
02456 void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
02457 void sqlite3VtabFinishParse(Parse*, Token*);
02458 void sqlite3VtabArgInit(Parse*);
02459 void sqlite3VtabArgExtend(Parse*, Token*);
02460 int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
02461 int sqlite3VtabCallConnect(Parse*, Table*);
02462 int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
02463 int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
02464 FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
02465 void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
02466 int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
02467 int sqlite3Reprepare(Vdbe*);
02468 void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
02469 CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
02470 
02471 
02472 /*
02473 ** Available fault injectors.  Should be numbered beginning with 0.
02474 */
02475 #define SQLITE_FAULTINJECTOR_MALLOC     0
02476 #define SQLITE_FAULTINJECTOR_COUNT      1
02477 
02478 /*
02479 ** The interface to the code in fault.c used for identifying "benign"
02480 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
02481 ** is not defined.
02482 */
02483 #ifndef SQLITE_OMIT_BUILTIN_TEST
02484   void sqlite3BeginBenignMalloc(void);
02485   void sqlite3EndBenignMalloc(void);
02486 #else
02487   #define sqlite3BeginBenignMalloc()
02488   #define sqlite3EndBenignMalloc()
02489 #endif
02490 
02491 #define IN_INDEX_ROWID           1
02492 #define IN_INDEX_EPH             2
02493 #define IN_INDEX_INDEX           3
02494 int sqlite3FindInIndex(Parse *, Expr *, int*);
02495 
02496 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
02497   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
02498   int sqlite3JournalSize(sqlite3_vfs *);
02499   int sqlite3JournalCreate(sqlite3_file *);
02500 #else
02501   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
02502 #endif
02503 
02504 void sqlite3MemJournalOpen(sqlite3_file *);
02505 int sqlite3MemJournalSize();
02506 int sqlite3IsMemJournal(sqlite3_file *);
02507 
02508 #if SQLITE_MAX_EXPR_DEPTH>0
02509   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
02510   int sqlite3SelectExprHeight(Select *);
02511   int sqlite3ExprCheckHeight(Parse*, int);
02512 #else
02513   #define sqlite3ExprSetHeight(x,y)
02514   #define sqlite3SelectExprHeight(x) 0
02515   #define sqlite3ExprCheckHeight(x,y)
02516 #endif
02517 
02518 u32 sqlite3Get4byte(const u8*);
02519 void sqlite3Put4byte(u8*, u32);
02520 
02521 #ifdef SQLITE_SSE
02522 #include "sseInt.h"
02523 #endif
02524 
02525 #ifdef SQLITE_DEBUG
02526   void sqlite3ParserTrace(FILE*, char *);
02527 #endif
02528 
02529 /*
02530 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
02531 ** sqlite3IoTrace is a pointer to a printf-like routine used to
02532 ** print I/O tracing messages. 
02533 */
02534 #ifdef SQLITE_ENABLE_IOTRACE
02535 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
02536   void sqlite3VdbeIOTraceSql(Vdbe*);
02537 SQLITE_EXTERN void (*sqlite3IoTrace)(const char*,...);
02538 #else
02539 # define IOTRACE(A)
02540 # define sqlite3VdbeIOTraceSql(X)
02541 #endif
02542 
02543 #endif

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:56 2011 by Doxygen 1.6.1