xref: /illumos-gate/usr/src/lib/libsqlite/src/sqliteInt.h (revision 4e9cfc9a015e8ca7d41f7d018c74dc8a692305b3)
1 
2 #pragma ident	"%Z%%M%	%I%	%E% SMI"
3 
4 /*
5 ** 2001 September 15
6 **
7 ** The author disclaims copyright to this source code.  In place of
8 ** a legal notice, here is a blessing:
9 **
10 **    May you do good and not evil.
11 **    May you find forgiveness for yourself and forgive others.
12 **    May you share freely, never taking more than you give.
13 **
14 *************************************************************************
15 ** Internal interface definitions for SQLite.
16 **
17 ** @(#) $Id: sqliteInt.h,v 1.220.2.1 2004/07/15 13:37:05 drh Exp $
18 */
19 #include "config.h"
20 #include "sqlite.h"
21 #include "hash.h"
22 #include "parse.h"
23 #include "btree.h"
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <assert.h>
28 
29 /*
30 ** The maximum number of in-memory pages to use for the main database
31 ** table and for temporary tables.
32 */
33 #define MAX_PAGES   2000
34 #define TEMP_PAGES   500
35 
36 /*
37 ** If the following macro is set to 1, then NULL values are considered
38 ** distinct for the SELECT DISTINCT statement and for UNION or EXCEPT
39 ** compound queries.  No other SQL database engine (among those tested)
40 ** works this way except for OCELOT.  But the SQL92 spec implies that
41 ** this is how things should work.
42 **
43 ** If the following macro is set to 0, then NULLs are indistinct for
44 ** SELECT DISTINCT and for UNION.
45 */
46 #define NULL_ALWAYS_DISTINCT 0
47 
48 /*
49 ** If the following macro is set to 1, then NULL values are considered
50 ** distinct when determining whether or not two entries are the same
51 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
52 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
53 ** is the way things are suppose to work.
54 **
55 ** If the following macro is set to 0, the NULLs are indistinct for
56 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
57 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
58 ** work.
59 */
60 #define NULL_DISTINCT_FOR_UNIQUE 1
61 
62 /*
63 ** The maximum number of attached databases.  This must be at least 2
64 ** in order to support the main database file (0) and the file used to
65 ** hold temporary tables (1).  And it must be less than 256 because
66 ** an unsigned character is used to stored the database index.
67 */
68 #define MAX_ATTACHED 10
69 
70 /*
71 ** The next macro is used to determine where TEMP tables and indices
72 ** are stored.  Possible values:
73 **
74 **   0    Always use a temporary files
75 **   1    Use a file unless overridden by "PRAGMA temp_store"
76 **   2    Use memory unless overridden by "PRAGMA temp_store"
77 **   3    Always use memory
78 */
79 #ifndef TEMP_STORE
80 # define TEMP_STORE 1
81 #endif
82 
83 /*
84 ** When building SQLite for embedded systems where memory is scarce,
85 ** you can define one or more of the following macros to omit extra
86 ** features of the library and thus keep the size of the library to
87 ** a minimum.
88 */
89 /* #define SQLITE_OMIT_AUTHORIZATION  1 */
90 /* #define SQLITE_OMIT_INMEMORYDB     1 */
91 /* #define SQLITE_OMIT_VACUUM         1 */
92 /* #define SQLITE_OMIT_DATETIME_FUNCS 1 */
93 /* #define SQLITE_OMIT_PROGRESS_CALLBACK 1 */
94 
95 /*
96 ** Integers of known sizes.  These typedefs might change for architectures
97 ** where the sizes very.  Preprocessor macros are available so that the
98 ** types can be conveniently redefined at compile-type.  Like this:
99 **
100 **         cc '-DUINTPTR_TYPE=long long int' ...
101 */
102 #ifndef UINT32_TYPE
103 # define UINT32_TYPE unsigned int
104 #endif
105 #ifndef UINT16_TYPE
106 # define UINT16_TYPE unsigned short int
107 #endif
108 #ifndef INT16_TYPE
109 # define INT16_TYPE short int
110 #endif
111 #ifndef UINT8_TYPE
112 # define UINT8_TYPE unsigned char
113 #endif
114 #ifndef INT8_TYPE
115 # define INT8_TYPE signed char
116 #endif
117 #ifndef INTPTR_TYPE
118 # if SQLITE_PTR_SZ==4
119 #   define INTPTR_TYPE int
120 # else
121 #   define INTPTR_TYPE long long
122 # endif
123 #endif
124 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
125 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
126 typedef INT16_TYPE i16;            /* 2-byte signed integer */
127 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
128 typedef UINT8_TYPE i8;             /* 1-byte signed integer */
129 typedef INTPTR_TYPE ptr;           /* Big enough to hold a pointer */
130 typedef unsigned INTPTR_TYPE uptr; /* Big enough to hold a pointer */
131 
132 /*
133 ** Defer sourcing vdbe.h until after the "u8" typedef is defined.
134 */
135 #include "vdbe.h"
136 
137 /*
138 ** Most C compilers these days recognize "long double", don't they?
139 ** Just in case we encounter one that does not, we will create a macro
140 ** for long double so that it can be easily changed to just "double".
141 */
142 #ifndef LONGDOUBLE_TYPE
143 # define LONGDOUBLE_TYPE long double
144 #endif
145 
146 /*
147 ** This macro casts a pointer to an integer.  Useful for doing
148 ** pointer arithmetic.
149 */
150 #define Addr(X)  ((uptr)X)
151 
152 /*
153 ** The maximum number of bytes of data that can be put into a single
154 ** row of a single table.  The upper bound on this limit is 16777215
155 ** bytes (or 16MB-1).  We have arbitrarily set the limit to just 1MB
156 ** here because the overflow page chain is inefficient for really big
157 ** records and we want to discourage people from thinking that
158 ** multi-megabyte records are OK.  If your needs are different, you can
159 ** change this define and recompile to increase or decrease the record
160 ** size.
161 **
162 ** The 16777198 is computed as follows:  238 bytes of payload on the
163 ** original pages plus 16448 overflow pages each holding 1020 bytes of
164 ** data.
165 */
166 #define MAX_BYTES_PER_ROW  1048576
167 /* #define MAX_BYTES_PER_ROW 16777198 */
168 
169 /*
170 ** If memory allocation problems are found, recompile with
171 **
172 **      -DMEMORY_DEBUG=1
173 **
174 ** to enable some sanity checking on malloc() and free().  To
175 ** check for memory leaks, recompile with
176 **
177 **      -DMEMORY_DEBUG=2
178 **
179 ** and a line of text will be written to standard error for
180 ** each malloc() and free().  This output can be analyzed
181 ** by an AWK script to determine if there are any leaks.
182 */
183 #ifdef MEMORY_DEBUG
184 # define sqliteMalloc(X)    sqliteMalloc_(X,1,__FILE__,__LINE__)
185 # define sqliteMallocRaw(X) sqliteMalloc_(X,0,__FILE__,__LINE__)
186 # define sqliteFree(X)      sqliteFree_(X,__FILE__,__LINE__)
187 # define sqliteRealloc(X,Y) sqliteRealloc_(X,Y,__FILE__,__LINE__)
188 # define sqliteStrDup(X)    sqliteStrDup_(X,__FILE__,__LINE__)
189 # define sqliteStrNDup(X,Y) sqliteStrNDup_(X,Y,__FILE__,__LINE__)
190   void sqliteStrRealloc(char**);
191 #else
192 # define sqliteRealloc_(X,Y) sqliteRealloc(X,Y)
193 # define sqliteStrRealloc(X)
194 #endif
195 
196 /*
197 ** This variable gets set if malloc() ever fails.  After it gets set,
198 ** the SQLite library shuts down permanently.
199 */
200 extern int sqlite_malloc_failed;
201 
202 /*
203 ** The following global variables are used for testing and debugging
204 ** only.  They only work if MEMORY_DEBUG is defined.
205 */
206 #ifdef MEMORY_DEBUG
207 extern int sqlite_nMalloc;       /* Number of sqliteMalloc() calls */
208 extern int sqlite_nFree;         /* Number of sqliteFree() calls */
209 extern int sqlite_iMallocFail;   /* Fail sqliteMalloc() after this many calls */
210 #endif
211 
212 /*
213 ** Name of the master database table.  The master database table
214 ** is a special table that holds the names and attributes of all
215 ** user tables and indices.
216 */
217 #define MASTER_NAME       "sqlite_master"
218 #define TEMP_MASTER_NAME  "sqlite_temp_master"
219 
220 /*
221 ** The name of the schema table.
222 */
223 #define SCHEMA_TABLE(x)  (x?TEMP_MASTER_NAME:MASTER_NAME)
224 
225 /*
226 ** A convenience macro that returns the number of elements in
227 ** an array.
228 */
229 #define ArraySize(X)    (sizeof(X)/sizeof(X[0]))
230 
231 /*
232 ** Forward references to structures
233 */
234 typedef struct Column Column;
235 typedef struct Table Table;
236 typedef struct Index Index;
237 typedef struct Instruction Instruction;
238 typedef struct Expr Expr;
239 typedef struct ExprList ExprList;
240 typedef struct Parse Parse;
241 typedef struct Token Token;
242 typedef struct IdList IdList;
243 typedef struct SrcList SrcList;
244 typedef struct WhereInfo WhereInfo;
245 typedef struct WhereLevel WhereLevel;
246 typedef struct Select Select;
247 typedef struct AggExpr AggExpr;
248 typedef struct FuncDef FuncDef;
249 typedef struct Trigger Trigger;
250 typedef struct TriggerStep TriggerStep;
251 typedef struct TriggerStack TriggerStack;
252 typedef struct FKey FKey;
253 typedef struct Db Db;
254 typedef struct AuthContext AuthContext;
255 
256 /*
257 ** Each database file to be accessed by the system is an instance
258 ** of the following structure.  There are normally two of these structures
259 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
260 ** aDb[1] is the database file used to hold temporary tables.  Additional
261 ** databases may be attached.
262 */
263 struct Db {
264   char *zName;         /* Name of this database */
265   Btree *pBt;          /* The B*Tree structure for this database file */
266   int schema_cookie;   /* Database schema version number for this file */
267   Hash tblHash;        /* All tables indexed by name */
268   Hash idxHash;        /* All (named) indices indexed by name */
269   Hash trigHash;       /* All triggers indexed by name */
270   Hash aFKey;          /* Foreign keys indexed by to-table */
271   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
272   u16 flags;           /* Flags associated with this database */
273   void *pAux;          /* Auxiliary data.  Usually NULL */
274   void (*xFreeAux)(void*);  /* Routine to free pAux */
275 };
276 
277 /*
278 ** These macros can be used to test, set, or clear bits in the
279 ** Db.flags field.
280 */
281 #define DbHasProperty(D,I,P)     (((D)->aDb[I].flags&(P))==(P))
282 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].flags&(P))!=0)
283 #define DbSetProperty(D,I,P)     (D)->aDb[I].flags|=(P)
284 #define DbClearProperty(D,I,P)   (D)->aDb[I].flags&=~(P)
285 
286 /*
287 ** Allowed values for the DB.flags field.
288 **
289 ** The DB_Locked flag is set when the first OP_Transaction or OP_Checkpoint
290 ** opcode is emitted for a database.  This prevents multiple occurances
291 ** of those opcodes for the same database in the same program.  Similarly,
292 ** the DB_Cookie flag is set when the OP_VerifyCookie opcode is emitted,
293 ** and prevents duplicate OP_VerifyCookies from taking up space and slowing
294 ** down execution.
295 **
296 ** The DB_SchemaLoaded flag is set after the database schema has been
297 ** read into internal hash tables.
298 **
299 ** DB_UnresetViews means that one or more views have column names that
300 ** have been filled out.  If the schema changes, these column names might
301 ** changes and so the view will need to be reset.
302 */
303 #define DB_Locked          0x0001  /* OP_Transaction opcode has been emitted */
304 #define DB_Cookie          0x0002  /* OP_VerifyCookie opcode has been emiited */
305 #define DB_SchemaLoaded    0x0004  /* The schema has been loaded */
306 #define DB_UnresetViews    0x0008  /* Some views have defined column names */
307 
308 
309 /*
310 ** Each database is an instance of the following structure.
311 **
312 ** The sqlite.file_format is initialized by the database file
313 ** and helps determines how the data in the database file is
314 ** represented.  This field allows newer versions of the library
315 ** to read and write older databases.  The various file formats
316 ** are as follows:
317 **
318 **     file_format==1    Version 2.1.0.
319 **     file_format==2    Version 2.2.0. Add support for INTEGER PRIMARY KEY.
320 **     file_format==3    Version 2.6.0. Fix empty-string index bug.
321 **     file_format==4    Version 2.7.0. Add support for separate numeric and
322 **                       text datatypes.
323 **
324 ** The sqlite.temp_store determines where temporary database files
325 ** are stored.  If 1, then a file is created to hold those tables.  If
326 ** 2, then they are held in memory.  0 means use the default value in
327 ** the TEMP_STORE macro.
328 **
329 ** The sqlite.lastRowid records the last insert rowid generated by an
330 ** insert statement.  Inserts on views do not affect its value.  Each
331 ** trigger has its own context, so that lastRowid can be updated inside
332 ** triggers as usual.  The previous value will be restored once the trigger
333 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
334 ** longer (since after version 2.8.12) reset to -1.
335 **
336 ** The sqlite.nChange does not count changes within triggers and keeps no
337 ** context.  It is reset at start of sqlite_exec.
338 ** The sqlite.lsChange represents the number of changes made by the last
339 ** insert, update, or delete statement.  It remains constant throughout the
340 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
341 ** context stack just like lastRowid so that the count of changes
342 ** within a trigger is not seen outside the trigger.  Changes to views do not
343 ** affect the value of lsChange.
344 ** The sqlite.csChange keeps track of the number of current changes (since
345 ** the last statement) and is used to update sqlite_lsChange.
346 */
347 struct sqlite {
348   int nDb;                      /* Number of backends currently in use */
349   Db *aDb;                      /* All backends */
350   Db aDbStatic[2];              /* Static space for the 2 default backends */
351   int flags;                    /* Miscellanous flags. See below */
352   u8 file_format;               /* What file format version is this database? */
353   u8 safety_level;              /* How aggressive at synching data to disk */
354   u8 want_to_close;             /* Close after all VDBEs are deallocated */
355   u8 temp_store;                /* 1=file, 2=memory, 0=compile-time default */
356   u8 onError;                   /* Default conflict algorithm */
357   int next_cookie;              /* Next value of aDb[0].schema_cookie */
358   int cache_size;               /* Number of pages to use in the cache */
359   int nTable;                   /* Number of tables in the database */
360   void *pBusyArg;               /* 1st Argument to the busy callback */
361   int (*xBusyCallback)(void *,const char*,int);  /* The busy callback */
362   void *pCommitArg;             /* Argument to xCommitCallback() */
363   int (*xCommitCallback)(void*);/* Invoked at every commit. */
364   Hash aFunc;                   /* All functions that can be in SQL exprs */
365   int lastRowid;                /* ROWID of most recent insert (see above) */
366   int priorNewRowid;            /* Last randomly generated ROWID */
367   int magic;                    /* Magic number for detect library misuse */
368   int nChange;                  /* Number of rows changed (see above) */
369   int lsChange;                 /* Last statement change count (see above) */
370   int csChange;                 /* Current statement change count (see above) */
371   struct sqliteInitInfo {       /* Information used during initialization */
372     int iDb;                       /* When back is being initialized */
373     int newTnum;                   /* Rootpage of table being initialized */
374     u8 busy;                       /* TRUE if currently initializing */
375   } init;
376   struct Vdbe *pVdbe;           /* List of active virtual machines */
377   void (*xTrace)(void*,const char*);     /* Trace function */
378   void *pTraceArg;                       /* Argument to the trace function */
379 #ifndef SQLITE_OMIT_AUTHORIZATION
380   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
381                                 /* Access authorization function */
382   void *pAuthArg;               /* 1st argument to the access auth function */
383 #endif
384 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
385   int (*xProgress)(void *);     /* The progress callback */
386   void *pProgressArg;           /* Argument to the progress callback */
387   int nProgressOps;             /* Number of opcodes for progress callback */
388 #endif
389 };
390 
391 /*
392 ** Possible values for the sqlite.flags and or Db.flags fields.
393 **
394 ** On sqlite.flags, the SQLITE_InTrans value means that we have
395 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
396 ** transaction is active on that particular database file.
397 */
398 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
399 #define SQLITE_Initialized    0x00000002  /* True after initialization */
400 #define SQLITE_Interrupt      0x00000004  /* Cancel current operation */
401 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
402 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
403 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
404 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
405 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
406                                           /*   DELETE, or UPDATE and return */
407                                           /*   the count using a callback. */
408 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
409                                           /*   result set is empty */
410 #define SQLITE_ReportTypes    0x00000200  /* Include information on datatypes */
411                                           /*   in 4th argument of callback */
412 
413 /*
414 ** Possible values for the sqlite.magic field.
415 ** The numbers are obtained at random and have no special meaning, other
416 ** than being distinct from one another.
417 */
418 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
419 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
420 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
421 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
422 
423 /*
424 ** Each SQL function is defined by an instance of the following
425 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
426 ** hash table.  When multiple functions have the same name, the hash table
427 ** points to a linked list of these structures.
428 */
429 struct FuncDef {
430   void (*xFunc)(sqlite_func*,int,const char**);  /* Regular function */
431   void (*xStep)(sqlite_func*,int,const char**);  /* Aggregate function step */
432   void (*xFinalize)(sqlite_func*);           /* Aggregate function finializer */
433   signed char nArg;         /* Number of arguments.  -1 means unlimited */
434   signed char dataType;     /* Arg that determines datatype.  -1=NUMERIC, */
435                             /* -2=TEXT. -3=SQLITE_ARGS */
436   u8 includeTypes;          /* Add datatypes to args of xFunc and xStep */
437   void *pUserData;          /* User data parameter */
438   FuncDef *pNext;           /* Next function with same name */
439 };
440 
441 /*
442 ** information about each column of an SQL table is held in an instance
443 ** of this structure.
444 */
445 struct Column {
446   char *zName;     /* Name of this column */
447   char *zDflt;     /* Default value of this column */
448   char *zType;     /* Data type for this column */
449   u8 notNull;      /* True if there is a NOT NULL constraint */
450   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
451   u8 sortOrder;    /* Some combination of SQLITE_SO_... values */
452   u8 dottedName;   /* True if zName contains a "." character */
453 };
454 
455 /*
456 ** The allowed sort orders.
457 **
458 ** The TEXT and NUM values use bits that do not overlap with DESC and ASC.
459 ** That way the two can be combined into a single number.
460 */
461 #define SQLITE_SO_UNK       0  /* Use the default collating type.  (SCT_NUM) */
462 #define SQLITE_SO_TEXT      2  /* Sort using memcmp() */
463 #define SQLITE_SO_NUM       4  /* Sort using sqliteCompare() */
464 #define SQLITE_SO_TYPEMASK  6  /* Mask to extract the collating sequence */
465 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
466 #define SQLITE_SO_DESC      1  /* Sort in descending order */
467 #define SQLITE_SO_DIRMASK   1  /* Mask to extract the sort direction */
468 
469 /*
470 ** Each SQL table is represented in memory by an instance of the
471 ** following structure.
472 **
473 ** Table.zName is the name of the table.  The case of the original
474 ** CREATE TABLE statement is stored, but case is not significant for
475 ** comparisons.
476 **
477 ** Table.nCol is the number of columns in this table.  Table.aCol is a
478 ** pointer to an array of Column structures, one for each column.
479 **
480 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
481 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
482 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
483 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
484 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
485 ** is generated for each row of the table.  Table.hasPrimKey is true if
486 ** the table has any PRIMARY KEY, INTEGER or otherwise.
487 **
488 ** Table.tnum is the page number for the root BTree page of the table in the
489 ** database file.  If Table.iDb is the index of the database table backend
490 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
491 ** holds temporary tables and indices.  If Table.isTransient
492 ** is true, then the table is stored in a file that is automatically deleted
493 ** when the VDBE cursor to the table is closed.  In this case Table.tnum
494 ** refers VDBE cursor number that holds the table open, not to the root
495 ** page number.  Transient tables are used to hold the results of a
496 ** sub-query that appears instead of a real table name in the FROM clause
497 ** of a SELECT statement.
498 */
499 struct Table {
500   char *zName;     /* Name of the table */
501   int nCol;        /* Number of columns in this table */
502   Column *aCol;    /* Information about each column */
503   int iPKey;       /* If not less then 0, use aCol[iPKey] as the primary key */
504   Index *pIndex;   /* List of SQL indexes on this table. */
505   int tnum;        /* Root BTree node for this table (see note above) */
506   Select *pSelect; /* NULL for tables.  Points to definition if a view. */
507   u8 readOnly;     /* True if this table should not be written by the user */
508   u8 iDb;          /* Index into sqlite.aDb[] of the backend for this table */
509   u8 isTransient;  /* True if automatically deleted when VDBE finishes */
510   u8 hasPrimKey;   /* True if there exists a primary key */
511   u8 keyConf;      /* What to do in case of uniqueness conflict on iPKey */
512   Trigger *pTrigger; /* List of SQL triggers on this table */
513   FKey *pFKey;       /* Linked list of all foreign keys in this table */
514 };
515 
516 /*
517 ** Each foreign key constraint is an instance of the following structure.
518 **
519 ** A foreign key is associated with two tables.  The "from" table is
520 ** the table that contains the REFERENCES clause that creates the foreign
521 ** key.  The "to" table is the table that is named in the REFERENCES clause.
522 ** Consider this example:
523 **
524 **     CREATE TABLE ex1(
525 **       a INTEGER PRIMARY KEY,
526 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
527 **     );
528 **
529 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
530 **
531 ** Each REFERENCES clause generates an instance of the following structure
532 ** which is attached to the from-table.  The to-table need not exist when
533 ** the from-table is created.  The existance of the to-table is not checked
534 ** until an attempt is made to insert data into the from-table.
535 **
536 ** The sqlite.aFKey hash table stores pointers to this structure
537 ** given the name of a to-table.  For each to-table, all foreign keys
538 ** associated with that table are on a linked list using the FKey.pNextTo
539 ** field.
540 */
541 struct FKey {
542   Table *pFrom;     /* The table that constains the REFERENCES clause */
543   FKey *pNextFrom;  /* Next foreign key in pFrom */
544   char *zTo;        /* Name of table that the key points to */
545   FKey *pNextTo;    /* Next foreign key that points to zTo */
546   int nCol;         /* Number of columns in this key */
547   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
548     int iFrom;         /* Index of column in pFrom */
549     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
550   } *aCol;          /* One entry for each of nCol column s */
551   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
552   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
553   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
554   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
555 };
556 
557 /*
558 ** SQLite supports many different ways to resolve a contraint
559 ** error.  ROLLBACK processing means that a constraint violation
560 ** causes the operation in process to fail and for the current transaction
561 ** to be rolled back.  ABORT processing means the operation in process
562 ** fails and any prior changes from that one operation are backed out,
563 ** but the transaction is not rolled back.  FAIL processing means that
564 ** the operation in progress stops and returns an error code.  But prior
565 ** changes due to the same operation are not backed out and no rollback
566 ** occurs.  IGNORE means that the particular row that caused the constraint
567 ** error is not inserted or updated.  Processing continues and no error
568 ** is returned.  REPLACE means that preexisting database rows that caused
569 ** a UNIQUE constraint violation are removed so that the new insert or
570 ** update can proceed.  Processing continues and no error is reported.
571 **
572 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
573 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
574 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
575 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
576 ** referenced table row is propagated into the row that holds the
577 ** foreign key.
578 **
579 ** The following symbolic values are used to record which type
580 ** of action to take.
581 */
582 #define OE_None     0   /* There is no constraint to check */
583 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
584 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
585 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
586 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
587 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
588 
589 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
590 #define OE_SetNull  7   /* Set the foreign key value to NULL */
591 #define OE_SetDflt  8   /* Set the foreign key value to its default */
592 #define OE_Cascade  9   /* Cascade the changes */
593 
594 #define OE_Default  99  /* Do whatever the default action is */
595 
596 /*
597 ** Each SQL index is represented in memory by an
598 ** instance of the following structure.
599 **
600 ** The columns of the table that are to be indexed are described
601 ** by the aiColumn[] field of this structure.  For example, suppose
602 ** we have the following table and index:
603 **
604 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
605 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
606 **
607 ** In the Table structure describing Ex1, nCol==3 because there are
608 ** three columns in the table.  In the Index structure describing
609 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
610 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
611 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
612 ** The second column to be indexed (c1) has an index of 0 in
613 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
614 **
615 ** The Index.onError field determines whether or not the indexed columns
616 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
617 ** it means this is not a unique index.  Otherwise it is a unique index
618 ** and the value of Index.onError indicate the which conflict resolution
619 ** algorithm to employ whenever an attempt is made to insert a non-unique
620 ** element.
621 */
622 struct Index {
623   char *zName;     /* Name of this index */
624   int nColumn;     /* Number of columns in the table used by this index */
625   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
626   Table *pTable;   /* The SQL table being indexed */
627   int tnum;        /* Page containing root of this index in database file */
628   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
629   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
630   u8 iDb;          /* Index in sqlite.aDb[] of where this index is stored */
631   Index *pNext;    /* The next index associated with the same table */
632 };
633 
634 /*
635 ** Each token coming out of the lexer is an instance of
636 ** this structure.  Tokens are also used as part of an expression.
637 **
638 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
639 ** may contain random values.  Do not make any assuptions about Token.dyn
640 ** and Token.n when Token.z==0.
641 */
642 struct Token {
643   const char *z;      /* Text of the token.  Not NULL-terminated! */
644   unsigned dyn  : 1;  /* True for malloced memory, false for static */
645   unsigned n    : 31; /* Number of characters in this token */
646 };
647 
648 /*
649 ** Each node of an expression in the parse tree is an instance
650 ** of this structure.
651 **
652 ** Expr.op is the opcode.  The integer parser token codes are reused
653 ** as opcodes here.  For example, the parser defines TK_GE to be an integer
654 ** code representing the ">=" operator.  This same integer code is reused
655 ** to represent the greater-than-or-equal-to operator in the expression
656 ** tree.
657 **
658 ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
659 ** of argument if the expression is a function.
660 **
661 ** Expr.token is the operator token for this node.  For some expressions
662 ** that have subexpressions, Expr.token can be the complete text that gave
663 ** rise to the Expr.  In the latter case, the token is marked as being
664 ** a compound token.
665 **
666 ** An expression of the form ID or ID.ID refers to a column in a table.
667 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
668 ** the integer cursor number of a VDBE cursor pointing to that table and
669 ** Expr.iColumn is the column number for the specific column.  If the
670 ** expression is used as a result in an aggregate SELECT, then the
671 ** value is also stored in the Expr.iAgg column in the aggregate so that
672 ** it can be accessed after all aggregates are computed.
673 **
674 ** If the expression is a function, the Expr.iTable is an integer code
675 ** representing which function.  If the expression is an unbound variable
676 ** marker (a question mark character '?' in the original SQL) then the
677 ** Expr.iTable holds the index number for that variable.
678 **
679 ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
680 ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
681 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
682 ** operand.
683 */
684 struct Expr {
685   u8 op;                 /* Operation performed by this node */
686   u8 dataType;           /* Either SQLITE_SO_TEXT or SQLITE_SO_NUM */
687   u8 iDb;                /* Database referenced by this expression */
688   u8 flags;              /* Various flags.  See below */
689   Expr *pLeft, *pRight;  /* Left and right subnodes */
690   ExprList *pList;       /* A list of expressions used as function arguments
691                          ** or in "<expr> IN (<expr-list)" */
692   Token token;           /* An operand token */
693   Token span;            /* Complete text of the expression */
694   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
695                          ** iColumn-th field of the iTable-th table. */
696   int iAgg;              /* When op==TK_COLUMN and pParse->useAgg==TRUE, pull
697                          ** result from the iAgg-th element of the aggregator */
698   Select *pSelect;       /* When the expression is a sub-select.  Also the
699                          ** right side of "<expr> IN (<select>)" */
700 };
701 
702 /*
703 ** The following are the meanings of bits in the Expr.flags field.
704 */
705 #define EP_FromJoin     0x0001  /* Originated in ON or USING clause of a join */
706 
707 /*
708 ** These macros can be used to test, set, or clear bits in the
709 ** Expr.flags field.
710 */
711 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
712 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
713 #define ExprSetProperty(E,P)     (E)->flags|=(P)
714 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
715 
716 /*
717 ** A list of expressions.  Each expression may optionally have a
718 ** name.  An expr/name combination can be used in several ways, such
719 ** as the list of "expr AS ID" fields following a "SELECT" or in the
720 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
721 ** also be used as the argument to a function, in which case the a.zName
722 ** field is not used.
723 */
724 struct ExprList {
725   int nExpr;             /* Number of expressions on the list */
726   int nAlloc;            /* Number of entries allocated below */
727   struct ExprList_item {
728     Expr *pExpr;           /* The list of expressions */
729     char *zName;           /* Token associated with this expression */
730     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
731     u8 isAgg;              /* True if this is an aggregate like count(*) */
732     u8 done;               /* A flag to indicate when processing is finished */
733   } *a;                  /* One entry for each expression */
734 };
735 
736 /*
737 ** An instance of this structure can hold a simple list of identifiers,
738 ** such as the list "a,b,c" in the following statements:
739 **
740 **      INSERT INTO t(a,b,c) VALUES ...;
741 **      CREATE INDEX idx ON t(a,b,c);
742 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
743 **
744 ** The IdList.a.idx field is used when the IdList represents the list of
745 ** column names after a table name in an INSERT statement.  In the statement
746 **
747 **     INSERT INTO t(a,b,c) ...
748 **
749 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
750 */
751 struct IdList {
752   int nId;         /* Number of identifiers on the list */
753   int nAlloc;      /* Number of entries allocated for a[] below */
754   struct IdList_item {
755     char *zName;      /* Name of the identifier */
756     int idx;          /* Index in some Table.aCol[] of a column named zName */
757   } *a;
758 };
759 
760 /*
761 ** The following structure describes the FROM clause of a SELECT statement.
762 ** Each table or subquery in the FROM clause is a separate element of
763 ** the SrcList.a[] array.
764 **
765 ** With the addition of multiple database support, the following structure
766 ** can also be used to describe a particular table such as the table that
767 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
768 ** such a table must be a simple name: ID.  But in SQLite, the table can
769 ** now be identified by a database name, a dot, then the table name: ID.ID.
770 */
771 struct SrcList {
772   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
773   i16 nAlloc;      /* Number of entries allocated in a[] below */
774   struct SrcList_item {
775     char *zDatabase;  /* Name of database holding this table */
776     char *zName;      /* Name of the table */
777     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
778     Table *pTab;      /* An SQL table corresponding to zName */
779     Select *pSelect;  /* A SELECT statement used in place of a table name */
780     int jointype;     /* Type of join between this table and the next */
781     int iCursor;      /* The VDBE cursor number used to access this table */
782     Expr *pOn;        /* The ON clause of a join */
783     IdList *pUsing;   /* The USING clause of a join */
784   } a[1];             /* One entry for each identifier on the list */
785 };
786 
787 /*
788 ** Permitted values of the SrcList.a.jointype field
789 */
790 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
791 #define JT_NATURAL   0x0002    /* True for a "natural" join */
792 #define JT_LEFT      0x0004    /* Left outer join */
793 #define JT_RIGHT     0x0008    /* Right outer join */
794 #define JT_OUTER     0x0010    /* The "OUTER" keyword is present */
795 #define JT_ERROR     0x0020    /* unknown or unsupported join type */
796 
797 /*
798 ** For each nested loop in a WHERE clause implementation, the WhereInfo
799 ** structure contains a single instance of this structure.  This structure
800 ** is intended to be private the the where.c module and should not be
801 ** access or modified by other modules.
802 */
803 struct WhereLevel {
804   int iMem;            /* Memory cell used by this level */
805   Index *pIdx;         /* Index used */
806   int iCur;            /* Cursor number used for this index */
807   int score;           /* How well this indexed scored */
808   int brk;             /* Jump here to break out of the loop */
809   int cont;            /* Jump here to continue with the next loop cycle */
810   int op, p1, p2;      /* Opcode used to terminate the loop */
811   int iLeftJoin;       /* Memory cell used to implement LEFT OUTER JOIN */
812   int top;             /* First instruction of interior of the loop */
813   int inOp, inP1, inP2;/* Opcode used to implement an IN operator */
814   int bRev;            /* Do the scan in the reverse direction */
815 };
816 
817 /*
818 ** The WHERE clause processing routine has two halves.  The
819 ** first part does the start of the WHERE loop and the second
820 ** half does the tail of the WHERE loop.  An instance of
821 ** this structure is returned by the first half and passed
822 ** into the second half to give some continuity.
823 */
824 struct WhereInfo {
825   Parse *pParse;
826   SrcList *pTabList;   /* List of tables in the join */
827   int iContinue;       /* Jump here to continue with next record */
828   int iBreak;          /* Jump here to break out of the loop */
829   int nLevel;          /* Number of nested loop */
830   int savedNTab;       /* Value of pParse->nTab before WhereBegin() */
831   int peakNTab;        /* Value of pParse->nTab after WhereBegin() */
832   WhereLevel a[1];     /* Information about each nest loop in the WHERE */
833 };
834 
835 /*
836 ** An instance of the following structure contains all information
837 ** needed to generate code for a single SELECT statement.
838 **
839 ** The zSelect field is used when the Select structure must be persistent.
840 ** Normally, the expression tree points to tokens in the original input
841 ** string that encodes the select.  But if the Select structure must live
842 ** longer than its input string (for example when it is used to describe
843 ** a VIEW) we have to make a copy of the input string so that the nodes
844 ** of the expression tree will have something to point to.  zSelect is used
845 ** to hold that copy.
846 **
847 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
848 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
849 ** limit and nOffset to the value of the offset (or 0 if there is not
850 ** offset).  But later on, nLimit and nOffset become the memory locations
851 ** in the VDBE that record the limit and offset counters.
852 */
853 struct Select {
854   ExprList *pEList;      /* The fields of the result */
855   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
856   u8 isDistinct;         /* True if the DISTINCT keyword is present */
857   SrcList *pSrc;         /* The FROM clause */
858   Expr *pWhere;          /* The WHERE clause */
859   ExprList *pGroupBy;    /* The GROUP BY clause */
860   Expr *pHaving;         /* The HAVING clause */
861   ExprList *pOrderBy;    /* The ORDER BY clause */
862   Select *pPrior;        /* Prior select in a compound select statement */
863   int nLimit, nOffset;   /* LIMIT and OFFSET values.  -1 means not used */
864   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
865   char *zSelect;         /* Complete text of the SELECT command */
866 };
867 
868 /*
869 ** The results of a select can be distributed in several ways.
870 */
871 #define SRT_Callback     1  /* Invoke a callback with each row of result */
872 #define SRT_Mem          2  /* Store result in a memory cell */
873 #define SRT_Set          3  /* Store result as unique keys in a table */
874 #define SRT_Union        5  /* Store result as keys in a table */
875 #define SRT_Except       6  /* Remove result from a UNION table */
876 #define SRT_Table        7  /* Store result as data with a unique key */
877 #define SRT_TempTable    8  /* Store result in a trasient table */
878 #define SRT_Discard      9  /* Do not save the results anywhere */
879 #define SRT_Sorter      10  /* Store results in the sorter */
880 #define SRT_Subroutine  11  /* Call a subroutine to handle results */
881 
882 /*
883 ** When a SELECT uses aggregate functions (like "count(*)" or "avg(f1)")
884 ** we have to do some additional analysis of expressions.  An instance
885 ** of the following structure holds information about a single subexpression
886 ** somewhere in the SELECT statement.  An array of these structures holds
887 ** all the information we need to generate code for aggregate
888 ** expressions.
889 **
890 ** Note that when analyzing a SELECT containing aggregates, both
891 ** non-aggregate field variables and aggregate functions are stored
892 ** in the AggExpr array of the Parser structure.
893 **
894 ** The pExpr field points to an expression that is part of either the
895 ** field list, the GROUP BY clause, the HAVING clause or the ORDER BY
896 ** clause.  The expression will be freed when those clauses are cleaned
897 ** up.  Do not try to delete the expression attached to AggExpr.pExpr.
898 **
899 ** If AggExpr.pExpr==0, that means the expression is "count(*)".
900 */
901 struct AggExpr {
902   int isAgg;        /* if TRUE contains an aggregate function */
903   Expr *pExpr;      /* The expression */
904   FuncDef *pFunc;   /* Information about the aggregate function */
905 };
906 
907 /*
908 ** An SQL parser context.  A copy of this structure is passed through
909 ** the parser and down into all the parser action routine in order to
910 ** carry around information that is global to the entire parse.
911 */
912 struct Parse {
913   sqlite *db;          /* The main database structure */
914   int rc;              /* Return code from execution */
915   char *zErrMsg;       /* An error message */
916   Token sErrToken;     /* The token at which the error occurred */
917   Token sFirstToken;   /* The first token parsed */
918   Token sLastToken;    /* The last token parsed */
919   const char *zTail;   /* All SQL text past the last semicolon parsed */
920   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
921   Vdbe *pVdbe;         /* An engine for executing database bytecode */
922   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
923   u8 explain;          /* True if the EXPLAIN flag is found on the query */
924   u8 nameClash;        /* A permanent table name clashes with temp table name */
925   u8 useAgg;           /* If true, extract field values from the aggregator
926                        ** while generating expressions.  Normally false */
927   int nErr;            /* Number of errors seen */
928   int nTab;            /* Number of previously allocated VDBE cursors */
929   int nMem;            /* Number of memory cells used so far */
930   int nSet;            /* Number of sets used so far */
931   int nAgg;            /* Number of aggregate expressions */
932   int nVar;            /* Number of '?' variables seen in the SQL so far */
933   AggExpr *aAgg;       /* An array of aggregate expressions */
934   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
935   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
936   TriggerStack *trigStack;  /* Trigger actions being coded */
937 };
938 
939 /*
940 ** An instance of the following structure can be declared on a stack and used
941 ** to save the Parse.zAuthContext value so that it can be restored later.
942 */
943 struct AuthContext {
944   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
945   Parse *pParse;              /* The Parse structure */
946 };
947 
948 /*
949 ** Bitfield flags for P2 value in OP_PutIntKey and OP_Delete
950 */
951 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
952 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
953 #define OPFLAG_CSCHANGE  4    /* Set to update db->csChange */
954 
955 /*
956  * Each trigger present in the database schema is stored as an instance of
957  * struct Trigger.
958  *
959  * Pointers to instances of struct Trigger are stored in two ways.
960  * 1. In the "trigHash" hash table (part of the sqlite* that represents the
961  *    database). This allows Trigger structures to be retrieved by name.
962  * 2. All triggers associated with a single table form a linked list, using the
963  *    pNext member of struct Trigger. A pointer to the first element of the
964  *    linked list is stored as the "pTrigger" member of the associated
965  *    struct Table.
966  *
967  * The "step_list" member points to the first element of a linked list
968  * containing the SQL statements specified as the trigger program.
969  */
970 struct Trigger {
971   char *name;             /* The name of the trigger                        */
972   char *table;            /* The table or view to which the trigger applies */
973   u8 iDb;                 /* Database containing this trigger               */
974   u8 iTabDb;              /* Database containing Trigger.table              */
975   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
976   u8 tr_tm;               /* One of TK_BEFORE, TK_AFTER */
977   Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
978   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
979                              the <column-list> is stored here */
980   int foreach;            /* One of TK_ROW or TK_STATEMENT */
981   Token nameToken;        /* Token containing zName. Use during parsing only */
982 
983   TriggerStep *step_list; /* Link list of trigger program steps             */
984   Trigger *pNext;         /* Next trigger associated with the table */
985 };
986 
987 /*
988  * An instance of struct TriggerStep is used to store a single SQL statement
989  * that is a part of a trigger-program.
990  *
991  * Instances of struct TriggerStep are stored in a singly linked list (linked
992  * using the "pNext" member) referenced by the "step_list" member of the
993  * associated struct Trigger instance. The first element of the linked list is
994  * the first step of the trigger-program.
995  *
996  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
997  * "SELECT" statement. The meanings of the other members is determined by the
998  * value of "op" as follows:
999  *
1000  * (op == TK_INSERT)
1001  * orconf    -> stores the ON CONFLICT algorithm
1002  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
1003  *              this stores a pointer to the SELECT statement. Otherwise NULL.
1004  * target    -> A token holding the name of the table to insert into.
1005  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
1006  *              this stores values to be inserted. Otherwise NULL.
1007  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
1008  *              statement, then this stores the column-names to be
1009  *              inserted into.
1010  *
1011  * (op == TK_DELETE)
1012  * target    -> A token holding the name of the table to delete from.
1013  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
1014  *              Otherwise NULL.
1015  *
1016  * (op == TK_UPDATE)
1017  * target    -> A token holding the name of the table to update rows of.
1018  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
1019  *              Otherwise NULL.
1020  * pExprList -> A list of the columns to update and the expressions to update
1021  *              them to. See sqliteUpdate() documentation of "pChanges"
1022  *              argument.
1023  *
1024  */
1025 struct TriggerStep {
1026   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
1027   int orconf;          /* OE_Rollback etc. */
1028   Trigger *pTrig;      /* The trigger that this step is a part of */
1029 
1030   Select *pSelect;     /* Valid for SELECT and sometimes
1031 			  INSERT steps (when pExprList == 0) */
1032   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
1033   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
1034   ExprList *pExprList; /* Valid for UPDATE statements and sometimes
1035 			   INSERT steps (when pSelect == 0)         */
1036   IdList *pIdList;     /* Valid for INSERT statements only */
1037 
1038   TriggerStep * pNext; /* Next in the link-list */
1039 };
1040 
1041 /*
1042  * An instance of struct TriggerStack stores information required during code
1043  * generation of a single trigger program. While the trigger program is being
1044  * coded, its associated TriggerStack instance is pointed to by the
1045  * "pTriggerStack" member of the Parse structure.
1046  *
1047  * The pTab member points to the table that triggers are being coded on. The
1048  * newIdx member contains the index of the vdbe cursor that points at the temp
1049  * table that stores the new.* references. If new.* references are not valid
1050  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
1051  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
1052  *
1053  * The ON CONFLICT policy to be used for the trigger program steps is stored
1054  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause
1055  * specified for individual triggers steps is used.
1056  *
1057  * struct TriggerStack has a "pNext" member, to allow linked lists to be
1058  * constructed. When coding nested triggers (triggers fired by other triggers)
1059  * each nested trigger stores its parent trigger's TriggerStack as the "pNext"
1060  * pointer. Once the nested trigger has been coded, the pNext value is restored
1061  * to the pTriggerStack member of the Parse stucture and coding of the parent
1062  * trigger continues.
1063  *
1064  * Before a nested trigger is coded, the linked list pointed to by the
1065  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
1066  * recursively. If this condition is detected, the nested trigger is not coded.
1067  */
1068 struct TriggerStack {
1069   Table *pTab;         /* Table that triggers are currently being coded on */
1070   int newIdx;          /* Index of vdbe cursor to "new" temp table */
1071   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
1072   int orconf;          /* Current orconf policy */
1073   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
1074   Trigger *pTrigger;   /* The trigger currently being coded */
1075   TriggerStack *pNext; /* Next trigger down on the trigger stack */
1076 };
1077 
1078 /*
1079 ** The following structure contains information used by the sqliteFix...
1080 ** routines as they walk the parse tree to make database references
1081 ** explicit.
1082 */
1083 typedef struct DbFixer DbFixer;
1084 struct DbFixer {
1085   Parse *pParse;      /* The parsing context.  Error messages written here */
1086   const char *zDb;    /* Make sure all objects are contained in this database */
1087   const char *zType;  /* Type of the container - used for error messages */
1088   const Token *pName; /* Name of the container - used for error messages */
1089 };
1090 
1091 /*
1092  * This global flag is set for performance testing of triggers. When it is set
1093  * SQLite will perform the overhead of building new and old trigger references
1094  * even when no triggers exist
1095  */
1096 extern int always_code_trigger_setup;
1097 
1098 /*
1099 ** Internal function prototypes
1100 */
1101 int sqliteStrICmp(const char *, const char *);
1102 int sqliteStrNICmp(const char *, const char *, int);
1103 int sqliteHashNoCase(const char *, int);
1104 int sqliteIsNumber(const char*);
1105 int sqliteCompare(const char *, const char *);
1106 int sqliteSortCompare(const char *, const char *);
1107 void sqliteRealToSortable(double r, char *);
1108 #ifdef MEMORY_DEBUG
1109   void *sqliteMalloc_(int,int,char*,int);
1110   void sqliteFree_(void*,char*,int);
1111   void *sqliteRealloc_(void*,int,char*,int);
1112   char *sqliteStrDup_(const char*,char*,int);
1113   char *sqliteStrNDup_(const char*, int,char*,int);
1114   void sqliteCheckMemory(void*,int);
1115 #else
1116   void *sqliteMalloc(int);
1117   void *sqliteMallocRaw(int);
1118   void sqliteFree(void*);
1119   void *sqliteRealloc(void*,int);
1120   char *sqliteStrDup(const char*);
1121   char *sqliteStrNDup(const char*, int);
1122 # define sqliteCheckMemory(a,b)
1123 #endif
1124 char *sqliteMPrintf(const char*, ...);
1125 char *sqliteVMPrintf(const char*, va_list);
1126 void sqliteSetString(char **, const char *, ...);
1127 void sqliteSetNString(char **, ...);
1128 void sqliteErrorMsg(Parse*, const char*, ...);
1129 void sqliteDequote(char*);
1130 int sqliteKeywordCode(const char*, int);
1131 int sqliteRunParser(Parse*, const char*, char **);
1132 void sqliteExec(Parse*);
1133 Expr *sqliteExpr(int, Expr*, Expr*, Token*);
1134 void sqliteExprSpan(Expr*,Token*,Token*);
1135 Expr *sqliteExprFunction(ExprList*, Token*);
1136 void sqliteExprDelete(Expr*);
1137 ExprList *sqliteExprListAppend(ExprList*,Expr*,Token*);
1138 void sqliteExprListDelete(ExprList*);
1139 int sqliteInit(sqlite*, char**);
1140 void sqlitePragma(Parse*,Token*,Token*,int);
1141 void sqliteResetInternalSchema(sqlite*, int);
1142 void sqliteBeginParse(Parse*,int);
1143 void sqliteRollbackInternalChanges(sqlite*);
1144 void sqliteCommitInternalChanges(sqlite*);
1145 Table *sqliteResultSetOfSelect(Parse*,char*,Select*);
1146 void sqliteOpenMasterTable(Vdbe *v, int);
1147 void sqliteStartTable(Parse*,Token*,Token*,int,int);
1148 void sqliteAddColumn(Parse*,Token*);
1149 void sqliteAddNotNull(Parse*, int);
1150 void sqliteAddPrimaryKey(Parse*, IdList*, int);
1151 void sqliteAddColumnType(Parse*,Token*,Token*);
1152 void sqliteAddDefaultValue(Parse*,Token*,int);
1153 int sqliteCollateType(const char*, int);
1154 void sqliteAddCollateType(Parse*, int);
1155 void sqliteEndTable(Parse*,Token*,Select*);
1156 void sqliteCreateView(Parse*,Token*,Token*,Select*,int);
1157 int sqliteViewGetColumnNames(Parse*,Table*);
1158 void sqliteDropTable(Parse*, Token*, int);
1159 void sqliteDeleteTable(sqlite*, Table*);
1160 void sqliteInsert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
1161 IdList *sqliteIdListAppend(IdList*, Token*);
1162 int sqliteIdListIndex(IdList*,const char*);
1163 SrcList *sqliteSrcListAppend(SrcList*, Token*, Token*);
1164 void sqliteSrcListAddAlias(SrcList*, Token*);
1165 void sqliteSrcListAssignCursors(Parse*, SrcList*);
1166 void sqliteIdListDelete(IdList*);
1167 void sqliteSrcListDelete(SrcList*);
1168 void sqliteCreateIndex(Parse*,Token*,SrcList*,IdList*,int,Token*,Token*);
1169 void sqliteDropIndex(Parse*, SrcList*);
1170 void sqliteAddKeyType(Vdbe*, ExprList*);
1171 void sqliteAddIdxKeyType(Vdbe*, Index*);
1172 int sqliteSelect(Parse*, Select*, int, int, Select*, int, int*);
1173 Select *sqliteSelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
1174                         int,int,int);
1175 void sqliteSelectDelete(Select*);
1176 void sqliteSelectUnbind(Select*);
1177 Table *sqliteSrcListLookup(Parse*, SrcList*);
1178 int sqliteIsReadOnly(Parse*, Table*, int);
1179 void sqliteDeleteFrom(Parse*, SrcList*, Expr*);
1180 void sqliteUpdate(Parse*, SrcList*, ExprList*, Expr*, int);
1181 WhereInfo *sqliteWhereBegin(Parse*, SrcList*, Expr*, int, ExprList**);
1182 void sqliteWhereEnd(WhereInfo*);
1183 void sqliteExprCode(Parse*, Expr*);
1184 int sqliteExprCodeExprList(Parse*, ExprList*, int);
1185 void sqliteExprIfTrue(Parse*, Expr*, int, int);
1186 void sqliteExprIfFalse(Parse*, Expr*, int, int);
1187 Table *sqliteFindTable(sqlite*,const char*, const char*);
1188 Table *sqliteLocateTable(Parse*,const char*, const char*);
1189 Index *sqliteFindIndex(sqlite*,const char*, const char*);
1190 void sqliteUnlinkAndDeleteIndex(sqlite*,Index*);
1191 void sqliteCopy(Parse*, SrcList*, Token*, Token*, int);
1192 void sqliteVacuum(Parse*, Token*);
1193 int sqliteRunVacuum(char**, sqlite*);
1194 int sqliteGlobCompare(const unsigned char*,const unsigned char*);
1195 int sqliteLikeCompare(const unsigned char*,const unsigned char*);
1196 char *sqliteTableNameFromToken(Token*);
1197 int sqliteExprCheck(Parse*, Expr*, int, int*);
1198 int sqliteExprType(Expr*);
1199 int sqliteExprCompare(Expr*, Expr*);
1200 int sqliteFuncId(Token*);
1201 int sqliteExprResolveIds(Parse*, SrcList*, ExprList*, Expr*);
1202 int sqliteExprAnalyzeAggregates(Parse*, Expr*);
1203 Vdbe *sqliteGetVdbe(Parse*);
1204 void sqliteRandomness(int, void*);
1205 void sqliteRollbackAll(sqlite*);
1206 void sqliteCodeVerifySchema(Parse*, int);
1207 void sqliteBeginTransaction(Parse*, int);
1208 void sqliteCommitTransaction(Parse*);
1209 void sqliteRollbackTransaction(Parse*);
1210 int sqliteExprIsConstant(Expr*);
1211 int sqliteExprIsInteger(Expr*, int*);
1212 int sqliteIsRowid(const char*);
1213 void sqliteGenerateRowDelete(sqlite*, Vdbe*, Table*, int, int);
1214 void sqliteGenerateRowIndexDelete(sqlite*, Vdbe*, Table*, int, char*);
1215 void sqliteGenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
1216 void sqliteCompleteInsertion(Parse*, Table*, int, char*, int, int, int);
1217 int sqliteOpenTableAndIndices(Parse*, Table*, int);
1218 void sqliteBeginWriteOperation(Parse*, int, int);
1219 void sqliteEndWriteOperation(Parse*);
1220 Expr *sqliteExprDup(Expr*);
1221 void sqliteTokenCopy(Token*, Token*);
1222 ExprList *sqliteExprListDup(ExprList*);
1223 SrcList *sqliteSrcListDup(SrcList*);
1224 IdList *sqliteIdListDup(IdList*);
1225 Select *sqliteSelectDup(Select*);
1226 FuncDef *sqliteFindFunction(sqlite*,const char*,int,int,int);
1227 void sqliteRegisterBuiltinFunctions(sqlite*);
1228 void sqliteRegisterDateTimeFunctions(sqlite*);
1229 int sqliteSafetyOn(sqlite*);
1230 int sqliteSafetyOff(sqlite*);
1231 int sqliteSafetyCheck(sqlite*);
1232 void sqliteChangeCookie(sqlite*, Vdbe*);
1233 void sqliteBeginTrigger(Parse*, Token*,int,int,IdList*,SrcList*,int,Expr*,int);
1234 void sqliteFinishTrigger(Parse*, TriggerStep*, Token*);
1235 void sqliteDropTrigger(Parse*, SrcList*);
1236 void sqliteDropTriggerPtr(Parse*, Trigger*, int);
1237 int sqliteTriggersExist(Parse* , Trigger* , int , int , int, ExprList*);
1238 int sqliteCodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int,
1239                          int, int);
1240 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
1241 void sqliteDeleteTriggerStep(TriggerStep*);
1242 TriggerStep *sqliteTriggerSelectStep(Select*);
1243 TriggerStep *sqliteTriggerInsertStep(Token*, IdList*, ExprList*, Select*, int);
1244 TriggerStep *sqliteTriggerUpdateStep(Token*, ExprList*, Expr*, int);
1245 TriggerStep *sqliteTriggerDeleteStep(Token*, Expr*);
1246 void sqliteDeleteTrigger(Trigger*);
1247 int sqliteJoinType(Parse*, Token*, Token*, Token*);
1248 void sqliteCreateForeignKey(Parse*, IdList*, Token*, IdList*, int);
1249 void sqliteDeferForeignKey(Parse*, int);
1250 #ifndef SQLITE_OMIT_AUTHORIZATION
1251   void sqliteAuthRead(Parse*,Expr*,SrcList*);
1252   int sqliteAuthCheck(Parse*,int, const char*, const char*, const char*);
1253   void sqliteAuthContextPush(Parse*, AuthContext*, const char*);
1254   void sqliteAuthContextPop(AuthContext*);
1255 #else
1256 # define sqliteAuthRead(a,b,c)
1257 # define sqliteAuthCheck(a,b,c,d,e)    SQLITE_OK
1258 # define sqliteAuthContextPush(a,b,c)
1259 # define sqliteAuthContextPop(a)  ((void)(a))
1260 #endif
1261 void sqliteAttach(Parse*, Token*, Token*, Token*);
1262 void sqliteDetach(Parse*, Token*);
1263 int sqliteBtreeFactory(const sqlite *db, const char *zFilename,
1264                        int mode, int nPg, Btree **ppBtree);
1265 int sqliteFixInit(DbFixer*, Parse*, int, const char*, const Token*);
1266 int sqliteFixSrcList(DbFixer*, SrcList*);
1267 int sqliteFixSelect(DbFixer*, Select*);
1268 int sqliteFixExpr(DbFixer*, Expr*);
1269 int sqliteFixExprList(DbFixer*, ExprList*);
1270 int sqliteFixTriggerStep(DbFixer*, TriggerStep*);
1271 double sqliteAtoF(const char *z, const char **);
1272 char *sqlite_snprintf(int,char*,const char*,...);
1273 int sqliteFitsIn32Bits(const char *);
1274