Back to index

lightning-sunbird  0.9+nobinonly
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.493 2006/04/04 01:54:55 drh Exp $
00015 */
00016 #ifndef _SQLITEINT_H_
00017 #define _SQLITEINT_H_
00018 
00019 /*
00020 ** Extra interface definitions for those who need them
00021 */
00022 #ifdef SQLITE_EXTRA
00023 # include "sqliteExtra.h"
00024 #endif
00025 
00026 /*
00027 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
00028 ** Setting NDEBUG makes the code smaller and run faster.  So the following
00029 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
00030 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
00031 ** feature.
00032 */
00033 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
00034 # define NDEBUG 1
00035 #endif
00036 
00037 /*
00038 ** These #defines should enable >2GB file support on Posix if the
00039 ** underlying operating system supports it.  If the OS lacks
00040 ** large file support, or if the OS is windows, these should be no-ops.
00041 **
00042 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
00043 ** on the compiler command line.  This is necessary if you are compiling
00044 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
00045 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
00046 ** without this option, LFS is enable.  But LFS does not exist in the kernel
00047 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
00048 ** portability you should omit LFS.
00049 **
00050 ** Similar is true for MacOS.  LFS is only supported on MacOS 9 and later.
00051 */
00052 #ifndef SQLITE_DISABLE_LFS
00053 # define _LARGE_FILE       1
00054 # ifndef _FILE_OFFSET_BITS
00055 #   define _FILE_OFFSET_BITS 64
00056 # endif
00057 # define _LARGEFILE_SOURCE 1
00058 #endif
00059 
00060 #include "sqlite3.h"
00061 #include "hash.h"
00062 #include "parse.h"
00063 #include <stdio.h>
00064 #include <stdlib.h>
00065 #include <string.h>
00066 #include <assert.h>
00067 #include <stddef.h>
00068 
00069 /*
00070 ** If compiling for a processor that lacks floating point support,
00071 ** substitute integer for floating-point
00072 */
00073 #ifdef SQLITE_OMIT_FLOATING_POINT
00074 # define double sqlite_int64
00075 # define LONGDOUBLE_TYPE sqlite_int64
00076 # ifndef SQLITE_BIG_DBL
00077 #   define SQLITE_BIG_DBL (0x7fffffffffffffff)
00078 # endif
00079 # define SQLITE_OMIT_DATETIME_FUNCS 1
00080 # define SQLITE_OMIT_TRACE 1
00081 #endif
00082 #ifndef SQLITE_BIG_DBL
00083 # define SQLITE_BIG_DBL (1e99)
00084 #endif
00085 
00086 /*
00087 ** The maximum number of in-memory pages to use for the main database
00088 ** table and for temporary tables. Internally, the MAX_PAGES and 
00089 ** TEMP_PAGES macros are used. To override the default values at
00090 ** compilation time, the SQLITE_DEFAULT_CACHE_SIZE and 
00091 ** SQLITE_DEFAULT_TEMP_CACHE_SIZE macros should be set.
00092 */
00093 #ifdef SQLITE_DEFAULT_CACHE_SIZE
00094 # define MAX_PAGES SQLITE_DEFAULT_CACHE_SIZE
00095 #else
00096 # define MAX_PAGES   2000
00097 #endif
00098 #ifdef SQLITE_DEFAULT_TEMP_CACHE_SIZE
00099 # define TEMP_PAGES SQLITE_DEFAULT_TEMP_CACHE_SIZE
00100 #else
00101 # define TEMP_PAGES   500
00102 #endif
00103 
00104 /*
00105 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
00106 ** afterward. Having this macro allows us to cause the C compiler 
00107 ** to omit code used by TEMP tables without messy #ifndef statements.
00108 */
00109 #ifdef SQLITE_OMIT_TEMPDB
00110 #define OMIT_TEMPDB 1
00111 #else
00112 #define OMIT_TEMPDB 0
00113 #endif
00114 
00115 /*
00116 ** If the following macro is set to 1, then NULL values are considered
00117 ** distinct when determining whether or not two entries are the same
00118 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
00119 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
00120 ** is the way things are suppose to work.
00121 **
00122 ** If the following macro is set to 0, the NULLs are indistinct for
00123 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
00124 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
00125 ** work.
00126 */
00127 #define NULL_DISTINCT_FOR_UNIQUE 1
00128 
00129 /*
00130 ** The maximum number of attached databases.  This must be at least 2
00131 ** in order to support the main database file (0) and the file used to
00132 ** hold temporary tables (1).  And it must be less than 32 because
00133 ** we use a bitmask of databases with a u32 in places (for example
00134 ** the Parse.cookieMask field).
00135 */
00136 #define MAX_ATTACHED 10
00137 
00138 /*
00139 ** The maximum value of a ?nnn wildcard that the parser will accept.
00140 */
00141 #define SQLITE_MAX_VARIABLE_NUMBER 999
00142 
00143 /*
00144 ** The "file format" number is an integer that is incremented whenever
00145 ** the VDBE-level file format changes.  The following macros define the
00146 ** the default file format for new databases and the maximum file format
00147 ** that the library can read.
00148 */
00149 #define SQLITE_MAX_FILE_FORMAT 4
00150 #ifndef SQLITE_DEFAULT_FILE_FORMAT
00151 # define SQLITE_DEFAULT_FILE_FORMAT 4
00152 #endif
00153 
00154 /*
00155 ** Provide a default value for TEMP_STORE in case it is not specified
00156 ** on the command-line
00157 */
00158 #ifndef TEMP_STORE
00159 # define TEMP_STORE 1
00160 #endif
00161 
00162 /*
00163 ** GCC does not define the offsetof() macro so we'll have to do it
00164 ** ourselves.
00165 */
00166 #ifndef offsetof
00167 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
00168 #endif
00169 
00170 /*
00171 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
00172 ** not, there are still machines out there that use EBCDIC.)
00173 */
00174 #if 'A' == '\301'
00175 # define SQLITE_EBCDIC 1
00176 #else
00177 # define SQLITE_ASCII 1
00178 #endif
00179 
00180 /*
00181 ** Integers of known sizes.  These typedefs might change for architectures
00182 ** where the sizes very.  Preprocessor macros are available so that the
00183 ** types can be conveniently redefined at compile-type.  Like this:
00184 **
00185 **         cc '-DUINTPTR_TYPE=long long int' ...
00186 */
00187 #ifndef UINT32_TYPE
00188 # define UINT32_TYPE unsigned int
00189 #endif
00190 #ifndef UINT16_TYPE
00191 # define UINT16_TYPE unsigned short int
00192 #endif
00193 #ifndef INT16_TYPE
00194 # define INT16_TYPE short int
00195 #endif
00196 #ifndef UINT8_TYPE
00197 # define UINT8_TYPE unsigned char
00198 #endif
00199 #ifndef INT8_TYPE
00200 # define INT8_TYPE signed char
00201 #endif
00202 #ifndef LONGDOUBLE_TYPE
00203 # define LONGDOUBLE_TYPE long double
00204 #endif
00205 typedef sqlite_int64 i64;          /* 8-byte signed integer */
00206 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
00207 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
00208 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
00209 typedef INT16_TYPE i16;            /* 2-byte signed integer */
00210 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
00211 typedef UINT8_TYPE i8;             /* 1-byte signed integer */
00212 
00213 /*
00214 ** Macros to determine whether the machine is big or little endian,
00215 ** evaluated at runtime.
00216 */
00217 extern const int sqlite3one;
00218 #define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
00219 #define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
00220 
00221 /*
00222 ** An instance of the following structure is used to store the busy-handler
00223 ** callback for a given sqlite handle. 
00224 **
00225 ** The sqlite.busyHandler member of the sqlite struct contains the busy
00226 ** callback for the database handle. Each pager opened via the sqlite
00227 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
00228 ** callback is currently invoked only from within pager.c.
00229 */
00230 typedef struct BusyHandler BusyHandler;
00231 struct BusyHandler {
00232   int (*xFunc)(void *,int);  /* The busy callback */
00233   void *pArg;                /* First arg to busy callback */
00234   int nBusy;                 /* Incremented with each busy call */
00235 };
00236 
00237 /*
00238 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
00239 ** "BusyHandler typedefs.
00240 */
00241 #include "vdbe.h"
00242 #include "btree.h"
00243 #include "pager.h"
00244 
00245 #ifdef SQLITE_MEMDEBUG
00246 /*
00247 ** The following global variables are used for testing and debugging
00248 ** only.  They only work if SQLITE_MEMDEBUG is defined.
00249 */
00250 extern int sqlite3_nMalloc;      /* Number of sqliteMalloc() calls */
00251 extern int sqlite3_nFree;        /* Number of sqliteFree() calls */
00252 extern int sqlite3_iMallocFail;  /* Fail sqliteMalloc() after this many calls */
00253 extern int sqlite3_iMallocReset; /* Set iMallocFail to this when it reaches 0 */
00254 
00255 extern void *sqlite3_pFirst;         /* Pointer to linked list of allocations */
00256 extern int sqlite3_nMaxAlloc;        /* High water mark of ThreadData.nAlloc */
00257 extern int sqlite3_mallocDisallowed; /* assert() in sqlite3Malloc() if set */
00258 extern int sqlite3_isFail;           /* True if all malloc calls should fail */
00259 extern const char *sqlite3_zFile;    /* Filename to associate debug info with */
00260 extern int sqlite3_iLine;            /* Line number for debug info */
00261 
00262 #define ENTER_MALLOC (sqlite3_zFile = __FILE__, sqlite3_iLine = __LINE__)
00263 #define sqliteMalloc(x)          (ENTER_MALLOC, sqlite3Malloc(x,1))
00264 #define sqliteMallocRaw(x)       (ENTER_MALLOC, sqlite3MallocRaw(x,1))
00265 #define sqliteRealloc(x,y)       (ENTER_MALLOC, sqlite3Realloc(x,y))
00266 #define sqliteStrDup(x)          (ENTER_MALLOC, sqlite3StrDup(x))
00267 #define sqliteStrNDup(x,y)       (ENTER_MALLOC, sqlite3StrNDup(x,y))
00268 #define sqliteReallocOrFree(x,y) (ENTER_MALLOC, sqlite3ReallocOrFree(x,y))
00269 
00270 #else
00271 
00272 #define ENTER_MALLOC 0
00273 #define sqliteMalloc(x)          sqlite3Malloc(x,1)
00274 #define sqliteMallocRaw(x)       sqlite3MallocRaw(x,1)
00275 #define sqliteRealloc(x,y)       sqlite3Realloc(x,y)
00276 #define sqliteStrDup(x)          sqlite3StrDup(x)
00277 #define sqliteStrNDup(x,y)       sqlite3StrNDup(x,y)
00278 #define sqliteReallocOrFree(x,y) sqlite3ReallocOrFree(x,y)
00279 
00280 #endif
00281 
00282 #define sqliteFree(x)          sqlite3FreeX(x)
00283 #define sqliteAllocSize(x)     sqlite3AllocSize(x)
00284 
00285 
00286 /*
00287 ** An instance of this structure might be allocated to store information
00288 ** specific to a single thread.
00289 */
00290 struct ThreadData {
00291   int dummy;               /* So that this structure is never empty */
00292 
00293 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
00294   int nSoftHeapLimit;      /* Suggested max mem allocation.  No limit if <0 */
00295   int nAlloc;              /* Number of bytes currently allocated */
00296   Pager *pPager;           /* Linked list of all pagers in this thread */
00297 #endif
00298 
00299 #ifndef SQLITE_OMIT_SHARED_CACHE
00300   u8 useSharedData;        /* True if shared pagers and schemas are enabled */
00301   BtShared *pBtree;        /* Linked list of all currently open BTrees */
00302 #endif
00303 };
00304 
00305 /*
00306 ** Name of the master database table.  The master database table
00307 ** is a special table that holds the names and attributes of all
00308 ** user tables and indices.
00309 */
00310 #define MASTER_NAME       "sqlite_master"
00311 #define TEMP_MASTER_NAME  "sqlite_temp_master"
00312 
00313 /*
00314 ** The root-page of the master database table.
00315 */
00316 #define MASTER_ROOT       1
00317 
00318 /*
00319 ** The name of the schema table.
00320 */
00321 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
00322 
00323 /*
00324 ** A convenience macro that returns the number of elements in
00325 ** an array.
00326 */
00327 #define ArraySize(X)    (sizeof(X)/sizeof(X[0]))
00328 
00329 /*
00330 ** Forward references to structures
00331 */
00332 typedef struct AggInfo AggInfo;
00333 typedef struct AuthContext AuthContext;
00334 typedef struct CollSeq CollSeq;
00335 typedef struct Column Column;
00336 typedef struct Db Db;
00337 typedef struct Schema Schema;
00338 typedef struct Expr Expr;
00339 typedef struct ExprList ExprList;
00340 typedef struct FKey FKey;
00341 typedef struct FuncDef FuncDef;
00342 typedef struct IdList IdList;
00343 typedef struct Index Index;
00344 typedef struct KeyClass KeyClass;
00345 typedef struct KeyInfo KeyInfo;
00346 typedef struct NameContext NameContext;
00347 typedef struct Parse Parse;
00348 typedef struct Select Select;
00349 typedef struct SrcList SrcList;
00350 typedef struct ThreadData ThreadData;
00351 typedef struct Table Table;
00352 typedef struct TableLock TableLock;
00353 typedef struct Token Token;
00354 typedef struct TriggerStack TriggerStack;
00355 typedef struct TriggerStep TriggerStep;
00356 typedef struct Trigger Trigger;
00357 typedef struct WhereInfo WhereInfo;
00358 typedef struct WhereLevel WhereLevel;
00359 
00360 /*
00361 ** Each database file to be accessed by the system is an instance
00362 ** of the following structure.  There are normally two of these structures
00363 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
00364 ** aDb[1] is the database file used to hold temporary tables.  Additional
00365 ** databases may be attached.
00366 */
00367 struct Db {
00368   char *zName;         /* Name of this database */
00369   Btree *pBt;          /* The B*Tree structure for this database file */
00370   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
00371   u8 safety_level;     /* How aggressive at synching data to disk */
00372   void *pAux;               /* Auxiliary data.  Usually NULL */
00373   void (*xFreeAux)(void*);  /* Routine to free pAux */
00374   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
00375 };
00376 
00377 /*
00378 ** An instance of the following structure stores a database schema.
00379 */
00380 struct Schema {
00381   int schema_cookie;   /* Database schema version number for this file */
00382   Hash tblHash;        /* All tables indexed by name */
00383   Hash idxHash;        /* All (named) indices indexed by name */
00384   Hash trigHash;       /* All triggers indexed by name */
00385   Hash aFKey;          /* Foreign keys indexed by to-table */
00386   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
00387   u8 file_format;      /* Schema format version for this file */
00388   u8 enc;              /* Text encoding used by this database */
00389   u16 flags;           /* Flags associated with this schema */
00390   int cache_size;      /* Number of pages to use in the cache */
00391 };
00392 
00393 /*
00394 ** These macros can be used to test, set, or clear bits in the 
00395 ** Db.flags field.
00396 */
00397 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
00398 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
00399 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
00400 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
00401 
00402 /*
00403 ** Allowed values for the DB.flags field.
00404 **
00405 ** The DB_SchemaLoaded flag is set after the database schema has been
00406 ** read into internal hash tables.
00407 **
00408 ** DB_UnresetViews means that one or more views have column names that
00409 ** have been filled out.  If the schema changes, these column names might
00410 ** changes and so the view will need to be reset.
00411 */
00412 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
00413 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
00414 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
00415 
00416 #define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
00417 
00418 /*
00419 ** Each database is an instance of the following structure.
00420 **
00421 ** The sqlite.lastRowid records the last insert rowid generated by an
00422 ** insert statement.  Inserts on views do not affect its value.  Each
00423 ** trigger has its own context, so that lastRowid can be updated inside
00424 ** triggers as usual.  The previous value will be restored once the trigger
00425 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
00426 ** longer (since after version 2.8.12) reset to -1.
00427 **
00428 ** The sqlite.nChange does not count changes within triggers and keeps no
00429 ** context.  It is reset at start of sqlite3_exec.
00430 ** The sqlite.lsChange represents the number of changes made by the last
00431 ** insert, update, or delete statement.  It remains constant throughout the
00432 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
00433 ** context stack just like lastRowid so that the count of changes
00434 ** within a trigger is not seen outside the trigger.  Changes to views do not
00435 ** affect the value of lsChange.
00436 ** The sqlite.csChange keeps track of the number of current changes (since
00437 ** the last statement) and is used to update sqlite_lsChange.
00438 **
00439 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
00440 ** store the most recent error code and, if applicable, string. The
00441 ** internal function sqlite3Error() is used to set these variables
00442 ** consistently.
00443 */
00444 struct sqlite3 {
00445   int nDb;                      /* Number of backends currently in use */
00446   Db *aDb;                      /* All backends */
00447   int flags;                    /* Miscellanous flags. See below */
00448   int errCode;                  /* Most recent error code (SQLITE_*) */
00449   u8 autoCommit;                /* The auto-commit flag. */
00450   u8 temp_store;                /* 1: file 2: memory 0: default */
00451   int nTable;                   /* Number of tables in the database */
00452   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
00453   i64 lastRowid;                /* ROWID of most recent insert (see above) */
00454   i64 priorNewRowid;            /* Last randomly generated ROWID */
00455   int magic;                    /* Magic number for detect library misuse */
00456   int nChange;                  /* Value returned by sqlite3_changes() */
00457   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
00458   struct sqlite3InitInfo {      /* Information used during initialization */
00459     int iDb;                    /* When back is being initialized */
00460     int newTnum;                /* Rootpage of table being initialized */
00461     u8 busy;                    /* TRUE if currently initializing */
00462   } init;
00463   struct Vdbe *pVdbe;           /* List of active virtual machines */
00464   int activeVdbeCnt;            /* Number of vdbes currently executing */
00465   void (*xTrace)(void*,const char*);        /* Trace function */
00466   void *pTraceArg;                          /* Argument to the trace function */
00467   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
00468   void *pProfileArg;                        /* Argument to profile function */
00469   void *pCommitArg;                 /* Argument to xCommitCallback() */   
00470   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
00471   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
00472   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
00473   void *pUpdateArg;
00474   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
00475   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
00476   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
00477   void *pCollNeededArg;
00478   sqlite3_value *pErr;          /* Most recent error message */
00479   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
00480   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
00481 #ifndef SQLITE_OMIT_AUTHORIZATION
00482   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
00483                                 /* Access authorization function */
00484   void *pAuthArg;               /* 1st argument to the access auth function */
00485 #endif
00486 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
00487   int (*xProgress)(void *);     /* The progress callback */
00488   void *pProgressArg;           /* Argument to the progress callback */
00489   int nProgressOps;             /* Number of opcodes for progress callback */
00490 #endif
00491 #ifndef SQLITE_OMIT_GLOBALRECOVER
00492   sqlite3 *pNext;               /* Linked list of open db handles. */
00493 #endif
00494   Hash aFunc;                   /* All functions that can be in SQL exprs */
00495   Hash aCollSeq;                /* All collating sequences */
00496   BusyHandler busyHandler;      /* Busy callback */
00497   int busyTimeout;             /* Busy handler timeout, in msec */
00498   Db aDbStatic[2];              /* Static space for the 2 default backends */
00499 #ifdef SQLITE_SSE
00500   sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
00501 #endif
00502 };
00503 
00504 /*
00505 ** A macro to discover the encoding of a database.
00506 */
00507 #define ENC(db) ((db)->aDb[0].pSchema->enc)
00508 
00509 /*
00510 ** Possible values for the sqlite.flags and or Db.flags fields.
00511 **
00512 ** On sqlite.flags, the SQLITE_InTrans value means that we have
00513 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
00514 ** transaction is active on that particular database file.
00515 */
00516 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
00517 #define SQLITE_Interrupt      0x00000004  /* Cancel current operation */
00518 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
00519 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
00520 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
00521 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
00522 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
00523                                           /*   DELETE, or UPDATE and return */
00524                                           /*   the count using a callback. */
00525 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
00526                                           /*   result set is empty */
00527 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
00528 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
00529 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
00530 #define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
00531                                           ** accessing read-only databases */
00532 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
00533 #define SQLITE_ReadUncommitted 0x00004000  /* For shared-cache mode */
00534 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
00535 #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
00536 
00537 /*
00538 ** Possible values for the sqlite.magic field.
00539 ** The numbers are obtained at random and have no special meaning, other
00540 ** than being distinct from one another.
00541 */
00542 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
00543 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
00544 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
00545 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
00546 
00547 /*
00548 ** Each SQL function is defined by an instance of the following
00549 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
00550 ** hash table.  When multiple functions have the same name, the hash table
00551 ** points to a linked list of these structures.
00552 */
00553 struct FuncDef {
00554   i16 nArg;            /* Number of arguments.  -1 means unlimited */
00555   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
00556   u8 needCollSeq;      /* True if sqlite3GetFuncCollSeq() might be called */
00557   u8 flags;            /* Some combination of SQLITE_FUNC_* */
00558   void *pUserData;     /* User data parameter */
00559   FuncDef *pNext;      /* Next function with same name */
00560   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
00561   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
00562   void (*xFinalize)(sqlite3_context*);                /* Aggregate finializer */
00563   char zName[1];       /* SQL name of the function.  MUST BE LAST */
00564 };
00565 
00566 /*
00567 ** Possible values for FuncDef.flags
00568 */
00569 #define SQLITE_FUNC_LIKE   0x01  /* Candidate for the LIKE optimization */
00570 #define SQLITE_FUNC_CASE   0x02  /* Case-sensitive LIKE-type function */
00571 
00572 /*
00573 ** information about each column of an SQL table is held in an instance
00574 ** of this structure.
00575 */
00576 struct Column {
00577   char *zName;     /* Name of this column */
00578   Expr *pDflt;     /* Default value of this column */
00579   char *zType;     /* Data type for this column */
00580   char *zColl;     /* Collating sequence.  If NULL, use the default */
00581   u8 notNull;      /* True if there is a NOT NULL constraint */
00582   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
00583   char affinity;   /* One of the SQLITE_AFF_... values */
00584 };
00585 
00586 /*
00587 ** A "Collating Sequence" is defined by an instance of the following
00588 ** structure. Conceptually, a collating sequence consists of a name and
00589 ** a comparison routine that defines the order of that sequence.
00590 **
00591 ** There may two seperate implementations of the collation function, one
00592 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
00593 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
00594 ** native byte order. When a collation sequence is invoked, SQLite selects
00595 ** the version that will require the least expensive encoding
00596 ** translations, if any.
00597 **
00598 ** The CollSeq.pUser member variable is an extra parameter that passed in
00599 ** as the first argument to the UTF-8 comparison function, xCmp.
00600 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
00601 ** xCmp16.
00602 **
00603 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
00604 ** collating sequence is undefined.  Indices built on an undefined
00605 ** collating sequence may not be read or written.
00606 */
00607 struct CollSeq {
00608   char *zName;         /* Name of the collating sequence, UTF-8 encoded */
00609   u8 enc;              /* Text encoding handled by xCmp() */
00610   u8 type;             /* One of the SQLITE_COLL_... values below */
00611   void *pUser;         /* First argument to xCmp() */
00612   int (*xCmp)(void*,int, const void*, int, const void*);
00613 };
00614 
00615 /*
00616 ** Allowed values of CollSeq flags:
00617 */
00618 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
00619 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
00620 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
00621 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
00622 
00623 /*
00624 ** A sort order can be either ASC or DESC.
00625 */
00626 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
00627 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
00628 
00629 /*
00630 ** Column affinity types.
00631 **
00632 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
00633 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
00634 ** the speed a little by number the values consecutively.  
00635 **
00636 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
00637 ** when multiple affinity types are concatenated into a string and
00638 ** used as the P3 operand, they will be more readable.
00639 **
00640 ** Note also that the numeric types are grouped together so that testing
00641 ** for a numeric type is a single comparison.
00642 */
00643 #define SQLITE_AFF_TEXT     'a'
00644 #define SQLITE_AFF_NONE     'b'
00645 #define SQLITE_AFF_NUMERIC  'c'
00646 #define SQLITE_AFF_INTEGER  'd'
00647 #define SQLITE_AFF_REAL     'e'
00648 
00649 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
00650 
00651 /*
00652 ** Each SQL table is represented in memory by an instance of the
00653 ** following structure.
00654 **
00655 ** Table.zName is the name of the table.  The case of the original
00656 ** CREATE TABLE statement is stored, but case is not significant for
00657 ** comparisons.
00658 **
00659 ** Table.nCol is the number of columns in this table.  Table.aCol is a
00660 ** pointer to an array of Column structures, one for each column.
00661 **
00662 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
00663 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
00664 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
00665 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
00666 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
00667 ** is generated for each row of the table.  Table.hasPrimKey is true if
00668 ** the table has any PRIMARY KEY, INTEGER or otherwise.
00669 **
00670 ** Table.tnum is the page number for the root BTree page of the table in the
00671 ** database file.  If Table.iDb is the index of the database table backend
00672 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
00673 ** holds temporary tables and indices.  If Table.isTransient
00674 ** is true, then the table is stored in a file that is automatically deleted
00675 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
00676 ** refers VDBE cursor number that holds the table open, not to the root
00677 ** page number.  Transient tables are used to hold the results of a
00678 ** sub-query that appears instead of a real table name in the FROM clause 
00679 ** of a SELECT statement.
00680 */
00681 struct Table {
00682   char *zName;     /* Name of the table */
00683   int nCol;        /* Number of columns in this table */
00684   Column *aCol;    /* Information about each column */
00685   int iPKey;       /* If not less then 0, use aCol[iPKey] as the primary key */
00686   Index *pIndex;   /* List of SQL indexes on this table. */
00687   int tnum;        /* Root BTree node for this table (see note above) */
00688   Select *pSelect; /* NULL for tables.  Points to definition if a view. */
00689   u8 readOnly;     /* True if this table should not be written by the user */
00690   u8 isTransient;  /* True if automatically deleted when VDBE finishes */
00691   u8 hasPrimKey;   /* True if there exists a primary key */
00692   u8 keyConf;      /* What to do in case of uniqueness conflict on iPKey */
00693   u8 autoInc;      /* True if the integer primary key is autoincrement */
00694   int nRef;          /* Number of pointers to this Table */
00695   Trigger *pTrigger; /* List of SQL triggers on this table */
00696   FKey *pFKey;       /* Linked list of all foreign keys in this table */
00697   char *zColAff;     /* String defining the affinity of each column */
00698 #ifndef SQLITE_OMIT_CHECK
00699   Expr *pCheck;      /* The AND of all CHECK constraints */
00700 #endif
00701 #ifndef SQLITE_OMIT_ALTERTABLE
00702   int addColOffset;  /* Offset in CREATE TABLE statement to add a new column */
00703 #endif
00704   Schema *pSchema;
00705 };
00706 
00707 /*
00708 ** Each foreign key constraint is an instance of the following structure.
00709 **
00710 ** A foreign key is associated with two tables.  The "from" table is
00711 ** the table that contains the REFERENCES clause that creates the foreign
00712 ** key.  The "to" table is the table that is named in the REFERENCES clause.
00713 ** Consider this example:
00714 **
00715 **     CREATE TABLE ex1(
00716 **       a INTEGER PRIMARY KEY,
00717 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
00718 **     );
00719 **
00720 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
00721 **
00722 ** Each REFERENCES clause generates an instance of the following structure
00723 ** which is attached to the from-table.  The to-table need not exist when
00724 ** the from-table is created.  The existance of the to-table is not checked
00725 ** until an attempt is made to insert data into the from-table.
00726 **
00727 ** The sqlite.aFKey hash table stores pointers to this structure
00728 ** given the name of a to-table.  For each to-table, all foreign keys
00729 ** associated with that table are on a linked list using the FKey.pNextTo
00730 ** field.
00731 */
00732 struct FKey {
00733   Table *pFrom;     /* The table that constains the REFERENCES clause */
00734   FKey *pNextFrom;  /* Next foreign key in pFrom */
00735   char *zTo;        /* Name of table that the key points to */
00736   FKey *pNextTo;    /* Next foreign key that points to zTo */
00737   int nCol;         /* Number of columns in this key */
00738   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
00739     int iFrom;         /* Index of column in pFrom */
00740     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
00741   } *aCol;          /* One entry for each of nCol column s */
00742   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
00743   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
00744   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
00745   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
00746 };
00747 
00748 /*
00749 ** SQLite supports many different ways to resolve a contraint
00750 ** error.  ROLLBACK processing means that a constraint violation
00751 ** causes the operation in process to fail and for the current transaction
00752 ** to be rolled back.  ABORT processing means the operation in process
00753 ** fails and any prior changes from that one operation are backed out,
00754 ** but the transaction is not rolled back.  FAIL processing means that
00755 ** the operation in progress stops and returns an error code.  But prior
00756 ** changes due to the same operation are not backed out and no rollback
00757 ** occurs.  IGNORE means that the particular row that caused the constraint
00758 ** error is not inserted or updated.  Processing continues and no error
00759 ** is returned.  REPLACE means that preexisting database rows that caused
00760 ** a UNIQUE constraint violation are removed so that the new insert or
00761 ** update can proceed.  Processing continues and no error is reported.
00762 **
00763 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
00764 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
00765 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
00766 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
00767 ** referenced table row is propagated into the row that holds the
00768 ** foreign key.
00769 ** 
00770 ** The following symbolic values are used to record which type
00771 ** of action to take.
00772 */
00773 #define OE_None     0   /* There is no constraint to check */
00774 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
00775 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
00776 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
00777 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
00778 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
00779 
00780 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
00781 #define OE_SetNull  7   /* Set the foreign key value to NULL */
00782 #define OE_SetDflt  8   /* Set the foreign key value to its default */
00783 #define OE_Cascade  9   /* Cascade the changes */
00784 
00785 #define OE_Default  99  /* Do whatever the default action is */
00786 
00787 
00788 /*
00789 ** An instance of the following structure is passed as the first
00790 ** argument to sqlite3VdbeKeyCompare and is used to control the 
00791 ** comparison of the two index keys.
00792 **
00793 ** If the KeyInfo.incrKey value is true and the comparison would
00794 ** otherwise be equal, then return a result as if the second key
00795 ** were larger.
00796 */
00797 struct KeyInfo {
00798   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
00799   u8 incrKey;         /* Increase 2nd key by epsilon before comparison */
00800   int nField;         /* Number of entries in aColl[] */
00801   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
00802   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
00803 };
00804 
00805 /*
00806 ** Each SQL index is represented in memory by an
00807 ** instance of the following structure.
00808 **
00809 ** The columns of the table that are to be indexed are described
00810 ** by the aiColumn[] field of this structure.  For example, suppose
00811 ** we have the following table and index:
00812 **
00813 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
00814 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
00815 **
00816 ** In the Table structure describing Ex1, nCol==3 because there are
00817 ** three columns in the table.  In the Index structure describing
00818 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
00819 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
00820 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
00821 ** The second column to be indexed (c1) has an index of 0 in
00822 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
00823 **
00824 ** The Index.onError field determines whether or not the indexed columns
00825 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
00826 ** it means this is not a unique index.  Otherwise it is a unique index
00827 ** and the value of Index.onError indicate the which conflict resolution 
00828 ** algorithm to employ whenever an attempt is made to insert a non-unique
00829 ** element.
00830 */
00831 struct Index {
00832   char *zName;     /* Name of this index */
00833   int nColumn;     /* Number of columns in the table used by this index */
00834   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
00835   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
00836   Table *pTable;   /* The SQL table being indexed */
00837   int tnum;        /* Page containing root of this index in database file */
00838   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
00839   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
00840   char *zColAff;   /* String defining the affinity of each column */
00841   Index *pNext;    /* The next index associated with the same table */
00842   Schema *pSchema; /* Schema containing this index */
00843   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
00844   char **azColl;   /* Array of collation sequence names for index */
00845 };
00846 
00847 /*
00848 ** Each token coming out of the lexer is an instance of
00849 ** this structure.  Tokens are also used as part of an expression.
00850 **
00851 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
00852 ** may contain random values.  Do not make any assuptions about Token.dyn
00853 ** and Token.n when Token.z==0.
00854 */
00855 struct Token {
00856   const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
00857   unsigned dyn  : 1;      /* True for malloced memory, false for static */
00858   unsigned n    : 31;     /* Number of characters in this token */
00859 };
00860 
00861 /*
00862 ** An instance of this structure contains information needed to generate
00863 ** code for a SELECT that contains aggregate functions.
00864 **
00865 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
00866 ** pointer to this structure.  The Expr.iColumn field is the index in
00867 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
00868 ** code for that node.
00869 **
00870 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
00871 ** original Select structure that describes the SELECT statement.  These
00872 ** fields do not need to be freed when deallocating the AggInfo structure.
00873 */
00874 struct AggInfo {
00875   u8 directMode;          /* Direct rendering mode means take data directly
00876                           ** from source tables rather than from accumulators */
00877   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
00878                           ** than the source table */
00879   int sortingIdx;         /* Cursor number of the sorting index */
00880   ExprList *pGroupBy;     /* The group by clause */
00881   int nSortingColumn;     /* Number of columns in the sorting index */
00882   struct AggInfo_col {    /* For each column used in source tables */
00883     int iTable;              /* Cursor number of the source table */
00884     int iColumn;             /* Column number within the source table */
00885     int iSorterColumn;       /* Column number in the sorting index */
00886     int iMem;                /* Memory location that acts as accumulator */
00887     Expr *pExpr;             /* The original expression */
00888   } *aCol;
00889   int nColumn;            /* Number of used entries in aCol[] */
00890   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
00891   int nAccumulator;       /* Number of columns that show through to the output.
00892                           ** Additional columns are used only as parameters to
00893                           ** aggregate functions */
00894   struct AggInfo_func {   /* For each aggregate function */
00895     Expr *pExpr;             /* Expression encoding the function */
00896     FuncDef *pFunc;          /* The aggregate function implementation */
00897     int iMem;                /* Memory location that acts as accumulator */
00898     int iDistinct;           /* Virtual table used to enforce DISTINCT */
00899   } *aFunc;
00900   int nFunc;              /* Number of entries in aFunc[] */
00901   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
00902 };
00903 
00904 /*
00905 ** Each node of an expression in the parse tree is an instance
00906 ** of this structure.
00907 **
00908 ** Expr.op is the opcode.  The integer parser token codes are reused
00909 ** as opcodes here.  For example, the parser defines TK_GE to be an integer
00910 ** code representing the ">=" operator.  This same integer code is reused
00911 ** to represent the greater-than-or-equal-to operator in the expression
00912 ** tree.
00913 **
00914 ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
00915 ** of argument if the expression is a function.
00916 **
00917 ** Expr.token is the operator token for this node.  For some expressions
00918 ** that have subexpressions, Expr.token can be the complete text that gave
00919 ** rise to the Expr.  In the latter case, the token is marked as being
00920 ** a compound token.
00921 **
00922 ** An expression of the form ID or ID.ID refers to a column in a table.
00923 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
00924 ** the integer cursor number of a VDBE cursor pointing to that table and
00925 ** Expr.iColumn is the column number for the specific column.  If the
00926 ** expression is used as a result in an aggregate SELECT, then the
00927 ** value is also stored in the Expr.iAgg column in the aggregate so that
00928 ** it can be accessed after all aggregates are computed.
00929 **
00930 ** If the expression is a function, the Expr.iTable is an integer code
00931 ** representing which function.  If the expression is an unbound variable
00932 ** marker (a question mark character '?' in the original SQL) then the
00933 ** Expr.iTable holds the index number for that variable.
00934 **
00935 ** If the expression is a subquery then Expr.iColumn holds an integer
00936 ** register number containing the result of the subquery.  If the
00937 ** subquery gives a constant result, then iTable is -1.  If the subquery
00938 ** gives a different answer at different times during statement processing
00939 ** then iTable is the address of a subroutine that computes the subquery.
00940 **
00941 ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
00942 ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
00943 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
00944 ** operand.
00945 **
00946 ** If the Expr is of type OP_Column, and the table it is selecting from
00947 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
00948 ** corresponding table definition.
00949 */
00950 struct Expr {
00951   u8 op;                 /* Operation performed by this node */
00952   char affinity;         /* The affinity of the column or 0 if not a column */
00953   u8 flags;              /* Various flags.  See below */
00954   CollSeq *pColl;        /* The collation type of the column or 0 */
00955   Expr *pLeft, *pRight;  /* Left and right subnodes */
00956   ExprList *pList;       /* A list of expressions used as function arguments
00957                          ** or in "<expr> IN (<expr-list)" */
00958   Token token;           /* An operand token */
00959   Token span;            /* Complete text of the expression */
00960   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
00961                          ** iColumn-th field of the iTable-th table. */
00962   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
00963   int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
00964   int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
00965   Select *pSelect;       /* When the expression is a sub-select.  Also the
00966                          ** right side of "<expr> IN (<select>)" */
00967   Table *pTab;           /* Table for OP_Column expressions. */
00968   Schema *pSchema;
00969 };
00970 
00971 /*
00972 ** The following are the meanings of bits in the Expr.flags field.
00973 */
00974 #define EP_FromJoin     0x01  /* Originated in ON or USING clause of a join */
00975 #define EP_Agg          0x02  /* Contains one or more aggregate functions */
00976 #define EP_Resolved     0x04  /* IDs have been resolved to COLUMNs */
00977 #define EP_Error        0x08  /* Expression contains one or more errors */
00978 #define EP_Distinct     0x10  /* Aggregate function with DISTINCT keyword */
00979 #define EP_VarSelect    0x20  /* pSelect is correlated, not constant */
00980 #define EP_Dequoted     0x40  /* True if the string has been dequoted */
00981 
00982 /*
00983 ** These macros can be used to test, set, or clear bits in the 
00984 ** Expr.flags field.
00985 */
00986 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
00987 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
00988 #define ExprSetProperty(E,P)     (E)->flags|=(P)
00989 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
00990 
00991 /*
00992 ** A list of expressions.  Each expression may optionally have a
00993 ** name.  An expr/name combination can be used in several ways, such
00994 ** as the list of "expr AS ID" fields following a "SELECT" or in the
00995 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
00996 ** also be used as the argument to a function, in which case the a.zName
00997 ** field is not used.
00998 */
00999 struct ExprList {
01000   int nExpr;             /* Number of expressions on the list */
01001   int nAlloc;            /* Number of entries allocated below */
01002   int iECursor;          /* VDBE Cursor associated with this ExprList */
01003   struct ExprList_item {
01004     Expr *pExpr;           /* The list of expressions */
01005     char *zName;           /* Token associated with this expression */
01006     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
01007     u8 isAgg;              /* True if this is an aggregate like count(*) */
01008     u8 done;               /* A flag to indicate when processing is finished */
01009   } *a;                  /* One entry for each expression */
01010 };
01011 
01012 /*
01013 ** An instance of this structure can hold a simple list of identifiers,
01014 ** such as the list "a,b,c" in the following statements:
01015 **
01016 **      INSERT INTO t(a,b,c) VALUES ...;
01017 **      CREATE INDEX idx ON t(a,b,c);
01018 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
01019 **
01020 ** The IdList.a.idx field is used when the IdList represents the list of
01021 ** column names after a table name in an INSERT statement.  In the statement
01022 **
01023 **     INSERT INTO t(a,b,c) ...
01024 **
01025 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
01026 */
01027 struct IdList {
01028   struct IdList_item {
01029     char *zName;      /* Name of the identifier */
01030     int idx;          /* Index in some Table.aCol[] of a column named zName */
01031   } *a;
01032   int nId;         /* Number of identifiers on the list */
01033   int nAlloc;      /* Number of entries allocated for a[] below */
01034 };
01035 
01036 /*
01037 ** The bitmask datatype defined below is used for various optimizations.
01038 */
01039 typedef unsigned int Bitmask;
01040 
01041 /*
01042 ** The following structure describes the FROM clause of a SELECT statement.
01043 ** Each table or subquery in the FROM clause is a separate element of
01044 ** the SrcList.a[] array.
01045 **
01046 ** With the addition of multiple database support, the following structure
01047 ** can also be used to describe a particular table such as the table that
01048 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
01049 ** such a table must be a simple name: ID.  But in SQLite, the table can
01050 ** now be identified by a database name, a dot, then the table name: ID.ID.
01051 */
01052 struct SrcList {
01053   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
01054   i16 nAlloc;      /* Number of entries allocated in a[] below */
01055   struct SrcList_item {
01056     char *zDatabase;  /* Name of database holding this table */
01057     char *zName;      /* Name of the table */
01058     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
01059     Table *pTab;      /* An SQL table corresponding to zName */
01060     Select *pSelect;  /* A SELECT statement used in place of a table name */
01061     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
01062     u8 jointype;      /* Type of join between this table and the next */
01063     i16 iCursor;      /* The VDBE cursor number used to access this table */
01064     Expr *pOn;        /* The ON clause of a join */
01065     IdList *pUsing;   /* The USING clause of a join */
01066     Bitmask colUsed;  /* Bit N (1<<N) set if column N or pTab is used */
01067   } a[1];             /* One entry for each identifier on the list */
01068 };
01069 
01070 /*
01071 ** Permitted values of the SrcList.a.jointype field
01072 */
01073 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
01074 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
01075 #define JT_NATURAL   0x0004    /* True for a "natural" join */
01076 #define JT_LEFT      0x0008    /* Left outer join */
01077 #define JT_RIGHT     0x0010    /* Right outer join */
01078 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
01079 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
01080 
01081 /*
01082 ** For each nested loop in a WHERE clause implementation, the WhereInfo
01083 ** structure contains a single instance of this structure.  This structure
01084 ** is intended to be private the the where.c module and should not be
01085 ** access or modified by other modules.
01086 */
01087 struct WhereLevel {
01088   int iFrom;            /* Which entry in the FROM clause */
01089   int flags;            /* Flags associated with this level */
01090   int iMem;             /* First memory cell used by this level */
01091   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
01092   Index *pIdx;          /* Index used.  NULL if no index */
01093   int iTabCur;          /* The VDBE cursor used to access the table */
01094   int iIdxCur;          /* The VDBE cursor used to acesss pIdx */
01095   int brk;              /* Jump here to break out of the loop */
01096   int cont;             /* Jump here to continue with the next loop cycle */
01097   int top;              /* First instruction of interior of the loop */
01098   int op, p1, p2;       /* Opcode used to terminate the loop */
01099   int nEq;              /* Number of == or IN constraints on this loop */
01100   int nIn;              /* Number of IN operators constraining this loop */
01101   int *aInLoop;         /* Loop terminators for IN operators */
01102 };
01103 
01104 /*
01105 ** The WHERE clause processing routine has two halves.  The
01106 ** first part does the start of the WHERE loop and the second
01107 ** half does the tail of the WHERE loop.  An instance of
01108 ** this structure is returned by the first half and passed
01109 ** into the second half to give some continuity.
01110 */
01111 struct WhereInfo {
01112   Parse *pParse;
01113   SrcList *pTabList;   /* List of tables in the join */
01114   int iTop;            /* The very beginning of the WHERE loop */
01115   int iContinue;       /* Jump here to continue with next record */
01116   int iBreak;          /* Jump here to break out of the loop */
01117   int nLevel;          /* Number of nested loop */
01118   WhereLevel a[1];     /* Information about each nest loop in the WHERE */
01119 };
01120 
01121 /*
01122 ** A NameContext defines a context in which to resolve table and column
01123 ** names.  The context consists of a list of tables (the pSrcList) field and
01124 ** a list of named expression (pEList).  The named expression list may
01125 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
01126 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
01127 ** pEList corresponds to the result set of a SELECT and is NULL for
01128 ** other statements.
01129 **
01130 ** NameContexts can be nested.  When resolving names, the inner-most 
01131 ** context is searched first.  If no match is found, the next outer
01132 ** context is checked.  If there is still no match, the next context
01133 ** is checked.  This process continues until either a match is found
01134 ** or all contexts are check.  When a match is found, the nRef member of
01135 ** the context containing the match is incremented. 
01136 **
01137 ** Each subquery gets a new NameContext.  The pNext field points to the
01138 ** NameContext in the parent query.  Thus the process of scanning the
01139 ** NameContext list corresponds to searching through successively outer
01140 ** subqueries looking for a match.
01141 */
01142 struct NameContext {
01143   Parse *pParse;       /* The parser */
01144   SrcList *pSrcList;   /* One or more tables used to resolve names */
01145   ExprList *pEList;    /* Optional list of named expressions */
01146   int nRef;            /* Number of names resolved by this context */
01147   int nErr;            /* Number of errors encountered while resolving names */
01148   u8 allowAgg;         /* Aggregate functions allowed here */
01149   u8 hasAgg;           /* True if aggregates are seen */
01150   u8 isCheck;          /* True if resolving names in a CHECK constraint */
01151   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
01152   AggInfo *pAggInfo;   /* Information about aggregates at this level */
01153   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
01154 };
01155 
01156 /*
01157 ** An instance of the following structure contains all information
01158 ** needed to generate code for a single SELECT statement.
01159 **
01160 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
01161 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
01162 ** limit and nOffset to the value of the offset (or 0 if there is not
01163 ** offset).  But later on, nLimit and nOffset become the memory locations
01164 ** in the VDBE that record the limit and offset counters.
01165 **
01166 ** addrOpenVirt[] entries contain the address of OP_OpenVirtual opcodes.
01167 ** These addresses must be stored so that we can go back and fill in
01168 ** the P3_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
01169 ** the number of columns in P2 can be computed at the same time
01170 ** as the OP_OpenVirtual instruction is coded because not
01171 ** enough information about the compound query is known at that point.
01172 ** The KeyInfo for addrOpenVirt[0] and [1] contains collating sequences
01173 ** for the result set.  The KeyInfo for addrOpenVirt[2] contains collating
01174 ** sequences for the ORDER BY clause.
01175 */
01176 struct Select {
01177   ExprList *pEList;      /* The fields of the result */
01178   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
01179   u8 isDistinct;         /* True if the DISTINCT keyword is present */
01180   u8 isResolved;         /* True once sqlite3SelectResolve() has run. */
01181   u8 isAgg;              /* True if this is an aggregate query */
01182   u8 usesVirt;           /* True if uses an OpenVirtual opcode */
01183   u8 disallowOrderBy;    /* Do not allow an ORDER BY to be attached if TRUE */
01184   SrcList *pSrc;         /* The FROM clause */
01185   Expr *pWhere;          /* The WHERE clause */
01186   ExprList *pGroupBy;    /* The GROUP BY clause */
01187   Expr *pHaving;         /* The HAVING clause */
01188   ExprList *pOrderBy;    /* The ORDER BY clause */
01189   Select *pPrior;        /* Prior select in a compound select statement */
01190   Select *pRightmost;    /* Right-most select in a compound select statement */
01191   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
01192   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
01193   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
01194   int addrOpenVirt[3];   /* OP_OpenVirtual opcodes related to this select */
01195 };
01196 
01197 /*
01198 ** The results of a select can be distributed in several ways.
01199 */
01200 #define SRT_Union        1  /* Store result as keys in an index */
01201 #define SRT_Except       2  /* Remove result from a UNION index */
01202 #define SRT_Discard      3  /* Do not save the results anywhere */
01203 
01204 /* The ORDER BY clause is ignored for all of the above */
01205 #define IgnorableOrderby(X) (X<=SRT_Discard)
01206 
01207 #define SRT_Callback     4  /* Invoke a callback with each row of result */
01208 #define SRT_Mem          5  /* Store result in a memory cell */
01209 #define SRT_Set          6  /* Store non-null results as keys in an index */
01210 #define SRT_Table        7  /* Store result as data with an automatic rowid */
01211 #define SRT_VirtualTab   8  /* Create virtual table and store like SRT_Table */
01212 #define SRT_Subroutine   9  /* Call a subroutine to handle results */
01213 #define SRT_Exists      10  /* Store 1 if the result is not empty */
01214 
01215 /*
01216 ** An SQL parser context.  A copy of this structure is passed through
01217 ** the parser and down into all the parser action routine in order to
01218 ** carry around information that is global to the entire parse.
01219 **
01220 ** The structure is divided into two parts.  When the parser and code
01221 ** generate call themselves recursively, the first part of the structure
01222 ** is constant but the second part is reset at the beginning and end of
01223 ** each recursion.
01224 **
01225 ** The nTableLock and aTableLock variables are only used if the shared-cache 
01226 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
01227 ** used to store the set of table-locks required by the statement being
01228 ** compiled. Function sqlite3TableLock() is used to add entries to the
01229 ** list.
01230 */
01231 struct Parse {
01232   sqlite3 *db;         /* The main database structure */
01233   int rc;              /* Return code from execution */
01234   char *zErrMsg;       /* An error message */
01235   Vdbe *pVdbe;         /* An engine for executing database bytecode */
01236   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
01237   u8 nameClash;        /* A permanent table name clashes with temp table name */
01238   u8 checkSchema;      /* Causes schema cookie check after an error */
01239   u8 nested;           /* Number of nested calls to the parser/code generator */
01240   int nErr;            /* Number of errors seen */
01241   int nTab;            /* Number of previously allocated VDBE cursors */
01242   int nMem;            /* Number of memory cells used so far */
01243   int nSet;            /* Number of sets used so far */
01244   int ckOffset;        /* Stack offset to data used by CHECK constraints */
01245   u32 writeMask;       /* Start a write transaction on these databases */
01246   u32 cookieMask;      /* Bitmask of schema verified databases */
01247   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
01248   int cookieValue[MAX_ATTACHED+2];  /* Values of cookies to verify */
01249 #ifndef SQLITE_OMIT_SHARED_CACHE
01250   int nTableLock;        /* Number of locks in aTableLock */
01251   TableLock *aTableLock; /* Required table locks for shared-cache mode */
01252 #endif
01253 
01254   /* Above is constant between recursions.  Below is reset before and after
01255   ** each recursion */
01256 
01257   int nVar;            /* Number of '?' variables seen in the SQL so far */
01258   int nVarExpr;        /* Number of used slots in apVarExpr[] */
01259   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
01260   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
01261   u8 explain;          /* True if the EXPLAIN flag is found on the query */
01262   Token sErrToken;     /* The token at which the error occurred */
01263   Token sNameToken;    /* Token with unqualified schema object name */
01264   Token sLastToken;    /* The last token parsed */
01265   const char *zSql;    /* All SQL text */
01266   const char *zTail;   /* All SQL text past the last semicolon parsed */
01267   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
01268   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
01269   TriggerStack *trigStack;  /* Trigger actions being coded */
01270   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
01271 };
01272 
01273 /*
01274 ** An instance of the following structure can be declared on a stack and used
01275 ** to save the Parse.zAuthContext value so that it can be restored later.
01276 */
01277 struct AuthContext {
01278   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
01279   Parse *pParse;              /* The Parse structure */
01280 };
01281 
01282 /*
01283 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
01284 */
01285 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
01286 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
01287 #define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
01288 
01289 /*
01290  * Each trigger present in the database schema is stored as an instance of
01291  * struct Trigger. 
01292  *
01293  * Pointers to instances of struct Trigger are stored in two ways.
01294  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
01295  *    database). This allows Trigger structures to be retrieved by name.
01296  * 2. All triggers associated with a single table form a linked list, using the
01297  *    pNext member of struct Trigger. A pointer to the first element of the
01298  *    linked list is stored as the "pTrigger" member of the associated
01299  *    struct Table.
01300  *
01301  * The "step_list" member points to the first element of a linked list
01302  * containing the SQL statements specified as the trigger program.
01303  */
01304 struct Trigger {
01305   char *name;             /* The name of the trigger                        */
01306   char *table;            /* The table or view to which the trigger applies */
01307   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
01308   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
01309   Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
01310   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
01311                              the <column-list> is stored here */
01312   int foreach;            /* One of TK_ROW or TK_STATEMENT */
01313   Token nameToken;        /* Token containing zName. Use during parsing only */
01314   Schema *pSchema;        /* Schema containing the trigger */
01315   Schema *pTabSchema;     /* Schema containing the table */
01316   TriggerStep *step_list; /* Link list of trigger program steps             */
01317   Trigger *pNext;         /* Next trigger associated with the table */
01318 };
01319 
01320 /*
01321 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
01322 ** determine which. 
01323 **
01324 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
01325 ** In that cases, the constants below can be ORed together.
01326 */
01327 #define TRIGGER_BEFORE  1
01328 #define TRIGGER_AFTER   2
01329 
01330 /*
01331  * An instance of struct TriggerStep is used to store a single SQL statement
01332  * that is a part of a trigger-program. 
01333  *
01334  * Instances of struct TriggerStep are stored in a singly linked list (linked
01335  * using the "pNext" member) referenced by the "step_list" member of the 
01336  * associated struct Trigger instance. The first element of the linked list is
01337  * the first step of the trigger-program.
01338  * 
01339  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
01340  * "SELECT" statement. The meanings of the other members is determined by the 
01341  * value of "op" as follows:
01342  *
01343  * (op == TK_INSERT)
01344  * orconf    -> stores the ON CONFLICT algorithm
01345  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
01346  *              this stores a pointer to the SELECT statement. Otherwise NULL.
01347  * target    -> A token holding the name of the table to insert into.
01348  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
01349  *              this stores values to be inserted. Otherwise NULL.
01350  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
01351  *              statement, then this stores the column-names to be
01352  *              inserted into.
01353  *
01354  * (op == TK_DELETE)
01355  * target    -> A token holding the name of the table to delete from.
01356  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
01357  *              Otherwise NULL.
01358  * 
01359  * (op == TK_UPDATE)
01360  * target    -> A token holding the name of the table to update rows of.
01361  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
01362  *              Otherwise NULL.
01363  * pExprList -> A list of the columns to update and the expressions to update
01364  *              them to. See sqlite3Update() documentation of "pChanges"
01365  *              argument.
01366  * 
01367  */
01368 struct TriggerStep {
01369   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
01370   int orconf;          /* OE_Rollback etc. */
01371   Trigger *pTrig;      /* The trigger that this step is a part of */
01372 
01373   Select *pSelect;     /* Valid for SELECT and sometimes 
01374                        INSERT steps (when pExprList == 0) */
01375   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
01376   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
01377   ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
01378                         INSERT steps (when pSelect == 0)         */
01379   IdList *pIdList;     /* Valid for INSERT statements only */
01380   TriggerStep *pNext;  /* Next in the link-list */
01381   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
01382 };
01383 
01384 /*
01385  * An instance of struct TriggerStack stores information required during code
01386  * generation of a single trigger program. While the trigger program is being
01387  * coded, its associated TriggerStack instance is pointed to by the
01388  * "pTriggerStack" member of the Parse structure.
01389  *
01390  * The pTab member points to the table that triggers are being coded on. The 
01391  * newIdx member contains the index of the vdbe cursor that points at the temp
01392  * table that stores the new.* references. If new.* references are not valid
01393  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
01394  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
01395  *
01396  * The ON CONFLICT policy to be used for the trigger program steps is stored 
01397  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
01398  * specified for individual triggers steps is used.
01399  *
01400  * struct TriggerStack has a "pNext" member, to allow linked lists to be
01401  * constructed. When coding nested triggers (triggers fired by other triggers)
01402  * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
01403  * pointer. Once the nested trigger has been coded, the pNext value is restored
01404  * to the pTriggerStack member of the Parse stucture and coding of the parent
01405  * trigger continues.
01406  *
01407  * Before a nested trigger is coded, the linked list pointed to by the 
01408  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
01409  * recursively. If this condition is detected, the nested trigger is not coded.
01410  */
01411 struct TriggerStack {
01412   Table *pTab;         /* Table that triggers are currently being coded on */
01413   int newIdx;          /* Index of vdbe cursor to "new" temp table */
01414   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
01415   int orconf;          /* Current orconf policy */
01416   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
01417   Trigger *pTrigger;   /* The trigger currently being coded */
01418   TriggerStack *pNext; /* Next trigger down on the trigger stack */
01419 };
01420 
01421 /*
01422 ** The following structure contains information used by the sqliteFix...
01423 ** routines as they walk the parse tree to make database references
01424 ** explicit.  
01425 */
01426 typedef struct DbFixer DbFixer;
01427 struct DbFixer {
01428   Parse *pParse;      /* The parsing context.  Error messages written here */
01429   const char *zDb;    /* Make sure all objects are contained in this database */
01430   const char *zType;  /* Type of the container - used for error messages */
01431   const Token *pName; /* Name of the container - used for error messages */
01432 };
01433 
01434 /*
01435 ** A pointer to this structure is used to communicate information
01436 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
01437 */
01438 typedef struct {
01439   sqlite3 *db;        /* The database being initialized */
01440   char **pzErrMsg;    /* Error message stored here */
01441 } InitData;
01442 
01443 /*
01444  * This global flag is set for performance testing of triggers. When it is set
01445  * SQLite will perform the overhead of building new and old trigger references 
01446  * even when no triggers exist
01447  */
01448 extern int sqlite3_always_code_trigger_setup;
01449 
01450 /*
01451 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
01452 ** builds) or a function call (for debugging).  If it is a function call,
01453 ** it allows the operator to set a breakpoint at the spot where database
01454 ** corruption is first detected.
01455 */
01456 #ifdef SQLITE_DEBUG
01457   extern int sqlite3Corrupt(void);
01458 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
01459 #else
01460 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
01461 #endif
01462 
01463 /*
01464 ** Internal function prototypes
01465 */
01466 int sqlite3StrICmp(const char *, const char *);
01467 int sqlite3StrNICmp(const char *, const char *, int);
01468 int sqlite3HashNoCase(const char *, int);
01469 int sqlite3IsNumber(const char*, int*, u8);
01470 int sqlite3Compare(const char *, const char *);
01471 int sqlite3SortCompare(const char *, const char *);
01472 void sqlite3RealToSortable(double r, char *);
01473 
01474 void *sqlite3Malloc(int,int);
01475 void *sqlite3MallocRaw(int,int);
01476 void sqlite3Free(void*);
01477 void *sqlite3Realloc(void*,int);
01478 char *sqlite3StrDup(const char*);
01479 char *sqlite3StrNDup(const char*, int);
01480 # define sqlite3CheckMemory(a,b)
01481 void sqlite3ReallocOrFree(void**,int);
01482 void sqlite3FreeX(void*);
01483 void *sqlite3MallocX(int);
01484 int sqlite3AllocSize(void *);
01485 
01486 char *sqlite3MPrintf(const char*, ...);
01487 char *sqlite3VMPrintf(const char*, va_list);
01488 void sqlite3DebugPrintf(const char*, ...);
01489 void *sqlite3TextToPtr(const char*);
01490 void sqlite3SetString(char **, ...);
01491 void sqlite3ErrorMsg(Parse*, const char*, ...);
01492 void sqlite3ErrorClear(Parse*);
01493 void sqlite3Dequote(char*);
01494 void sqlite3DequoteExpr(Expr*);
01495 int sqlite3KeywordCode(const unsigned char*, int);
01496 int sqlite3RunParser(Parse*, const char*, char **);
01497 void sqlite3FinishCoding(Parse*);
01498 Expr *sqlite3Expr(int, Expr*, Expr*, const Token*);
01499 Expr *sqlite3RegisterExpr(Parse*,Token*);
01500 Expr *sqlite3ExprAnd(Expr*, Expr*);
01501 void sqlite3ExprSpan(Expr*,Token*,Token*);
01502 Expr *sqlite3ExprFunction(ExprList*, Token*);
01503 void sqlite3ExprAssignVarNumber(Parse*, Expr*);
01504 void sqlite3ExprDelete(Expr*);
01505 ExprList *sqlite3ExprListAppend(ExprList*,Expr*,Token*);
01506 void sqlite3ExprListDelete(ExprList*);
01507 int sqlite3Init(sqlite3*, char**);
01508 int sqlite3InitCallback(void*, int, char**, char**);
01509 void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
01510 void sqlite3ResetInternalSchema(sqlite3*, int);
01511 void sqlite3BeginParse(Parse*,int);
01512 void sqlite3RollbackInternalChanges(sqlite3*);
01513 void sqlite3CommitInternalChanges(sqlite3*);
01514 Table *sqlite3ResultSetOfSelect(Parse*,char*,Select*);
01515 void sqlite3OpenMasterTable(Parse *, int);
01516 void sqlite3StartTable(Parse*,Token*,Token*,int,int,int);
01517 void sqlite3AddColumn(Parse*,Token*);
01518 void sqlite3AddNotNull(Parse*, int);
01519 void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
01520 void sqlite3AddCheckConstraint(Parse*, Expr*);
01521 void sqlite3AddColumnType(Parse*,Token*);
01522 void sqlite3AddDefaultValue(Parse*,Expr*);
01523 void sqlite3AddCollateType(Parse*, const char*, int);
01524 void sqlite3EndTable(Parse*,Token*,Token*,Select*);
01525 
01526 #ifndef SQLITE_OMIT_VIEW
01527   void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int);
01528   int sqlite3ViewGetColumnNames(Parse*,Table*);
01529 #else
01530 # define sqlite3ViewGetColumnNames(A,B) 0
01531 #endif
01532 
01533 void sqlite3DropTable(Parse*, SrcList*, int, int);
01534 void sqlite3DeleteTable(sqlite3*, Table*);
01535 void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
01536 int sqlite3ArrayAllocate(void**,int,int);
01537 IdList *sqlite3IdListAppend(IdList*, Token*);
01538 int sqlite3IdListIndex(IdList*,const char*);
01539 SrcList *sqlite3SrcListAppend(SrcList*, Token*, Token*);
01540 void sqlite3SrcListAddAlias(SrcList*, Token*);
01541 void sqlite3SrcListAssignCursors(Parse*, SrcList*);
01542 void sqlite3IdListDelete(IdList*);
01543 void sqlite3SrcListDelete(SrcList*);
01544 void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
01545                         Token*, int, int);
01546 void sqlite3DropIndex(Parse*, SrcList*, int);
01547 void sqlite3AddKeyType(Vdbe*, ExprList*);
01548 void sqlite3AddIdxKeyType(Vdbe*, Index*);
01549 int sqlite3Select(Parse*, Select*, int, int, Select*, int, int*, char *aff);
01550 Select *sqlite3SelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
01551                         int,Expr*,Expr*);
01552 void sqlite3SelectDelete(Select*);
01553 void sqlite3SelectUnbind(Select*);
01554 Table *sqlite3SrcListLookup(Parse*, SrcList*);
01555 int sqlite3IsReadOnly(Parse*, Table*, int);
01556 void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
01557 void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
01558 void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
01559 WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**);
01560 void sqlite3WhereEnd(WhereInfo*);
01561 void sqlite3ExprCode(Parse*, Expr*);
01562 void sqlite3ExprCodeAndCache(Parse*, Expr*);
01563 int sqlite3ExprCodeExprList(Parse*, ExprList*);
01564 void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
01565 void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
01566 void sqlite3NextedParse(Parse*, const char*, ...);
01567 Table *sqlite3FindTable(sqlite3*,const char*, const char*);
01568 Table *sqlite3LocateTable(Parse*,const char*, const char*);
01569 Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
01570 void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
01571 void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
01572 void sqlite3Vacuum(Parse*);
01573 int sqlite3RunVacuum(char**, sqlite3*);
01574 char *sqlite3NameFromToken(Token*);
01575 int sqlite3ExprCheck(Parse*, Expr*, int, int*);
01576 int sqlite3ExprCompare(Expr*, Expr*);
01577 int sqliteFuncId(Token*);
01578 int sqlite3ExprResolveNames(NameContext *, Expr *);
01579 int sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
01580 int sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
01581 Vdbe *sqlite3GetVdbe(Parse*);
01582 void sqlite3Randomness(int, void*);
01583 void sqlite3RollbackAll(sqlite3*);
01584 void sqlite3CodeVerifySchema(Parse*, int);
01585 void sqlite3BeginTransaction(Parse*, int);
01586 void sqlite3CommitTransaction(Parse*);
01587 void sqlite3RollbackTransaction(Parse*);
01588 int sqlite3ExprIsConstant(Expr*);
01589 int sqlite3ExprIsConstantOrFunction(Expr*);
01590 int sqlite3ExprIsInteger(Expr*, int*);
01591 int sqlite3IsRowid(const char*);
01592 void sqlite3GenerateRowDelete(sqlite3*, Vdbe*, Table*, int, int);
01593 void sqlite3GenerateRowIndexDelete(Vdbe*, Table*, int, char*);
01594 void sqlite3GenerateIndexKey(Vdbe*, Index*, int);
01595 void sqlite3GenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
01596 void sqlite3CompleteInsertion(Parse*, Table*, int, char*, int, int, int);
01597 void sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
01598 void sqlite3BeginWriteOperation(Parse*, int, int);
01599 Expr *sqlite3ExprDup(Expr*);
01600 void sqlite3TokenCopy(Token*, Token*);
01601 ExprList *sqlite3ExprListDup(ExprList*);
01602 SrcList *sqlite3SrcListDup(SrcList*);
01603 IdList *sqlite3IdListDup(IdList*);
01604 Select *sqlite3SelectDup(Select*);
01605 FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
01606 void sqlite3RegisterBuiltinFunctions(sqlite3*);
01607 void sqlite3RegisterDateTimeFunctions(sqlite3*);
01608 int sqlite3SafetyOn(sqlite3*);
01609 int sqlite3SafetyOff(sqlite3*);
01610 int sqlite3SafetyCheck(sqlite3*);
01611 void sqlite3ChangeCookie(sqlite3*, Vdbe*, int);
01612 
01613 #ifndef SQLITE_OMIT_TRIGGER
01614   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
01615                            int,Expr*,int);
01616   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
01617   void sqlite3DropTrigger(Parse*, SrcList*);
01618   void sqlite3DropTriggerPtr(Parse*, Trigger*);
01619   int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
01620   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
01621                            int, int);
01622   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
01623   void sqlite3DeleteTriggerStep(TriggerStep*);
01624   TriggerStep *sqlite3TriggerSelectStep(Select*);
01625   TriggerStep *sqlite3TriggerInsertStep(Token*, IdList*, ExprList*,Select*,int);
01626   TriggerStep *sqlite3TriggerUpdateStep(Token*, ExprList*, Expr*, int);
01627   TriggerStep *sqlite3TriggerDeleteStep(Token*, Expr*);
01628   void sqlite3DeleteTrigger(Trigger*);
01629   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
01630 #else
01631 # define sqlite3TriggersExist(A,B,C,D,E,F) 0
01632 # define sqlite3DeleteTrigger(A)
01633 # define sqlite3DropTriggerPtr(A,B)
01634 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
01635 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) 0
01636 #endif
01637 
01638 int sqlite3JoinType(Parse*, Token*, Token*, Token*);
01639 void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
01640 void sqlite3DeferForeignKey(Parse*, int);
01641 #ifndef SQLITE_OMIT_AUTHORIZATION
01642   void sqlite3AuthRead(Parse*,Expr*,SrcList*);
01643   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
01644   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
01645   void sqlite3AuthContextPop(AuthContext*);
01646 #else
01647 # define sqlite3AuthRead(a,b,c)
01648 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
01649 # define sqlite3AuthContextPush(a,b,c)
01650 # define sqlite3AuthContextPop(a)  ((void)(a))
01651 #endif
01652 void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
01653 void sqlite3Detach(Parse*, Expr*);
01654 int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
01655                        int omitJournal, int nCache, Btree **ppBtree);
01656 int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
01657 int sqlite3FixSrcList(DbFixer*, SrcList*);
01658 int sqlite3FixSelect(DbFixer*, Select*);
01659 int sqlite3FixExpr(DbFixer*, Expr*);
01660 int sqlite3FixExprList(DbFixer*, ExprList*);
01661 int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
01662 int sqlite3AtoF(const char *z, double*);
01663 char *sqlite3_snprintf(int,char*,const char*,...);
01664 int sqlite3GetInt32(const char *, int*);
01665 int sqlite3FitsIn64Bits(const char *);
01666 int sqlite3utf16ByteLen(const void *pData, int nChar);
01667 int sqlite3utf8CharLen(const char *pData, int nByte);
01668 int sqlite3ReadUtf8(const unsigned char *);
01669 int sqlite3PutVarint(unsigned char *, u64);
01670 int sqlite3GetVarint(const unsigned char *, u64 *);
01671 int sqlite3GetVarint32(const unsigned char *, u32 *);
01672 int sqlite3VarintLen(u64 v);
01673 void sqlite3IndexAffinityStr(Vdbe *, Index *);
01674 void sqlite3TableAffinityStr(Vdbe *, Table *);
01675 char sqlite3CompareAffinity(Expr *pExpr, char aff2);
01676 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
01677 char sqlite3ExprAffinity(Expr *pExpr);
01678 int sqlite3atoi64(const char*, i64*);
01679 void sqlite3Error(sqlite3*, int, const char*,...);
01680 void *sqlite3HexToBlob(const char *z);
01681 int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
01682 const char *sqlite3ErrStr(int);
01683 int sqlite3ReadUniChar(const char *zStr, int *pOffset, u8 *pEnc, int fold);
01684 int sqlite3ReadSchema(Parse *pParse);
01685 CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
01686 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
01687 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
01688 int sqlite3CheckCollSeq(Parse *, CollSeq *);
01689 int sqlite3CheckIndexCollSeq(Parse *, Index *);
01690 int sqlite3CheckObjectName(Parse *, const char *);
01691 void sqlite3VdbeSetChanges(sqlite3 *, int);
01692 void sqlite3utf16Substr(sqlite3_context *,int,sqlite3_value **);
01693 
01694 const void *sqlite3ValueText(sqlite3_value*, u8);
01695 int sqlite3ValueBytes(sqlite3_value*, u8);
01696 void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, void(*)(void*));
01697 void sqlite3ValueFree(sqlite3_value*);
01698 sqlite3_value *sqlite3ValueNew(void);
01699 char *sqlite3utf16to8(const void*, int);
01700 int sqlite3ValueFromExpr(Expr *, u8, u8, sqlite3_value **);
01701 void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
01702 extern const unsigned char sqlite3UpperToLower[];
01703 void sqlite3RootPageMoved(Db*, int, int);
01704 void sqlite3Reindex(Parse*, Token*, Token*);
01705 void sqlite3AlterFunctions(sqlite3*);
01706 void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
01707 int sqlite3GetToken(const unsigned char *, int *);
01708 void sqlite3NestedParse(Parse*, const char*, ...);
01709 void sqlite3ExpirePreparedStatements(sqlite3*);
01710 void sqlite3CodeSubselect(Parse *, Expr *);
01711 int sqlite3SelectResolve(Parse *, Select *, NameContext *);
01712 void sqlite3ColumnDefault(Vdbe *, Table *, int);
01713 void sqlite3AlterFinishAddColumn(Parse *, Token *);
01714 void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
01715 const char *sqlite3TestErrorName(int);
01716 CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
01717 char sqlite3AffinityType(const Token*);
01718 void sqlite3Analyze(Parse*, Token*, Token*);
01719 int sqlite3InvokeBusyHandler(BusyHandler*);
01720 int sqlite3FindDb(sqlite3*, Token*);
01721 void sqlite3AnalysisLoad(sqlite3*,int iDB);
01722 void sqlite3DefaultRowEst(Index*);
01723 void sqlite3RegisterLikeFunctions(sqlite3*, int);
01724 int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
01725 ThreadData *sqlite3ThreadData(void);
01726 const ThreadData *sqlite3ThreadDataReadOnly(void);
01727 void sqlite3ReleaseThreadData(void);
01728 void sqlite3AttachFunctions(sqlite3 *);
01729 void sqlite3MinimumFileFormat(Parse*, int, int);
01730 void sqlite3SchemaFree(void *);
01731 Schema *sqlite3SchemaGet(Btree *);
01732 int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
01733 KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
01734 int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
01735   void (*)(sqlite3_context*,int,sqlite3_value **),
01736   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
01737 int sqlite3ApiExit(sqlite3 *db, int);
01738 int sqlite3MallocFailed(void);
01739 void sqlite3FailedMalloc(void);
01740 void sqlite3AbortOtherActiveVdbes(sqlite3 *, Vdbe *);
01741 int sqlite3OpenTempDatabase(Parse *);
01742 
01743 #ifndef SQLITE_OMIT_SHARED_CACHE
01744   void sqlite3TableLock(Parse *, int, int, u8, const char *);
01745 #else
01746   #define sqlite3TableLock(v,w,x,y,z)
01747 #endif
01748 
01749 #ifdef SQLITE_MEMDEBUG
01750   void sqlite3MallocDisallow(void);
01751   void sqlite3MallocAllow(void);
01752   int sqlite3TestMallocFail(void);
01753 #else
01754   #define sqlite3TestMallocFail() 0
01755   #define sqlite3MallocDisallow()
01756   #define sqlite3MallocAllow()
01757 #endif
01758 
01759 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
01760   void *sqlite3ThreadSafeMalloc(int);
01761   void sqlite3ThreadSafeFree(void *);
01762 #else
01763   #define sqlite3ThreadSafeMalloc sqlite3MallocX
01764   #define sqlite3ThreadSafeFree sqlite3FreeX
01765 #endif
01766 
01767 #ifdef SQLITE_SSE
01768 #include "sseInt.h"
01769 #endif
01770 
01771 #endif