Back to index

php5  5.3.10
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 203289 2005-12-20 15:26:26Z iliaa $
00015 */
00016 #include "config.h"
00017 #include "sqlite.h"
00018 #include "hash.h"
00019 #include "parse.h"
00020 #include "btree.h"
00021 #include <stdio.h>
00022 #include <stdlib.h>
00023 #include <string.h>
00024 #include <assert.h>
00025 
00026 /*
00027 ** The maximum number of in-memory pages to use for the main database
00028 ** table and for temporary tables.
00029 */
00030 #define MAX_PAGES   2000
00031 #define TEMP_PAGES   500
00032 
00033 /*
00034 ** If the following macro is set to 1, then NULL values are considered
00035 ** distinct for the SELECT DISTINCT statement and for UNION or EXCEPT
00036 ** compound queries.  No other SQL database engine (among those tested) 
00037 ** works this way except for OCELOT.  But the SQL92 spec implies that
00038 ** this is how things should work.
00039 **
00040 ** If the following macro is set to 0, then NULLs are indistinct for
00041 ** SELECT DISTINCT and for UNION.
00042 */
00043 #define NULL_ALWAYS_DISTINCT 0
00044 
00045 /*
00046 ** If the following macro is set to 1, then NULL values are considered
00047 ** distinct when determining whether or not two entries are the same
00048 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
00049 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
00050 ** is the way things are suppose to work.
00051 **
00052 ** If the following macro is set to 0, the NULLs are indistinct for
00053 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
00054 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
00055 ** work.
00056 */
00057 #define NULL_DISTINCT_FOR_UNIQUE 1
00058 
00059 /*
00060 ** The maximum number of attached databases.  This must be at least 2
00061 ** in order to support the main database file (0) and the file used to
00062 ** hold temporary tables (1).  And it must be less than 256 because
00063 ** an unsigned character is used to stored the database index.
00064 */
00065 #define MAX_ATTACHED 10
00066 
00067 /*
00068 ** The next macro is used to determine where TEMP tables and indices
00069 ** are stored.  Possible values:
00070 **
00071 **   0    Always use a temporary files
00072 **   1    Use a file unless overridden by "PRAGMA temp_store"
00073 **   2    Use memory unless overridden by "PRAGMA temp_store"
00074 **   3    Always use memory
00075 */
00076 #ifndef TEMP_STORE
00077 # define TEMP_STORE 1
00078 #endif
00079 
00080 /*
00081 ** When building SQLite for embedded systems where memory is scarce,
00082 ** you can define one or more of the following macros to omit extra
00083 ** features of the library and thus keep the size of the library to
00084 ** a minimum.
00085 */
00086 /* #define SQLITE_OMIT_AUTHORIZATION  1 */
00087 /* #define SQLITE_OMIT_INMEMORYDB     1 */
00088 /* #define SQLITE_OMIT_VACUUM         1 */
00089 /* #define SQLITE_OMIT_DATETIME_FUNCS 1 */
00090 /* #define SQLITE_OMIT_PROGRESS_CALLBACK 1 */
00091 
00092 /*
00093 ** Integers of known sizes.  These typedefs might change for architectures
00094 ** where the sizes very.  Preprocessor macros are available so that the
00095 ** types can be conveniently redefined at compile-type.  Like this:
00096 **
00097 **         cc '-DUINTPTR_TYPE=long long int' ...
00098 */
00099 #ifndef UINT32_TYPE
00100 # define UINT32_TYPE unsigned int
00101 #endif
00102 #ifndef UINT16_TYPE
00103 # define UINT16_TYPE unsigned short int
00104 #endif
00105 #ifndef INT16_TYPE
00106 # define INT16_TYPE short int
00107 #endif
00108 #ifndef UINT8_TYPE
00109 # define UINT8_TYPE unsigned char
00110 #endif
00111 #ifndef INT8_TYPE
00112 # define INT8_TYPE signed char
00113 #endif
00114 #ifndef INTPTR_TYPE
00115 # if SQLITE_PTR_SZ==4
00116 #   define INTPTR_TYPE int
00117 # else
00118 #   define INTPTR_TYPE long long
00119 # endif
00120 #endif
00121 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
00122 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
00123 typedef INT16_TYPE i16;            /* 2-byte signed integer */
00124 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
00125 typedef UINT8_TYPE i8;             /* 1-byte signed integer */
00126 typedef INTPTR_TYPE ptr;           /* Big enough to hold a pointer */
00127 typedef unsigned INTPTR_TYPE uptr; /* Big enough to hold a pointer */
00128 
00129 /*
00130 ** Defer sourcing vdbe.h until after the "u8" typedef is defined.
00131 */
00132 #include "vdbe.h"
00133 
00134 /*
00135 ** Most C compilers these days recognize "long double", don't they?
00136 ** Just in case we encounter one that does not, we will create a macro
00137 ** for long double so that it can be easily changed to just "double".
00138 */
00139 #ifndef LONGDOUBLE_TYPE
00140 # define LONGDOUBLE_TYPE long double
00141 #endif
00142 
00143 /*
00144 ** This macro casts a pointer to an integer.  Useful for doing
00145 ** pointer arithmetic.
00146 */
00147 #define Addr(X)  ((uptr)X)
00148 
00149 /*
00150 ** The maximum number of bytes of data that can be put into a single
00151 ** row of a single table.  The upper bound on this limit is 16777215
00152 ** bytes (or 16MB-1).  We have arbitrarily set the limit to just 1MB
00153 ** here because the overflow page chain is inefficient for really big
00154 ** records and we want to discourage people from thinking that 
00155 ** multi-megabyte records are OK.  If your needs are different, you can
00156 ** change this define and recompile to increase or decrease the record
00157 ** size.
00158 **
00159 ** The 16777198 is computed as follows:  238 bytes of payload on the
00160 ** original pages plus 16448 overflow pages each holding 1020 bytes of
00161 ** data.
00162 */
00163 #define MAX_BYTES_PER_ROW  1048576
00164 /* #define MAX_BYTES_PER_ROW 16777198 */
00165 
00166 /*
00167 ** If memory allocation problems are found, recompile with
00168 **
00169 **      -DMEMORY_DEBUG=1
00170 **
00171 ** to enable some sanity checking on malloc() and free().  To
00172 ** check for memory leaks, recompile with
00173 **
00174 **      -DMEMORY_DEBUG=2
00175 **
00176 ** and a line of text will be written to standard error for
00177 ** each malloc() and free().  This output can be analyzed
00178 ** by an AWK script to determine if there are any leaks.
00179 */
00180 #ifdef MEMORY_DEBUG
00181 # define sqliteMalloc(X)    sqliteMalloc_(X,1,__FILE__,__LINE__)
00182 # define sqliteMallocRaw(X) sqliteMalloc_(X,0,__FILE__,__LINE__)
00183 # define sqliteFree(X)      sqliteFree_(X,__FILE__,__LINE__)
00184 # define sqliteRealloc(X,Y) sqliteRealloc_(X,Y,__FILE__,__LINE__)
00185 # define sqliteStrDup(X)    sqliteStrDup_(X,__FILE__,__LINE__)
00186 # define sqliteStrNDup(X,Y) sqliteStrNDup_(X,Y,__FILE__,__LINE__)
00187   void sqliteStrRealloc(char**);
00188 #else
00189 # define sqliteRealloc_(X,Y) sqliteRealloc(X,Y)
00190 # define sqliteStrRealloc(X)
00191 #endif
00192 
00193 /*
00194 ** This variable gets set if malloc() ever fails.  After it gets set,
00195 ** the SQLite library shuts down permanently.
00196 */
00197 extern int sqlite_malloc_failed;
00198 
00199 /*
00200 ** The following global variables are used for testing and debugging
00201 ** only.  They only work if MEMORY_DEBUG is defined.
00202 */
00203 #ifdef MEMORY_DEBUG
00204 extern int sqlite_nMalloc;       /* Number of sqliteMalloc() calls */
00205 extern int sqlite_nFree;         /* Number of sqliteFree() calls */
00206 extern int sqlite_iMallocFail;   /* Fail sqliteMalloc() after this many calls */
00207 #endif
00208 
00209 /*
00210 ** Name of the master database table.  The master database table
00211 ** is a special table that holds the names and attributes of all
00212 ** user tables and indices.
00213 */
00214 #define MASTER_NAME       "sqlite_master"
00215 #define TEMP_MASTER_NAME  "sqlite_temp_master"
00216 
00217 /*
00218 ** The name of the schema table.
00219 */
00220 #define SCHEMA_TABLE(x)  (x?TEMP_MASTER_NAME:MASTER_NAME)
00221 
00222 /*
00223 ** A convenience macro that returns the number of elements in
00224 ** an array.
00225 */
00226 #define ArraySize(X)    (sizeof(X)/sizeof(X[0]))
00227 
00228 /*
00229 ** Forward references to structures
00230 */
00231 typedef struct Column Column;
00232 typedef struct Table Table;
00233 typedef struct Index Index;
00234 typedef struct Instruction Instruction;
00235 typedef struct Expr Expr;
00236 typedef struct ExprList ExprList;
00237 typedef struct Parse Parse;
00238 typedef struct Token Token;
00239 typedef struct IdList IdList;
00240 typedef struct SrcList SrcList;
00241 typedef struct WhereInfo WhereInfo;
00242 typedef struct WhereLevel WhereLevel;
00243 typedef struct Select Select;
00244 typedef struct AggExpr AggExpr;
00245 typedef struct FuncDef FuncDef;
00246 typedef struct Trigger Trigger;
00247 typedef struct TriggerStep TriggerStep;
00248 typedef struct TriggerStack TriggerStack;
00249 typedef struct FKey FKey;
00250 typedef struct Db Db;
00251 typedef struct AuthContext AuthContext;
00252 
00253 /*
00254 ** Each database file to be accessed by the system is an instance
00255 ** of the following structure.  There are normally two of these structures
00256 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
00257 ** aDb[1] is the database file used to hold temporary tables.  Additional
00258 ** databases may be attached.
00259 */
00260 struct Db {
00261   char *zName;         /* Name of this database */
00262   Btree *pBt;          /* The B*Tree structure for this database file */
00263   int schema_cookie;   /* Database schema version number for this file */
00264   Hash tblHash;        /* All tables indexed by name */
00265   Hash idxHash;        /* All (named) indices indexed by name */
00266   Hash trigHash;       /* All triggers indexed by name */
00267   Hash aFKey;          /* Foreign keys indexed by to-table */
00268   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
00269   u16 flags;           /* Flags associated with this database */
00270   void *pAux;          /* Auxiliary data.  Usually NULL */
00271   void (*xFreeAux)(void*);  /* Routine to free pAux */
00272 };
00273 
00274 /*
00275 ** These macros can be used to test, set, or clear bits in the 
00276 ** Db.flags field.
00277 */
00278 #define DbHasProperty(D,I,P)     (((D)->aDb[I].flags&(P))==(P))
00279 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].flags&(P))!=0)
00280 #define DbSetProperty(D,I,P)     (D)->aDb[I].flags|=(P)
00281 #define DbClearProperty(D,I,P)   (D)->aDb[I].flags&=~(P)
00282 
00283 /*
00284 ** Allowed values for the DB.flags field.
00285 **
00286 ** The DB_Locked flag is set when the first OP_Transaction or OP_Checkpoint
00287 ** opcode is emitted for a database.  This prevents multiple occurances
00288 ** of those opcodes for the same database in the same program.  Similarly,
00289 ** the DB_Cookie flag is set when the OP_VerifyCookie opcode is emitted,
00290 ** and prevents duplicate OP_VerifyCookies from taking up space and slowing
00291 ** down execution.
00292 **
00293 ** The DB_SchemaLoaded flag is set after the database schema has been
00294 ** read into internal hash tables.
00295 **
00296 ** DB_UnresetViews means that one or more views have column names that
00297 ** have been filled out.  If the schema changes, these column names might
00298 ** changes and so the view will need to be reset.
00299 */
00300 #define DB_Locked          0x0001  /* OP_Transaction opcode has been emitted */
00301 #define DB_Cookie          0x0002  /* OP_VerifyCookie opcode has been emiited */
00302 #define DB_SchemaLoaded    0x0004  /* The schema has been loaded */
00303 #define DB_UnresetViews    0x0008  /* Some views have defined column names */
00304 
00305 
00306 /*
00307 ** Each database is an instance of the following structure.
00308 **
00309 ** The sqlite.file_format is initialized by the database file
00310 ** and helps determines how the data in the database file is
00311 ** represented.  This field allows newer versions of the library
00312 ** to read and write older databases.  The various file formats
00313 ** are as follows:
00314 **
00315 **     file_format==1    Version 2.1.0.
00316 **     file_format==2    Version 2.2.0. Add support for INTEGER PRIMARY KEY.
00317 **     file_format==3    Version 2.6.0. Fix empty-string index bug.
00318 **     file_format==4    Version 2.7.0. Add support for separate numeric and
00319 **                       text datatypes.
00320 **
00321 ** The sqlite.temp_store determines where temporary database files
00322 ** are stored.  If 1, then a file is created to hold those tables.  If
00323 ** 2, then they are held in memory.  0 means use the default value in
00324 ** the TEMP_STORE macro.
00325 **
00326 ** The sqlite.lastRowid records the last insert rowid generated by an
00327 ** insert statement.  Inserts on views do not affect its value.  Each
00328 ** trigger has its own context, so that lastRowid can be updated inside
00329 ** triggers as usual.  The previous value will be restored once the trigger
00330 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
00331 ** longer (since after version 2.8.12) reset to -1.
00332 **
00333 ** The sqlite.nChange does not count changes within triggers and keeps no
00334 ** context.  It is reset at start of sqlite_exec.
00335 ** The sqlite.lsChange represents the number of changes made by the last
00336 ** insert, update, or delete statement.  It remains constant throughout the
00337 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
00338 ** context stack just like lastRowid so that the count of changes
00339 ** within a trigger is not seen outside the trigger.  Changes to views do not
00340 ** affect the value of lsChange.
00341 ** The sqlite.csChange keeps track of the number of current changes (since
00342 ** the last statement) and is used to update sqlite_lsChange.
00343 */
00344 struct sqlite {
00345   int nDb;                      /* Number of backends currently in use */
00346   Db *aDb;                      /* All backends */
00347   Db aDbStatic[2];              /* Static space for the 2 default backends */
00348   int flags;                    /* Miscellanous flags. See below */
00349   u8 file_format;               /* What file format version is this database? */
00350   u8 safety_level;              /* How aggressive at synching data to disk */
00351   u8 want_to_close;             /* Close after all VDBEs are deallocated */
00352   u8 temp_store;                /* 1=file, 2=memory, 0=compile-time default */
00353   u8 onError;                   /* Default conflict algorithm */
00354   int next_cookie;              /* Next value of aDb[0].schema_cookie */
00355   int cache_size;               /* Number of pages to use in the cache */
00356   int nTable;                   /* Number of tables in the database */
00357   void *pBusyArg;               /* 1st Argument to the busy callback */
00358   int (*xBusyCallback)(void *,const char*,int);  /* The busy callback */
00359   void *pCommitArg;             /* Argument to xCommitCallback() */   
00360   int (*xCommitCallback)(void*);/* Invoked at every commit. */
00361   Hash aFunc;                   /* All functions that can be in SQL exprs */
00362   int lastRowid;                /* ROWID of most recent insert (see above) */
00363   int priorNewRowid;            /* Last randomly generated ROWID */
00364   int magic;                    /* Magic number for detect library misuse */
00365   int nChange;                  /* Number of rows changed (see above) */
00366   int lsChange;                 /* Last statement change count (see above) */
00367   int csChange;                 /* Current statement change count (see above) */
00368   struct sqliteInitInfo {       /* Information used during initialization */
00369     int iDb;                       /* When back is being initialized */
00370     int newTnum;                   /* Rootpage of table being initialized */
00371     u8 busy;                       /* TRUE if currently initializing */
00372   } init;
00373   struct Vdbe *pVdbe;           /* List of active virtual machines */
00374   void (*xTrace)(void*,const char*);     /* Trace function */
00375   void *pTraceArg;                       /* Argument to the trace function */
00376 #ifndef SQLITE_OMIT_AUTHORIZATION
00377   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
00378                                 /* Access authorization function */
00379   void *pAuthArg;               /* 1st argument to the access auth function */
00380 #endif
00381 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
00382   int (*xProgress)(void *);     /* The progress callback */
00383   void *pProgressArg;           /* Argument to the progress callback */
00384   int nProgressOps;             /* Number of opcodes for progress callback */
00385 #endif
00386 };
00387 
00388 /*
00389 ** Possible values for the sqlite.flags and or Db.flags fields.
00390 **
00391 ** On sqlite.flags, the SQLITE_InTrans value means that we have
00392 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
00393 ** transaction is active on that particular database file.
00394 */
00395 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
00396 #define SQLITE_Initialized    0x00000002  /* True after initialization */
00397 #define SQLITE_Interrupt      0x00000004  /* Cancel current operation */
00398 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
00399 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
00400 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
00401 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
00402 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
00403                                           /*   DELETE, or UPDATE and return */
00404                                           /*   the count using a callback. */
00405 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
00406                                           /*   result set is empty */
00407 #define SQLITE_ReportTypes    0x00000200  /* Include information on datatypes */
00408                                           /*   in 4th argument of callback */
00409 
00410 /*
00411 ** Possible values for the sqlite.magic field.
00412 ** The numbers are obtained at random and have no special meaning, other
00413 ** than being distinct from one another.
00414 */
00415 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
00416 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
00417 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
00418 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
00419 
00420 /*
00421 ** Each SQL function is defined by an instance of the following
00422 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
00423 ** hash table.  When multiple functions have the same name, the hash table
00424 ** points to a linked list of these structures.
00425 */
00426 struct FuncDef {
00427   void (*xFunc)(sqlite_func*,int,const char**);  /* Regular function */
00428   void (*xStep)(sqlite_func*,int,const char**);  /* Aggregate function step */
00429   void (*xFinalize)(sqlite_func*);           /* Aggregate function finializer */
00430   signed char nArg;         /* Number of arguments.  -1 means unlimited */
00431   signed char dataType;     /* Arg that determines datatype.  -1=NUMERIC, */
00432                             /* -2=TEXT. -3=SQLITE_ARGS */
00433   u8 includeTypes;          /* Add datatypes to args of xFunc and xStep */
00434   void *pUserData;          /* User data parameter */
00435   FuncDef *pNext;           /* Next function with same name */
00436 };
00437 
00438 /*
00439 ** information about each column of an SQL table is held in an instance
00440 ** of this structure.
00441 */
00442 struct Column {
00443   char *zName;     /* Name of this column */
00444   char *zDflt;     /* Default value of this column */
00445   char *zType;     /* Data type for this column */
00446   u8 notNull;      /* True if there is a NOT NULL constraint */
00447   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
00448   u8 sortOrder;    /* Some combination of SQLITE_SO_... values */
00449   u8 dottedName;   /* True if zName contains a "." character */
00450 };
00451 
00452 /*
00453 ** The allowed sort orders.
00454 **
00455 ** The TEXT and NUM values use bits that do not overlap with DESC and ASC.
00456 ** That way the two can be combined into a single number.
00457 */
00458 #define SQLITE_SO_UNK       0  /* Use the default collating type.  (SCT_NUM) */
00459 #define SQLITE_SO_TEXT      2  /* Sort using memcmp() */
00460 #define SQLITE_SO_NUM       4  /* Sort using sqliteCompare() */
00461 #define SQLITE_SO_TYPEMASK  6  /* Mask to extract the collating sequence */
00462 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
00463 #define SQLITE_SO_DESC      1  /* Sort in descending order */
00464 #define SQLITE_SO_DIRMASK   1  /* Mask to extract the sort direction */
00465 
00466 /*
00467 ** Each SQL table is represented in memory by an instance of the
00468 ** following structure.
00469 **
00470 ** Table.zName is the name of the table.  The case of the original
00471 ** CREATE TABLE statement is stored, but case is not significant for
00472 ** comparisons.
00473 **
00474 ** Table.nCol is the number of columns in this table.  Table.aCol is a
00475 ** pointer to an array of Column structures, one for each column.
00476 **
00477 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
00478 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
00479 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
00480 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
00481 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
00482 ** is generated for each row of the table.  Table.hasPrimKey is true if
00483 ** the table has any PRIMARY KEY, INTEGER or otherwise.
00484 **
00485 ** Table.tnum is the page number for the root BTree page of the table in the
00486 ** database file.  If Table.iDb is the index of the database table backend
00487 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
00488 ** holds temporary tables and indices.  If Table.isTransient
00489 ** is true, then the table is stored in a file that is automatically deleted
00490 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
00491 ** refers VDBE cursor number that holds the table open, not to the root
00492 ** page number.  Transient tables are used to hold the results of a
00493 ** sub-query that appears instead of a real table name in the FROM clause 
00494 ** of a SELECT statement.
00495 */
00496 struct Table {
00497   char *zName;     /* Name of the table */
00498   int nCol;        /* Number of columns in this table */
00499   Column *aCol;    /* Information about each column */
00500   int iPKey;       /* If not less then 0, use aCol[iPKey] as the primary key */
00501   Index *pIndex;   /* List of SQL indexes on this table. */
00502   int tnum;        /* Root BTree node for this table (see note above) */
00503   Select *pSelect; /* NULL for tables.  Points to definition if a view. */
00504   u8 readOnly;     /* True if this table should not be written by the user */
00505   u8 iDb;          /* Index into sqlite.aDb[] of the backend for this table */
00506   u8 isTransient;  /* True if automatically deleted when VDBE finishes */
00507   u8 hasPrimKey;   /* True if there exists a primary key */
00508   u8 keyConf;      /* What to do in case of uniqueness conflict on iPKey */
00509   Trigger *pTrigger; /* List of SQL triggers on this table */
00510   FKey *pFKey;       /* Linked list of all foreign keys in this table */
00511 };
00512 
00513 /*
00514 ** Each foreign key constraint is an instance of the following structure.
00515 **
00516 ** A foreign key is associated with two tables.  The "from" table is
00517 ** the table that contains the REFERENCES clause that creates the foreign
00518 ** key.  The "to" table is the table that is named in the REFERENCES clause.
00519 ** Consider this example:
00520 **
00521 **     CREATE TABLE ex1(
00522 **       a INTEGER PRIMARY KEY,
00523 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
00524 **     );
00525 **
00526 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
00527 **
00528 ** Each REFERENCES clause generates an instance of the following structure
00529 ** which is attached to the from-table.  The to-table need not exist when
00530 ** the from-table is created.  The existance of the to-table is not checked
00531 ** until an attempt is made to insert data into the from-table.
00532 **
00533 ** The sqlite.aFKey hash table stores pointers to this structure
00534 ** given the name of a to-table.  For each to-table, all foreign keys
00535 ** associated with that table are on a linked list using the FKey.pNextTo
00536 ** field.
00537 */
00538 struct FKey {
00539   Table *pFrom;     /* The table that constains the REFERENCES clause */
00540   FKey *pNextFrom;  /* Next foreign key in pFrom */
00541   char *zTo;        /* Name of table that the key points to */
00542   FKey *pNextTo;    /* Next foreign key that points to zTo */
00543   int nCol;         /* Number of columns in this key */
00544   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
00545     int iFrom;         /* Index of column in pFrom */
00546     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
00547   } *aCol;          /* One entry for each of nCol column s */
00548   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
00549   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
00550   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
00551   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
00552 };
00553 
00554 /*
00555 ** SQLite supports many different ways to resolve a contraint
00556 ** error.  ROLLBACK processing means that a constraint violation
00557 ** causes the operation in process to fail and for the current transaction
00558 ** to be rolled back.  ABORT processing means the operation in process
00559 ** fails and any prior changes from that one operation are backed out,
00560 ** but the transaction is not rolled back.  FAIL processing means that
00561 ** the operation in progress stops and returns an error code.  But prior
00562 ** changes due to the same operation are not backed out and no rollback
00563 ** occurs.  IGNORE means that the particular row that caused the constraint
00564 ** error is not inserted or updated.  Processing continues and no error
00565 ** is returned.  REPLACE means that preexisting database rows that caused
00566 ** a UNIQUE constraint violation are removed so that the new insert or
00567 ** update can proceed.  Processing continues and no error is reported.
00568 **
00569 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
00570 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
00571 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
00572 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
00573 ** referenced table row is propagated into the row that holds the
00574 ** foreign key.
00575 ** 
00576 ** The following symbolic values are used to record which type
00577 ** of action to take.
00578 */
00579 #define OE_None     0   /* There is no constraint to check */
00580 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
00581 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
00582 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
00583 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
00584 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
00585 
00586 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
00587 #define OE_SetNull  7   /* Set the foreign key value to NULL */
00588 #define OE_SetDflt  8   /* Set the foreign key value to its default */
00589 #define OE_Cascade  9   /* Cascade the changes */
00590 
00591 #define OE_Default  99  /* Do whatever the default action is */
00592 
00593 /*
00594 ** Each SQL index is represented in memory by an
00595 ** instance of the following structure.
00596 **
00597 ** The columns of the table that are to be indexed are described
00598 ** by the aiColumn[] field of this structure.  For example, suppose
00599 ** we have the following table and index:
00600 **
00601 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
00602 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
00603 **
00604 ** In the Table structure describing Ex1, nCol==3 because there are
00605 ** three columns in the table.  In the Index structure describing
00606 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
00607 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
00608 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
00609 ** The second column to be indexed (c1) has an index of 0 in
00610 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
00611 **
00612 ** The Index.onError field determines whether or not the indexed columns
00613 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
00614 ** it means this is not a unique index.  Otherwise it is a unique index
00615 ** and the value of Index.onError indicate the which conflict resolution 
00616 ** algorithm to employ whenever an attempt is made to insert a non-unique
00617 ** element.
00618 */
00619 struct Index {
00620   char *zName;     /* Name of this index */
00621   int nColumn;     /* Number of columns in the table used by this index */
00622   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
00623   Table *pTable;   /* The SQL table being indexed */
00624   int tnum;        /* Page containing root of this index in database file */
00625   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
00626   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
00627   u8 iDb;          /* Index in sqlite.aDb[] of where this index is stored */
00628   Index *pNext;    /* The next index associated with the same table */
00629 };
00630 
00631 /*
00632 ** Each token coming out of the lexer is an instance of
00633 ** this structure.  Tokens are also used as part of an expression.
00634 **
00635 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
00636 ** may contain random values.  Do not make any assuptions about Token.dyn
00637 ** and Token.n when Token.z==0.
00638 */
00639 struct Token {
00640   const char *z;      /* Text of the token.  Not NULL-terminated! */
00641   unsigned dyn  : 1;  /* True for malloced memory, false for static */
00642   unsigned n    : 31; /* Number of characters in this token */
00643 };
00644 
00645 /*
00646 ** Each node of an expression in the parse tree is an instance
00647 ** of this structure.
00648 **
00649 ** Expr.op is the opcode.  The integer parser token codes are reused
00650 ** as opcodes here.  For example, the parser defines TK_GE to be an integer
00651 ** code representing the ">=" operator.  This same integer code is reused
00652 ** to represent the greater-than-or-equal-to operator in the expression
00653 ** tree.
00654 **
00655 ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
00656 ** of argument if the expression is a function.
00657 **
00658 ** Expr.token is the operator token for this node.  For some expressions
00659 ** that have subexpressions, Expr.token can be the complete text that gave
00660 ** rise to the Expr.  In the latter case, the token is marked as being
00661 ** a compound token.
00662 **
00663 ** An expression of the form ID or ID.ID refers to a column in a table.
00664 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
00665 ** the integer cursor number of a VDBE cursor pointing to that table and
00666 ** Expr.iColumn is the column number for the specific column.  If the
00667 ** expression is used as a result in an aggregate SELECT, then the
00668 ** value is also stored in the Expr.iAgg column in the aggregate so that
00669 ** it can be accessed after all aggregates are computed.
00670 **
00671 ** If the expression is a function, the Expr.iTable is an integer code
00672 ** representing which function.  If the expression is an unbound variable
00673 ** marker (a question mark character '?' in the original SQL) then the
00674 ** Expr.iTable holds the index number for that variable.
00675 **
00676 ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
00677 ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
00678 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
00679 ** operand.
00680 */
00681 struct Expr {
00682   u8 op;                 /* Operation performed by this node */
00683   u8 dataType;           /* Either SQLITE_SO_TEXT or SQLITE_SO_NUM */
00684   u8 iDb;                /* Database referenced by this expression */
00685   u8 flags;              /* Various flags.  See below */
00686   Expr *pLeft, *pRight;  /* Left and right subnodes */
00687   ExprList *pList;       /* A list of expressions used as function arguments
00688                          ** or in "<expr> IN (<expr-list)" */
00689   Token token;           /* An operand token */
00690   Token span;            /* Complete text of the expression */
00691   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
00692                          ** iColumn-th field of the iTable-th table. */
00693   int iAgg;              /* When op==TK_COLUMN and pParse->useAgg==TRUE, pull
00694                          ** result from the iAgg-th element of the aggregator */
00695   Select *pSelect;       /* When the expression is a sub-select.  Also the
00696                          ** right side of "<expr> IN (<select>)" */
00697 };
00698 
00699 /*
00700 ** The following are the meanings of bits in the Expr.flags field.
00701 */
00702 #define EP_FromJoin     0x0001  /* Originated in ON or USING clause of a join */
00703 
00704 /*
00705 ** These macros can be used to test, set, or clear bits in the 
00706 ** Expr.flags field.
00707 */
00708 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
00709 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
00710 #define ExprSetProperty(E,P)     (E)->flags|=(P)
00711 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
00712 
00713 /*
00714 ** A list of expressions.  Each expression may optionally have a
00715 ** name.  An expr/name combination can be used in several ways, such
00716 ** as the list of "expr AS ID" fields following a "SELECT" or in the
00717 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
00718 ** also be used as the argument to a function, in which case the a.zName
00719 ** field is not used.
00720 */
00721 struct ExprList {
00722   int nExpr;             /* Number of expressions on the list */
00723   int nAlloc;            /* Number of entries allocated below */
00724   struct ExprList_item {
00725     Expr *pExpr;           /* The list of expressions */
00726     char *zName;           /* Token associated with this expression */
00727     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
00728     u8 isAgg;              /* True if this is an aggregate like count(*) */
00729     u8 done;               /* A flag to indicate when processing is finished */
00730   } *a;                  /* One entry for each expression */
00731 };
00732 
00733 /*
00734 ** An instance of this structure can hold a simple list of identifiers,
00735 ** such as the list "a,b,c" in the following statements:
00736 **
00737 **      INSERT INTO t(a,b,c) VALUES ...;
00738 **      CREATE INDEX idx ON t(a,b,c);
00739 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
00740 **
00741 ** The IdList.a.idx field is used when the IdList represents the list of
00742 ** column names after a table name in an INSERT statement.  In the statement
00743 **
00744 **     INSERT INTO t(a,b,c) ...
00745 **
00746 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
00747 */
00748 struct IdList {
00749   int nId;         /* Number of identifiers on the list */
00750   int nAlloc;      /* Number of entries allocated for a[] below */
00751   struct IdList_item {
00752     char *zName;      /* Name of the identifier */
00753     int idx;          /* Index in some Table.aCol[] of a column named zName */
00754   } *a;
00755 };
00756 
00757 /*
00758 ** The following structure describes the FROM clause of a SELECT statement.
00759 ** Each table or subquery in the FROM clause is a separate element of
00760 ** the SrcList.a[] array.
00761 **
00762 ** With the addition of multiple database support, the following structure
00763 ** can also be used to describe a particular table such as the table that
00764 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
00765 ** such a table must be a simple name: ID.  But in SQLite, the table can
00766 ** now be identified by a database name, a dot, then the table name: ID.ID.
00767 */
00768 struct SrcList {
00769   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
00770   i16 nAlloc;      /* Number of entries allocated in a[] below */
00771   struct SrcList_item {
00772     char *zDatabase;  /* Name of database holding this table */
00773     char *zName;      /* Name of the table */
00774     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
00775     Table *pTab;      /* An SQL table corresponding to zName */
00776     Select *pSelect;  /* A SELECT statement used in place of a table name */
00777     int jointype;     /* Type of join between this table and the next */
00778     int iCursor;      /* The VDBE cursor number used to access this table */
00779     Expr *pOn;        /* The ON clause of a join */
00780     IdList *pUsing;   /* The USING clause of a join */
00781   } a[1];             /* One entry for each identifier on the list */
00782 };
00783 
00784 /*
00785 ** Permitted values of the SrcList.a.jointype field
00786 */
00787 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
00788 #define JT_NATURAL   0x0002    /* True for a "natural" join */
00789 #define JT_LEFT      0x0004    /* Left outer join */
00790 #define JT_RIGHT     0x0008    /* Right outer join */
00791 #define JT_OUTER     0x0010    /* The "OUTER" keyword is present */
00792 #define JT_ERROR     0x0020    /* unknown or unsupported join type */
00793 
00794 /*
00795 ** For each nested loop in a WHERE clause implementation, the WhereInfo
00796 ** structure contains a single instance of this structure.  This structure
00797 ** is intended to be private the the where.c module and should not be
00798 ** access or modified by other modules.
00799 */
00800 struct WhereLevel {
00801   int iMem;            /* Memory cell used by this level */
00802   Index *pIdx;         /* Index used */
00803   int iCur;            /* Cursor number used for this index */
00804   int score;           /* How well this indexed scored */
00805   int brk;             /* Jump here to break out of the loop */
00806   int cont;            /* Jump here to continue with the next loop cycle */
00807   int op, p1, p2;      /* Opcode used to terminate the loop */
00808   int iLeftJoin;       /* Memory cell used to implement LEFT OUTER JOIN */
00809   int top;             /* First instruction of interior of the loop */
00810   int inOp, inP1, inP2;/* Opcode used to implement an IN operator */
00811   int bRev;            /* Do the scan in the reverse direction */
00812 };
00813 
00814 /*
00815 ** The WHERE clause processing routine has two halves.  The
00816 ** first part does the start of the WHERE loop and the second
00817 ** half does the tail of the WHERE loop.  An instance of
00818 ** this structure is returned by the first half and passed
00819 ** into the second half to give some continuity.
00820 */
00821 struct WhereInfo {
00822   Parse *pParse;
00823   SrcList *pTabList;   /* List of tables in the join */
00824   int iContinue;       /* Jump here to continue with next record */
00825   int iBreak;          /* Jump here to break out of the loop */
00826   int nLevel;          /* Number of nested loop */
00827   int savedNTab;       /* Value of pParse->nTab before WhereBegin() */
00828   int peakNTab;        /* Value of pParse->nTab after WhereBegin() */
00829   WhereLevel a[1];     /* Information about each nest loop in the WHERE */
00830 };
00831 
00832 /*
00833 ** An instance of the following structure contains all information
00834 ** needed to generate code for a single SELECT statement.
00835 **
00836 ** The zSelect field is used when the Select structure must be persistent.
00837 ** Normally, the expression tree points to tokens in the original input
00838 ** string that encodes the select.  But if the Select structure must live
00839 ** longer than its input string (for example when it is used to describe
00840 ** a VIEW) we have to make a copy of the input string so that the nodes
00841 ** of the expression tree will have something to point to.  zSelect is used
00842 ** to hold that copy.
00843 **
00844 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
00845 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
00846 ** limit and nOffset to the value of the offset (or 0 if there is not
00847 ** offset).  But later on, nLimit and nOffset become the memory locations
00848 ** in the VDBE that record the limit and offset counters.
00849 */
00850 struct Select {
00851   ExprList *pEList;      /* The fields of the result */
00852   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
00853   u8 isDistinct;         /* True if the DISTINCT keyword is present */
00854   SrcList *pSrc;         /* The FROM clause */
00855   Expr *pWhere;          /* The WHERE clause */
00856   ExprList *pGroupBy;    /* The GROUP BY clause */
00857   Expr *pHaving;         /* The HAVING clause */
00858   ExprList *pOrderBy;    /* The ORDER BY clause */
00859   Select *pPrior;        /* Prior select in a compound select statement */
00860   int nLimit, nOffset;   /* LIMIT and OFFSET values.  -1 means not used */
00861   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
00862   char *zSelect;         /* Complete text of the SELECT command */
00863 };
00864 
00865 /*
00866 ** The results of a select can be distributed in several ways.
00867 */
00868 #define SRT_Callback     1  /* Invoke a callback with each row of result */
00869 #define SRT_Mem          2  /* Store result in a memory cell */
00870 #define SRT_Set          3  /* Store result as unique keys in a table */
00871 #define SRT_Union        5  /* Store result as keys in a table */
00872 #define SRT_Except       6  /* Remove result from a UNION table */
00873 #define SRT_Table        7  /* Store result as data with a unique key */
00874 #define SRT_TempTable    8  /* Store result in a trasient table */
00875 #define SRT_Discard      9  /* Do not save the results anywhere */
00876 #define SRT_Sorter      10  /* Store results in the sorter */
00877 #define SRT_Subroutine  11  /* Call a subroutine to handle results */
00878 
00879 /*
00880 ** When a SELECT uses aggregate functions (like "count(*)" or "avg(f1)")
00881 ** we have to do some additional analysis of expressions.  An instance
00882 ** of the following structure holds information about a single subexpression
00883 ** somewhere in the SELECT statement.  An array of these structures holds
00884 ** all the information we need to generate code for aggregate
00885 ** expressions.
00886 **
00887 ** Note that when analyzing a SELECT containing aggregates, both
00888 ** non-aggregate field variables and aggregate functions are stored
00889 ** in the AggExpr array of the Parser structure.
00890 **
00891 ** The pExpr field points to an expression that is part of either the
00892 ** field list, the GROUP BY clause, the HAVING clause or the ORDER BY
00893 ** clause.  The expression will be freed when those clauses are cleaned
00894 ** up.  Do not try to delete the expression attached to AggExpr.pExpr.
00895 **
00896 ** If AggExpr.pExpr==0, that means the expression is "count(*)".
00897 */
00898 struct AggExpr {
00899   int isAgg;        /* if TRUE contains an aggregate function */
00900   Expr *pExpr;      /* The expression */
00901   FuncDef *pFunc;   /* Information about the aggregate function */
00902 };
00903 
00904 /*
00905 ** An SQL parser context.  A copy of this structure is passed through
00906 ** the parser and down into all the parser action routine in order to
00907 ** carry around information that is global to the entire parse.
00908 */
00909 struct Parse {
00910   sqlite *db;          /* The main database structure */
00911   int rc;              /* Return code from execution */
00912   char *zErrMsg;       /* An error message */
00913   Token sErrToken;     /* The token at which the error occurred */
00914   Token sFirstToken;   /* The first token parsed */
00915   Token sLastToken;    /* The last token parsed */
00916   const char *zTail;   /* All SQL text past the last semicolon parsed */
00917   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
00918   Vdbe *pVdbe;         /* An engine for executing database bytecode */
00919   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
00920   u8 explain;          /* True if the EXPLAIN flag is found on the query */
00921   u8 nameClash;        /* A permanent table name clashes with temp table name */
00922   u8 useAgg;           /* If true, extract field values from the aggregator
00923                        ** while generating expressions.  Normally false */
00924   int nErr;            /* Number of errors seen */
00925   int nTab;            /* Number of previously allocated VDBE cursors */
00926   int nMem;            /* Number of memory cells used so far */
00927   int nSet;            /* Number of sets used so far */
00928   int nAgg;            /* Number of aggregate expressions */
00929   int nVar;            /* Number of '?' variables seen in the SQL so far */
00930   AggExpr *aAgg;       /* An array of aggregate expressions */
00931   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
00932   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
00933   TriggerStack *trigStack;  /* Trigger actions being coded */
00934 };
00935 
00936 /*
00937 ** An instance of the following structure can be declared on a stack and used
00938 ** to save the Parse.zAuthContext value so that it can be restored later.
00939 */
00940 struct AuthContext {
00941   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
00942   Parse *pParse;              /* The Parse structure */
00943 };
00944 
00945 /*
00946 ** Bitfield flags for P2 value in OP_PutIntKey and OP_Delete
00947 */
00948 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
00949 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
00950 #define OPFLAG_CSCHANGE  4    /* Set to update db->csChange */
00951 
00952 /*
00953  * Each trigger present in the database schema is stored as an instance of
00954  * struct Trigger. 
00955  *
00956  * Pointers to instances of struct Trigger are stored in two ways.
00957  * 1. In the "trigHash" hash table (part of the sqlite* that represents the 
00958  *    database). This allows Trigger structures to be retrieved by name.
00959  * 2. All triggers associated with a single table form a linked list, using the
00960  *    pNext member of struct Trigger. A pointer to the first element of the
00961  *    linked list is stored as the "pTrigger" member of the associated
00962  *    struct Table.
00963  *
00964  * The "step_list" member points to the first element of a linked list
00965  * containing the SQL statements specified as the trigger program.
00966  */
00967 struct Trigger {
00968   char *name;             /* The name of the trigger                        */
00969   char *table;            /* The table or view to which the trigger applies */
00970   u8 iDb;                 /* Database containing this trigger               */
00971   u8 iTabDb;              /* Database containing Trigger.table              */
00972   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
00973   u8 tr_tm;               /* One of TK_BEFORE, TK_AFTER */
00974   Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
00975   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
00976                              the <column-list> is stored here */
00977   int foreach;            /* One of TK_ROW or TK_STATEMENT */
00978   Token nameToken;        /* Token containing zName. Use during parsing only */
00979 
00980   TriggerStep *step_list; /* Link list of trigger program steps             */
00981   Trigger *pNext;         /* Next trigger associated with the table */
00982 };
00983 
00984 /*
00985  * An instance of struct TriggerStep is used to store a single SQL statement
00986  * that is a part of a trigger-program. 
00987  *
00988  * Instances of struct TriggerStep are stored in a singly linked list (linked
00989  * using the "pNext" member) referenced by the "step_list" member of the 
00990  * associated struct Trigger instance. The first element of the linked list is
00991  * the first step of the trigger-program.
00992  * 
00993  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
00994  * "SELECT" statement. The meanings of the other members is determined by the 
00995  * value of "op" as follows:
00996  *
00997  * (op == TK_INSERT)
00998  * orconf    -> stores the ON CONFLICT algorithm
00999  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
01000  *              this stores a pointer to the SELECT statement. Otherwise NULL.
01001  * target    -> A token holding the name of the table to insert into.
01002  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
01003  *              this stores values to be inserted. Otherwise NULL.
01004  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
01005  *              statement, then this stores the column-names to be
01006  *              inserted into.
01007  *
01008  * (op == TK_DELETE)
01009  * target    -> A token holding the name of the table to delete from.
01010  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
01011  *              Otherwise NULL.
01012  * 
01013  * (op == TK_UPDATE)
01014  * target    -> A token holding the name of the table to update rows of.
01015  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
01016  *              Otherwise NULL.
01017  * pExprList -> A list of the columns to update and the expressions to update
01018  *              them to. See sqliteUpdate() documentation of "pChanges"
01019  *              argument.
01020  * 
01021  */
01022 struct TriggerStep {
01023   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
01024   int orconf;          /* OE_Rollback etc. */
01025   Trigger *pTrig;      /* The trigger that this step is a part of */
01026 
01027   Select *pSelect;     /* Valid for SELECT and sometimes 
01028                        INSERT steps (when pExprList == 0) */
01029   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
01030   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
01031   ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
01032                         INSERT steps (when pSelect == 0)         */
01033   IdList *pIdList;     /* Valid for INSERT statements only */
01034 
01035   TriggerStep * pNext; /* Next in the link-list */
01036 };
01037 
01038 /*
01039  * An instance of struct TriggerStack stores information required during code
01040  * generation of a single trigger program. While the trigger program is being
01041  * coded, its associated TriggerStack instance is pointed to by the
01042  * "pTriggerStack" member of the Parse structure.
01043  *
01044  * The pTab member points to the table that triggers are being coded on. The 
01045  * newIdx member contains the index of the vdbe cursor that points at the temp
01046  * table that stores the new.* references. If new.* references are not valid
01047  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
01048  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
01049  *
01050  * The ON CONFLICT policy to be used for the trigger program steps is stored 
01051  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
01052  * specified for individual triggers steps is used.
01053  *
01054  * struct TriggerStack has a "pNext" member, to allow linked lists to be
01055  * constructed. When coding nested triggers (triggers fired by other triggers)
01056  * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
01057  * pointer. Once the nested trigger has been coded, the pNext value is restored
01058  * to the pTriggerStack member of the Parse stucture and coding of the parent
01059  * trigger continues.
01060  *
01061  * Before a nested trigger is coded, the linked list pointed to by the 
01062  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
01063  * recursively. If this condition is detected, the nested trigger is not coded.
01064  */
01065 struct TriggerStack {
01066   Table *pTab;         /* Table that triggers are currently being coded on */
01067   int newIdx;          /* Index of vdbe cursor to "new" temp table */
01068   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
01069   int orconf;          /* Current orconf policy */
01070   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
01071   Trigger *pTrigger;   /* The trigger currently being coded */
01072   TriggerStack *pNext; /* Next trigger down on the trigger stack */
01073 };
01074 
01075 /*
01076 ** The following structure contains information used by the sqliteFix...
01077 ** routines as they walk the parse tree to make database references
01078 ** explicit.  
01079 */
01080 typedef struct DbFixer DbFixer;
01081 struct DbFixer {
01082   Parse *pParse;      /* The parsing context.  Error messages written here */
01083   const char *zDb;    /* Make sure all objects are contained in this database */
01084   const char *zType;  /* Type of the container - used for error messages */
01085   const Token *pName; /* Name of the container - used for error messages */
01086 };
01087 
01088 /*
01089  * This global flag is set for performance testing of triggers. When it is set
01090  * SQLite will perform the overhead of building new and old trigger references 
01091  * even when no triggers exist
01092  */
01093 extern int always_code_trigger_setup;
01094 
01095 /*
01096 ** Internal function prototypes
01097 */
01098 int sqliteStrICmp(const char *, const char *);
01099 int sqliteStrNICmp(const char *, const char *, int);
01100 int sqliteHashNoCase(const char *, int);
01101 int sqliteIsNumber(const char*);
01102 int sqliteCompare(const char *, const char *);
01103 int sqliteSortCompare(const char *, const char *);
01104 void sqliteRealToSortable(double r, char *);
01105 #ifdef MEMORY_DEBUG
01106   void *sqliteMalloc_(int,int,char*,int);
01107   void sqliteFree_(void*,char*,int);
01108   void *sqliteRealloc_(void*,int,char*,int);
01109   char *sqliteStrDup_(const char*,char*,int);
01110   char *sqliteStrNDup_(const char*, int,char*,int);
01111   void sqliteCheckMemory(void*,int);
01112 #else
01113   void *sqliteMalloc(int);
01114   void *sqliteMallocRaw(int);
01115   void sqliteFree(void*);
01116   void *sqliteRealloc(void*,int);
01117   char *sqliteStrDup(const char*);
01118   char *sqliteStrNDup(const char*, int);
01119 # define sqliteCheckMemory(a,b)
01120 #endif
01121 char *sqliteMPrintf(const char*, ...);
01122 char *sqliteVMPrintf(const char*, va_list);
01123 void sqliteSetString(char **, ...);
01124 void sqliteSetNString(char **, ...);
01125 void sqliteErrorMsg(Parse*, const char*, ...);
01126 void sqliteDequote(char*);
01127 int sqliteKeywordCode(const char*, int);
01128 int sqliteRunParser(Parse*, const char*, char **);
01129 void sqliteExec(Parse*);
01130 Expr *sqliteExpr(int, Expr*, Expr*, Token*);
01131 void sqliteExprSpan(Expr*,Token*,Token*);
01132 Expr *sqliteExprFunction(ExprList*, Token*);
01133 void sqliteExprDelete(Expr*);
01134 ExprList *sqliteExprListAppend(ExprList*,Expr*,Token*);
01135 void sqliteExprListDelete(ExprList*);
01136 int sqliteInit(sqlite*, char**);
01137 void sqlitePragma(Parse*,Token*,Token*,int);
01138 void sqliteResetInternalSchema(sqlite*, int);
01139 void sqliteBeginParse(Parse*,int);
01140 void sqliteRollbackInternalChanges(sqlite*);
01141 void sqliteCommitInternalChanges(sqlite*);
01142 Table *sqliteResultSetOfSelect(Parse*,char*,Select*);
01143 void sqliteOpenMasterTable(Vdbe *v, int);
01144 void sqliteStartTable(Parse*,Token*,Token*,int,int);
01145 void sqliteAddColumn(Parse*,Token*);
01146 void sqliteAddNotNull(Parse*, int);
01147 void sqliteAddPrimaryKey(Parse*, IdList*, int);
01148 void sqliteAddColumnType(Parse*,Token*,Token*);
01149 void sqliteAddDefaultValue(Parse*,Token*,int);
01150 int sqliteCollateType(const char*, int);
01151 void sqliteAddCollateType(Parse*, int);
01152 void sqliteEndTable(Parse*,Token*,Select*);
01153 void sqliteCreateView(Parse*,Token*,Token*,Select*,int);
01154 int sqliteViewGetColumnNames(Parse*,Table*);
01155 void sqliteDropTable(Parse*, Token*, int);
01156 void sqliteDeleteTable(sqlite*, Table*);
01157 void sqliteInsert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
01158 IdList *sqliteIdListAppend(IdList*, Token*);
01159 int sqliteIdListIndex(IdList*,const char*);
01160 SrcList *sqliteSrcListAppend(SrcList*, Token*, Token*);
01161 void sqliteSrcListAddAlias(SrcList*, Token*);
01162 void sqliteSrcListAssignCursors(Parse*, SrcList*);
01163 void sqliteIdListDelete(IdList*);
01164 void sqliteSrcListDelete(SrcList*);
01165 void sqliteCreateIndex(Parse*,Token*,SrcList*,IdList*,int,Token*,Token*);
01166 void sqliteDropIndex(Parse*, SrcList*);
01167 void sqliteAddKeyType(Vdbe*, ExprList*);
01168 void sqliteAddIdxKeyType(Vdbe*, Index*);
01169 int sqliteSelect(Parse*, Select*, int, int, Select*, int, int*);
01170 Select *sqliteSelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
01171                         int,int,int);
01172 void sqliteSelectDelete(Select*);
01173 void sqliteSelectUnbind(Select*);
01174 Table *sqliteSrcListLookup(Parse*, SrcList*);
01175 int sqliteIsReadOnly(Parse*, Table*, int);
01176 void sqliteDeleteFrom(Parse*, SrcList*, Expr*);
01177 void sqliteUpdate(Parse*, SrcList*, ExprList*, Expr*, int);
01178 WhereInfo *sqliteWhereBegin(Parse*, SrcList*, Expr*, int, ExprList**);
01179 void sqliteWhereEnd(WhereInfo*);
01180 void sqliteExprCode(Parse*, Expr*);
01181 int sqliteExprCodeExprList(Parse*, ExprList*, int);
01182 void sqliteExprIfTrue(Parse*, Expr*, int, int);
01183 void sqliteExprIfFalse(Parse*, Expr*, int, int);
01184 Table *sqliteFindTable(sqlite*,const char*, const char*);
01185 Table *sqliteLocateTable(Parse*,const char*, const char*);
01186 Index *sqliteFindIndex(sqlite*,const char*, const char*);
01187 void sqliteUnlinkAndDeleteIndex(sqlite*,Index*);
01188 void sqliteCopy(Parse*, SrcList*, Token*, Token*, int);
01189 void sqliteVacuum(Parse*, Token*);
01190 int sqliteRunVacuum(char**, sqlite*);
01191 int sqliteGlobCompare(const unsigned char*,const unsigned char*);
01192 int sqliteLikeCompare(const unsigned char*,const unsigned char*);
01193 char *sqliteTableNameFromToken(Token*);
01194 int sqliteExprCheck(Parse*, Expr*, int, int*);
01195 int sqliteExprType(Expr*);
01196 int sqliteExprCompare(Expr*, Expr*);
01197 int sqliteFuncId(Token*);
01198 int sqliteExprResolveIds(Parse*, SrcList*, ExprList*, Expr*);
01199 int sqliteExprAnalyzeAggregates(Parse*, Expr*);
01200 Vdbe *sqliteGetVdbe(Parse*);
01201 void sqliteRandomness(int, void*);
01202 void sqliteRollbackAll(sqlite*);
01203 void sqliteCodeVerifySchema(Parse*, int);
01204 void sqliteBeginTransaction(Parse*, int);
01205 void sqliteCommitTransaction(Parse*);
01206 void sqliteRollbackTransaction(Parse*);
01207 int sqliteExprIsConstant(Expr*);
01208 int sqliteExprIsInteger(Expr*, int*);
01209 int sqliteIsRowid(const char*);
01210 void sqliteGenerateRowDelete(sqlite*, Vdbe*, Table*, int, int);
01211 void sqliteGenerateRowIndexDelete(sqlite*, Vdbe*, Table*, int, char*);
01212 void sqliteGenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
01213 void sqliteCompleteInsertion(Parse*, Table*, int, char*, int, int, int);
01214 int sqliteOpenTableAndIndices(Parse*, Table*, int);
01215 void sqliteBeginWriteOperation(Parse*, int, int);
01216 void sqliteEndWriteOperation(Parse*);
01217 Expr *sqliteExprDup(Expr*);
01218 void sqliteTokenCopy(Token*, Token*);
01219 ExprList *sqliteExprListDup(ExprList*);
01220 SrcList *sqliteSrcListDup(SrcList*);
01221 IdList *sqliteIdListDup(IdList*);
01222 Select *sqliteSelectDup(Select*);
01223 FuncDef *sqliteFindFunction(sqlite*,const char*,int,int,int);
01224 void sqliteRegisterBuiltinFunctions(sqlite*);
01225 void sqliteRegisterDateTimeFunctions(sqlite*);
01226 int sqliteSafetyOn(sqlite*);
01227 int sqliteSafetyOff(sqlite*);
01228 int sqliteSafetyCheck(sqlite*);
01229 void sqliteChangeCookie(sqlite*, Vdbe*);
01230 void sqliteBeginTrigger(Parse*, Token*,int,int,IdList*,SrcList*,int,Expr*,int);
01231 void sqliteFinishTrigger(Parse*, TriggerStep*, Token*);
01232 void sqliteDropTrigger(Parse*, SrcList*);
01233 void sqliteDropTriggerPtr(Parse*, Trigger*, int);
01234 int sqliteTriggersExist(Parse* , Trigger* , int , int , int, ExprList*);
01235 int sqliteCodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
01236                          int, int);
01237 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
01238 void sqliteDeleteTriggerStep(TriggerStep*);
01239 TriggerStep *sqliteTriggerSelectStep(Select*);
01240 TriggerStep *sqliteTriggerInsertStep(Token*, IdList*, ExprList*, Select*, int);
01241 TriggerStep *sqliteTriggerUpdateStep(Token*, ExprList*, Expr*, int);
01242 TriggerStep *sqliteTriggerDeleteStep(Token*, Expr*);
01243 void sqliteDeleteTrigger(Trigger*);
01244 int sqliteJoinType(Parse*, Token*, Token*, Token*);
01245 void sqliteCreateForeignKey(Parse*, IdList*, Token*, IdList*, int);
01246 void sqliteDeferForeignKey(Parse*, int);
01247 #ifndef SQLITE_OMIT_AUTHORIZATION
01248   void sqliteAuthRead(Parse*,Expr*,SrcList*);
01249   int sqliteAuthCheck(Parse*,int, const char*, const char*, const char*);
01250   void sqliteAuthContextPush(Parse*, AuthContext*, const char*);
01251   void sqliteAuthContextPop(AuthContext*);
01252 #else
01253 # define sqliteAuthRead(a,b,c)
01254 # define sqliteAuthCheck(a,b,c,d,e)    SQLITE_OK
01255 # define sqliteAuthContextPush(a,b,c)
01256 # define sqliteAuthContextPop(a)  ((void)(a))
01257 #endif
01258 void sqliteAttach(Parse*, Token*, Token*, Token*);
01259 void sqliteDetach(Parse*, Token*);
01260 int sqliteBtreeFactory(const sqlite *db, const char *zFilename,
01261                        int mode, int nPg, Btree **ppBtree);
01262 int sqliteFixInit(DbFixer*, Parse*, int, const char*, const Token*);
01263 int sqliteFixSrcList(DbFixer*, SrcList*);
01264 int sqliteFixSelect(DbFixer*, Select*);
01265 int sqliteFixExpr(DbFixer*, Expr*);
01266 int sqliteFixExprList(DbFixer*, ExprList*);
01267 int sqliteFixTriggerStep(DbFixer*, TriggerStep*);
01268 double sqliteAtoF(const char *z, const char **);
01269 char *sqlite_snprintf(int,char*,const char*,...);
01270 int sqliteFitsIn32Bits(const char *);