xref: /sqlite-3.40.0/src/sqliteInt.h (revision be217793)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** Internal interface definitions for SQLite.
13 **
14 ** @(#) $Id: sqliteInt.h,v 1.840 2009/03/02 17:18:48 shane Exp $
15 */
16 #ifndef _SQLITEINT_H_
17 #define _SQLITEINT_H_
18 
19 /*
20 ** Include the configuration header output by 'configure' if we're using the
21 ** autoconf-based build
22 */
23 #ifdef _HAVE_SQLITE_CONFIG_H
24 #include "config.h"
25 #endif
26 
27 #include "sqliteLimit.h"
28 
29 /* Disable nuisance warnings on Borland compilers */
30 #if defined(__BORLANDC__)
31 #pragma warn -rch /* unreachable code */
32 #pragma warn -ccc /* Condition is always true or false */
33 #pragma warn -aus /* Assigned value is never used */
34 #pragma warn -csu /* Comparing signed and unsigned */
35 #pragma warn -spa /* Suspicious pointer arithmetic */
36 #endif
37 
38 /* Needed for various definitions... */
39 #ifndef _GNU_SOURCE
40 # define _GNU_SOURCE
41 #endif
42 
43 /*
44 ** Include standard header files as necessary
45 */
46 #ifdef HAVE_STDINT_H
47 #include <stdint.h>
48 #endif
49 #ifdef HAVE_INTTYPES_H
50 #include <inttypes.h>
51 #endif
52 
53 /*
54  * This macro is used to "hide" some ugliness in casting an int
55  * value to a ptr value under the MSVC 64-bit compiler.   Casting
56  * non 64-bit values to ptr types results in a "hard" error with
57  * the MSVC 64-bit compiler which this attempts to avoid.
58  *
59  * A simple compiler pragma or casting sequence could not be found
60  * to correct this in all situations, so this macro was introduced.
61  *
62  * It could be argued that the intptr_t type could be used in this
63  * case, but that type is not available on all compilers, or
64  * requires the #include of specific headers which differs between
65  * platforms.
66  */
67 #define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
68 #define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
69 
70 /*
71 ** These #defines should enable >2GB file support on POSIX if the
72 ** underlying operating system supports it.  If the OS lacks
73 ** large file support, or if the OS is windows, these should be no-ops.
74 **
75 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
76 ** system #includes.  Hence, this block of code must be the very first
77 ** code in all source files.
78 **
79 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
80 ** on the compiler command line.  This is necessary if you are compiling
81 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
82 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
83 ** without this option, LFS is enable.  But LFS does not exist in the kernel
84 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
85 ** portability you should omit LFS.
86 **
87 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
88 */
89 #ifndef SQLITE_DISABLE_LFS
90 # define _LARGE_FILE       1
91 # ifndef _FILE_OFFSET_BITS
92 #   define _FILE_OFFSET_BITS 64
93 # endif
94 # define _LARGEFILE_SOURCE 1
95 #endif
96 
97 
98 /*
99 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
100 ** Older versions of SQLite used an optional THREADSAFE macro.
101 ** We support that for legacy
102 */
103 #if !defined(SQLITE_THREADSAFE)
104 #if defined(THREADSAFE)
105 # define SQLITE_THREADSAFE THREADSAFE
106 #else
107 # define SQLITE_THREADSAFE 1
108 #endif
109 #endif
110 
111 /*
112 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
113 ** It determines whether or not the features related to
114 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
115 ** be overridden at runtime using the sqlite3_config() API.
116 */
117 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
118 # define SQLITE_DEFAULT_MEMSTATUS 1
119 #endif
120 
121 /*
122 ** Exactly one of the following macros must be defined in order to
123 ** specify which memory allocation subsystem to use.
124 **
125 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
126 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
127 **     SQLITE_MEMORY_SIZE            // internal allocator #1
128 **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
129 **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
130 **
131 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
132 ** the default.
133 */
134 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
135     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
136     defined(SQLITE_POW2_MEMORY_SIZE)>1
137 # error "At most one of the following compile-time configuration options\
138  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
139  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
140 #endif
141 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
142     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
143     defined(SQLITE_POW2_MEMORY_SIZE)==0
144 # define SQLITE_SYSTEM_MALLOC 1
145 #endif
146 
147 /*
148 ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
149 ** sizes of memory allocations below this value where possible.
150 */
151 #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
152 # define SQLITE_MALLOC_SOFT_LIMIT 1024
153 #endif
154 
155 /*
156 ** We need to define _XOPEN_SOURCE as follows in order to enable
157 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
158 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
159 ** so it is omitted there.  See ticket #2673.
160 **
161 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
162 ** implemented on some systems.  So we avoid defining it at all
163 ** if it is already defined or if it is unneeded because we are
164 ** not doing a threadsafe build.  Ticket #2681.
165 **
166 ** See also ticket #2741.
167 */
168 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
169 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
170 #endif
171 
172 /*
173 ** The TCL headers are only needed when compiling the TCL bindings.
174 */
175 #if defined(SQLITE_TCL) || defined(TCLSH)
176 # include <tcl.h>
177 #endif
178 
179 /*
180 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
181 ** Setting NDEBUG makes the code smaller and run faster.  So the following
182 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
183 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
184 ** feature.
185 */
186 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
187 # define NDEBUG 1
188 #endif
189 
190 /*
191 ** The testcase() macro is used to aid in coverage testing.  When
192 ** doing coverage testing, the condition inside the argument to
193 ** testcase() must be evaluated both true and false in order to
194 ** get full branch coverage.  The testcase() macro is inserted
195 ** to help ensure adequate test coverage in places where simple
196 ** condition/decision coverage is inadequate.  For example, testcase()
197 ** can be used to make sure boundary values are tested.  For
198 ** bitmask tests, testcase() can be used to make sure each bit
199 ** is significant and used at least once.  On switch statements
200 ** where multiple cases go to the same block of code, testcase()
201 ** can insure that all cases are evaluated.
202 **
203 */
204 #ifdef SQLITE_COVERAGE_TEST
205   void sqlite3Coverage(int);
206 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
207 #else
208 # define testcase(X)
209 #endif
210 
211 /*
212 ** The TESTONLY macro is used to enclose variable declarations or
213 ** other bits of code that are needed to support the arguments
214 ** within testcase() and assert() macros.
215 */
216 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
217 # define TESTONLY(X)  X
218 #else
219 # define TESTONLY(X)
220 #endif
221 
222 /*
223 ** The ALWAYS and NEVER macros surround boolean expressions which
224 ** are intended to always be true or false, respectively.  Such
225 ** expressions could be omitted from the code completely.  But they
226 ** are included in a few cases in order to enhance the resilience
227 ** of SQLite to unexpected behavior - to make the code "self-healing"
228 ** or "ductile" rather than being "brittle" and crashing at the first
229 ** hint of unplanned behavior.
230 **
231 ** In other words, ALWAYS and NEVER are added for defensive code.
232 **
233 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
234 ** be true and false so that the unreachable code then specify will
235 ** not be counted as untested code.
236 */
237 #if defined(SQLITE_COVERAGE_TEST)
238 # define ALWAYS(X)      (1)
239 # define NEVER(X)       (0)
240 #elif !defined(NDEBUG)
241   int sqlite3Assert(void);
242 # define ALWAYS(X)      ((X)?1:sqlite3Assert())
243 # define NEVER(X)       ((X)?sqlite3Assert():0)
244 #else
245 # define ALWAYS(X)      (X)
246 # define NEVER(X)       (X)
247 #endif
248 
249 /*
250 ** The macro unlikely() is a hint that surrounds a boolean
251 ** expression that is usually false.  Macro likely() surrounds
252 ** a boolean expression that is usually true.  GCC is able to
253 ** use these hints to generate better code, sometimes.
254 */
255 #if defined(__GNUC__) && 0
256 # define likely(X)    __builtin_expect((X),1)
257 # define unlikely(X)  __builtin_expect((X),0)
258 #else
259 # define likely(X)    !!(X)
260 # define unlikely(X)  !!(X)
261 #endif
262 
263 /*
264 ** Sometimes we need a small amount of code such as a variable initialization
265 ** to setup for a later assert() statement.  We do not want this code to
266 ** appear when assert() is disabled.  The following macro is therefore
267 ** used to contain that setup code.  The "VVA" acronym stands for
268 ** "Verification, Validation, and Accreditation".  In other words, the
269 ** code within VVA_ONLY() will only run during verification processes.
270 */
271 #ifndef NDEBUG
272 # define VVA_ONLY(X)  X
273 #else
274 # define VVA_ONLY(X)
275 #endif
276 
277 #include "sqlite3.h"
278 #include "hash.h"
279 #include "parse.h"
280 #include <stdio.h>
281 #include <stdlib.h>
282 #include <string.h>
283 #include <assert.h>
284 #include <stddef.h>
285 
286 /*
287 ** If compiling for a processor that lacks floating point support,
288 ** substitute integer for floating-point
289 */
290 #ifdef SQLITE_OMIT_FLOATING_POINT
291 # define double sqlite_int64
292 # define LONGDOUBLE_TYPE sqlite_int64
293 # ifndef SQLITE_BIG_DBL
294 #   define SQLITE_BIG_DBL (0x7fffffffffffffff)
295 # endif
296 # define SQLITE_OMIT_DATETIME_FUNCS 1
297 # define SQLITE_OMIT_TRACE 1
298 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
299 #endif
300 #ifndef SQLITE_BIG_DBL
301 # define SQLITE_BIG_DBL (1e99)
302 #endif
303 
304 /*
305 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
306 ** afterward. Having this macro allows us to cause the C compiler
307 ** to omit code used by TEMP tables without messy #ifndef statements.
308 */
309 #ifdef SQLITE_OMIT_TEMPDB
310 #define OMIT_TEMPDB 1
311 #else
312 #define OMIT_TEMPDB 0
313 #endif
314 
315 /*
316 ** If the following macro is set to 1, then NULL values are considered
317 ** distinct when determining whether or not two entries are the same
318 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
319 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
320 ** is the way things are suppose to work.
321 **
322 ** If the following macro is set to 0, the NULLs are indistinct for
323 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
324 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
325 ** work.
326 */
327 #define NULL_DISTINCT_FOR_UNIQUE 1
328 
329 /*
330 ** The "file format" number is an integer that is incremented whenever
331 ** the VDBE-level file format changes.  The following macros define the
332 ** the default file format for new databases and the maximum file format
333 ** that the library can read.
334 */
335 #define SQLITE_MAX_FILE_FORMAT 4
336 #ifndef SQLITE_DEFAULT_FILE_FORMAT
337 # define SQLITE_DEFAULT_FILE_FORMAT 1
338 #endif
339 
340 /*
341 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
342 ** on the command-line
343 */
344 #ifndef SQLITE_TEMP_STORE
345 # define SQLITE_TEMP_STORE 1
346 #endif
347 
348 /*
349 ** GCC does not define the offsetof() macro so we'll have to do it
350 ** ourselves.
351 */
352 #ifndef offsetof
353 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
354 #endif
355 
356 /*
357 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
358 ** not, there are still machines out there that use EBCDIC.)
359 */
360 #if 'A' == '\301'
361 # define SQLITE_EBCDIC 1
362 #else
363 # define SQLITE_ASCII 1
364 #endif
365 
366 /*
367 ** Integers of known sizes.  These typedefs might change for architectures
368 ** where the sizes very.  Preprocessor macros are available so that the
369 ** types can be conveniently redefined at compile-type.  Like this:
370 **
371 **         cc '-DUINTPTR_TYPE=long long int' ...
372 */
373 #ifndef UINT32_TYPE
374 # ifdef HAVE_UINT32_T
375 #  define UINT32_TYPE uint32_t
376 # else
377 #  define UINT32_TYPE unsigned int
378 # endif
379 #endif
380 #ifndef UINT16_TYPE
381 # ifdef HAVE_UINT16_T
382 #  define UINT16_TYPE uint16_t
383 # else
384 #  define UINT16_TYPE unsigned short int
385 # endif
386 #endif
387 #ifndef INT16_TYPE
388 # ifdef HAVE_INT16_T
389 #  define INT16_TYPE int16_t
390 # else
391 #  define INT16_TYPE short int
392 # endif
393 #endif
394 #ifndef UINT8_TYPE
395 # ifdef HAVE_UINT8_T
396 #  define UINT8_TYPE uint8_t
397 # else
398 #  define UINT8_TYPE unsigned char
399 # endif
400 #endif
401 #ifndef INT8_TYPE
402 # ifdef HAVE_INT8_T
403 #  define INT8_TYPE int8_t
404 # else
405 #  define INT8_TYPE signed char
406 # endif
407 #endif
408 #ifndef LONGDOUBLE_TYPE
409 # define LONGDOUBLE_TYPE long double
410 #endif
411 typedef sqlite_int64 i64;          /* 8-byte signed integer */
412 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
413 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
414 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
415 typedef INT16_TYPE i16;            /* 2-byte signed integer */
416 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
417 typedef INT8_TYPE i8;              /* 1-byte signed integer */
418 
419 /*
420 ** Macros to determine whether the machine is big or little endian,
421 ** evaluated at runtime.
422 */
423 #ifdef SQLITE_AMALGAMATION
424 const int sqlite3one = 1;
425 #else
426 extern const int sqlite3one;
427 #endif
428 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
429                              || defined(__x86_64) || defined(__x86_64__)
430 # define SQLITE_BIGENDIAN    0
431 # define SQLITE_LITTLEENDIAN 1
432 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
433 #else
434 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
435 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
436 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
437 #endif
438 
439 /*
440 ** Constants for the largest and smallest possible 64-bit signed integers.
441 ** These macros are designed to work correctly on both 32-bit and 64-bit
442 ** compilers.
443 */
444 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
445 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
446 
447 /*
448 ** An instance of the following structure is used to store the busy-handler
449 ** callback for a given sqlite handle.
450 **
451 ** The sqlite.busyHandler member of the sqlite struct contains the busy
452 ** callback for the database handle. Each pager opened via the sqlite
453 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
454 ** callback is currently invoked only from within pager.c.
455 */
456 typedef struct BusyHandler BusyHandler;
457 struct BusyHandler {
458   int (*xFunc)(void *,int);  /* The busy callback */
459   void *pArg;                /* First arg to busy callback */
460   int nBusy;                 /* Incremented with each busy call */
461 };
462 
463 /*
464 ** Name of the master database table.  The master database table
465 ** is a special table that holds the names and attributes of all
466 ** user tables and indices.
467 */
468 #define MASTER_NAME       "sqlite_master"
469 #define TEMP_MASTER_NAME  "sqlite_temp_master"
470 
471 /*
472 ** The root-page of the master database table.
473 */
474 #define MASTER_ROOT       1
475 
476 /*
477 ** The name of the schema table.
478 */
479 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
480 
481 /*
482 ** A convenience macro that returns the number of elements in
483 ** an array.
484 */
485 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
486 
487 /*
488 ** The following value as a destructor means to use sqlite3DbFree().
489 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
490 */
491 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
492 
493 /*
494 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
495 ** not support Writable Static Data (WSD) such as global and static variables.
496 ** All variables must either be on the stack or dynamically allocated from
497 ** the heap.  When WSD is unsupported, the variable declarations scattered
498 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
499 ** macro is used for this purpose.  And instead of referencing the variable
500 ** directly, we use its constant as a key to lookup the run-time allocated
501 ** buffer that holds real variable.  The constant is also the initializer
502 ** for the run-time allocated buffer.
503 **
504 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
505 ** macros become no-ops and have zero performance impact.
506 */
507 #ifdef SQLITE_OMIT_WSD
508   #define SQLITE_WSD const
509   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
510   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
511   int sqlite3_wsd_init(int N, int J);
512   void *sqlite3_wsd_find(void *K, int L);
513 #else
514   #define SQLITE_WSD
515   #define GLOBAL(t,v) v
516   #define sqlite3GlobalConfig sqlite3Config
517 #endif
518 
519 /*
520 ** The following macros are used to suppress compiler warnings and to
521 ** make it clear to human readers when a function parameter is deliberately
522 ** left unused within the body of a function. This usually happens when
523 ** a function is called via a function pointer. For example the
524 ** implementation of an SQL aggregate step callback may not use the
525 ** parameter indicating the number of arguments passed to the aggregate,
526 ** if it knows that this is enforced elsewhere.
527 **
528 ** When a function parameter is not used at all within the body of a function,
529 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
530 ** However, these macros may also be used to suppress warnings related to
531 ** parameters that may or may not be used depending on compilation options.
532 ** For example those parameters only used in assert() statements. In these
533 ** cases the parameters are named as per the usual conventions.
534 */
535 #define UNUSED_PARAMETER(x) (void)(x)
536 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
537 
538 /*
539 ** Forward references to structures
540 */
541 typedef struct AggInfo AggInfo;
542 typedef struct AuthContext AuthContext;
543 typedef struct Bitvec Bitvec;
544 typedef struct RowSet RowSet;
545 typedef struct CollSeq CollSeq;
546 typedef struct Column Column;
547 typedef struct Db Db;
548 typedef struct Schema Schema;
549 typedef struct Expr Expr;
550 typedef struct ExprList ExprList;
551 typedef struct FKey FKey;
552 typedef struct FuncDef FuncDef;
553 typedef struct FuncDefHash FuncDefHash;
554 typedef struct IdList IdList;
555 typedef struct Index Index;
556 typedef struct KeyClass KeyClass;
557 typedef struct KeyInfo KeyInfo;
558 typedef struct Lookaside Lookaside;
559 typedef struct LookasideSlot LookasideSlot;
560 typedef struct Module Module;
561 typedef struct NameContext NameContext;
562 typedef struct Parse Parse;
563 typedef struct Savepoint Savepoint;
564 typedef struct Select Select;
565 typedef struct SrcList SrcList;
566 typedef struct StrAccum StrAccum;
567 typedef struct Table Table;
568 typedef struct TableLock TableLock;
569 typedef struct Token Token;
570 typedef struct TriggerStack TriggerStack;
571 typedef struct TriggerStep TriggerStep;
572 typedef struct Trigger Trigger;
573 typedef struct UnpackedRecord UnpackedRecord;
574 typedef struct Walker Walker;
575 typedef struct WherePlan WherePlan;
576 typedef struct WhereInfo WhereInfo;
577 typedef struct WhereLevel WhereLevel;
578 
579 /*
580 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
581 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
582 ** pointer types (i.e. FuncDef) defined above.
583 */
584 #include "btree.h"
585 #include "vdbe.h"
586 #include "pager.h"
587 #include "pcache.h"
588 
589 #include "os.h"
590 #include "mutex.h"
591 
592 
593 /*
594 ** Each database file to be accessed by the system is an instance
595 ** of the following structure.  There are normally two of these structures
596 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
597 ** aDb[1] is the database file used to hold temporary tables.  Additional
598 ** databases may be attached.
599 */
600 struct Db {
601   char *zName;         /* Name of this database */
602   Btree *pBt;          /* The B*Tree structure for this database file */
603   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
604   u8 safety_level;     /* How aggressive at syncing data to disk */
605   void *pAux;               /* Auxiliary data.  Usually NULL */
606   void (*xFreeAux)(void*);  /* Routine to free pAux */
607   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
608 };
609 
610 /*
611 ** An instance of the following structure stores a database schema.
612 **
613 ** If there are no virtual tables configured in this schema, the
614 ** Schema.db variable is set to NULL. After the first virtual table
615 ** has been added, it is set to point to the database connection
616 ** used to create the connection. Once a virtual table has been
617 ** added to the Schema structure and the Schema.db variable populated,
618 ** only that database connection may use the Schema to prepare
619 ** statements.
620 */
621 struct Schema {
622   int schema_cookie;   /* Database schema version number for this file */
623   Hash tblHash;        /* All tables indexed by name */
624   Hash idxHash;        /* All (named) indices indexed by name */
625   Hash trigHash;       /* All triggers indexed by name */
626   Hash aFKey;          /* Foreign keys indexed by to-table */
627   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
628   u8 file_format;      /* Schema format version for this file */
629   u8 enc;              /* Text encoding used by this database */
630   u16 flags;           /* Flags associated with this schema */
631   int cache_size;      /* Number of pages to use in the cache */
632 #ifndef SQLITE_OMIT_VIRTUALTABLE
633   sqlite3 *db;         /* "Owner" connection. See comment above */
634 #endif
635 };
636 
637 /*
638 ** These macros can be used to test, set, or clear bits in the
639 ** Db.flags field.
640 */
641 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
642 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
643 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
644 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
645 
646 /*
647 ** Allowed values for the DB.flags field.
648 **
649 ** The DB_SchemaLoaded flag is set after the database schema has been
650 ** read into internal hash tables.
651 **
652 ** DB_UnresetViews means that one or more views have column names that
653 ** have been filled out.  If the schema changes, these column names might
654 ** changes and so the view will need to be reset.
655 */
656 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
657 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
658 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
659 
660 /*
661 ** The number of different kinds of things that can be limited
662 ** using the sqlite3_limit() interface.
663 */
664 #define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1)
665 
666 /*
667 ** Lookaside malloc is a set of fixed-size buffers that can be used
668 ** to satisfy small transient memory allocation requests for objects
669 ** associated with a particular database connection.  The use of
670 ** lookaside malloc provides a significant performance enhancement
671 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
672 ** SQL statements.
673 **
674 ** The Lookaside structure holds configuration information about the
675 ** lookaside malloc subsystem.  Each available memory allocation in
676 ** the lookaside subsystem is stored on a linked list of LookasideSlot
677 ** objects.
678 */
679 struct Lookaside {
680   u16 sz;                 /* Size of each buffer in bytes */
681   u8 bEnabled;            /* True if use lookaside.  False to ignore it */
682   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
683   int nOut;               /* Number of buffers currently checked out */
684   int mxOut;              /* Highwater mark for nOut */
685   LookasideSlot *pFree;   /* List of available buffers */
686   void *pStart;           /* First byte of available memory space */
687   void *pEnd;             /* First byte past end of available space */
688 };
689 struct LookasideSlot {
690   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
691 };
692 
693 /*
694 ** A hash table for function definitions.
695 **
696 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
697 ** Collisions are on the FuncDef.pHash chain.
698 */
699 struct FuncDefHash {
700   FuncDef *a[23];       /* Hash table for functions */
701 };
702 
703 /*
704 ** Each database is an instance of the following structure.
705 **
706 ** The sqlite.lastRowid records the last insert rowid generated by an
707 ** insert statement.  Inserts on views do not affect its value.  Each
708 ** trigger has its own context, so that lastRowid can be updated inside
709 ** triggers as usual.  The previous value will be restored once the trigger
710 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
711 ** longer (since after version 2.8.12) reset to -1.
712 **
713 ** The sqlite.nChange does not count changes within triggers and keeps no
714 ** context.  It is reset at start of sqlite3_exec.
715 ** The sqlite.lsChange represents the number of changes made by the last
716 ** insert, update, or delete statement.  It remains constant throughout the
717 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
718 ** context stack just like lastRowid so that the count of changes
719 ** within a trigger is not seen outside the trigger.  Changes to views do not
720 ** affect the value of lsChange.
721 ** The sqlite.csChange keeps track of the number of current changes (since
722 ** the last statement) and is used to update sqlite_lsChange.
723 **
724 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
725 ** store the most recent error code and, if applicable, string. The
726 ** internal function sqlite3Error() is used to set these variables
727 ** consistently.
728 */
729 struct sqlite3 {
730   sqlite3_vfs *pVfs;            /* OS Interface */
731   int nDb;                      /* Number of backends currently in use */
732   Db *aDb;                      /* All backends */
733   int flags;                    /* Miscellaneous flags. See below */
734   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
735   int errCode;                  /* Most recent error code (SQLITE_*) */
736   int errMask;                  /* & result codes with this before returning */
737   u8 autoCommit;                /* The auto-commit flag. */
738   u8 temp_store;                /* 1: file 2: memory 0: default */
739   u8 mallocFailed;              /* True if we have seen a malloc failure */
740   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
741   u8 dfltJournalMode;           /* Default journal mode for attached dbs */
742   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
743   int nextPagesize;             /* Pagesize after VACUUM if >0 */
744   int nTable;                   /* Number of tables in the database */
745   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
746   i64 lastRowid;                /* ROWID of most recent insert (see above) */
747   i64 priorNewRowid;            /* Last randomly generated ROWID */
748   u32 magic;                    /* Magic number for detect library misuse */
749   int nChange;                  /* Value returned by sqlite3_changes() */
750   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
751   sqlite3_mutex *mutex;         /* Connection mutex */
752   int aLimit[SQLITE_N_LIMIT];   /* Limits */
753   struct sqlite3InitInfo {      /* Information used during initialization */
754     int iDb;                    /* When back is being initialized */
755     int newTnum;                /* Rootpage of table being initialized */
756     u8 busy;                    /* TRUE if currently initializing */
757   } init;
758   int nExtension;               /* Number of loaded extensions */
759   void **aExtension;            /* Array of shared library handles */
760   struct Vdbe *pVdbe;           /* List of active virtual machines */
761   int activeVdbeCnt;            /* Number of VDBEs currently executing */
762   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
763   void (*xTrace)(void*,const char*);        /* Trace function */
764   void *pTraceArg;                          /* Argument to the trace function */
765   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
766   void *pProfileArg;                        /* Argument to profile function */
767   void *pCommitArg;                 /* Argument to xCommitCallback() */
768   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
769   void *pRollbackArg;               /* Argument to xRollbackCallback() */
770   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
771   void *pUpdateArg;
772   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
773   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
774   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
775   void *pCollNeededArg;
776   sqlite3_value *pErr;          /* Most recent error message */
777   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
778   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
779   union {
780     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
781     double notUsed1;            /* Spacer */
782   } u1;
783   Lookaside lookaside;          /* Lookaside malloc configuration */
784 #ifndef SQLITE_OMIT_AUTHORIZATION
785   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
786                                 /* Access authorization function */
787   void *pAuthArg;               /* 1st argument to the access auth function */
788 #endif
789 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
790   int (*xProgress)(void *);     /* The progress callback */
791   void *pProgressArg;           /* Argument to the progress callback */
792   int nProgressOps;             /* Number of opcodes for progress callback */
793 #endif
794 #ifndef SQLITE_OMIT_VIRTUALTABLE
795   Hash aModule;                 /* populated by sqlite3_create_module() */
796   Table *pVTab;                 /* vtab with active Connect/Create method */
797   sqlite3_vtab **aVTrans;       /* Virtual tables with open transactions */
798   int nVTrans;                  /* Allocated size of aVTrans */
799 #endif
800   FuncDefHash aFunc;            /* Hash table of connection functions */
801   Hash aCollSeq;                /* All collating sequences */
802   BusyHandler busyHandler;      /* Busy callback */
803   int busyTimeout;              /* Busy handler timeout, in msec */
804   Db aDbStatic[2];              /* Static space for the 2 default backends */
805 #ifdef SQLITE_SSE
806   sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
807 #endif
808   Savepoint *pSavepoint;        /* List of active savepoints */
809   int nSavepoint;               /* Number of non-transaction savepoints */
810   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
811 };
812 
813 /*
814 ** A macro to discover the encoding of a database.
815 */
816 #define ENC(db) ((db)->aDb[0].pSchema->enc)
817 
818 /*
819 ** Possible values for the sqlite.flags and or Db.flags fields.
820 **
821 ** On sqlite.flags, the SQLITE_InTrans value means that we have
822 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
823 ** transaction is active on that particular database file.
824 */
825 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
826 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
827 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
828 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
829 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
830 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
831                                           /*   DELETE, or UPDATE and return */
832                                           /*   the count using a callback. */
833 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
834                                           /*   result set is empty */
835 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
836 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
837 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
838 #define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when
839                                           ** accessing read-only databases */
840 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
841 #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
842 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
843 #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
844 #define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */
845 
846 #define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
847 #define SQLITE_SharedCache    0x00080000  /* Cache sharing is enabled */
848 #define SQLITE_Vtab           0x00100000  /* There exists a virtual table */
849 #define SQLITE_CommitBusy     0x00200000  /* In the process of committing */
850 #define SQLITE_ReverseOrder   0x00400000  /* Reverse unordered SELECTs */
851 
852 /*
853 ** Possible values for the sqlite.magic field.
854 ** The numbers are obtained at random and have no special meaning, other
855 ** than being distinct from one another.
856 */
857 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
858 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
859 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
860 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
861 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
862 
863 /*
864 ** Each SQL function is defined by an instance of the following
865 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
866 ** hash table.  When multiple functions have the same name, the hash table
867 ** points to a linked list of these structures.
868 */
869 struct FuncDef {
870   i16 nArg;            /* Number of arguments.  -1 means unlimited */
871   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
872   u8 flags;            /* Some combination of SQLITE_FUNC_* */
873   void *pUserData;     /* User data parameter */
874   FuncDef *pNext;      /* Next function with same name */
875   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
876   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
877   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
878   char *zName;         /* SQL name of the function. */
879   FuncDef *pHash;      /* Next with a different name but the same hash */
880 };
881 
882 /*
883 ** Possible values for FuncDef.flags
884 */
885 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
886 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
887 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
888 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
889 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
890 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
891 
892 /*
893 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
894 ** used to create the initializers for the FuncDef structures.
895 **
896 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
897 **     Used to create a scalar function definition of a function zName
898 **     implemented by C function xFunc that accepts nArg arguments. The
899 **     value passed as iArg is cast to a (void*) and made available
900 **     as the user-data (sqlite3_user_data()) for the function. If
901 **     argument bNC is true, then the FuncDef.needCollate flag is set.
902 **
903 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
904 **     Used to create an aggregate function definition implemented by
905 **     the C functions xStep and xFinal. The first four parameters
906 **     are interpreted in the same way as the first 4 parameters to
907 **     FUNCTION().
908 **
909 **   LIKEFUNC(zName, nArg, pArg, flags)
910 **     Used to create a scalar function definition of a function zName
911 **     that accepts nArg arguments and is implemented by a call to C
912 **     function likeFunc. Argument pArg is cast to a (void *) and made
913 **     available as the function user-data (sqlite3_user_data()). The
914 **     FuncDef.flags variable is set to the value passed as the flags
915 **     parameter.
916 */
917 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
918   {nArg, SQLITE_UTF8, bNC*8, SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
919 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
920   {nArg, SQLITE_UTF8, bNC*8, pArg, 0, xFunc, 0, 0, #zName, 0}
921 #define LIKEFUNC(zName, nArg, arg, flags) \
922   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
923 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
924   {nArg, SQLITE_UTF8, nc*8, SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
925 
926 /*
927 ** All current savepoints are stored in a linked list starting at
928 ** sqlite3.pSavepoint. The first element in the list is the most recently
929 ** opened savepoint. Savepoints are added to the list by the vdbe
930 ** OP_Savepoint instruction.
931 */
932 struct Savepoint {
933   char *zName;                        /* Savepoint name (nul-terminated) */
934   Savepoint *pNext;                   /* Parent savepoint (if any) */
935 };
936 
937 /*
938 ** The following are used as the second parameter to sqlite3Savepoint(),
939 ** and as the P1 argument to the OP_Savepoint instruction.
940 */
941 #define SAVEPOINT_BEGIN      0
942 #define SAVEPOINT_RELEASE    1
943 #define SAVEPOINT_ROLLBACK   2
944 
945 
946 /*
947 ** Each SQLite module (virtual table definition) is defined by an
948 ** instance of the following structure, stored in the sqlite3.aModule
949 ** hash table.
950 */
951 struct Module {
952   const sqlite3_module *pModule;       /* Callback pointers */
953   const char *zName;                   /* Name passed to create_module() */
954   void *pAux;                          /* pAux passed to create_module() */
955   void (*xDestroy)(void *);            /* Module destructor function */
956 };
957 
958 /*
959 ** information about each column of an SQL table is held in an instance
960 ** of this structure.
961 */
962 struct Column {
963   char *zName;     /* Name of this column */
964   Expr *pDflt;     /* Default value of this column */
965   char *zType;     /* Data type for this column */
966   char *zColl;     /* Collating sequence.  If NULL, use the default */
967   u8 notNull;      /* True if there is a NOT NULL constraint */
968   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
969   char affinity;   /* One of the SQLITE_AFF_... values */
970 #ifndef SQLITE_OMIT_VIRTUALTABLE
971   u8 isHidden;     /* True if this column is 'hidden' */
972 #endif
973 };
974 
975 /*
976 ** A "Collating Sequence" is defined by an instance of the following
977 ** structure. Conceptually, a collating sequence consists of a name and
978 ** a comparison routine that defines the order of that sequence.
979 **
980 ** There may two separate implementations of the collation function, one
981 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
982 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
983 ** native byte order. When a collation sequence is invoked, SQLite selects
984 ** the version that will require the least expensive encoding
985 ** translations, if any.
986 **
987 ** The CollSeq.pUser member variable is an extra parameter that passed in
988 ** as the first argument to the UTF-8 comparison function, xCmp.
989 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
990 ** xCmp16.
991 **
992 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
993 ** collating sequence is undefined.  Indices built on an undefined
994 ** collating sequence may not be read or written.
995 */
996 struct CollSeq {
997   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
998   u8 enc;               /* Text encoding handled by xCmp() */
999   u8 type;              /* One of the SQLITE_COLL_... values below */
1000   void *pUser;          /* First argument to xCmp() */
1001   int (*xCmp)(void*,int, const void*, int, const void*);
1002   void (*xDel)(void*);  /* Destructor for pUser */
1003 };
1004 
1005 /*
1006 ** Allowed values of CollSeq.type:
1007 */
1008 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
1009 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
1010 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
1011 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
1012 
1013 /*
1014 ** A sort order can be either ASC or DESC.
1015 */
1016 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
1017 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
1018 
1019 /*
1020 ** Column affinity types.
1021 **
1022 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
1023 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
1024 ** the speed a little by numbering the values consecutively.
1025 **
1026 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
1027 ** when multiple affinity types are concatenated into a string and
1028 ** used as the P4 operand, they will be more readable.
1029 **
1030 ** Note also that the numeric types are grouped together so that testing
1031 ** for a numeric type is a single comparison.
1032 */
1033 #define SQLITE_AFF_TEXT     'a'
1034 #define SQLITE_AFF_NONE     'b'
1035 #define SQLITE_AFF_NUMERIC  'c'
1036 #define SQLITE_AFF_INTEGER  'd'
1037 #define SQLITE_AFF_REAL     'e'
1038 
1039 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
1040 
1041 /*
1042 ** The SQLITE_AFF_MASK values masks off the significant bits of an
1043 ** affinity value.
1044 */
1045 #define SQLITE_AFF_MASK     0x67
1046 
1047 /*
1048 ** Additional bit values that can be ORed with an affinity without
1049 ** changing the affinity.
1050 */
1051 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
1052 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
1053 
1054 /*
1055 ** Each SQL table is represented in memory by an instance of the
1056 ** following structure.
1057 **
1058 ** Table.zName is the name of the table.  The case of the original
1059 ** CREATE TABLE statement is stored, but case is not significant for
1060 ** comparisons.
1061 **
1062 ** Table.nCol is the number of columns in this table.  Table.aCol is a
1063 ** pointer to an array of Column structures, one for each column.
1064 **
1065 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
1066 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
1067 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
1068 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
1069 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
1070 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
1071 ** the table has any PRIMARY KEY, INTEGER or otherwise.
1072 **
1073 ** Table.tnum is the page number for the root BTree page of the table in the
1074 ** database file.  If Table.iDb is the index of the database table backend
1075 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
1076 ** holds temporary tables and indices.  If TF_Ephemeral is set
1077 ** then the table is stored in a file that is automatically deleted
1078 ** when the VDBE cursor to the table is closed.  In this case Table.tnum
1079 ** refers VDBE cursor number that holds the table open, not to the root
1080 ** page number.  Transient tables are used to hold the results of a
1081 ** sub-query that appears instead of a real table name in the FROM clause
1082 ** of a SELECT statement.
1083 */
1084 struct Table {
1085   sqlite3 *db;         /* Associated database connection.  Might be NULL. */
1086   char *zName;         /* Name of the table or view */
1087   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
1088   int nCol;            /* Number of columns in this table */
1089   Column *aCol;        /* Information about each column */
1090   Index *pIndex;       /* List of SQL indexes on this table. */
1091   int tnum;            /* Root BTree node for this table (see note above) */
1092   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
1093   u16 nRef;            /* Number of pointers to this Table */
1094   u8 tabFlags;         /* Mask of TF_* values */
1095   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
1096   FKey *pFKey;         /* Linked list of all foreign keys in this table */
1097   char *zColAff;       /* String defining the affinity of each column */
1098 #ifndef SQLITE_OMIT_CHECK
1099   Expr *pCheck;        /* The AND of all CHECK constraints */
1100 #endif
1101 #ifndef SQLITE_OMIT_ALTERTABLE
1102   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
1103 #endif
1104 #ifndef SQLITE_OMIT_VIRTUALTABLE
1105   Module *pMod;        /* Pointer to the implementation of the module */
1106   sqlite3_vtab *pVtab; /* Pointer to the module instance */
1107   int nModuleArg;      /* Number of arguments to the module */
1108   char **azModuleArg;  /* Text of all module args. [0] is module name */
1109 #endif
1110   Trigger *pTrigger;   /* List of triggers stored in pSchema */
1111   Schema *pSchema;     /* Schema that contains this table */
1112   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
1113 };
1114 
1115 /*
1116 ** Allowed values for Tabe.tabFlags.
1117 */
1118 #define TF_Readonly        0x01    /* Read-only system table */
1119 #define TF_Ephemeral       0x02    /* An ephemeral table */
1120 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
1121 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
1122 #define TF_Virtual         0x10    /* Is a virtual table */
1123 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
1124 
1125 
1126 
1127 /*
1128 ** Test to see whether or not a table is a virtual table.  This is
1129 ** done as a macro so that it will be optimized out when virtual
1130 ** table support is omitted from the build.
1131 */
1132 #ifndef SQLITE_OMIT_VIRTUALTABLE
1133 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
1134 #  define IsHiddenColumn(X) ((X)->isHidden)
1135 #else
1136 #  define IsVirtual(X)      0
1137 #  define IsHiddenColumn(X) 0
1138 #endif
1139 
1140 /*
1141 ** Each foreign key constraint is an instance of the following structure.
1142 **
1143 ** A foreign key is associated with two tables.  The "from" table is
1144 ** the table that contains the REFERENCES clause that creates the foreign
1145 ** key.  The "to" table is the table that is named in the REFERENCES clause.
1146 ** Consider this example:
1147 **
1148 **     CREATE TABLE ex1(
1149 **       a INTEGER PRIMARY KEY,
1150 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
1151 **     );
1152 **
1153 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
1154 **
1155 ** Each REFERENCES clause generates an instance of the following structure
1156 ** which is attached to the from-table.  The to-table need not exist when
1157 ** the from-table is created.  The existence of the to-table is not checked
1158 ** until an attempt is made to insert data into the from-table.
1159 **
1160 ** The sqlite.aFKey hash table stores pointers to this structure
1161 ** given the name of a to-table.  For each to-table, all foreign keys
1162 ** associated with that table are on a linked list using the FKey.pNextTo
1163 ** field.
1164 */
1165 struct FKey {
1166   Table *pFrom;     /* The table that contains the REFERENCES clause */
1167   FKey *pNextFrom;  /* Next foreign key in pFrom */
1168   char *zTo;        /* Name of table that the key points to */
1169   FKey *pNextTo;    /* Next foreign key that points to zTo */
1170   int nCol;         /* Number of columns in this key */
1171   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
1172     int iFrom;         /* Index of column in pFrom */
1173     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
1174   } *aCol;          /* One entry for each of nCol column s */
1175   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
1176   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
1177   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
1178   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
1179 };
1180 
1181 /*
1182 ** SQLite supports many different ways to resolve a constraint
1183 ** error.  ROLLBACK processing means that a constraint violation
1184 ** causes the operation in process to fail and for the current transaction
1185 ** to be rolled back.  ABORT processing means the operation in process
1186 ** fails and any prior changes from that one operation are backed out,
1187 ** but the transaction is not rolled back.  FAIL processing means that
1188 ** the operation in progress stops and returns an error code.  But prior
1189 ** changes due to the same operation are not backed out and no rollback
1190 ** occurs.  IGNORE means that the particular row that caused the constraint
1191 ** error is not inserted or updated.  Processing continues and no error
1192 ** is returned.  REPLACE means that preexisting database rows that caused
1193 ** a UNIQUE constraint violation are removed so that the new insert or
1194 ** update can proceed.  Processing continues and no error is reported.
1195 **
1196 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
1197 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
1198 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
1199 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
1200 ** referenced table row is propagated into the row that holds the
1201 ** foreign key.
1202 **
1203 ** The following symbolic values are used to record which type
1204 ** of action to take.
1205 */
1206 #define OE_None     0   /* There is no constraint to check */
1207 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
1208 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
1209 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
1210 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
1211 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
1212 
1213 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
1214 #define OE_SetNull  7   /* Set the foreign key value to NULL */
1215 #define OE_SetDflt  8   /* Set the foreign key value to its default */
1216 #define OE_Cascade  9   /* Cascade the changes */
1217 
1218 #define OE_Default  99  /* Do whatever the default action is */
1219 
1220 
1221 /*
1222 ** An instance of the following structure is passed as the first
1223 ** argument to sqlite3VdbeKeyCompare and is used to control the
1224 ** comparison of the two index keys.
1225 */
1226 struct KeyInfo {
1227   sqlite3 *db;        /* The database connection */
1228   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
1229   u16 nField;         /* Number of entries in aColl[] */
1230   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
1231   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
1232 };
1233 
1234 /*
1235 ** An instance of the following structure holds information about a
1236 ** single index record that has already been parsed out into individual
1237 ** values.
1238 **
1239 ** A record is an object that contains one or more fields of data.
1240 ** Records are used to store the content of a table row and to store
1241 ** the key of an index.  A blob encoding of a record is created by
1242 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
1243 ** OP_Column opcode.
1244 **
1245 ** This structure holds a record that has already been disassembled
1246 ** into its constituent fields.
1247 */
1248 struct UnpackedRecord {
1249   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
1250   u16 nField;         /* Number of entries in apMem[] */
1251   u16 flags;          /* Boolean settings.  UNPACKED_... below */
1252   Mem *aMem;          /* Values */
1253 };
1254 
1255 /*
1256 ** Allowed values of UnpackedRecord.flags
1257 */
1258 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
1259 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
1260 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
1261 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
1262 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
1263 
1264 /*
1265 ** Each SQL index is represented in memory by an
1266 ** instance of the following structure.
1267 **
1268 ** The columns of the table that are to be indexed are described
1269 ** by the aiColumn[] field of this structure.  For example, suppose
1270 ** we have the following table and index:
1271 **
1272 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
1273 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
1274 **
1275 ** In the Table structure describing Ex1, nCol==3 because there are
1276 ** three columns in the table.  In the Index structure describing
1277 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
1278 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
1279 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
1280 ** The second column to be indexed (c1) has an index of 0 in
1281 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
1282 **
1283 ** The Index.onError field determines whether or not the indexed columns
1284 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
1285 ** it means this is not a unique index.  Otherwise it is a unique index
1286 ** and the value of Index.onError indicate the which conflict resolution
1287 ** algorithm to employ whenever an attempt is made to insert a non-unique
1288 ** element.
1289 */
1290 struct Index {
1291   char *zName;     /* Name of this index */
1292   int nColumn;     /* Number of columns in the table used by this index */
1293   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
1294   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
1295   Table *pTable;   /* The SQL table being indexed */
1296   int tnum;        /* Page containing root of this index in database file */
1297   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
1298   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
1299   char *zColAff;   /* String defining the affinity of each column */
1300   Index *pNext;    /* The next index associated with the same table */
1301   Schema *pSchema; /* Schema containing this index */
1302   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
1303   char **azColl;   /* Array of collation sequence names for index */
1304 };
1305 
1306 /*
1307 ** Each token coming out of the lexer is an instance of
1308 ** this structure.  Tokens are also used as part of an expression.
1309 **
1310 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
1311 ** may contain random values.  Do not make any assumptions about Token.dyn
1312 ** and Token.n when Token.z==0.
1313 */
1314 struct Token {
1315   const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
1316   unsigned dyn  : 1;      /* True for malloced memory, false for static */
1317   unsigned n    : 31;     /* Number of characters in this token */
1318 };
1319 
1320 /*
1321 ** An instance of this structure contains information needed to generate
1322 ** code for a SELECT that contains aggregate functions.
1323 **
1324 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
1325 ** pointer to this structure.  The Expr.iColumn field is the index in
1326 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
1327 ** code for that node.
1328 **
1329 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
1330 ** original Select structure that describes the SELECT statement.  These
1331 ** fields do not need to be freed when deallocating the AggInfo structure.
1332 */
1333 struct AggInfo {
1334   u8 directMode;          /* Direct rendering mode means take data directly
1335                           ** from source tables rather than from accumulators */
1336   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
1337                           ** than the source table */
1338   int sortingIdx;         /* Cursor number of the sorting index */
1339   ExprList *pGroupBy;     /* The group by clause */
1340   int nSortingColumn;     /* Number of columns in the sorting index */
1341   struct AggInfo_col {    /* For each column used in source tables */
1342     Table *pTab;             /* Source table */
1343     int iTable;              /* Cursor number of the source table */
1344     int iColumn;             /* Column number within the source table */
1345     int iSorterColumn;       /* Column number in the sorting index */
1346     int iMem;                /* Memory location that acts as accumulator */
1347     Expr *pExpr;             /* The original expression */
1348   } *aCol;
1349   int nColumn;            /* Number of used entries in aCol[] */
1350   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
1351   int nAccumulator;       /* Number of columns that show through to the output.
1352                           ** Additional columns are used only as parameters to
1353                           ** aggregate functions */
1354   struct AggInfo_func {   /* For each aggregate function */
1355     Expr *pExpr;             /* Expression encoding the function */
1356     FuncDef *pFunc;          /* The aggregate function implementation */
1357     int iMem;                /* Memory location that acts as accumulator */
1358     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
1359   } *aFunc;
1360   int nFunc;              /* Number of entries in aFunc[] */
1361   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
1362 };
1363 
1364 /*
1365 ** Each node of an expression in the parse tree is an instance
1366 ** of this structure.
1367 **
1368 ** Expr.op is the opcode. The integer parser token codes are reused
1369 ** as opcodes here. For example, the parser defines TK_GE to be an integer
1370 ** code representing the ">=" operator. This same integer code is reused
1371 ** to represent the greater-than-or-equal-to operator in the expression
1372 ** tree.
1373 **
1374 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
1375 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
1376 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
1377 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
1378 ** then Expr.token contains the name of the function.
1379 **
1380 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
1381 ** binary operator. Either or both may be NULL.
1382 **
1383 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
1384 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
1385 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
1386 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
1387 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
1388 ** valid.
1389 **
1390 ** An expression of the form ID or ID.ID refers to a column in a table.
1391 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
1392 ** the integer cursor number of a VDBE cursor pointing to that table and
1393 ** Expr.iColumn is the column number for the specific column.  If the
1394 ** expression is used as a result in an aggregate SELECT, then the
1395 ** value is also stored in the Expr.iAgg column in the aggregate so that
1396 ** it can be accessed after all aggregates are computed.
1397 **
1398 ** If the expression is an unbound variable marker (a question mark
1399 ** character '?' in the original SQL) then the Expr.iTable holds the index
1400 ** number for that variable.
1401 **
1402 ** If the expression is a subquery then Expr.iColumn holds an integer
1403 ** register number containing the result of the subquery.  If the
1404 ** subquery gives a constant result, then iTable is -1.  If the subquery
1405 ** gives a different answer at different times during statement processing
1406 ** then iTable is the address of a subroutine that computes the subquery.
1407 **
1408 ** If the Expr is of type OP_Column, and the table it is selecting from
1409 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
1410 ** corresponding table definition.
1411 **
1412 ** ALLOCATION NOTES:
1413 **
1414 ** Expr structures may be stored as part of the in-memory database schema,
1415 ** for example as part of trigger, view or table definitions. In this case,
1416 ** the amount of memory consumed by complex expressions may be significant.
1417 ** For this reason, less than sizeof(Expr) bytes may be allocated for some
1418 ** Expr structs stored as part of the in-memory database schema.
1419 **
1420 ** If the EP_Reduced flag is set in Expr.flags, then only EXPR_REDUCEDSIZE
1421 ** bytes of space are allocated for the expression structure. This is enough
1422 ** space to store all fields up to and including the "Token span;" field.
1423 **
1424 ** If the EP_TokenOnly flag is set in Expr.flags, then only EXPR_TOKENONLYSIZE
1425 ** bytes of space are allocated for the expression structure. This is enough
1426 ** space to store all fields up to and including the "Token token;" field.
1427 */
1428 struct Expr {
1429   u8 op;                 /* Operation performed by this node */
1430   char affinity;         /* The affinity of the column or 0 if not a column */
1431   u16 flags;             /* Various flags.  See below */
1432   Token token;           /* An operand token */
1433 
1434   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
1435   ** space is allocated for the fields below this point. An attempt to
1436   ** access them will result in a segfault or malfunction.
1437   *********************************************************************/
1438 
1439   Token span;            /* Complete text of the expression */
1440 
1441   /* If the EP_SpanOnly flag is set in the Expr.flags mask, then no
1442   ** space is allocated for the fields below this point. An attempt to
1443   ** access them will result in a segfault or malfunction.
1444   *********************************************************************/
1445 
1446   Expr *pLeft;           /* Left subnode */
1447   Expr *pRight;          /* Right subnode */
1448   union {
1449     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
1450     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
1451   } x;
1452   CollSeq *pColl;        /* The collation type of the column or 0 */
1453 
1454   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
1455   ** space is allocated for the fields below this point. An attempt to
1456   ** access them will result in a segfault or malfunction.
1457   *********************************************************************/
1458 
1459   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
1460                          ** iColumn-th field of the iTable-th table. */
1461   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
1462   int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
1463   int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
1464   Table *pTab;           /* Table for TK_COLUMN expressions. */
1465 #if SQLITE_MAX_EXPR_DEPTH>0
1466   int nHeight;           /* Height of the tree headed by this node */
1467 #endif
1468 };
1469 
1470 /*
1471 ** The following are the meanings of bits in the Expr.flags field.
1472 */
1473 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
1474 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
1475 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
1476 #define EP_Error      0x0008  /* Expression contains one or more errors */
1477 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
1478 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
1479 #define EP_Dequoted   0x0040  /* True if the string has been dequoted */
1480 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
1481 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
1482 #define EP_AnyAff     0x0200  /* Can take a cached column of any affinity */
1483 #define EP_FixedDest  0x0400  /* Result needed in a specific register */
1484 #define EP_IntValue   0x0800  /* Integer value contained in iTable */
1485 #define EP_xIsSelect  0x1000  /* x.pSelect is valid (otherwise x.pList is) */
1486 
1487 #define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
1488 #define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
1489 #define EP_SpanOnly   0x8000  /* Expr struct is EXPR_SPANONLYSIZE bytes only */
1490 
1491 /*
1492 ** These macros can be used to test, set, or clear bits in the
1493 ** Expr.flags field.
1494 */
1495 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
1496 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
1497 #define ExprSetProperty(E,P)     (E)->flags|=(P)
1498 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
1499 
1500 /*
1501 ** Macros to determine the number of bytes required by a normal Expr
1502 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
1503 ** and an Expr struct with the EP_TokenOnly flag set.
1504 */
1505 #define EXPR_FULLSIZE           sizeof(Expr)
1506 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)
1507 #define EXPR_TOKENONLYSIZE      offsetof(Expr,span)
1508 #define EXPR_SPANONLYSIZE       offsetof(Expr,pLeft)
1509 
1510 /*
1511 ** Flags passed to the sqlite3ExprDup() function. See the header comment
1512 ** above sqlite3ExprDup() for details.
1513 */
1514 #define EXPRDUP_REDUCE 0x0001
1515 #define EXPRDUP_SPAN   0x0002
1516 
1517 /*
1518 ** A list of expressions.  Each expression may optionally have a
1519 ** name.  An expr/name combination can be used in several ways, such
1520 ** as the list of "expr AS ID" fields following a "SELECT" or in the
1521 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
1522 ** also be used as the argument to a function, in which case the a.zName
1523 ** field is not used.
1524 */
1525 struct ExprList {
1526   int nExpr;             /* Number of expressions on the list */
1527   int nAlloc;            /* Number of entries allocated below */
1528   int iECursor;          /* VDBE Cursor associated with this ExprList */
1529   struct ExprList_item {
1530     Expr *pExpr;           /* The list of expressions */
1531     char *zName;           /* Token associated with this expression */
1532     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
1533     u8 done;               /* A flag to indicate when processing is finished */
1534     u16 iCol;              /* For ORDER BY, column number in result set */
1535     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
1536   } *a;                  /* One entry for each expression */
1537 };
1538 
1539 /*
1540 ** An instance of this structure can hold a simple list of identifiers,
1541 ** such as the list "a,b,c" in the following statements:
1542 **
1543 **      INSERT INTO t(a,b,c) VALUES ...;
1544 **      CREATE INDEX idx ON t(a,b,c);
1545 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
1546 **
1547 ** The IdList.a.idx field is used when the IdList represents the list of
1548 ** column names after a table name in an INSERT statement.  In the statement
1549 **
1550 **     INSERT INTO t(a,b,c) ...
1551 **
1552 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
1553 */
1554 struct IdList {
1555   struct IdList_item {
1556     char *zName;      /* Name of the identifier */
1557     int idx;          /* Index in some Table.aCol[] of a column named zName */
1558   } *a;
1559   int nId;         /* Number of identifiers on the list */
1560   int nAlloc;      /* Number of entries allocated for a[] below */
1561 };
1562 
1563 /*
1564 ** The bitmask datatype defined below is used for various optimizations.
1565 **
1566 ** Changing this from a 64-bit to a 32-bit type limits the number of
1567 ** tables in a join to 32 instead of 64.  But it also reduces the size
1568 ** of the library by 738 bytes on ix86.
1569 */
1570 typedef u64 Bitmask;
1571 
1572 /*
1573 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
1574 */
1575 #define BMS  ((int)(sizeof(Bitmask)*8))
1576 
1577 /*
1578 ** The following structure describes the FROM clause of a SELECT statement.
1579 ** Each table or subquery in the FROM clause is a separate element of
1580 ** the SrcList.a[] array.
1581 **
1582 ** With the addition of multiple database support, the following structure
1583 ** can also be used to describe a particular table such as the table that
1584 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
1585 ** such a table must be a simple name: ID.  But in SQLite, the table can
1586 ** now be identified by a database name, a dot, then the table name: ID.ID.
1587 **
1588 ** The jointype starts out showing the join type between the current table
1589 ** and the next table on the list.  The parser builds the list this way.
1590 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
1591 ** jointype expresses the join between the table and the previous table.
1592 */
1593 struct SrcList {
1594   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
1595   i16 nAlloc;      /* Number of entries allocated in a[] below */
1596   struct SrcList_item {
1597     char *zDatabase;  /* Name of database holding this table */
1598     char *zName;      /* Name of the table */
1599     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
1600     Table *pTab;      /* An SQL table corresponding to zName */
1601     Select *pSelect;  /* A SELECT statement used in place of a table name */
1602     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
1603     u8 jointype;      /* Type of join between this able and the previous */
1604     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
1605     int iCursor;      /* The VDBE cursor number used to access this table */
1606     Expr *pOn;        /* The ON clause of a join */
1607     IdList *pUsing;   /* The USING clause of a join */
1608     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
1609     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
1610     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
1611   } a[1];             /* One entry for each identifier on the list */
1612 };
1613 
1614 /*
1615 ** Permitted values of the SrcList.a.jointype field
1616 */
1617 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
1618 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
1619 #define JT_NATURAL   0x0004    /* True for a "natural" join */
1620 #define JT_LEFT      0x0008    /* Left outer join */
1621 #define JT_RIGHT     0x0010    /* Right outer join */
1622 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
1623 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
1624 
1625 
1626 /*
1627 ** A WherePlan object holds information that describes a lookup
1628 ** strategy.
1629 **
1630 ** This object is intended to be opaque outside of the where.c module.
1631 ** It is included here only so that that compiler will know how big it
1632 ** is.  None of the fields in this object should be used outside of
1633 ** the where.c module.
1634 **
1635 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
1636 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
1637 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
1638 ** case that more than one of these conditions is true.
1639 */
1640 struct WherePlan {
1641   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
1642   u32 nEq;                       /* Number of == constraints */
1643   union {
1644     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
1645     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
1646     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
1647   } u;
1648 };
1649 
1650 /*
1651 ** For each nested loop in a WHERE clause implementation, the WhereInfo
1652 ** structure contains a single instance of this structure.  This structure
1653 ** is intended to be private the the where.c module and should not be
1654 ** access or modified by other modules.
1655 **
1656 ** The pIdxInfo field is used to help pick the best index on a
1657 ** virtual table.  The pIdxInfo pointer contains indexing
1658 ** information for the i-th table in the FROM clause before reordering.
1659 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
1660 ** All other information in the i-th WhereLevel object for the i-th table
1661 ** after FROM clause ordering.
1662 */
1663 struct WhereLevel {
1664   WherePlan plan;       /* query plan for this element of the FROM clause */
1665   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
1666   int iTabCur;          /* The VDBE cursor used to access the table */
1667   int iIdxCur;          /* The VDBE cursor used to access pIdx */
1668   int addrBrk;          /* Jump here to break out of the loop */
1669   int addrNxt;          /* Jump here to start the next IN combination */
1670   int addrCont;         /* Jump here to continue with the next loop cycle */
1671   int addrFirst;        /* First instruction of interior of the loop */
1672   u8 iFrom;             /* Which entry in the FROM clause */
1673   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
1674   int p1, p2;           /* Operands of the opcode used to ends the loop */
1675   union {               /* Information that depends on plan.wsFlags */
1676     struct {
1677       int nIn;              /* Number of entries in aInLoop[] */
1678       struct InLoop {
1679         int iCur;              /* The VDBE cursor used by this IN operator */
1680         int addrInTop;         /* Top of the IN loop */
1681       } *aInLoop;           /* Information about each nested IN operator */
1682     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
1683   } u;
1684 
1685   /* The following field is really not part of the current level.  But
1686   ** we need a place to cache virtual table index information for each
1687   ** virtual table in the FROM clause and the WhereLevel structure is
1688   ** a convenient place since there is one WhereLevel for each FROM clause
1689   ** element.
1690   */
1691   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
1692 };
1693 
1694 /*
1695 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin().
1696 */
1697 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
1698 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
1699 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
1700 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
1701 #define WHERE_FILL_ROWSET      0x0008  /* Save results in a RowSet object */
1702 #define WHERE_OMIT_OPEN        0x0010  /* Table cursor are already open */
1703 #define WHERE_OMIT_CLOSE       0x0020  /* Omit close of table & index cursors */
1704 
1705 /*
1706 ** The WHERE clause processing routine has two halves.  The
1707 ** first part does the start of the WHERE loop and the second
1708 ** half does the tail of the WHERE loop.  An instance of
1709 ** this structure is returned by the first half and passed
1710 ** into the second half to give some continuity.
1711 */
1712 struct WhereInfo {
1713   Parse *pParse;       /* Parsing and code generating context */
1714   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
1715   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
1716   int regRowSet;                 /* Store rowids in this rowset if >=0 */
1717   SrcList *pTabList;             /* List of tables in the join */
1718   int iTop;                      /* The very beginning of the WHERE loop */
1719   int iContinue;                 /* Jump here to continue with next record */
1720   int iBreak;                    /* Jump here to break out of the loop */
1721   int nLevel;                    /* Number of nested loop */
1722   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
1723   WhereLevel a[1];               /* Information about each nest loop in WHERE */
1724 };
1725 
1726 /*
1727 ** A NameContext defines a context in which to resolve table and column
1728 ** names.  The context consists of a list of tables (the pSrcList) field and
1729 ** a list of named expression (pEList).  The named expression list may
1730 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
1731 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
1732 ** pEList corresponds to the result set of a SELECT and is NULL for
1733 ** other statements.
1734 **
1735 ** NameContexts can be nested.  When resolving names, the inner-most
1736 ** context is searched first.  If no match is found, the next outer
1737 ** context is checked.  If there is still no match, the next context
1738 ** is checked.  This process continues until either a match is found
1739 ** or all contexts are check.  When a match is found, the nRef member of
1740 ** the context containing the match is incremented.
1741 **
1742 ** Each subquery gets a new NameContext.  The pNext field points to the
1743 ** NameContext in the parent query.  Thus the process of scanning the
1744 ** NameContext list corresponds to searching through successively outer
1745 ** subqueries looking for a match.
1746 */
1747 struct NameContext {
1748   Parse *pParse;       /* The parser */
1749   SrcList *pSrcList;   /* One or more tables used to resolve names */
1750   ExprList *pEList;    /* Optional list of named expressions */
1751   int nRef;            /* Number of names resolved by this context */
1752   int nErr;            /* Number of errors encountered while resolving names */
1753   u8 allowAgg;         /* Aggregate functions allowed here */
1754   u8 hasAgg;           /* True if aggregates are seen */
1755   u8 isCheck;          /* True if resolving names in a CHECK constraint */
1756   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
1757   AggInfo *pAggInfo;   /* Information about aggregates at this level */
1758   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
1759 };
1760 
1761 /*
1762 ** An instance of the following structure contains all information
1763 ** needed to generate code for a single SELECT statement.
1764 **
1765 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
1766 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
1767 ** limit and nOffset to the value of the offset (or 0 if there is not
1768 ** offset).  But later on, nLimit and nOffset become the memory locations
1769 ** in the VDBE that record the limit and offset counters.
1770 **
1771 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
1772 ** These addresses must be stored so that we can go back and fill in
1773 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
1774 ** the number of columns in P2 can be computed at the same time
1775 ** as the OP_OpenEphm instruction is coded because not
1776 ** enough information about the compound query is known at that point.
1777 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
1778 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
1779 ** sequences for the ORDER BY clause.
1780 */
1781 struct Select {
1782   ExprList *pEList;      /* The fields of the result */
1783   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
1784   char affinity;         /* MakeRecord with this affinity for SRT_Set */
1785   u16 selFlags;          /* Various SF_* values */
1786   SrcList *pSrc;         /* The FROM clause */
1787   Expr *pWhere;          /* The WHERE clause */
1788   ExprList *pGroupBy;    /* The GROUP BY clause */
1789   Expr *pHaving;         /* The HAVING clause */
1790   ExprList *pOrderBy;    /* The ORDER BY clause */
1791   Select *pPrior;        /* Prior select in a compound select statement */
1792   Select *pNext;         /* Next select to the left in a compound */
1793   Select *pRightmost;    /* Right-most select in a compound select statement */
1794   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
1795   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
1796   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
1797   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
1798 };
1799 
1800 /*
1801 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
1802 ** "Select Flag".
1803 */
1804 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
1805 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
1806 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
1807 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
1808 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
1809 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
1810 
1811 
1812 /*
1813 ** The results of a select can be distributed in several ways.  The
1814 ** "SRT" prefix means "SELECT Result Type".
1815 */
1816 #define SRT_Union        1  /* Store result as keys in an index */
1817 #define SRT_Except       2  /* Remove result from a UNION index */
1818 #define SRT_Exists       3  /* Store 1 if the result is not empty */
1819 #define SRT_Discard      4  /* Do not save the results anywhere */
1820 
1821 /* The ORDER BY clause is ignored for all of the above */
1822 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
1823 
1824 #define SRT_Output       5  /* Output each row of result */
1825 #define SRT_Mem          6  /* Store result in a memory cell */
1826 #define SRT_Set          7  /* Store results as keys in an index */
1827 #define SRT_Table        8  /* Store result as data with an automatic rowid */
1828 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
1829 #define SRT_Coroutine   10  /* Generate a single row of result */
1830 
1831 /*
1832 ** A structure used to customize the behavior of sqlite3Select(). See
1833 ** comments above sqlite3Select() for details.
1834 */
1835 typedef struct SelectDest SelectDest;
1836 struct SelectDest {
1837   u8 eDest;         /* How to dispose of the results */
1838   u8 affinity;      /* Affinity used when eDest==SRT_Set */
1839   int iParm;        /* A parameter used by the eDest disposal method */
1840   int iMem;         /* Base register where results are written */
1841   int nMem;         /* Number of registers allocated */
1842 };
1843 
1844 /*
1845 ** An SQL parser context.  A copy of this structure is passed through
1846 ** the parser and down into all the parser action routine in order to
1847 ** carry around information that is global to the entire parse.
1848 **
1849 ** The structure is divided into two parts.  When the parser and code
1850 ** generate call themselves recursively, the first part of the structure
1851 ** is constant but the second part is reset at the beginning and end of
1852 ** each recursion.
1853 **
1854 ** The nTableLock and aTableLock variables are only used if the shared-cache
1855 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
1856 ** used to store the set of table-locks required by the statement being
1857 ** compiled. Function sqlite3TableLock() is used to add entries to the
1858 ** list.
1859 */
1860 struct Parse {
1861   sqlite3 *db;         /* The main database structure */
1862   int rc;              /* Return code from execution */
1863   char *zErrMsg;       /* An error message */
1864   Vdbe *pVdbe;         /* An engine for executing database bytecode */
1865   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
1866   u8 nameClash;        /* A permanent table name clashes with temp table name */
1867   u8 checkSchema;      /* Causes schema cookie check after an error */
1868   u8 nested;           /* Number of nested calls to the parser/code generator */
1869   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
1870   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
1871   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
1872   int aTempReg[8];     /* Holding area for temporary registers */
1873   int nRangeReg;       /* Size of the temporary register block */
1874   int iRangeReg;       /* First register in temporary register block */
1875   int nErr;            /* Number of errors seen */
1876   int nTab;            /* Number of previously allocated VDBE cursors */
1877   int nMem;            /* Number of memory cells used so far */
1878   int nSet;            /* Number of sets used so far */
1879   int ckBase;          /* Base register of data during check constraints */
1880   int disableColCache; /* True to disable adding to column cache */
1881   int nColCache;       /* Number of entries in the column cache */
1882   int iColCache;       /* Next entry of the cache to replace */
1883   struct yColCache {
1884     int iTable;           /* Table cursor number */
1885     int iColumn;          /* Table column number */
1886     char affChange;       /* True if this register has had an affinity change */
1887     int iReg;             /* Register holding value of this column */
1888   } aColCache[10];     /* One for each valid column cache entry */
1889   u32 writeMask;       /* Start a write transaction on these databases */
1890   u32 cookieMask;      /* Bitmask of schema verified databases */
1891   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
1892   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
1893 #ifndef SQLITE_OMIT_SHARED_CACHE
1894   int nTableLock;        /* Number of locks in aTableLock */
1895   TableLock *aTableLock; /* Required table locks for shared-cache mode */
1896 #endif
1897   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
1898   int regRoot;         /* Register holding root page number for new objects */
1899 
1900   /* Above is constant between recursions.  Below is reset before and after
1901   ** each recursion */
1902 
1903   int nVar;            /* Number of '?' variables seen in the SQL so far */
1904   int nVarExpr;        /* Number of used slots in apVarExpr[] */
1905   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
1906   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
1907   int nAlias;          /* Number of aliased result set columns */
1908   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
1909   int *aAlias;         /* Register used to hold aliased result */
1910   u8 explain;          /* True if the EXPLAIN flag is found on the query */
1911   Token sErrToken;     /* The token at which the error occurred */
1912   Token sNameToken;    /* Token with unqualified schema object name */
1913   Token sLastToken;    /* The last token parsed */
1914   const char *zSql;    /* All SQL text */
1915   const char *zTail;   /* All SQL text past the last semicolon parsed */
1916   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
1917   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
1918   TriggerStack *trigStack;  /* Trigger actions being coded */
1919   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
1920 #ifndef SQLITE_OMIT_VIRTUALTABLE
1921   Token sArg;                /* Complete text of a module argument */
1922   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
1923   int nVtabLock;             /* Number of virtual tables to lock */
1924   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
1925 #endif
1926   int nHeight;            /* Expression tree height of current sub-select */
1927   Table *pZombieTab;      /* List of Table objects to delete after code gen */
1928 };
1929 
1930 #ifdef SQLITE_OMIT_VIRTUALTABLE
1931   #define IN_DECLARE_VTAB 0
1932 #else
1933   #define IN_DECLARE_VTAB (pParse->declareVtab)
1934 #endif
1935 
1936 /*
1937 ** An instance of the following structure can be declared on a stack and used
1938 ** to save the Parse.zAuthContext value so that it can be restored later.
1939 */
1940 struct AuthContext {
1941   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
1942   Parse *pParse;              /* The Parse structure */
1943 };
1944 
1945 /*
1946 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
1947 */
1948 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
1949 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
1950 #define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
1951 #define OPFLAG_APPEND    8    /* This is likely to be an append */
1952 
1953 /*
1954  * Each trigger present in the database schema is stored as an instance of
1955  * struct Trigger.
1956  *
1957  * Pointers to instances of struct Trigger are stored in two ways.
1958  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
1959  *    database). This allows Trigger structures to be retrieved by name.
1960  * 2. All triggers associated with a single table form a linked list, using the
1961  *    pNext member of struct Trigger. A pointer to the first element of the
1962  *    linked list is stored as the "pTrigger" member of the associated
1963  *    struct Table.
1964  *
1965  * The "step_list" member points to the first element of a linked list
1966  * containing the SQL statements specified as the trigger program.
1967  */
1968 struct Trigger {
1969   char *name;             /* The name of the trigger                        */
1970   char *table;            /* The table or view to which the trigger applies */
1971   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
1972   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
1973   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
1974   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
1975                              the <column-list> is stored here */
1976   Token nameToken;        /* Token containing zName. Use during parsing only */
1977   Schema *pSchema;        /* Schema containing the trigger */
1978   Schema *pTabSchema;     /* Schema containing the table */
1979   TriggerStep *step_list; /* Link list of trigger program steps             */
1980   Trigger *pNext;         /* Next trigger associated with the table */
1981 };
1982 
1983 /*
1984 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
1985 ** determine which.
1986 **
1987 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
1988 ** In that cases, the constants below can be ORed together.
1989 */
1990 #define TRIGGER_BEFORE  1
1991 #define TRIGGER_AFTER   2
1992 
1993 /*
1994  * An instance of struct TriggerStep is used to store a single SQL statement
1995  * that is a part of a trigger-program.
1996  *
1997  * Instances of struct TriggerStep are stored in a singly linked list (linked
1998  * using the "pNext" member) referenced by the "step_list" member of the
1999  * associated struct Trigger instance. The first element of the linked list is
2000  * the first step of the trigger-program.
2001  *
2002  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
2003  * "SELECT" statement. The meanings of the other members is determined by the
2004  * value of "op" as follows:
2005  *
2006  * (op == TK_INSERT)
2007  * orconf    -> stores the ON CONFLICT algorithm
2008  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
2009  *              this stores a pointer to the SELECT statement. Otherwise NULL.
2010  * target    -> A token holding the name of the table to insert into.
2011  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
2012  *              this stores values to be inserted. Otherwise NULL.
2013  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
2014  *              statement, then this stores the column-names to be
2015  *              inserted into.
2016  *
2017  * (op == TK_DELETE)
2018  * target    -> A token holding the name of the table to delete from.
2019  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
2020  *              Otherwise NULL.
2021  *
2022  * (op == TK_UPDATE)
2023  * target    -> A token holding the name of the table to update rows of.
2024  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
2025  *              Otherwise NULL.
2026  * pExprList -> A list of the columns to update and the expressions to update
2027  *              them to. See sqlite3Update() documentation of "pChanges"
2028  *              argument.
2029  *
2030  */
2031 struct TriggerStep {
2032   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
2033   int orconf;          /* OE_Rollback etc. */
2034   Trigger *pTrig;      /* The trigger that this step is a part of */
2035 
2036   Select *pSelect;     /* Valid for SELECT and sometimes
2037                           INSERT steps (when pExprList == 0) */
2038   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
2039   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
2040   ExprList *pExprList; /* Valid for UPDATE statements and sometimes
2041                            INSERT steps (when pSelect == 0)         */
2042   IdList *pIdList;     /* Valid for INSERT statements only */
2043   TriggerStep *pNext;  /* Next in the link-list */
2044   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
2045 };
2046 
2047 /*
2048  * An instance of struct TriggerStack stores information required during code
2049  * generation of a single trigger program. While the trigger program is being
2050  * coded, its associated TriggerStack instance is pointed to by the
2051  * "pTriggerStack" member of the Parse structure.
2052  *
2053  * The pTab member points to the table that triggers are being coded on. The
2054  * newIdx member contains the index of the vdbe cursor that points at the temp
2055  * table that stores the new.* references. If new.* references are not valid
2056  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
2057  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
2058  *
2059  * The ON CONFLICT policy to be used for the trigger program steps is stored
2060  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause
2061  * specified for individual triggers steps is used.
2062  *
2063  * struct TriggerStack has a "pNext" member, to allow linked lists to be
2064  * constructed. When coding nested triggers (triggers fired by other triggers)
2065  * each nested trigger stores its parent trigger's TriggerStack as the "pNext"
2066  * pointer. Once the nested trigger has been coded, the pNext value is restored
2067  * to the pTriggerStack member of the Parse stucture and coding of the parent
2068  * trigger continues.
2069  *
2070  * Before a nested trigger is coded, the linked list pointed to by the
2071  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
2072  * recursively. If this condition is detected, the nested trigger is not coded.
2073  */
2074 struct TriggerStack {
2075   Table *pTab;         /* Table that triggers are currently being coded on */
2076   int newIdx;          /* Index of vdbe cursor to "new" temp table */
2077   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
2078   u32 newColMask;
2079   u32 oldColMask;
2080   int orconf;          /* Current orconf policy */
2081   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
2082   Trigger *pTrigger;   /* The trigger currently being coded */
2083   TriggerStack *pNext; /* Next trigger down on the trigger stack */
2084 };
2085 
2086 /*
2087 ** The following structure contains information used by the sqliteFix...
2088 ** routines as they walk the parse tree to make database references
2089 ** explicit.
2090 */
2091 typedef struct DbFixer DbFixer;
2092 struct DbFixer {
2093   Parse *pParse;      /* The parsing context.  Error messages written here */
2094   const char *zDb;    /* Make sure all objects are contained in this database */
2095   const char *zType;  /* Type of the container - used for error messages */
2096   const Token *pName; /* Name of the container - used for error messages */
2097 };
2098 
2099 /*
2100 ** An objected used to accumulate the text of a string where we
2101 ** do not necessarily know how big the string will be in the end.
2102 */
2103 struct StrAccum {
2104   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
2105   char *zBase;         /* A base allocation.  Not from malloc. */
2106   char *zText;         /* The string collected so far */
2107   int  nChar;          /* Length of the string so far */
2108   int  nAlloc;         /* Amount of space allocated in zText */
2109   int  mxAlloc;        /* Maximum allowed string length */
2110   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
2111   u8   useMalloc;      /* True if zText is enlargeable using realloc */
2112   u8   tooBig;         /* Becomes true if string size exceeds limits */
2113 };
2114 
2115 /*
2116 ** A pointer to this structure is used to communicate information
2117 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
2118 */
2119 typedef struct {
2120   sqlite3 *db;        /* The database being initialized */
2121   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
2122   char **pzErrMsg;    /* Error message stored here */
2123   int rc;             /* Result code stored here */
2124 } InitData;
2125 
2126 /*
2127 ** Structure containing global configuration data for the SQLite library.
2128 **
2129 ** This structure also contains some state information.
2130 */
2131 struct Sqlite3Config {
2132   int bMemstat;                     /* True to enable memory status */
2133   int bCoreMutex;                   /* True to enable core mutexing */
2134   int bFullMutex;                   /* True to enable full mutexing */
2135   int mxStrlen;                     /* Maximum string length */
2136   int szLookaside;                  /* Default lookaside buffer size */
2137   int nLookaside;                   /* Default lookaside buffer count */
2138   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
2139   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
2140   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
2141   void *pHeap;                      /* Heap storage space */
2142   int nHeap;                        /* Size of pHeap[] */
2143   int mnReq, mxReq;                 /* Min and max heap requests sizes */
2144   void *pScratch;                   /* Scratch memory */
2145   int szScratch;                    /* Size of each scratch buffer */
2146   int nScratch;                     /* Number of scratch buffers */
2147   void *pPage;                      /* Page cache memory */
2148   int szPage;                       /* Size of each page in pPage[] */
2149   int nPage;                        /* Number of pages in pPage[] */
2150   int mxParserStack;                /* maximum depth of the parser stack */
2151   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
2152   /* The above might be initialized to non-zero.  The following need to always
2153   ** initially be zero, however. */
2154   int isInit;                       /* True after initialization has finished */
2155   int inProgress;                   /* True while initialization in progress */
2156   int isMallocInit;                 /* True after malloc is initialized */
2157   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
2158   int nRefInitMutex;                /* Number of users of pInitMutex */
2159 };
2160 
2161 /*
2162 ** Context pointer passed down through the tree-walk.
2163 */
2164 struct Walker {
2165   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
2166   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
2167   Parse *pParse;                            /* Parser context.  */
2168   union {                                   /* Extra data for callback */
2169     NameContext *pNC;                          /* Naming context */
2170     int i;                                     /* Integer value */
2171   } u;
2172 };
2173 
2174 /* Forward declarations */
2175 int sqlite3WalkExpr(Walker*, Expr*);
2176 int sqlite3WalkExprList(Walker*, ExprList*);
2177 int sqlite3WalkSelect(Walker*, Select*);
2178 int sqlite3WalkSelectExpr(Walker*, Select*);
2179 int sqlite3WalkSelectFrom(Walker*, Select*);
2180 
2181 /*
2182 ** Return code from the parse-tree walking primitives and their
2183 ** callbacks.
2184 */
2185 #define WRC_Continue    0   /* Continue down into children */
2186 #define WRC_Prune       1   /* Omit children but continue walking siblings */
2187 #define WRC_Abort       2   /* Abandon the tree walk */
2188 
2189 /*
2190 ** Assuming zIn points to the first byte of a UTF-8 character,
2191 ** advance zIn to point to the first byte of the next UTF-8 character.
2192 */
2193 #define SQLITE_SKIP_UTF8(zIn) {                        \
2194   if( (*(zIn++))>=0xc0 ){                              \
2195     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
2196   }                                                    \
2197 }
2198 
2199 /*
2200 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
2201 ** builds) or a function call (for debugging).  If it is a function call,
2202 ** it allows the operator to set a breakpoint at the spot where database
2203 ** corruption is first detected.
2204 */
2205 #ifdef SQLITE_DEBUG
2206   int sqlite3Corrupt(void);
2207 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
2208 #else
2209 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
2210 #endif
2211 
2212 /*
2213 ** The following macros mimic the standard library functions toupper(),
2214 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
2215 ** sqlite versions only work for ASCII characters, regardless of locale.
2216 */
2217 #ifdef SQLITE_ASCII
2218 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
2219 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
2220 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
2221 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
2222 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
2223 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
2224 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
2225 #else
2226 # include <ctype.h>
2227 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
2228 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
2229 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
2230 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
2231 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
2232 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
2233 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
2234 #endif
2235 
2236 /*
2237 ** Internal function prototypes
2238 */
2239 int sqlite3StrICmp(const char *, const char *);
2240 int sqlite3StrNICmp(const char *, const char *, int);
2241 int sqlite3IsNumber(const char*, int*, u8);
2242 int sqlite3Strlen(sqlite3*, const char*);
2243 int sqlite3Strlen30(const char*);
2244 
2245 int sqlite3MallocInit(void);
2246 void sqlite3MallocEnd(void);
2247 void *sqlite3Malloc(int);
2248 void *sqlite3MallocZero(int);
2249 void *sqlite3DbMallocZero(sqlite3*, int);
2250 void *sqlite3DbMallocRaw(sqlite3*, int);
2251 char *sqlite3DbStrDup(sqlite3*,const char*);
2252 char *sqlite3DbStrNDup(sqlite3*,const char*, int);
2253 void *sqlite3Realloc(void*, int);
2254 void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
2255 void *sqlite3DbRealloc(sqlite3 *, void *, int);
2256 void sqlite3DbFree(sqlite3*, void*);
2257 int sqlite3MallocSize(void*);
2258 int sqlite3DbMallocSize(sqlite3*, void*);
2259 void *sqlite3ScratchMalloc(int);
2260 void sqlite3ScratchFree(void*);
2261 void *sqlite3PageMalloc(int);
2262 void sqlite3PageFree(void*);
2263 void sqlite3MemSetDefault(void);
2264 void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
2265 int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
2266 
2267 #ifdef SQLITE_ENABLE_MEMSYS3
2268 const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
2269 #endif
2270 #ifdef SQLITE_ENABLE_MEMSYS5
2271 const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
2272 #endif
2273 
2274 
2275 #ifndef SQLITE_MUTEX_OMIT
2276   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
2277   sqlite3_mutex *sqlite3MutexAlloc(int);
2278   int sqlite3MutexInit(void);
2279   int sqlite3MutexEnd(void);
2280 #endif
2281 
2282 int sqlite3StatusValue(int);
2283 void sqlite3StatusAdd(int, int);
2284 void sqlite3StatusSet(int, int);
2285 
2286 int sqlite3IsNaN(double);
2287 
2288 void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
2289 char *sqlite3MPrintf(sqlite3*,const char*, ...);
2290 char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
2291 char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
2292 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
2293   void sqlite3DebugPrintf(const char*, ...);
2294 #endif
2295 #if defined(SQLITE_TEST)
2296   void *sqlite3TestTextToPtr(const char*);
2297 #endif
2298 void sqlite3SetString(char **, sqlite3*, const char*, ...);
2299 void sqlite3ErrorMsg(Parse*, const char*, ...);
2300 void sqlite3ErrorClear(Parse*);
2301 void sqlite3Dequote(char*);
2302 void sqlite3DequoteExpr(sqlite3*, Expr*);
2303 int sqlite3KeywordCode(const unsigned char*, int);
2304 int sqlite3RunParser(Parse*, const char*, char **);
2305 void sqlite3FinishCoding(Parse*);
2306 int sqlite3GetTempReg(Parse*);
2307 void sqlite3ReleaseTempReg(Parse*,int);
2308 int sqlite3GetTempRange(Parse*,int);
2309 void sqlite3ReleaseTempRange(Parse*,int,int);
2310 Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
2311 Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
2312 Expr *sqlite3RegisterExpr(Parse*,Token*);
2313 Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
2314 void sqlite3ExprSpan(Expr*,Token*,Token*);
2315 Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
2316 void sqlite3ExprAssignVarNumber(Parse*, Expr*);
2317 void sqlite3ExprClear(sqlite3*, Expr*);
2318 void sqlite3ExprDelete(sqlite3*, Expr*);
2319 ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
2320 void sqlite3ExprListDelete(sqlite3*, ExprList*);
2321 int sqlite3Init(sqlite3*, char**);
2322 int sqlite3InitCallback(void*, int, char**, char**);
2323 void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
2324 void sqlite3ResetInternalSchema(sqlite3*, int);
2325 void sqlite3BeginParse(Parse*,int);
2326 void sqlite3CommitInternalChanges(sqlite3*);
2327 Table *sqlite3ResultSetOfSelect(Parse*,Select*);
2328 void sqlite3OpenMasterTable(Parse *, int);
2329 void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
2330 void sqlite3AddColumn(Parse*,Token*);
2331 void sqlite3AddNotNull(Parse*, int);
2332 void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
2333 void sqlite3AddCheckConstraint(Parse*, Expr*);
2334 void sqlite3AddColumnType(Parse*,Token*);
2335 void sqlite3AddDefaultValue(Parse*,Expr*);
2336 void sqlite3AddCollateType(Parse*, Token*);
2337 void sqlite3EndTable(Parse*,Token*,Token*,Select*);
2338 
2339 Bitvec *sqlite3BitvecCreate(u32);
2340 int sqlite3BitvecTest(Bitvec*, u32);
2341 int sqlite3BitvecSet(Bitvec*, u32);
2342 void sqlite3BitvecClear(Bitvec*, u32);
2343 void sqlite3BitvecDestroy(Bitvec*);
2344 u32 sqlite3BitvecSize(Bitvec*);
2345 int sqlite3BitvecBuiltinTest(int,int*);
2346 
2347 RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
2348 void sqlite3RowSetClear(RowSet*);
2349 void sqlite3RowSetInsert(RowSet*, i64);
2350 int sqlite3RowSetNext(RowSet*, i64*);
2351 
2352 void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
2353 
2354 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
2355   int sqlite3ViewGetColumnNames(Parse*,Table*);
2356 #else
2357 # define sqlite3ViewGetColumnNames(A,B) 0
2358 #endif
2359 
2360 void sqlite3DropTable(Parse*, SrcList*, int, int);
2361 void sqlite3DeleteTable(Table*);
2362 void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
2363 void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
2364 IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
2365 int sqlite3IdListIndex(IdList*,const char*);
2366 SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
2367 SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
2368 SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
2369                                       Token*, Select*, Expr*, IdList*);
2370 void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
2371 int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
2372 void sqlite3SrcListShiftJoinType(SrcList*);
2373 void sqlite3SrcListAssignCursors(Parse*, SrcList*);
2374 void sqlite3IdListDelete(sqlite3*, IdList*);
2375 void sqlite3SrcListDelete(sqlite3*, SrcList*);
2376 void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
2377                         Token*, int, int);
2378 void sqlite3DropIndex(Parse*, SrcList*, int);
2379 int sqlite3Select(Parse*, Select*, SelectDest*);
2380 Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
2381                          Expr*,ExprList*,int,Expr*,Expr*);
2382 void sqlite3SelectDelete(sqlite3*, Select*);
2383 Table *sqlite3SrcListLookup(Parse*, SrcList*);
2384 int sqlite3IsReadOnly(Parse*, Table*, int);
2385 void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
2386 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
2387 Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
2388 #endif
2389 void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
2390 void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
2391 WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8, int);
2392 void sqlite3WhereEnd(WhereInfo*);
2393 int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
2394 void sqlite3ExprCodeMove(Parse*, int, int, int);
2395 void sqlite3ExprCodeCopy(Parse*, int, int, int);
2396 void sqlite3ExprClearColumnCache(Parse*, int);
2397 void sqlite3ExprCacheAffinityChange(Parse*, int, int);
2398 void sqlite3ExprWritableRegister(Parse*,int);
2399 void sqlite3ExprHardCopy(Parse*,int,int);
2400 int sqlite3ExprCode(Parse*, Expr*, int);
2401 int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
2402 int sqlite3ExprCodeTarget(Parse*, Expr*, int);
2403 int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
2404 void sqlite3ExprCodeConstants(Parse*, Expr*);
2405 int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
2406 void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
2407 void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
2408 Table *sqlite3FindTable(sqlite3*,const char*, const char*);
2409 Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
2410 Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
2411 void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
2412 void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
2413 void sqlite3Vacuum(Parse*);
2414 int sqlite3RunVacuum(char**, sqlite3*);
2415 char *sqlite3NameFromToken(sqlite3*, Token*);
2416 int sqlite3ExprCompare(Expr*, Expr*);
2417 void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
2418 void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
2419 Vdbe *sqlite3GetVdbe(Parse*);
2420 Expr *sqlite3CreateIdExpr(Parse *, const char*);
2421 void sqlite3PrngSaveState(void);
2422 void sqlite3PrngRestoreState(void);
2423 void sqlite3PrngResetState(void);
2424 void sqlite3RollbackAll(sqlite3*);
2425 void sqlite3CodeVerifySchema(Parse*, int);
2426 void sqlite3BeginTransaction(Parse*, int);
2427 void sqlite3CommitTransaction(Parse*);
2428 void sqlite3RollbackTransaction(Parse*);
2429 void sqlite3Savepoint(Parse*, int, Token*);
2430 void sqlite3CloseSavepoints(sqlite3 *);
2431 int sqlite3ExprIsConstant(Expr*);
2432 int sqlite3ExprIsConstantNotJoin(Expr*);
2433 int sqlite3ExprIsConstantOrFunction(Expr*);
2434 int sqlite3ExprIsInteger(Expr*, int*);
2435 int sqlite3IsRowid(const char*);
2436 void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
2437 void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
2438 int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
2439 void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
2440                                      int*,int,int,int,int);
2441 void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
2442 int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
2443 void sqlite3BeginWriteOperation(Parse*, int, int);
2444 Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
2445 void sqlite3TokenCopy(sqlite3*,Token*, Token*);
2446 ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
2447 SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
2448 IdList *sqlite3IdListDup(sqlite3*,IdList*);
2449 Select *sqlite3SelectDup(sqlite3*,Select*,int);
2450 void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
2451 FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
2452 void sqlite3RegisterBuiltinFunctions(sqlite3*);
2453 void sqlite3RegisterDateTimeFunctions(void);
2454 void sqlite3RegisterGlobalFunctions(void);
2455 #ifdef SQLITE_DEBUG
2456   int sqlite3SafetyOn(sqlite3*);
2457   int sqlite3SafetyOff(sqlite3*);
2458 #else
2459 # define sqlite3SafetyOn(A) 0
2460 # define sqlite3SafetyOff(A) 0
2461 #endif
2462 int sqlite3SafetyCheckOk(sqlite3*);
2463 int sqlite3SafetyCheckSickOrOk(sqlite3*);
2464 void sqlite3ChangeCookie(Parse*, int);
2465 
2466 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
2467 void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
2468 #endif
2469 
2470 #ifndef SQLITE_OMIT_TRIGGER
2471   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
2472                            Expr*,int, int);
2473   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
2474   void sqlite3DropTrigger(Parse*, SrcList*, int);
2475   void sqlite3DropTriggerPtr(Parse*, Trigger*);
2476   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
2477   Trigger *sqlite3TriggerList(Parse *, Table *);
2478   int sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
2479                             int, int, int, int, u32*, u32*);
2480   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
2481   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
2482   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
2483   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
2484                                         ExprList*,Select*,int);
2485   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
2486   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
2487   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
2488   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
2489 #else
2490 # define sqlite3TriggersExist(B,C,D,E,F) 0
2491 # define sqlite3DeleteTrigger(A,B)
2492 # define sqlite3DropTriggerPtr(A,B)
2493 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
2494 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K,L) 0
2495 #endif
2496 
2497 int sqlite3JoinType(Parse*, Token*, Token*, Token*);
2498 void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
2499 void sqlite3DeferForeignKey(Parse*, int);
2500 #ifndef SQLITE_OMIT_AUTHORIZATION
2501   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
2502   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
2503   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
2504   void sqlite3AuthContextPop(AuthContext*);
2505 #else
2506 # define sqlite3AuthRead(a,b,c,d)
2507 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
2508 # define sqlite3AuthContextPush(a,b,c)
2509 # define sqlite3AuthContextPop(a)  ((void)(a))
2510 #endif
2511 void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
2512 void sqlite3Detach(Parse*, Expr*);
2513 int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
2514                        int omitJournal, int nCache, int flags, Btree **ppBtree);
2515 int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
2516 int sqlite3FixSrcList(DbFixer*, SrcList*);
2517 int sqlite3FixSelect(DbFixer*, Select*);
2518 int sqlite3FixExpr(DbFixer*, Expr*);
2519 int sqlite3FixExprList(DbFixer*, ExprList*);
2520 int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
2521 int sqlite3AtoF(const char *z, double*);
2522 int sqlite3GetInt32(const char *, int*);
2523 int sqlite3FitsIn64Bits(const char *, int);
2524 int sqlite3Utf16ByteLen(const void *pData, int nChar);
2525 int sqlite3Utf8CharLen(const char *pData, int nByte);
2526 int sqlite3Utf8Read(const u8*, const u8*, const u8**);
2527 
2528 /*
2529 ** Routines to read and write variable-length integers.  These used to
2530 ** be defined locally, but now we use the varint routines in the util.c
2531 ** file.  Code should use the MACRO forms below, as the Varint32 versions
2532 ** are coded to assume the single byte case is already handled (which
2533 ** the MACRO form does).
2534 */
2535 int sqlite3PutVarint(unsigned char*, u64);
2536 int sqlite3PutVarint32(unsigned char*, u32);
2537 u8 sqlite3GetVarint(const unsigned char *, u64 *);
2538 u8 sqlite3GetVarint32(const unsigned char *, u32 *);
2539 int sqlite3VarintLen(u64 v);
2540 
2541 /*
2542 ** The header of a record consists of a sequence variable-length integers.
2543 ** These integers are almost always small and are encoded as a single byte.
2544 ** The following macros take advantage this fact to provide a fast encode
2545 ** and decode of the integers in a record header.  It is faster for the common
2546 ** case where the integer is a single byte.  It is a little slower when the
2547 ** integer is two or more bytes.  But overall it is faster.
2548 **
2549 ** The following expressions are equivalent:
2550 **
2551 **     x = sqlite3GetVarint32( A, &B );
2552 **     x = sqlite3PutVarint32( A, B );
2553 **
2554 **     x = getVarint32( A, B );
2555 **     x = putVarint32( A, B );
2556 **
2557 */
2558 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
2559 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
2560 #define getVarint    sqlite3GetVarint
2561 #define putVarint    sqlite3PutVarint
2562 
2563 
2564 void sqlite3IndexAffinityStr(Vdbe *, Index *);
2565 void sqlite3TableAffinityStr(Vdbe *, Table *);
2566 char sqlite3CompareAffinity(Expr *pExpr, char aff2);
2567 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
2568 char sqlite3ExprAffinity(Expr *pExpr);
2569 int sqlite3Atoi64(const char*, i64*);
2570 void sqlite3Error(sqlite3*, int, const char*,...);
2571 void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
2572 int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
2573 const char *sqlite3ErrStr(int);
2574 int sqlite3ReadSchema(Parse *pParse);
2575 CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
2576 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
2577 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
2578 Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
2579 int sqlite3CheckCollSeq(Parse *, CollSeq *);
2580 int sqlite3CheckObjectName(Parse *, const char *);
2581 void sqlite3VdbeSetChanges(sqlite3 *, int);
2582 
2583 const void *sqlite3ValueText(sqlite3_value*, u8);
2584 int sqlite3ValueBytes(sqlite3_value*, u8);
2585 void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
2586                         void(*)(void*));
2587 void sqlite3ValueFree(sqlite3_value*);
2588 sqlite3_value *sqlite3ValueNew(sqlite3 *);
2589 char *sqlite3Utf16to8(sqlite3 *, const void*, int);
2590 int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
2591 void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
2592 #ifndef SQLITE_AMALGAMATION
2593 extern const unsigned char sqlite3UpperToLower[];
2594 extern const unsigned char sqlite3CtypeMap[];
2595 extern SQLITE_WSD struct Sqlite3Config sqlite3Config;
2596 extern SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
2597 extern int sqlite3PendingByte;
2598 #endif
2599 void sqlite3RootPageMoved(Db*, int, int);
2600 void sqlite3Reindex(Parse*, Token*, Token*);
2601 void sqlite3AlterFunctions(sqlite3*);
2602 void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
2603 int sqlite3GetToken(const unsigned char *, int *);
2604 void sqlite3NestedParse(Parse*, const char*, ...);
2605 void sqlite3ExpirePreparedStatements(sqlite3*);
2606 void sqlite3CodeSubselect(Parse *, Expr *, int, int);
2607 void sqlite3SelectPrep(Parse*, Select*, NameContext*);
2608 int sqlite3ResolveExprNames(NameContext*, Expr*);
2609 void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
2610 int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
2611 void sqlite3ColumnDefault(Vdbe *, Table *, int);
2612 void sqlite3AlterFinishAddColumn(Parse *, Token *);
2613 void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
2614 CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
2615 char sqlite3AffinityType(const Token*);
2616 void sqlite3Analyze(Parse*, Token*, Token*);
2617 int sqlite3InvokeBusyHandler(BusyHandler*);
2618 int sqlite3FindDb(sqlite3*, Token*);
2619 int sqlite3FindDbName(sqlite3 *, const char *);
2620 int sqlite3AnalysisLoad(sqlite3*,int iDB);
2621 void sqlite3DefaultRowEst(Index*);
2622 void sqlite3RegisterLikeFunctions(sqlite3*, int);
2623 int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
2624 void sqlite3MinimumFileFormat(Parse*, int, int);
2625 void sqlite3SchemaFree(void *);
2626 Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
2627 int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
2628 KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
2629 int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
2630   void (*)(sqlite3_context*,int,sqlite3_value **),
2631   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
2632 int sqlite3ApiExit(sqlite3 *db, int);
2633 int sqlite3OpenTempDatabase(Parse *);
2634 
2635 void sqlite3StrAccumInit(StrAccum*, char*, int, int);
2636 void sqlite3StrAccumAppend(StrAccum*,const char*,int);
2637 char *sqlite3StrAccumFinish(StrAccum*);
2638 void sqlite3StrAccumReset(StrAccum*);
2639 void sqlite3SelectDestInit(SelectDest*,int,int);
2640 
2641 void sqlite3BackupRestart(sqlite3_backup *);
2642 void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
2643 
2644 /*
2645 ** The interface to the LEMON-generated parser
2646 */
2647 void *sqlite3ParserAlloc(void*(*)(size_t));
2648 void sqlite3ParserFree(void*, void(*)(void*));
2649 void sqlite3Parser(void*, int, Token, Parse*);
2650 #ifdef YYTRACKMAXSTACKDEPTH
2651   int sqlite3ParserStackPeak(void*);
2652 #endif
2653 
2654 int sqlite3AutoLoadExtensions(sqlite3*);
2655 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2656   void sqlite3CloseExtensions(sqlite3*);
2657 #else
2658 # define sqlite3CloseExtensions(X)
2659 #endif
2660 
2661 #ifndef SQLITE_OMIT_SHARED_CACHE
2662   void sqlite3TableLock(Parse *, int, int, u8, const char *);
2663 #else
2664   #define sqlite3TableLock(v,w,x,y,z)
2665 #endif
2666 
2667 #ifdef SQLITE_TEST
2668   int sqlite3Utf8To8(unsigned char*);
2669 #endif
2670 
2671 #ifdef SQLITE_OMIT_VIRTUALTABLE
2672 #  define sqlite3VtabClear(X)
2673 #  define sqlite3VtabSync(X,Y) SQLITE_OK
2674 #  define sqlite3VtabRollback(X)
2675 #  define sqlite3VtabCommit(X)
2676 #  define sqlite3VtabInSync(db) 0
2677 #else
2678    void sqlite3VtabClear(Table*);
2679    int sqlite3VtabSync(sqlite3 *db, char **);
2680    int sqlite3VtabRollback(sqlite3 *db);
2681    int sqlite3VtabCommit(sqlite3 *db);
2682 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
2683 #endif
2684 void sqlite3VtabMakeWritable(Parse*,Table*);
2685 void sqlite3VtabLock(sqlite3_vtab*);
2686 void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
2687 void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
2688 void sqlite3VtabFinishParse(Parse*, Token*);
2689 void sqlite3VtabArgInit(Parse*);
2690 void sqlite3VtabArgExtend(Parse*, Token*);
2691 int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
2692 int sqlite3VtabCallConnect(Parse*, Table*);
2693 int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
2694 int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
2695 FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
2696 void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
2697 int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
2698 int sqlite3Reprepare(Vdbe*);
2699 void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
2700 CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
2701 
2702 
2703 /*
2704 ** Available fault injectors.  Should be numbered beginning with 0.
2705 */
2706 #define SQLITE_FAULTINJECTOR_MALLOC     0
2707 #define SQLITE_FAULTINJECTOR_COUNT      1
2708 
2709 /*
2710 ** The interface to the code in fault.c used for identifying "benign"
2711 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
2712 ** is not defined.
2713 */
2714 #ifndef SQLITE_OMIT_BUILTIN_TEST
2715   void sqlite3BeginBenignMalloc(void);
2716   void sqlite3EndBenignMalloc(void);
2717 #else
2718   #define sqlite3BeginBenignMalloc()
2719   #define sqlite3EndBenignMalloc()
2720 #endif
2721 
2722 #define IN_INDEX_ROWID           1
2723 #define IN_INDEX_EPH             2
2724 #define IN_INDEX_INDEX           3
2725 int sqlite3FindInIndex(Parse *, Expr *, int*);
2726 
2727 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
2728   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
2729   int sqlite3JournalSize(sqlite3_vfs *);
2730   int sqlite3JournalCreate(sqlite3_file *);
2731 #else
2732   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
2733 #endif
2734 
2735 void sqlite3MemJournalOpen(sqlite3_file *);
2736 int sqlite3MemJournalSize(void);
2737 int sqlite3IsMemJournal(sqlite3_file *);
2738 
2739 #if SQLITE_MAX_EXPR_DEPTH>0
2740   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
2741   int sqlite3SelectExprHeight(Select *);
2742   int sqlite3ExprCheckHeight(Parse*, int);
2743 #else
2744   #define sqlite3ExprSetHeight(x,y)
2745   #define sqlite3SelectExprHeight(x) 0
2746   #define sqlite3ExprCheckHeight(x,y)
2747 #endif
2748 
2749 u32 sqlite3Get4byte(const u8*);
2750 void sqlite3Put4byte(u8*, u32);
2751 
2752 #ifdef SQLITE_SSE
2753 #include "sseInt.h"
2754 #endif
2755 
2756 #ifdef SQLITE_DEBUG
2757   void sqlite3ParserTrace(FILE*, char *);
2758 #endif
2759 
2760 /*
2761 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
2762 ** sqlite3IoTrace is a pointer to a printf-like routine used to
2763 ** print I/O tracing messages.
2764 */
2765 #ifdef SQLITE_ENABLE_IOTRACE
2766 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
2767   void sqlite3VdbeIOTraceSql(Vdbe*);
2768 SQLITE_EXTERN void (*sqlite3IoTrace)(const char*,...);
2769 #else
2770 # define IOTRACE(A)
2771 # define sqlite3VdbeIOTraceSql(X)
2772 #endif
2773 
2774 #endif
2775