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