xref: /sqlite-3.40.0/src/sqliteInt.h (revision a3fdec71)
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 */
15 #include "sqlite3.h"
16 #ifndef _SQLITEINT_H_
17 #define _SQLITEINT_H_
18 
19 /*
20 ** These #defines should enable >2GB file support on POSIX if the
21 ** underlying operating system supports it.  If the OS lacks
22 ** large file support, or if the OS is windows, these should be no-ops.
23 **
24 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
25 ** system #includes.  Hence, this block of code must be the very first
26 ** code in all source files.
27 **
28 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
29 ** on the compiler command line.  This is necessary if you are compiling
30 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
31 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
32 ** without this option, LFS is enable.  But LFS does not exist in the kernel
33 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
34 ** portability you should omit LFS.
35 **
36 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
37 */
38 #ifndef SQLITE_DISABLE_LFS
39 # define _LARGE_FILE       1
40 # ifndef _FILE_OFFSET_BITS
41 #   define _FILE_OFFSET_BITS 64
42 # endif
43 # define _LARGEFILE_SOURCE 1
44 #endif
45 
46 /*
47 ** Include the configuration header output by 'configure' if we're using the
48 ** autoconf-based build
49 */
50 #ifdef _HAVE_SQLITE_CONFIG_H
51 #include "config.h"
52 #endif
53 
54 #include "sqliteLimit.h"
55 
56 /* Disable nuisance warnings on Borland compilers */
57 #if defined(__BORLANDC__)
58 #pragma warn -rch /* unreachable code */
59 #pragma warn -ccc /* Condition is always true or false */
60 #pragma warn -aus /* Assigned value is never used */
61 #pragma warn -csu /* Comparing signed and unsigned */
62 #pragma warn -spa /* Suspicious pointer arithmetic */
63 #endif
64 
65 /* Needed for various definitions... */
66 #ifndef _GNU_SOURCE
67 # define _GNU_SOURCE
68 #endif
69 
70 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
71 # define _BSD_SOURCE
72 #endif
73 
74 /*
75 ** Include standard header files as necessary
76 */
77 #ifdef HAVE_STDINT_H
78 #include <stdint.h>
79 #endif
80 #ifdef HAVE_INTTYPES_H
81 #include <inttypes.h>
82 #endif
83 
84 /*
85 ** The following macros are used to cast pointers to integers and
86 ** integers to pointers.  The way you do this varies from one compiler
87 ** to the next, so we have developed the following set of #if statements
88 ** to generate appropriate macros for a wide range of compilers.
89 **
90 ** The correct "ANSI" way to do this is to use the intptr_t type.
91 ** Unfortunately, that typedef is not available on all compilers, or
92 ** if it is available, it requires an #include of specific headers
93 ** that vary from one machine to the next.
94 **
95 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
96 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
97 ** So we have to define the macros in different ways depending on the
98 ** compiler.
99 */
100 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
101 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
102 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
103 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
104 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
105 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
106 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
107 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
108 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
109 #else                          /* Generates a warning - but it always works */
110 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
111 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
112 #endif
113 
114 /*
115 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
116 ** 0 means mutexes are permanently disable and the library is never
117 ** threadsafe.  1 means the library is serialized which is the highest
118 ** level of threadsafety.  2 means the library is multithreaded - multiple
119 ** threads can use SQLite as long as no two threads try to use the same
120 ** database connection at the same time.
121 **
122 ** Older versions of SQLite used an optional THREADSAFE macro.
123 ** We support that for legacy.
124 */
125 #if !defined(SQLITE_THREADSAFE)
126 # if defined(THREADSAFE)
127 #   define SQLITE_THREADSAFE THREADSAFE
128 # else
129 #   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
130 # endif
131 #endif
132 
133 /*
134 ** Powersafe overwrite is on by default.  But can be turned off using
135 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
136 */
137 #ifndef SQLITE_POWERSAFE_OVERWRITE
138 # define SQLITE_POWERSAFE_OVERWRITE 1
139 #endif
140 
141 /*
142 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
143 ** It determines whether or not the features related to
144 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
145 ** be overridden at runtime using the sqlite3_config() API.
146 */
147 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
148 # define SQLITE_DEFAULT_MEMSTATUS 1
149 #endif
150 
151 /*
152 ** Exactly one of the following macros must be defined in order to
153 ** specify which memory allocation subsystem to use.
154 **
155 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
156 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
157 **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
158 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
159 **
160 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
161 ** assert() macro is enabled, each call into the Win32 native heap subsystem
162 ** will cause HeapValidate to be called.  If heap validation should fail, an
163 ** assertion will be triggered.
164 **
165 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
166 ** the default.
167 */
168 #if defined(SQLITE_SYSTEM_MALLOC) \
169   + defined(SQLITE_WIN32_MALLOC) \
170   + defined(SQLITE_ZERO_MALLOC) \
171   + defined(SQLITE_MEMDEBUG)>1
172 # error "Two or more of the following compile-time configuration options\
173  are defined but at most one is allowed:\
174  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
175  SQLITE_ZERO_MALLOC"
176 #endif
177 #if defined(SQLITE_SYSTEM_MALLOC) \
178   + defined(SQLITE_WIN32_MALLOC) \
179   + defined(SQLITE_ZERO_MALLOC) \
180   + defined(SQLITE_MEMDEBUG)==0
181 # define SQLITE_SYSTEM_MALLOC 1
182 #endif
183 
184 /*
185 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
186 ** sizes of memory allocations below this value where possible.
187 */
188 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
189 # define SQLITE_MALLOC_SOFT_LIMIT 1024
190 #endif
191 
192 /*
193 ** We need to define _XOPEN_SOURCE as follows in order to enable
194 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
195 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
196 ** it.
197 */
198 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
199 #  define _XOPEN_SOURCE 600
200 #endif
201 
202 /*
203 ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
204 ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
205 ** make it true by defining or undefining NDEBUG.
206 **
207 ** Setting NDEBUG makes the code smaller and faster by disabling the
208 ** assert() statements in the code.  So we want the default action
209 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
210 ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
211 ** feature.
212 */
213 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
214 # define NDEBUG 1
215 #endif
216 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
217 # undef NDEBUG
218 #endif
219 
220 /*
221 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
222 */
223 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
224 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
225 #endif
226 
227 /*
228 ** The testcase() macro is used to aid in coverage testing.  When
229 ** doing coverage testing, the condition inside the argument to
230 ** testcase() must be evaluated both true and false in order to
231 ** get full branch coverage.  The testcase() macro is inserted
232 ** to help ensure adequate test coverage in places where simple
233 ** condition/decision coverage is inadequate.  For example, testcase()
234 ** can be used to make sure boundary values are tested.  For
235 ** bitmask tests, testcase() can be used to make sure each bit
236 ** is significant and used at least once.  On switch statements
237 ** where multiple cases go to the same block of code, testcase()
238 ** can insure that all cases are evaluated.
239 **
240 */
241 #ifdef SQLITE_COVERAGE_TEST
242   void sqlite3Coverage(int);
243 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
244 #else
245 # define testcase(X)
246 #endif
247 
248 /*
249 ** The TESTONLY macro is used to enclose variable declarations or
250 ** other bits of code that are needed to support the arguments
251 ** within testcase() and assert() macros.
252 */
253 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
254 # define TESTONLY(X)  X
255 #else
256 # define TESTONLY(X)
257 #endif
258 
259 /*
260 ** Sometimes we need a small amount of code such as a variable initialization
261 ** to setup for a later assert() statement.  We do not want this code to
262 ** appear when assert() is disabled.  The following macro is therefore
263 ** used to contain that setup code.  The "VVA" acronym stands for
264 ** "Verification, Validation, and Accreditation".  In other words, the
265 ** code within VVA_ONLY() will only run during verification processes.
266 */
267 #ifndef NDEBUG
268 # define VVA_ONLY(X)  X
269 #else
270 # define VVA_ONLY(X)
271 #endif
272 
273 /*
274 ** The ALWAYS and NEVER macros surround boolean expressions which
275 ** are intended to always be true or false, respectively.  Such
276 ** expressions could be omitted from the code completely.  But they
277 ** are included in a few cases in order to enhance the resilience
278 ** of SQLite to unexpected behavior - to make the code "self-healing"
279 ** or "ductile" rather than being "brittle" and crashing at the first
280 ** hint of unplanned behavior.
281 **
282 ** In other words, ALWAYS and NEVER are added for defensive code.
283 **
284 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
285 ** be true and false so that the unreachable code they specify will
286 ** not be counted as untested code.
287 */
288 #if defined(SQLITE_COVERAGE_TEST)
289 # define ALWAYS(X)      (1)
290 # define NEVER(X)       (0)
291 #elif !defined(NDEBUG)
292 # define ALWAYS(X)      ((X)?1:(assert(0),0))
293 # define NEVER(X)       ((X)?(assert(0),1):0)
294 #else
295 # define ALWAYS(X)      (X)
296 # define NEVER(X)       (X)
297 #endif
298 
299 /*
300 ** Return true (non-zero) if the input is a integer that is too large
301 ** to fit in 32-bits.  This macro is used inside of various testcase()
302 ** macros to verify that we have tested SQLite for large-file support.
303 */
304 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
305 
306 /*
307 ** The macro unlikely() is a hint that surrounds a boolean
308 ** expression that is usually false.  Macro likely() surrounds
309 ** a boolean expression that is usually true.  These hints could,
310 ** in theory, be used by the compiler to generate better code, but
311 ** currently they are just comments for human readers.
312 */
313 #define likely(X)    (X)
314 #define unlikely(X)  (X)
315 
316 #include "hash.h"
317 #include "parse.h"
318 #include <stdio.h>
319 #include <stdlib.h>
320 #include <string.h>
321 #include <assert.h>
322 #include <stddef.h>
323 
324 /*
325 ** If compiling for a processor that lacks floating point support,
326 ** substitute integer for floating-point
327 */
328 #ifdef SQLITE_OMIT_FLOATING_POINT
329 # define double sqlite_int64
330 # define float sqlite_int64
331 # define LONGDOUBLE_TYPE sqlite_int64
332 # ifndef SQLITE_BIG_DBL
333 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
334 # endif
335 # define SQLITE_OMIT_DATETIME_FUNCS 1
336 # define SQLITE_OMIT_TRACE 1
337 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
338 # undef SQLITE_HAVE_ISNAN
339 #endif
340 #ifndef SQLITE_BIG_DBL
341 # define SQLITE_BIG_DBL (1e99)
342 #endif
343 
344 /*
345 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
346 ** afterward. Having this macro allows us to cause the C compiler
347 ** to omit code used by TEMP tables without messy #ifndef statements.
348 */
349 #ifdef SQLITE_OMIT_TEMPDB
350 #define OMIT_TEMPDB 1
351 #else
352 #define OMIT_TEMPDB 0
353 #endif
354 
355 /*
356 ** The "file format" number is an integer that is incremented whenever
357 ** the VDBE-level file format changes.  The following macros define the
358 ** the default file format for new databases and the maximum file format
359 ** that the library can read.
360 */
361 #define SQLITE_MAX_FILE_FORMAT 4
362 #ifndef SQLITE_DEFAULT_FILE_FORMAT
363 # define SQLITE_DEFAULT_FILE_FORMAT 4
364 #endif
365 
366 /*
367 ** Determine whether triggers are recursive by default.  This can be
368 ** changed at run-time using a pragma.
369 */
370 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
371 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
372 #endif
373 
374 /*
375 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
376 ** on the command-line
377 */
378 #ifndef SQLITE_TEMP_STORE
379 # define SQLITE_TEMP_STORE 1
380 # define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
381 #endif
382 
383 /*
384 ** GCC does not define the offsetof() macro so we'll have to do it
385 ** ourselves.
386 */
387 #ifndef offsetof
388 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
389 #endif
390 
391 /*
392 ** Macros to compute minimum and maximum of two numbers.
393 */
394 #define MIN(A,B) ((A)<(B)?(A):(B))
395 #define MAX(A,B) ((A)>(B)?(A):(B))
396 
397 /*
398 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
399 ** not, there are still machines out there that use EBCDIC.)
400 */
401 #if 'A' == '\301'
402 # define SQLITE_EBCDIC 1
403 #else
404 # define SQLITE_ASCII 1
405 #endif
406 
407 /*
408 ** Integers of known sizes.  These typedefs might change for architectures
409 ** where the sizes very.  Preprocessor macros are available so that the
410 ** types can be conveniently redefined at compile-type.  Like this:
411 **
412 **         cc '-DUINTPTR_TYPE=long long int' ...
413 */
414 #ifndef UINT32_TYPE
415 # ifdef HAVE_UINT32_T
416 #  define UINT32_TYPE uint32_t
417 # else
418 #  define UINT32_TYPE unsigned int
419 # endif
420 #endif
421 #ifndef UINT16_TYPE
422 # ifdef HAVE_UINT16_T
423 #  define UINT16_TYPE uint16_t
424 # else
425 #  define UINT16_TYPE unsigned short int
426 # endif
427 #endif
428 #ifndef INT16_TYPE
429 # ifdef HAVE_INT16_T
430 #  define INT16_TYPE int16_t
431 # else
432 #  define INT16_TYPE short int
433 # endif
434 #endif
435 #ifndef UINT8_TYPE
436 # ifdef HAVE_UINT8_T
437 #  define UINT8_TYPE uint8_t
438 # else
439 #  define UINT8_TYPE unsigned char
440 # endif
441 #endif
442 #ifndef INT8_TYPE
443 # ifdef HAVE_INT8_T
444 #  define INT8_TYPE int8_t
445 # else
446 #  define INT8_TYPE signed char
447 # endif
448 #endif
449 #ifndef LONGDOUBLE_TYPE
450 # define LONGDOUBLE_TYPE long double
451 #endif
452 typedef sqlite_int64 i64;          /* 8-byte signed integer */
453 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
454 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
455 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
456 typedef INT16_TYPE i16;            /* 2-byte signed integer */
457 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
458 typedef INT8_TYPE i8;              /* 1-byte signed integer */
459 
460 /*
461 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
462 ** that can be stored in a u32 without loss of data.  The value
463 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
464 ** have to specify the value in the less intuitive manner shown:
465 */
466 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
467 
468 /*
469 ** The datatype used to store estimates of the number of rows in a
470 ** table or index.  This is an unsigned integer type.  For 99.9% of
471 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
472 ** can be used at compile-time if desired.
473 */
474 #ifdef SQLITE_64BIT_STATS
475  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
476 #else
477  typedef u32 tRowcnt;    /* 32-bit is the default */
478 #endif
479 
480 /*
481 ** Estimated quantities used for query planning are stored as 16-bit
482 ** logarithms.  For quantity X, the value stored is 10*log2(X).  This
483 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
484 ** But the allowed values are "grainy".  Not every value is representable.
485 ** For example, quantities 16 and 17 are both represented by a LogEst
486 ** of 40.  However, since LogEst quantatites are suppose to be estimates,
487 ** not exact values, this imprecision is not a problem.
488 **
489 ** "LogEst" is short for "Logarithimic Estimate".
490 **
491 ** Examples:
492 **      1 -> 0              20 -> 43          10000 -> 132
493 **      2 -> 10             25 -> 46          25000 -> 146
494 **      3 -> 16            100 -> 66        1000000 -> 199
495 **      4 -> 20           1000 -> 99        1048576 -> 200
496 **     10 -> 33           1024 -> 100    4294967296 -> 320
497 **
498 ** The LogEst can be negative to indicate fractional values.
499 ** Examples:
500 **
501 **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
502 */
503 typedef INT16_TYPE LogEst;
504 
505 /*
506 ** Macros to determine whether the machine is big or little endian,
507 ** evaluated at runtime.
508 */
509 #ifdef SQLITE_AMALGAMATION
510 const int sqlite3one = 1;
511 #else
512 extern const int sqlite3one;
513 #endif
514 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
515                              || defined(__x86_64) || defined(__x86_64__)
516 # define SQLITE_BIGENDIAN    0
517 # define SQLITE_LITTLEENDIAN 1
518 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
519 #else
520 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
521 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
522 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
523 #endif
524 
525 /*
526 ** Constants for the largest and smallest possible 64-bit signed integers.
527 ** These macros are designed to work correctly on both 32-bit and 64-bit
528 ** compilers.
529 */
530 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
531 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
532 
533 /*
534 ** Round up a number to the next larger multiple of 8.  This is used
535 ** to force 8-byte alignment on 64-bit architectures.
536 */
537 #define ROUND8(x)     (((x)+7)&~7)
538 
539 /*
540 ** Round down to the nearest multiple of 8
541 */
542 #define ROUNDDOWN8(x) ((x)&~7)
543 
544 /*
545 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
546 ** macro is used only within assert() to verify that the code gets
547 ** all alignment restrictions correct.
548 **
549 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
550 ** underlying malloc() implemention might return us 4-byte aligned
551 ** pointers.  In that case, only verify 4-byte alignment.
552 */
553 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
554 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
555 #else
556 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
557 #endif
558 
559 /*
560 ** Disable MMAP on platforms where it is known to not work
561 */
562 #if defined(__OpenBSD__) || defined(__QNXNTO__)
563 # undef SQLITE_MAX_MMAP_SIZE
564 # define SQLITE_MAX_MMAP_SIZE 0
565 #endif
566 
567 /*
568 ** Default maximum size of memory used by memory-mapped I/O in the VFS
569 */
570 #ifdef __APPLE__
571 # include <TargetConditionals.h>
572 # if TARGET_OS_IPHONE
573 #   undef SQLITE_MAX_MMAP_SIZE
574 #   define SQLITE_MAX_MMAP_SIZE 0
575 # endif
576 #endif
577 #ifndef SQLITE_MAX_MMAP_SIZE
578 # if defined(__linux__) \
579   || defined(_WIN32) \
580   || (defined(__APPLE__) && defined(__MACH__)) \
581   || defined(__sun)
582 #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
583 # else
584 #   define SQLITE_MAX_MMAP_SIZE 0
585 # endif
586 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
587 #endif
588 
589 /*
590 ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
591 ** default MMAP_SIZE is specified at compile-time, make sure that it does
592 ** not exceed the maximum mmap size.
593 */
594 #ifndef SQLITE_DEFAULT_MMAP_SIZE
595 # define SQLITE_DEFAULT_MMAP_SIZE 0
596 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
597 #endif
598 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
599 # undef SQLITE_DEFAULT_MMAP_SIZE
600 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
601 #endif
602 
603 /*
604 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
605 ** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
606 ** define SQLITE_ENABLE_STAT3_OR_STAT4
607 */
608 #ifdef SQLITE_ENABLE_STAT4
609 # undef SQLITE_ENABLE_STAT3
610 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
611 #elif SQLITE_ENABLE_STAT3
612 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
613 #elif SQLITE_ENABLE_STAT3_OR_STAT4
614 # undef SQLITE_ENABLE_STAT3_OR_STAT4
615 #endif
616 
617 /*
618 ** An instance of the following structure is used to store the busy-handler
619 ** callback for a given sqlite handle.
620 **
621 ** The sqlite.busyHandler member of the sqlite struct contains the busy
622 ** callback for the database handle. Each pager opened via the sqlite
623 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
624 ** callback is currently invoked only from within pager.c.
625 */
626 typedef struct BusyHandler BusyHandler;
627 struct BusyHandler {
628   int (*xFunc)(void *,int);  /* The busy callback */
629   void *pArg;                /* First arg to busy callback */
630   int nBusy;                 /* Incremented with each busy call */
631 };
632 
633 /*
634 ** Name of the master database table.  The master database table
635 ** is a special table that holds the names and attributes of all
636 ** user tables and indices.
637 */
638 #define MASTER_NAME       "sqlite_master"
639 #define TEMP_MASTER_NAME  "sqlite_temp_master"
640 
641 /*
642 ** The root-page of the master database table.
643 */
644 #define MASTER_ROOT       1
645 
646 /*
647 ** The name of the schema table.
648 */
649 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
650 
651 /*
652 ** A convenience macro that returns the number of elements in
653 ** an array.
654 */
655 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
656 
657 /*
658 ** Determine if the argument is a power of two
659 */
660 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
661 
662 /*
663 ** The following value as a destructor means to use sqlite3DbFree().
664 ** The sqlite3DbFree() routine requires two parameters instead of the
665 ** one parameter that destructors normally want.  So we have to introduce
666 ** this magic value that the code knows to handle differently.  Any
667 ** pointer will work here as long as it is distinct from SQLITE_STATIC
668 ** and SQLITE_TRANSIENT.
669 */
670 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
671 
672 /*
673 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
674 ** not support Writable Static Data (WSD) such as global and static variables.
675 ** All variables must either be on the stack or dynamically allocated from
676 ** the heap.  When WSD is unsupported, the variable declarations scattered
677 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
678 ** macro is used for this purpose.  And instead of referencing the variable
679 ** directly, we use its constant as a key to lookup the run-time allocated
680 ** buffer that holds real variable.  The constant is also the initializer
681 ** for the run-time allocated buffer.
682 **
683 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
684 ** macros become no-ops and have zero performance impact.
685 */
686 #ifdef SQLITE_OMIT_WSD
687   #define SQLITE_WSD const
688   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
689   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
690   int sqlite3_wsd_init(int N, int J);
691   void *sqlite3_wsd_find(void *K, int L);
692 #else
693   #define SQLITE_WSD
694   #define GLOBAL(t,v) v
695   #define sqlite3GlobalConfig sqlite3Config
696 #endif
697 
698 /*
699 ** The following macros are used to suppress compiler warnings and to
700 ** make it clear to human readers when a function parameter is deliberately
701 ** left unused within the body of a function. This usually happens when
702 ** a function is called via a function pointer. For example the
703 ** implementation of an SQL aggregate step callback may not use the
704 ** parameter indicating the number of arguments passed to the aggregate,
705 ** if it knows that this is enforced elsewhere.
706 **
707 ** When a function parameter is not used at all within the body of a function,
708 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
709 ** However, these macros may also be used to suppress warnings related to
710 ** parameters that may or may not be used depending on compilation options.
711 ** For example those parameters only used in assert() statements. In these
712 ** cases the parameters are named as per the usual conventions.
713 */
714 #define UNUSED_PARAMETER(x) (void)(x)
715 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
716 
717 /*
718 ** Forward references to structures
719 */
720 typedef struct AggInfo AggInfo;
721 typedef struct AuthContext AuthContext;
722 typedef struct AutoincInfo AutoincInfo;
723 typedef struct Bitvec Bitvec;
724 typedef struct CollSeq CollSeq;
725 typedef struct Column Column;
726 typedef struct Db Db;
727 typedef struct Schema Schema;
728 typedef struct Expr Expr;
729 typedef struct ExprList ExprList;
730 typedef struct ExprSpan ExprSpan;
731 typedef struct FKey FKey;
732 typedef struct FuncDestructor FuncDestructor;
733 typedef struct FuncDef FuncDef;
734 typedef struct FuncDefHash FuncDefHash;
735 typedef struct IdList IdList;
736 typedef struct Index Index;
737 typedef struct IndexSample IndexSample;
738 typedef struct KeyClass KeyClass;
739 typedef struct KeyInfo KeyInfo;
740 typedef struct Lookaside Lookaside;
741 typedef struct LookasideSlot LookasideSlot;
742 typedef struct Module Module;
743 typedef struct NameContext NameContext;
744 typedef struct Parse Parse;
745 typedef struct PrintfArguments PrintfArguments;
746 typedef struct RowSet RowSet;
747 typedef struct Savepoint Savepoint;
748 typedef struct Select Select;
749 typedef struct SelectDest SelectDest;
750 typedef struct SrcList SrcList;
751 typedef struct StrAccum StrAccum;
752 typedef struct Table Table;
753 typedef struct TableLock TableLock;
754 typedef struct Token Token;
755 typedef struct Trigger Trigger;
756 typedef struct TriggerPrg TriggerPrg;
757 typedef struct TriggerStep TriggerStep;
758 typedef struct UnpackedRecord UnpackedRecord;
759 typedef struct VTable VTable;
760 typedef struct VtabCtx VtabCtx;
761 typedef struct Walker Walker;
762 typedef struct WhereInfo WhereInfo;
763 typedef struct With With;
764 
765 /*
766 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
767 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
768 ** pointer types (i.e. FuncDef) defined above.
769 */
770 #include "btree.h"
771 #include "vdbe.h"
772 #include "pager.h"
773 #include "pcache.h"
774 
775 #include "os.h"
776 #include "mutex.h"
777 
778 
779 /*
780 ** Each database file to be accessed by the system is an instance
781 ** of the following structure.  There are normally two of these structures
782 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
783 ** aDb[1] is the database file used to hold temporary tables.  Additional
784 ** databases may be attached.
785 */
786 struct Db {
787   char *zName;         /* Name of this database */
788   Btree *pBt;          /* The B*Tree structure for this database file */
789   u8 safety_level;     /* How aggressive at syncing data to disk */
790   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
791 };
792 
793 /*
794 ** An instance of the following structure stores a database schema.
795 **
796 ** Most Schema objects are associated with a Btree.  The exception is
797 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
798 ** In shared cache mode, a single Schema object can be shared by multiple
799 ** Btrees that refer to the same underlying BtShared object.
800 **
801 ** Schema objects are automatically deallocated when the last Btree that
802 ** references them is destroyed.   The TEMP Schema is manually freed by
803 ** sqlite3_close().
804 *
805 ** A thread must be holding a mutex on the corresponding Btree in order
806 ** to access Schema content.  This implies that the thread must also be
807 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
808 ** For a TEMP Schema, only the connection mutex is required.
809 */
810 struct Schema {
811   int schema_cookie;   /* Database schema version number for this file */
812   int iGeneration;     /* Generation counter.  Incremented with each change */
813   Hash tblHash;        /* All tables indexed by name */
814   Hash idxHash;        /* All (named) indices indexed by name */
815   Hash trigHash;       /* All triggers indexed by name */
816   Hash fkeyHash;       /* All foreign keys by referenced table name */
817   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
818   u8 file_format;      /* Schema format version for this file */
819   u8 enc;              /* Text encoding used by this database */
820   u16 flags;           /* Flags associated with this schema */
821   int cache_size;      /* Number of pages to use in the cache */
822 };
823 
824 /*
825 ** These macros can be used to test, set, or clear bits in the
826 ** Db.pSchema->flags field.
827 */
828 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
829 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
830 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
831 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
832 
833 /*
834 ** Allowed values for the DB.pSchema->flags field.
835 **
836 ** The DB_SchemaLoaded flag is set after the database schema has been
837 ** read into internal hash tables.
838 **
839 ** DB_UnresetViews means that one or more views have column names that
840 ** have been filled out.  If the schema changes, these column names might
841 ** changes and so the view will need to be reset.
842 */
843 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
844 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
845 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
846 
847 /*
848 ** The number of different kinds of things that can be limited
849 ** using the sqlite3_limit() interface.
850 */
851 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
852 
853 /*
854 ** Lookaside malloc is a set of fixed-size buffers that can be used
855 ** to satisfy small transient memory allocation requests for objects
856 ** associated with a particular database connection.  The use of
857 ** lookaside malloc provides a significant performance enhancement
858 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
859 ** SQL statements.
860 **
861 ** The Lookaside structure holds configuration information about the
862 ** lookaside malloc subsystem.  Each available memory allocation in
863 ** the lookaside subsystem is stored on a linked list of LookasideSlot
864 ** objects.
865 **
866 ** Lookaside allocations are only allowed for objects that are associated
867 ** with a particular database connection.  Hence, schema information cannot
868 ** be stored in lookaside because in shared cache mode the schema information
869 ** is shared by multiple database connections.  Therefore, while parsing
870 ** schema information, the Lookaside.bEnabled flag is cleared so that
871 ** lookaside allocations are not used to construct the schema objects.
872 */
873 struct Lookaside {
874   u16 sz;                 /* Size of each buffer in bytes */
875   u8 bEnabled;            /* False to disable new lookaside allocations */
876   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
877   int nOut;               /* Number of buffers currently checked out */
878   int mxOut;              /* Highwater mark for nOut */
879   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
880   LookasideSlot *pFree;   /* List of available buffers */
881   void *pStart;           /* First byte of available memory space */
882   void *pEnd;             /* First byte past end of available space */
883 };
884 struct LookasideSlot {
885   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
886 };
887 
888 /*
889 ** A hash table for function definitions.
890 **
891 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
892 ** Collisions are on the FuncDef.pHash chain.
893 */
894 struct FuncDefHash {
895   FuncDef *a[23];       /* Hash table for functions */
896 };
897 
898 /*
899 ** Each database connection is an instance of the following structure.
900 */
901 struct sqlite3 {
902   sqlite3_vfs *pVfs;            /* OS Interface */
903   struct Vdbe *pVdbe;           /* List of active virtual machines */
904   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
905   sqlite3_mutex *mutex;         /* Connection mutex */
906   Db *aDb;                      /* All backends */
907   int nDb;                      /* Number of backends currently in use */
908   int flags;                    /* Miscellaneous flags. See below */
909   i64 lastRowid;                /* ROWID of most recent insert (see above) */
910   i64 szMmap;                   /* Default mmap_size setting */
911   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
912   int errCode;                  /* Most recent error code (SQLITE_*) */
913   int errMask;                  /* & result codes with this before returning */
914   u16 dbOptFlags;               /* Flags to enable/disable optimizations */
915   u8 autoCommit;                /* The auto-commit flag. */
916   u8 temp_store;                /* 1: file 2: memory 0: default */
917   u8 mallocFailed;              /* True if we have seen a malloc failure */
918   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
919   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
920   u8 suppressErr;               /* Do not issue error messages if true */
921   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
922   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
923   int nextPagesize;             /* Pagesize after VACUUM if >0 */
924   u32 magic;                    /* Magic number for detect library misuse */
925   int nChange;                  /* Value returned by sqlite3_changes() */
926   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
927   int aLimit[SQLITE_N_LIMIT];   /* Limits */
928   struct sqlite3InitInfo {      /* Information used during initialization */
929     int newTnum;                /* Rootpage of table being initialized */
930     u8 iDb;                     /* Which db file is being initialized */
931     u8 busy;                    /* TRUE if currently initializing */
932     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
933   } init;
934   int nVdbeActive;              /* Number of VDBEs currently running */
935   int nVdbeRead;                /* Number of active VDBEs that read or write */
936   int nVdbeWrite;               /* Number of active VDBEs that read and write */
937   int nVdbeExec;                /* Number of nested calls to VdbeExec() */
938   int nExtension;               /* Number of loaded extensions */
939   void **aExtension;            /* Array of shared library handles */
940   void (*xTrace)(void*,const char*);        /* Trace function */
941   void *pTraceArg;                          /* Argument to the trace function */
942   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
943   void *pProfileArg;                        /* Argument to profile function */
944   void *pCommitArg;                 /* Argument to xCommitCallback() */
945   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
946   void *pRollbackArg;               /* Argument to xRollbackCallback() */
947   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
948   void *pUpdateArg;
949   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
950 #ifndef SQLITE_OMIT_WAL
951   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
952   void *pWalArg;
953 #endif
954   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
955   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
956   void *pCollNeededArg;
957   sqlite3_value *pErr;          /* Most recent error message */
958   union {
959     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
960     double notUsed1;            /* Spacer */
961   } u1;
962   Lookaside lookaside;          /* Lookaside malloc configuration */
963 #ifndef SQLITE_OMIT_AUTHORIZATION
964   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
965                                 /* Access authorization function */
966   void *pAuthArg;               /* 1st argument to the access auth function */
967 #endif
968 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
969   int (*xProgress)(void *);     /* The progress callback */
970   void *pProgressArg;           /* Argument to the progress callback */
971   unsigned nProgressOps;        /* Number of opcodes for progress callback */
972 #endif
973 #ifndef SQLITE_OMIT_VIRTUALTABLE
974   int nVTrans;                  /* Allocated size of aVTrans */
975   Hash aModule;                 /* populated by sqlite3_create_module() */
976   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
977   VTable **aVTrans;             /* Virtual tables with open transactions */
978   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
979 #endif
980   FuncDefHash aFunc;            /* Hash table of connection functions */
981   Hash aCollSeq;                /* All collating sequences */
982   BusyHandler busyHandler;      /* Busy callback */
983   Db aDbStatic[2];              /* Static space for the 2 default backends */
984   Savepoint *pSavepoint;        /* List of active savepoints */
985   int busyTimeout;              /* Busy handler timeout, in msec */
986   int nSavepoint;               /* Number of non-transaction savepoints */
987   int nStatement;               /* Number of nested statement-transactions  */
988   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
989   i64 nDeferredImmCons;         /* Net deferred immediate constraints */
990   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
991 
992 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
993   /* The following variables are all protected by the STATIC_MASTER
994   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
995   **
996   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
997   ** unlock so that it can proceed.
998   **
999   ** When X.pBlockingConnection==Y, that means that something that X tried
1000   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
1001   ** held by Y.
1002   */
1003   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
1004   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
1005   void *pUnlockArg;                     /* Argument to xUnlockNotify */
1006   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
1007   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
1008 #endif
1009 };
1010 
1011 /*
1012 ** A macro to discover the encoding of a database.
1013 */
1014 #define ENC(db) ((db)->aDb[0].pSchema->enc)
1015 
1016 /*
1017 ** Possible values for the sqlite3.flags.
1018 */
1019 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
1020 #define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
1021 #define SQLITE_FullFSync      0x00000004  /* Use full fsync on the backend */
1022 #define SQLITE_CkptFullFSync  0x00000008  /* Use full fsync for checkpoint */
1023 #define SQLITE_CacheSpill     0x00000010  /* OK to spill pager cache */
1024 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
1025 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
1026 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
1027                                           /*   DELETE, or UPDATE and return */
1028                                           /*   the count using a callback. */
1029 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
1030                                           /*   result set is empty */
1031 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
1032 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
1033 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
1034 #define SQLITE_VdbeAddopTrace 0x00001000  /* Trace sqlite3VdbeAddOp() calls */
1035 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
1036 #define SQLITE_ReadUncommitted 0x0004000  /* For shared-cache mode */
1037 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
1038 #define SQLITE_RecoveryMode   0x00010000  /* Ignore schema errors */
1039 #define SQLITE_ReverseOrder   0x00020000  /* Reverse unordered SELECTs */
1040 #define SQLITE_RecTriggers    0x00040000  /* Enable recursive triggers */
1041 #define SQLITE_ForeignKeys    0x00080000  /* Enforce foreign key constraints  */
1042 #define SQLITE_AutoIndex      0x00100000  /* Enable automatic indexes */
1043 #define SQLITE_PreferBuiltin  0x00200000  /* Preference to built-in funcs */
1044 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
1045 #define SQLITE_EnableTrigger  0x00800000  /* True to enable triggers */
1046 #define SQLITE_DeferFKs       0x01000000  /* Defer all FK constraints */
1047 #define SQLITE_QueryOnly      0x02000000  /* Disable database changes */
1048 #define SQLITE_VdbeEQP        0x04000000  /* Debug EXPLAIN QUERY PLAN */
1049 
1050 
1051 /*
1052 ** Bits of the sqlite3.dbOptFlags field that are used by the
1053 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
1054 ** selectively disable various optimizations.
1055 */
1056 #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
1057 #define SQLITE_ColumnCache    0x0002   /* Column cache */
1058 #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
1059 #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
1060 /*                not used    0x0010   // Was: SQLITE_IdxRealAsInt */
1061 #define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
1062 #define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
1063 #define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
1064 #define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
1065 #define SQLITE_Transitive     0x0200   /* Transitive constraints */
1066 #define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
1067 #define SQLITE_Stat3          0x0800   /* Use the SQLITE_STAT3 table */
1068 #define SQLITE_AdjustOutEst   0x1000   /* Adjust output estimates using WHERE */
1069 #define SQLITE_AllOpts        0xffff   /* All optimizations */
1070 
1071 /*
1072 ** Macros for testing whether or not optimizations are enabled or disabled.
1073 */
1074 #ifndef SQLITE_OMIT_BUILTIN_TEST
1075 #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
1076 #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
1077 #else
1078 #define OptimizationDisabled(db, mask)  0
1079 #define OptimizationEnabled(db, mask)   1
1080 #endif
1081 
1082 /*
1083 ** Return true if it OK to factor constant expressions into the initialization
1084 ** code. The argument is a Parse object for the code generator.
1085 */
1086 #define ConstFactorOk(P) \
1087   ((P)->cookieGoto>0 && OptimizationEnabled((P)->db,SQLITE_FactorOutConst))
1088 
1089 /*
1090 ** Possible values for the sqlite.magic field.
1091 ** The numbers are obtained at random and have no special meaning, other
1092 ** than being distinct from one another.
1093 */
1094 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
1095 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
1096 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
1097 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
1098 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
1099 #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
1100 
1101 /*
1102 ** Each SQL function is defined by an instance of the following
1103 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
1104 ** hash table.  When multiple functions have the same name, the hash table
1105 ** points to a linked list of these structures.
1106 */
1107 struct FuncDef {
1108   i16 nArg;            /* Number of arguments.  -1 means unlimited */
1109   u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
1110   void *pUserData;     /* User data parameter */
1111   FuncDef *pNext;      /* Next function with same name */
1112   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
1113   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
1114   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
1115   char *zName;         /* SQL name of the function. */
1116   FuncDef *pHash;      /* Next with a different name but the same hash */
1117   FuncDestructor *pDestructor;   /* Reference counted destructor function */
1118 };
1119 
1120 /*
1121 ** This structure encapsulates a user-function destructor callback (as
1122 ** configured using create_function_v2()) and a reference counter. When
1123 ** create_function_v2() is called to create a function with a destructor,
1124 ** a single object of this type is allocated. FuncDestructor.nRef is set to
1125 ** the number of FuncDef objects created (either 1 or 3, depending on whether
1126 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
1127 ** member of each of the new FuncDef objects is set to point to the allocated
1128 ** FuncDestructor.
1129 **
1130 ** Thereafter, when one of the FuncDef objects is deleted, the reference
1131 ** count on this object is decremented. When it reaches 0, the destructor
1132 ** is invoked and the FuncDestructor structure freed.
1133 */
1134 struct FuncDestructor {
1135   int nRef;
1136   void (*xDestroy)(void *);
1137   void *pUserData;
1138 };
1139 
1140 /*
1141 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
1142 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
1143 ** are assert() statements in the code to verify this.
1144 */
1145 #define SQLITE_FUNC_ENCMASK  0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
1146 #define SQLITE_FUNC_LIKE     0x004 /* Candidate for the LIKE optimization */
1147 #define SQLITE_FUNC_CASE     0x008 /* Case-sensitive LIKE-type function */
1148 #define SQLITE_FUNC_EPHEM    0x010 /* Ephemeral.  Delete with VDBE */
1149 #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
1150 #define SQLITE_FUNC_LENGTH   0x040 /* Built-in length() function */
1151 #define SQLITE_FUNC_TYPEOF   0x080 /* Built-in typeof() function */
1152 #define SQLITE_FUNC_COUNT    0x100 /* Built-in count(*) aggregate */
1153 #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
1154 #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
1155 #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
1156 
1157 /*
1158 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
1159 ** used to create the initializers for the FuncDef structures.
1160 **
1161 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
1162 **     Used to create a scalar function definition of a function zName
1163 **     implemented by C function xFunc that accepts nArg arguments. The
1164 **     value passed as iArg is cast to a (void*) and made available
1165 **     as the user-data (sqlite3_user_data()) for the function. If
1166 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
1167 **
1168 **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
1169 **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
1170 **
1171 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
1172 **     Used to create an aggregate function definition implemented by
1173 **     the C functions xStep and xFinal. The first four parameters
1174 **     are interpreted in the same way as the first 4 parameters to
1175 **     FUNCTION().
1176 **
1177 **   LIKEFUNC(zName, nArg, pArg, flags)
1178 **     Used to create a scalar function definition of a function zName
1179 **     that accepts nArg arguments and is implemented by a call to C
1180 **     function likeFunc. Argument pArg is cast to a (void *) and made
1181 **     available as the function user-data (sqlite3_user_data()). The
1182 **     FuncDef.flags variable is set to the value passed as the flags
1183 **     parameter.
1184 */
1185 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
1186   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
1187    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
1188 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
1189   {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
1190    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
1191 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
1192   {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
1193    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
1194 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
1195   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
1196    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
1197 #define LIKEFUNC(zName, nArg, arg, flags) \
1198   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
1199    (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
1200 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
1201   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
1202    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
1203 
1204 /*
1205 ** All current savepoints are stored in a linked list starting at
1206 ** sqlite3.pSavepoint. The first element in the list is the most recently
1207 ** opened savepoint. Savepoints are added to the list by the vdbe
1208 ** OP_Savepoint instruction.
1209 */
1210 struct Savepoint {
1211   char *zName;                        /* Savepoint name (nul-terminated) */
1212   i64 nDeferredCons;                  /* Number of deferred fk violations */
1213   i64 nDeferredImmCons;               /* Number of deferred imm fk. */
1214   Savepoint *pNext;                   /* Parent savepoint (if any) */
1215 };
1216 
1217 /*
1218 ** The following are used as the second parameter to sqlite3Savepoint(),
1219 ** and as the P1 argument to the OP_Savepoint instruction.
1220 */
1221 #define SAVEPOINT_BEGIN      0
1222 #define SAVEPOINT_RELEASE    1
1223 #define SAVEPOINT_ROLLBACK   2
1224 
1225 
1226 /*
1227 ** Each SQLite module (virtual table definition) is defined by an
1228 ** instance of the following structure, stored in the sqlite3.aModule
1229 ** hash table.
1230 */
1231 struct Module {
1232   const sqlite3_module *pModule;       /* Callback pointers */
1233   const char *zName;                   /* Name passed to create_module() */
1234   void *pAux;                          /* pAux passed to create_module() */
1235   void (*xDestroy)(void *);            /* Module destructor function */
1236 };
1237 
1238 /*
1239 ** information about each column of an SQL table is held in an instance
1240 ** of this structure.
1241 */
1242 struct Column {
1243   char *zName;     /* Name of this column */
1244   Expr *pDflt;     /* Default value of this column */
1245   char *zDflt;     /* Original text of the default value */
1246   char *zType;     /* Data type for this column */
1247   char *zColl;     /* Collating sequence.  If NULL, use the default */
1248   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
1249   char affinity;   /* One of the SQLITE_AFF_... values */
1250   u8 szEst;        /* Estimated size of this column.  INT==1 */
1251   u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
1252 };
1253 
1254 /* Allowed values for Column.colFlags:
1255 */
1256 #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
1257 #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
1258 
1259 /*
1260 ** A "Collating Sequence" is defined by an instance of the following
1261 ** structure. Conceptually, a collating sequence consists of a name and
1262 ** a comparison routine that defines the order of that sequence.
1263 **
1264 ** If CollSeq.xCmp is NULL, it means that the
1265 ** collating sequence is undefined.  Indices built on an undefined
1266 ** collating sequence may not be read or written.
1267 */
1268 struct CollSeq {
1269   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
1270   u8 enc;               /* Text encoding handled by xCmp() */
1271   void *pUser;          /* First argument to xCmp() */
1272   int (*xCmp)(void*,int, const void*, int, const void*);
1273   void (*xDel)(void*);  /* Destructor for pUser */
1274 };
1275 
1276 /*
1277 ** A sort order can be either ASC or DESC.
1278 */
1279 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
1280 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
1281 
1282 /*
1283 ** Column affinity types.
1284 **
1285 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
1286 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
1287 ** the speed a little by numbering the values consecutively.
1288 **
1289 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
1290 ** when multiple affinity types are concatenated into a string and
1291 ** used as the P4 operand, they will be more readable.
1292 **
1293 ** Note also that the numeric types are grouped together so that testing
1294 ** for a numeric type is a single comparison.
1295 */
1296 #define SQLITE_AFF_TEXT     'a'
1297 #define SQLITE_AFF_NONE     'b'
1298 #define SQLITE_AFF_NUMERIC  'c'
1299 #define SQLITE_AFF_INTEGER  'd'
1300 #define SQLITE_AFF_REAL     'e'
1301 
1302 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
1303 
1304 /*
1305 ** The SQLITE_AFF_MASK values masks off the significant bits of an
1306 ** affinity value.
1307 */
1308 #define SQLITE_AFF_MASK     0x67
1309 
1310 /*
1311 ** Additional bit values that can be ORed with an affinity without
1312 ** changing the affinity.
1313 */
1314 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
1315 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
1316 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
1317 
1318 /*
1319 ** An object of this type is created for each virtual table present in
1320 ** the database schema.
1321 **
1322 ** If the database schema is shared, then there is one instance of this
1323 ** structure for each database connection (sqlite3*) that uses the shared
1324 ** schema. This is because each database connection requires its own unique
1325 ** instance of the sqlite3_vtab* handle used to access the virtual table
1326 ** implementation. sqlite3_vtab* handles can not be shared between
1327 ** database connections, even when the rest of the in-memory database
1328 ** schema is shared, as the implementation often stores the database
1329 ** connection handle passed to it via the xConnect() or xCreate() method
1330 ** during initialization internally. This database connection handle may
1331 ** then be used by the virtual table implementation to access real tables
1332 ** within the database. So that they appear as part of the callers
1333 ** transaction, these accesses need to be made via the same database
1334 ** connection as that used to execute SQL operations on the virtual table.
1335 **
1336 ** All VTable objects that correspond to a single table in a shared
1337 ** database schema are initially stored in a linked-list pointed to by
1338 ** the Table.pVTable member variable of the corresponding Table object.
1339 ** When an sqlite3_prepare() operation is required to access the virtual
1340 ** table, it searches the list for the VTable that corresponds to the
1341 ** database connection doing the preparing so as to use the correct
1342 ** sqlite3_vtab* handle in the compiled query.
1343 **
1344 ** When an in-memory Table object is deleted (for example when the
1345 ** schema is being reloaded for some reason), the VTable objects are not
1346 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
1347 ** immediately. Instead, they are moved from the Table.pVTable list to
1348 ** another linked list headed by the sqlite3.pDisconnect member of the
1349 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
1350 ** next time a statement is prepared using said sqlite3*. This is done
1351 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
1352 ** Refer to comments above function sqlite3VtabUnlockList() for an
1353 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
1354 ** list without holding the corresponding sqlite3.mutex mutex.
1355 **
1356 ** The memory for objects of this type is always allocated by
1357 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
1358 ** the first argument.
1359 */
1360 struct VTable {
1361   sqlite3 *db;              /* Database connection associated with this table */
1362   Module *pMod;             /* Pointer to module implementation */
1363   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
1364   int nRef;                 /* Number of pointers to this structure */
1365   u8 bConstraint;           /* True if constraints are supported */
1366   int iSavepoint;           /* Depth of the SAVEPOINT stack */
1367   VTable *pNext;            /* Next in linked list (see above) */
1368 };
1369 
1370 /*
1371 ** Each SQL table is represented in memory by an instance of the
1372 ** following structure.
1373 **
1374 ** Table.zName is the name of the table.  The case of the original
1375 ** CREATE TABLE statement is stored, but case is not significant for
1376 ** comparisons.
1377 **
1378 ** Table.nCol is the number of columns in this table.  Table.aCol is a
1379 ** pointer to an array of Column structures, one for each column.
1380 **
1381 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
1382 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
1383 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
1384 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
1385 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
1386 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
1387 ** the table has any PRIMARY KEY, INTEGER or otherwise.
1388 **
1389 ** Table.tnum is the page number for the root BTree page of the table in the
1390 ** database file.  If Table.iDb is the index of the database table backend
1391 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
1392 ** holds temporary tables and indices.  If TF_Ephemeral is set
1393 ** then the table is stored in a file that is automatically deleted
1394 ** when the VDBE cursor to the table is closed.  In this case Table.tnum
1395 ** refers VDBE cursor number that holds the table open, not to the root
1396 ** page number.  Transient tables are used to hold the results of a
1397 ** sub-query that appears instead of a real table name in the FROM clause
1398 ** of a SELECT statement.
1399 */
1400 struct Table {
1401   char *zName;         /* Name of the table or view */
1402   Column *aCol;        /* Information about each column */
1403   Index *pIndex;       /* List of SQL indexes on this table. */
1404   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
1405   FKey *pFKey;         /* Linked list of all foreign keys in this table */
1406   char *zColAff;       /* String defining the affinity of each column */
1407 #ifndef SQLITE_OMIT_CHECK
1408   ExprList *pCheck;    /* All CHECK constraints */
1409 #endif
1410   tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
1411   int tnum;            /* Root BTree node for this table (see note above) */
1412   i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
1413   i16 nCol;            /* Number of columns in this table */
1414   u16 nRef;            /* Number of pointers to this Table */
1415   LogEst szTabRow;     /* Estimated size of each table row in bytes */
1416   u8 tabFlags;         /* Mask of TF_* values */
1417   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
1418 #ifndef SQLITE_OMIT_ALTERTABLE
1419   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
1420 #endif
1421 #ifndef SQLITE_OMIT_VIRTUALTABLE
1422   int nModuleArg;      /* Number of arguments to the module */
1423   char **azModuleArg;  /* Text of all module args. [0] is module name */
1424   VTable *pVTable;     /* List of VTable objects. */
1425 #endif
1426   Trigger *pTrigger;   /* List of triggers stored in pSchema */
1427   Schema *pSchema;     /* Schema that contains this table */
1428   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
1429 };
1430 
1431 /*
1432 ** Allowed values for Table.tabFlags.
1433 */
1434 #define TF_Readonly        0x01    /* Read-only system table */
1435 #define TF_Ephemeral       0x02    /* An ephemeral table */
1436 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
1437 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
1438 #define TF_Virtual         0x10    /* Is a virtual table */
1439 #define TF_WithoutRowid    0x20    /* No rowid used. PRIMARY KEY is the key */
1440 
1441 
1442 /*
1443 ** Test to see whether or not a table is a virtual table.  This is
1444 ** done as a macro so that it will be optimized out when virtual
1445 ** table support is omitted from the build.
1446 */
1447 #ifndef SQLITE_OMIT_VIRTUALTABLE
1448 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
1449 #  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
1450 #else
1451 #  define IsVirtual(X)      0
1452 #  define IsHiddenColumn(X) 0
1453 #endif
1454 
1455 /* Does the table have a rowid */
1456 #define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
1457 
1458 /*
1459 ** Each foreign key constraint is an instance of the following structure.
1460 **
1461 ** A foreign key is associated with two tables.  The "from" table is
1462 ** the table that contains the REFERENCES clause that creates the foreign
1463 ** key.  The "to" table is the table that is named in the REFERENCES clause.
1464 ** Consider this example:
1465 **
1466 **     CREATE TABLE ex1(
1467 **       a INTEGER PRIMARY KEY,
1468 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
1469 **     );
1470 **
1471 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
1472 ** Equivalent names:
1473 **
1474 **     from-table == child-table
1475 **       to-table == parent-table
1476 **
1477 ** Each REFERENCES clause generates an instance of the following structure
1478 ** which is attached to the from-table.  The to-table need not exist when
1479 ** the from-table is created.  The existence of the to-table is not checked.
1480 **
1481 ** The list of all parents for child Table X is held at X.pFKey.
1482 **
1483 ** A list of all children for a table named Z (which might not even exist)
1484 ** is held in Schema.fkeyHash with a hash key of Z.
1485 */
1486 struct FKey {
1487   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
1488   FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
1489   char *zTo;        /* Name of table that the key points to (aka: Parent) */
1490   FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
1491   FKey *pPrevTo;    /* Previous with the same zTo */
1492   int nCol;         /* Number of columns in this key */
1493   /* EV: R-30323-21917 */
1494   u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
1495   u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
1496   Trigger *apTrigger[2];/* Triggers for aAction[] actions */
1497   struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
1498     int iFrom;            /* Index of column in pFrom */
1499     char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
1500   } aCol[1];            /* One entry for each of nCol columns */
1501 };
1502 
1503 /*
1504 ** SQLite supports many different ways to resolve a constraint
1505 ** error.  ROLLBACK processing means that a constraint violation
1506 ** causes the operation in process to fail and for the current transaction
1507 ** to be rolled back.  ABORT processing means the operation in process
1508 ** fails and any prior changes from that one operation are backed out,
1509 ** but the transaction is not rolled back.  FAIL processing means that
1510 ** the operation in progress stops and returns an error code.  But prior
1511 ** changes due to the same operation are not backed out and no rollback
1512 ** occurs.  IGNORE means that the particular row that caused the constraint
1513 ** error is not inserted or updated.  Processing continues and no error
1514 ** is returned.  REPLACE means that preexisting database rows that caused
1515 ** a UNIQUE constraint violation are removed so that the new insert or
1516 ** update can proceed.  Processing continues and no error is reported.
1517 **
1518 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
1519 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
1520 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
1521 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
1522 ** referenced table row is propagated into the row that holds the
1523 ** foreign key.
1524 **
1525 ** The following symbolic values are used to record which type
1526 ** of action to take.
1527 */
1528 #define OE_None     0   /* There is no constraint to check */
1529 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
1530 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
1531 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
1532 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
1533 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
1534 
1535 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
1536 #define OE_SetNull  7   /* Set the foreign key value to NULL */
1537 #define OE_SetDflt  8   /* Set the foreign key value to its default */
1538 #define OE_Cascade  9   /* Cascade the changes */
1539 
1540 #define OE_Default  10  /* Do whatever the default action is */
1541 
1542 
1543 /*
1544 ** An instance of the following structure is passed as the first
1545 ** argument to sqlite3VdbeKeyCompare and is used to control the
1546 ** comparison of the two index keys.
1547 **
1548 ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
1549 ** are nField slots for the columns of an index then one extra slot
1550 ** for the rowid at the end.
1551 */
1552 struct KeyInfo {
1553   u32 nRef;           /* Number of references to this KeyInfo object */
1554   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
1555   u16 nField;         /* Number of key columns in the index */
1556   u16 nXField;        /* Number of columns beyond the key columns */
1557   sqlite3 *db;        /* The database connection */
1558   u8 *aSortOrder;     /* Sort order for each column. */
1559   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
1560 };
1561 
1562 /*
1563 ** An instance of the following structure holds information about a
1564 ** single index record that has already been parsed out into individual
1565 ** values.
1566 **
1567 ** A record is an object that contains one or more fields of data.
1568 ** Records are used to store the content of a table row and to store
1569 ** the key of an index.  A blob encoding of a record is created by
1570 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
1571 ** OP_Column opcode.
1572 **
1573 ** This structure holds a record that has already been disassembled
1574 ** into its constituent fields.
1575 */
1576 struct UnpackedRecord {
1577   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
1578   u16 nField;         /* Number of entries in apMem[] */
1579   u8 flags;           /* Boolean settings.  UNPACKED_... below */
1580   Mem *aMem;          /* Values */
1581 };
1582 
1583 /*
1584 ** Allowed values of UnpackedRecord.flags
1585 */
1586 #define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
1587 #define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
1588 
1589 /*
1590 ** Each SQL index is represented in memory by an
1591 ** instance of the following structure.
1592 **
1593 ** The columns of the table that are to be indexed are described
1594 ** by the aiColumn[] field of this structure.  For example, suppose
1595 ** we have the following table and index:
1596 **
1597 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
1598 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
1599 **
1600 ** In the Table structure describing Ex1, nCol==3 because there are
1601 ** three columns in the table.  In the Index structure describing
1602 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
1603 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
1604 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
1605 ** The second column to be indexed (c1) has an index of 0 in
1606 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
1607 **
1608 ** The Index.onError field determines whether or not the indexed columns
1609 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
1610 ** it means this is not a unique index.  Otherwise it is a unique index
1611 ** and the value of Index.onError indicate the which conflict resolution
1612 ** algorithm to employ whenever an attempt is made to insert a non-unique
1613 ** element.
1614 */
1615 struct Index {
1616   char *zName;             /* Name of this index */
1617   i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
1618   tRowcnt *aiRowEst;       /* From ANALYZE: Est. rows selected by each column */
1619   Table *pTable;           /* The SQL table being indexed */
1620   char *zColAff;           /* String defining the affinity of each column */
1621   Index *pNext;            /* The next index associated with the same table */
1622   Schema *pSchema;         /* Schema containing this index */
1623   u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
1624   char **azColl;           /* Array of collation sequence names for index */
1625   Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
1626   KeyInfo *pKeyInfo;       /* A KeyInfo object suitable for this index */
1627   int tnum;                /* DB Page containing root of this index */
1628   LogEst szIdxRow;         /* Estimated average row size in bytes */
1629   u16 nKeyCol;             /* Number of columns forming the key */
1630   u16 nColumn;             /* Number of columns stored in the index */
1631   u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
1632   unsigned autoIndex:2;    /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
1633   unsigned bUnordered:1;   /* Use this index for == or IN queries only */
1634   unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
1635   unsigned isResized:1;    /* True if resizeIndexObject() has been called */
1636   unsigned isCovering:1;   /* True if this is a covering index */
1637 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1638   int nSample;             /* Number of elements in aSample[] */
1639   int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
1640   tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
1641   IndexSample *aSample;    /* Samples of the left-most key */
1642 #endif
1643 };
1644 
1645 /*
1646 ** Each sample stored in the sqlite_stat3 table is represented in memory
1647 ** using a structure of this type.  See documentation at the top of the
1648 ** analyze.c source file for additional information.
1649 */
1650 struct IndexSample {
1651   void *p;          /* Pointer to sampled record */
1652   int n;            /* Size of record in bytes */
1653   tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
1654   tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
1655   tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
1656 };
1657 
1658 /*
1659 ** Each token coming out of the lexer is an instance of
1660 ** this structure.  Tokens are also used as part of an expression.
1661 **
1662 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
1663 ** may contain random values.  Do not make any assumptions about Token.dyn
1664 ** and Token.n when Token.z==0.
1665 */
1666 struct Token {
1667   const char *z;     /* Text of the token.  Not NULL-terminated! */
1668   unsigned int n;    /* Number of characters in this token */
1669 };
1670 
1671 /*
1672 ** An instance of this structure contains information needed to generate
1673 ** code for a SELECT that contains aggregate functions.
1674 **
1675 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
1676 ** pointer to this structure.  The Expr.iColumn field is the index in
1677 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
1678 ** code for that node.
1679 **
1680 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
1681 ** original Select structure that describes the SELECT statement.  These
1682 ** fields do not need to be freed when deallocating the AggInfo structure.
1683 */
1684 struct AggInfo {
1685   u8 directMode;          /* Direct rendering mode means take data directly
1686                           ** from source tables rather than from accumulators */
1687   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
1688                           ** than the source table */
1689   int sortingIdx;         /* Cursor number of the sorting index */
1690   int sortingIdxPTab;     /* Cursor number of pseudo-table */
1691   int nSortingColumn;     /* Number of columns in the sorting index */
1692   int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
1693   ExprList *pGroupBy;     /* The group by clause */
1694   struct AggInfo_col {    /* For each column used in source tables */
1695     Table *pTab;             /* Source table */
1696     int iTable;              /* Cursor number of the source table */
1697     int iColumn;             /* Column number within the source table */
1698     int iSorterColumn;       /* Column number in the sorting index */
1699     int iMem;                /* Memory location that acts as accumulator */
1700     Expr *pExpr;             /* The original expression */
1701   } *aCol;
1702   int nColumn;            /* Number of used entries in aCol[] */
1703   int nAccumulator;       /* Number of columns that show through to the output.
1704                           ** Additional columns are used only as parameters to
1705                           ** aggregate functions */
1706   struct AggInfo_func {   /* For each aggregate function */
1707     Expr *pExpr;             /* Expression encoding the function */
1708     FuncDef *pFunc;          /* The aggregate function implementation */
1709     int iMem;                /* Memory location that acts as accumulator */
1710     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
1711   } *aFunc;
1712   int nFunc;              /* Number of entries in aFunc[] */
1713 };
1714 
1715 /*
1716 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
1717 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
1718 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
1719 ** it uses less memory in the Expr object, which is a big memory user
1720 ** in systems with lots of prepared statements.  And few applications
1721 ** need more than about 10 or 20 variables.  But some extreme users want
1722 ** to have prepared statements with over 32767 variables, and for them
1723 ** the option is available (at compile-time).
1724 */
1725 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
1726 typedef i16 ynVar;
1727 #else
1728 typedef int ynVar;
1729 #endif
1730 
1731 /*
1732 ** Each node of an expression in the parse tree is an instance
1733 ** of this structure.
1734 **
1735 ** Expr.op is the opcode. The integer parser token codes are reused
1736 ** as opcodes here. For example, the parser defines TK_GE to be an integer
1737 ** code representing the ">=" operator. This same integer code is reused
1738 ** to represent the greater-than-or-equal-to operator in the expression
1739 ** tree.
1740 **
1741 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
1742 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
1743 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
1744 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
1745 ** then Expr.token contains the name of the function.
1746 **
1747 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
1748 ** binary operator. Either or both may be NULL.
1749 **
1750 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
1751 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
1752 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
1753 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
1754 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
1755 ** valid.
1756 **
1757 ** An expression of the form ID or ID.ID refers to a column in a table.
1758 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
1759 ** the integer cursor number of a VDBE cursor pointing to that table and
1760 ** Expr.iColumn is the column number for the specific column.  If the
1761 ** expression is used as a result in an aggregate SELECT, then the
1762 ** value is also stored in the Expr.iAgg column in the aggregate so that
1763 ** it can be accessed after all aggregates are computed.
1764 **
1765 ** If the expression is an unbound variable marker (a question mark
1766 ** character '?' in the original SQL) then the Expr.iTable holds the index
1767 ** number for that variable.
1768 **
1769 ** If the expression is a subquery then Expr.iColumn holds an integer
1770 ** register number containing the result of the subquery.  If the
1771 ** subquery gives a constant result, then iTable is -1.  If the subquery
1772 ** gives a different answer at different times during statement processing
1773 ** then iTable is the address of a subroutine that computes the subquery.
1774 **
1775 ** If the Expr is of type OP_Column, and the table it is selecting from
1776 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
1777 ** corresponding table definition.
1778 **
1779 ** ALLOCATION NOTES:
1780 **
1781 ** Expr objects can use a lot of memory space in database schema.  To
1782 ** help reduce memory requirements, sometimes an Expr object will be
1783 ** truncated.  And to reduce the number of memory allocations, sometimes
1784 ** two or more Expr objects will be stored in a single memory allocation,
1785 ** together with Expr.zToken strings.
1786 **
1787 ** If the EP_Reduced and EP_TokenOnly flags are set when
1788 ** an Expr object is truncated.  When EP_Reduced is set, then all
1789 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
1790 ** are contained within the same memory allocation.  Note, however, that
1791 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
1792 ** allocated, regardless of whether or not EP_Reduced is set.
1793 */
1794 struct Expr {
1795   u8 op;                 /* Operation performed by this node */
1796   char affinity;         /* The affinity of the column or 0 if not a column */
1797   u32 flags;             /* Various flags.  EP_* See below */
1798   union {
1799     char *zToken;          /* Token value. Zero terminated and dequoted */
1800     int iValue;            /* Non-negative integer value if EP_IntValue */
1801   } u;
1802 
1803   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
1804   ** space is allocated for the fields below this point. An attempt to
1805   ** access them will result in a segfault or malfunction.
1806   *********************************************************************/
1807 
1808   Expr *pLeft;           /* Left subnode */
1809   Expr *pRight;          /* Right subnode */
1810   union {
1811     ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
1812     Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
1813   } x;
1814 
1815   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
1816   ** space is allocated for the fields below this point. An attempt to
1817   ** access them will result in a segfault or malfunction.
1818   *********************************************************************/
1819 
1820 #if SQLITE_MAX_EXPR_DEPTH>0
1821   int nHeight;           /* Height of the tree headed by this node */
1822 #endif
1823   int iTable;            /* TK_COLUMN: cursor number of table holding column
1824                          ** TK_REGISTER: register number
1825                          ** TK_TRIGGER: 1 -> new, 0 -> old
1826                          ** EP_Unlikely:  1000 times likelihood */
1827   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
1828                          ** TK_VARIABLE: variable number (always >= 1). */
1829   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
1830   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
1831   u8 op2;                /* TK_REGISTER: original value of Expr.op
1832                          ** TK_COLUMN: the value of p5 for OP_Column
1833                          ** TK_AGG_FUNCTION: nesting depth */
1834   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
1835   Table *pTab;           /* Table for TK_COLUMN expressions. */
1836 };
1837 
1838 /*
1839 ** The following are the meanings of bits in the Expr.flags field.
1840 */
1841 #define EP_FromJoin  0x000001 /* Originated in ON or USING clause of a join */
1842 #define EP_Agg       0x000002 /* Contains one or more aggregate functions */
1843 #define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
1844 #define EP_Error     0x000008 /* Expression contains one or more errors */
1845 #define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
1846 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
1847 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
1848 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
1849 #define EP_Collate   0x000100 /* Tree contains a TK_COLLATE opeartor */
1850       /* unused      0x000200 */
1851 #define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
1852 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
1853 #define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
1854 #define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
1855 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
1856 #define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
1857 #define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
1858 #define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
1859 #define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
1860 #define EP_Constant  0x080000 /* Node is a constant */
1861 
1862 /*
1863 ** These macros can be used to test, set, or clear bits in the
1864 ** Expr.flags field.
1865 */
1866 #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
1867 #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
1868 #define ExprSetProperty(E,P)     (E)->flags|=(P)
1869 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
1870 
1871 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
1872 ** and Accreditation only.  It works like ExprSetProperty() during VVA
1873 ** processes but is a no-op for delivery.
1874 */
1875 #ifdef SQLITE_DEBUG
1876 # define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
1877 #else
1878 # define ExprSetVVAProperty(E,P)
1879 #endif
1880 
1881 /*
1882 ** Macros to determine the number of bytes required by a normal Expr
1883 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
1884 ** and an Expr struct with the EP_TokenOnly flag set.
1885 */
1886 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
1887 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
1888 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
1889 
1890 /*
1891 ** Flags passed to the sqlite3ExprDup() function. See the header comment
1892 ** above sqlite3ExprDup() for details.
1893 */
1894 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
1895 
1896 /*
1897 ** A list of expressions.  Each expression may optionally have a
1898 ** name.  An expr/name combination can be used in several ways, such
1899 ** as the list of "expr AS ID" fields following a "SELECT" or in the
1900 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
1901 ** also be used as the argument to a function, in which case the a.zName
1902 ** field is not used.
1903 **
1904 ** By default the Expr.zSpan field holds a human-readable description of
1905 ** the expression that is used in the generation of error messages and
1906 ** column labels.  In this case, Expr.zSpan is typically the text of a
1907 ** column expression as it exists in a SELECT statement.  However, if
1908 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
1909 ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
1910 ** form is used for name resolution with nested FROM clauses.
1911 */
1912 struct ExprList {
1913   int nExpr;             /* Number of expressions on the list */
1914   int iECursor;          /* VDBE Cursor associated with this ExprList */
1915   struct ExprList_item { /* For each expression in the list */
1916     Expr *pExpr;            /* The list of expressions */
1917     char *zName;            /* Token associated with this expression */
1918     char *zSpan;            /* Original text of the expression */
1919     u8 sortOrder;           /* 1 for DESC or 0 for ASC */
1920     unsigned done :1;       /* A flag to indicate when processing is finished */
1921     unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
1922     unsigned reusable :1;   /* Constant expression is reusable */
1923     union {
1924       struct {
1925         u16 iOrderByCol;      /* For ORDER BY, column number in result set */
1926         u16 iAlias;           /* Index into Parse.aAlias[] for zName */
1927       } x;
1928       int iConstExprReg;      /* Register in which Expr value is cached */
1929     } u;
1930   } *a;                  /* Alloc a power of two greater or equal to nExpr */
1931 };
1932 
1933 /*
1934 ** An instance of this structure is used by the parser to record both
1935 ** the parse tree for an expression and the span of input text for an
1936 ** expression.
1937 */
1938 struct ExprSpan {
1939   Expr *pExpr;          /* The expression parse tree */
1940   const char *zStart;   /* First character of input text */
1941   const char *zEnd;     /* One character past the end of input text */
1942 };
1943 
1944 /*
1945 ** An instance of this structure can hold a simple list of identifiers,
1946 ** such as the list "a,b,c" in the following statements:
1947 **
1948 **      INSERT INTO t(a,b,c) VALUES ...;
1949 **      CREATE INDEX idx ON t(a,b,c);
1950 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
1951 **
1952 ** The IdList.a.idx field is used when the IdList represents the list of
1953 ** column names after a table name in an INSERT statement.  In the statement
1954 **
1955 **     INSERT INTO t(a,b,c) ...
1956 **
1957 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
1958 */
1959 struct IdList {
1960   struct IdList_item {
1961     char *zName;      /* Name of the identifier */
1962     int idx;          /* Index in some Table.aCol[] of a column named zName */
1963   } *a;
1964   int nId;         /* Number of identifiers on the list */
1965 };
1966 
1967 /*
1968 ** The bitmask datatype defined below is used for various optimizations.
1969 **
1970 ** Changing this from a 64-bit to a 32-bit type limits the number of
1971 ** tables in a join to 32 instead of 64.  But it also reduces the size
1972 ** of the library by 738 bytes on ix86.
1973 */
1974 typedef u64 Bitmask;
1975 
1976 /*
1977 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
1978 */
1979 #define BMS  ((int)(sizeof(Bitmask)*8))
1980 
1981 /*
1982 ** A bit in a Bitmask
1983 */
1984 #define MASKBIT(n)   (((Bitmask)1)<<(n))
1985 #define MASKBIT32(n) (((unsigned int)1)<<(n))
1986 
1987 /*
1988 ** The following structure describes the FROM clause of a SELECT statement.
1989 ** Each table or subquery in the FROM clause is a separate element of
1990 ** the SrcList.a[] array.
1991 **
1992 ** With the addition of multiple database support, the following structure
1993 ** can also be used to describe a particular table such as the table that
1994 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
1995 ** such a table must be a simple name: ID.  But in SQLite, the table can
1996 ** now be identified by a database name, a dot, then the table name: ID.ID.
1997 **
1998 ** The jointype starts out showing the join type between the current table
1999 ** and the next table on the list.  The parser builds the list this way.
2000 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
2001 ** jointype expresses the join between the table and the previous table.
2002 **
2003 ** In the colUsed field, the high-order bit (bit 63) is set if the table
2004 ** contains more than 63 columns and the 64-th or later column is used.
2005 */
2006 struct SrcList {
2007   u8 nSrc;        /* Number of tables or subqueries in the FROM clause */
2008   u8 nAlloc;      /* Number of entries allocated in a[] below */
2009   struct SrcList_item {
2010     Schema *pSchema;  /* Schema to which this item is fixed */
2011     char *zDatabase;  /* Name of database holding this table */
2012     char *zName;      /* Name of the table */
2013     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
2014     Table *pTab;      /* An SQL table corresponding to zName */
2015     Select *pSelect;  /* A SELECT statement used in place of a table name */
2016     int addrFillSub;  /* Address of subroutine to manifest a subquery */
2017     int regReturn;    /* Register holding return address of addrFillSub */
2018     u8 jointype;      /* Type of join between this able and the previous */
2019     unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
2020     unsigned isCorrelated :1;  /* True if sub-query is correlated */
2021     unsigned viaCoroutine :1;  /* Implemented as a co-routine */
2022     unsigned isRecursive :1;   /* True for recursive reference in WITH */
2023 #ifndef SQLITE_OMIT_EXPLAIN
2024     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
2025 #endif
2026     int iCursor;      /* The VDBE cursor number used to access this table */
2027     Expr *pOn;        /* The ON clause of a join */
2028     IdList *pUsing;   /* The USING clause of a join */
2029     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
2030     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
2031     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
2032   } a[1];             /* One entry for each identifier on the list */
2033 };
2034 
2035 /*
2036 ** Permitted values of the SrcList.a.jointype field
2037 */
2038 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
2039 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
2040 #define JT_NATURAL   0x0004    /* True for a "natural" join */
2041 #define JT_LEFT      0x0008    /* Left outer join */
2042 #define JT_RIGHT     0x0010    /* Right outer join */
2043 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
2044 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
2045 
2046 
2047 /*
2048 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
2049 ** and the WhereInfo.wctrlFlags member.
2050 */
2051 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
2052 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
2053 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
2054 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
2055 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
2056 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
2057 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
2058 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
2059 #define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
2060 #define WHERE_GROUPBY          0x0100 /* pOrderBy is really a GROUP BY */
2061 #define WHERE_DISTINCTBY       0x0200 /* pOrderby is really a DISTINCT clause */
2062 #define WHERE_WANT_DISTINCT    0x0400 /* All output needs to be distinct */
2063 
2064 /* Allowed return values from sqlite3WhereIsDistinct()
2065 */
2066 #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
2067 #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
2068 #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
2069 #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
2070 
2071 /*
2072 ** A NameContext defines a context in which to resolve table and column
2073 ** names.  The context consists of a list of tables (the pSrcList) field and
2074 ** a list of named expression (pEList).  The named expression list may
2075 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
2076 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
2077 ** pEList corresponds to the result set of a SELECT and is NULL for
2078 ** other statements.
2079 **
2080 ** NameContexts can be nested.  When resolving names, the inner-most
2081 ** context is searched first.  If no match is found, the next outer
2082 ** context is checked.  If there is still no match, the next context
2083 ** is checked.  This process continues until either a match is found
2084 ** or all contexts are check.  When a match is found, the nRef member of
2085 ** the context containing the match is incremented.
2086 **
2087 ** Each subquery gets a new NameContext.  The pNext field points to the
2088 ** NameContext in the parent query.  Thus the process of scanning the
2089 ** NameContext list corresponds to searching through successively outer
2090 ** subqueries looking for a match.
2091 */
2092 struct NameContext {
2093   Parse *pParse;       /* The parser */
2094   SrcList *pSrcList;   /* One or more tables used to resolve names */
2095   ExprList *pEList;    /* Optional list of result-set columns */
2096   AggInfo *pAggInfo;   /* Information about aggregates at this level */
2097   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
2098   int nRef;            /* Number of names resolved by this context */
2099   int nErr;            /* Number of errors encountered while resolving names */
2100   u8 ncFlags;          /* Zero or more NC_* flags defined below */
2101 };
2102 
2103 /*
2104 ** Allowed values for the NameContext, ncFlags field.
2105 */
2106 #define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
2107 #define NC_HasAgg    0x02    /* One or more aggregate functions seen */
2108 #define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
2109 #define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
2110 #define NC_PartIdx   0x10    /* True if resolving a partial index WHERE */
2111 
2112 /*
2113 ** An instance of the following structure contains all information
2114 ** needed to generate code for a single SELECT statement.
2115 **
2116 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
2117 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
2118 ** limit and nOffset to the value of the offset (or 0 if there is not
2119 ** offset).  But later on, nLimit and nOffset become the memory locations
2120 ** in the VDBE that record the limit and offset counters.
2121 **
2122 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
2123 ** These addresses must be stored so that we can go back and fill in
2124 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
2125 ** the number of columns in P2 can be computed at the same time
2126 ** as the OP_OpenEphm instruction is coded because not
2127 ** enough information about the compound query is known at that point.
2128 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
2129 ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
2130 ** sequences for the ORDER BY clause.
2131 */
2132 struct Select {
2133   ExprList *pEList;      /* The fields of the result */
2134   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
2135   u16 selFlags;          /* Various SF_* values */
2136   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
2137   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
2138   u64 nSelectRow;        /* Estimated number of result rows */
2139   SrcList *pSrc;         /* The FROM clause */
2140   Expr *pWhere;          /* The WHERE clause */
2141   ExprList *pGroupBy;    /* The GROUP BY clause */
2142   Expr *pHaving;         /* The HAVING clause */
2143   ExprList *pOrderBy;    /* The ORDER BY clause */
2144   Select *pPrior;        /* Prior select in a compound select statement */
2145   Select *pNext;         /* Next select to the left in a compound */
2146   Select *pRightmost;    /* Right-most select in a compound select statement */
2147   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
2148   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
2149   With *pWith;           /* WITH clause attached to this select. Or NULL. */
2150 };
2151 
2152 /*
2153 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
2154 ** "Select Flag".
2155 */
2156 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
2157 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
2158 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
2159 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
2160 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
2161 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
2162 #define SF_UseSorter       0x0040  /* Sort using a sorter */
2163 #define SF_Values          0x0080  /* Synthesized from VALUES clause */
2164 #define SF_Materialize     0x0100  /* Force materialization of views */
2165 #define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
2166 #define SF_MaybeConvert    0x0400  /* Need convertCompoundSelectToSubquery() */
2167 #define SF_Recursive       0x0800  /* The recursive part of a recursive CTE */
2168 
2169 
2170 /*
2171 ** The results of a SELECT can be distributed in several ways, as defined
2172 ** by one of the following macros.  The "SRT" prefix means "SELECT Result
2173 ** Type".
2174 **
2175 **     SRT_Union       Store results as a key in a temporary index
2176 **                     identified by pDest->iSDParm.
2177 **
2178 **     SRT_Except      Remove results from the temporary index pDest->iSDParm.
2179 **
2180 **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
2181 **                     set is not empty.
2182 **
2183 **     SRT_Discard     Throw the results away.  This is used by SELECT
2184 **                     statements within triggers whose only purpose is
2185 **                     the side-effects of functions.
2186 **
2187 ** All of the above are free to ignore their ORDER BY clause. Those that
2188 ** follow must honor the ORDER BY clause.
2189 **
2190 **     SRT_Output      Generate a row of output (using the OP_ResultRow
2191 **                     opcode) for each row in the result set.
2192 **
2193 **     SRT_Mem         Only valid if the result is a single column.
2194 **                     Store the first column of the first result row
2195 **                     in register pDest->iSDParm then abandon the rest
2196 **                     of the query.  This destination implies "LIMIT 1".
2197 **
2198 **     SRT_Set         The result must be a single column.  Store each
2199 **                     row of result as the key in table pDest->iSDParm.
2200 **                     Apply the affinity pDest->affSdst before storing
2201 **                     results.  Used to implement "IN (SELECT ...)".
2202 **
2203 **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
2204 **                     the result there. The cursor is left open after
2205 **                     returning.  This is like SRT_Table except that
2206 **                     this destination uses OP_OpenEphemeral to create
2207 **                     the table first.
2208 **
2209 **     SRT_Coroutine   Generate a co-routine that returns a new row of
2210 **                     results each time it is invoked.  The entry point
2211 **                     of the co-routine is stored in register pDest->iSDParm
2212 **                     and the result row is stored in pDest->nDest registers
2213 **                     starting with pDest->iSdst.
2214 **
2215 **     SRT_Table       Store results in temporary table pDest->iSDParm.
2216 **                     This is like SRT_EphemTab except that the table
2217 **                     is assumed to already be open.
2218 **
2219 **     SRT_DistTable   Store results in a temporary table pDest->iSDParm.
2220 **                     But also use temporary table pDest->iSDParm+1 as
2221 **                     a record of all prior results and ignore any duplicate
2222 **                     rows.  Name means:  "Distinct Table".
2223 **
2224 **     SRT_Queue       Store results in priority queue pDest->iSDParm (really
2225 **                     an index).  Append a sequence number so that all entries
2226 **                     are distinct.
2227 **
2228 **     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
2229 **                     the same record has never been stored before.  The
2230 **                     index at pDest->iSDParm+1 hold all prior stores.
2231 */
2232 #define SRT_Union        1  /* Store result as keys in an index */
2233 #define SRT_Except       2  /* Remove result from a UNION index */
2234 #define SRT_Exists       3  /* Store 1 if the result is not empty */
2235 #define SRT_Discard      4  /* Do not save the results anywhere */
2236 
2237 /* The ORDER BY clause is ignored for all of the above */
2238 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
2239 
2240 #define SRT_Output       5  /* Output each row of result */
2241 #define SRT_Mem          6  /* Store result in a memory cell */
2242 #define SRT_Set          7  /* Store results as keys in an index */
2243 #define SRT_EphemTab     8  /* Create transient tab and store like SRT_Table */
2244 #define SRT_Coroutine    9  /* Generate a single row of result */
2245 #define SRT_Table       10  /* Store result as data with an automatic rowid */
2246 #define SRT_DistTable   11  /* Like SRT_Table, but unique results only */
2247 #define SRT_Queue       12  /* Store result in an queue */
2248 #define SRT_DistQueue   13  /* Like SRT_Queue, but unique results only */
2249 
2250 /*
2251 ** An instance of this object describes where to put of the results of
2252 ** a SELECT statement.
2253 */
2254 struct SelectDest {
2255   u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
2256   char affSdst;        /* Affinity used when eDest==SRT_Set */
2257   int iSDParm;         /* A parameter used by the eDest disposal method */
2258   int iSdst;           /* Base register where results are written */
2259   int nSdst;           /* Number of registers allocated */
2260   ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
2261 };
2262 
2263 /*
2264 ** During code generation of statements that do inserts into AUTOINCREMENT
2265 ** tables, the following information is attached to the Table.u.autoInc.p
2266 ** pointer of each autoincrement table to record some side information that
2267 ** the code generator needs.  We have to keep per-table autoincrement
2268 ** information in case inserts are down within triggers.  Triggers do not
2269 ** normally coordinate their activities, but we do need to coordinate the
2270 ** loading and saving of autoincrement information.
2271 */
2272 struct AutoincInfo {
2273   AutoincInfo *pNext;   /* Next info block in a list of them all */
2274   Table *pTab;          /* Table this info block refers to */
2275   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
2276   int regCtr;           /* Memory register holding the rowid counter */
2277 };
2278 
2279 /*
2280 ** Size of the column cache
2281 */
2282 #ifndef SQLITE_N_COLCACHE
2283 # define SQLITE_N_COLCACHE 10
2284 #endif
2285 
2286 /*
2287 ** At least one instance of the following structure is created for each
2288 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
2289 ** statement. All such objects are stored in the linked list headed at
2290 ** Parse.pTriggerPrg and deleted once statement compilation has been
2291 ** completed.
2292 **
2293 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
2294 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
2295 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
2296 ** The Parse.pTriggerPrg list never contains two entries with the same
2297 ** values for both pTrigger and orconf.
2298 **
2299 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
2300 ** accessed (or set to 0 for triggers fired as a result of INSERT
2301 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
2302 ** a mask of new.* columns used by the program.
2303 */
2304 struct TriggerPrg {
2305   Trigger *pTrigger;      /* Trigger this program was coded from */
2306   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
2307   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
2308   int orconf;             /* Default ON CONFLICT policy */
2309   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
2310 };
2311 
2312 /*
2313 ** The yDbMask datatype for the bitmask of all attached databases.
2314 */
2315 #if SQLITE_MAX_ATTACHED>30
2316   typedef sqlite3_uint64 yDbMask;
2317 #else
2318   typedef unsigned int yDbMask;
2319 #endif
2320 
2321 /*
2322 ** An SQL parser context.  A copy of this structure is passed through
2323 ** the parser and down into all the parser action routine in order to
2324 ** carry around information that is global to the entire parse.
2325 **
2326 ** The structure is divided into two parts.  When the parser and code
2327 ** generate call themselves recursively, the first part of the structure
2328 ** is constant but the second part is reset at the beginning and end of
2329 ** each recursion.
2330 **
2331 ** The nTableLock and aTableLock variables are only used if the shared-cache
2332 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
2333 ** used to store the set of table-locks required by the statement being
2334 ** compiled. Function sqlite3TableLock() is used to add entries to the
2335 ** list.
2336 */
2337 struct Parse {
2338   sqlite3 *db;         /* The main database structure */
2339   char *zErrMsg;       /* An error message */
2340   Vdbe *pVdbe;         /* An engine for executing database bytecode */
2341   int rc;              /* Return code from execution */
2342   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
2343   u8 checkSchema;      /* Causes schema cookie check after an error */
2344   u8 nested;           /* Number of nested calls to the parser/code generator */
2345   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
2346   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
2347   u8 nColCache;        /* Number of entries in aColCache[] */
2348   u8 iColCache;        /* Next entry in aColCache[] to replace */
2349   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
2350   u8 mayAbort;         /* True if statement may throw an ABORT exception */
2351   u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
2352   int aTempReg[8];     /* Holding area for temporary registers */
2353   int nRangeReg;       /* Size of the temporary register block */
2354   int iRangeReg;       /* First register in temporary register block */
2355   int nErr;            /* Number of errors seen */
2356   int nTab;            /* Number of previously allocated VDBE cursors */
2357   int nMem;            /* Number of memory cells used so far */
2358   int nSet;            /* Number of sets used so far */
2359   int nOnce;           /* Number of OP_Once instructions so far */
2360   int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
2361   int nLabel;          /* Number of labels used */
2362   int *aLabel;         /* Space to hold the labels */
2363   int iFixedOp;        /* Never back out opcodes iFixedOp-1 or earlier */
2364   int ckBase;          /* Base register of data during check constraints */
2365   int iPartIdxTab;     /* Table corresponding to a partial index */
2366   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
2367   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
2368   struct yColCache {
2369     int iTable;           /* Table cursor number */
2370     int iColumn;          /* Table column number */
2371     u8 tempReg;           /* iReg is a temp register that needs to be freed */
2372     int iLevel;           /* Nesting level */
2373     int iReg;             /* Reg with value of this column. 0 means none. */
2374     int lru;              /* Least recently used entry has the smallest value */
2375   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
2376   ExprList *pConstExpr;/* Constant expressions */
2377   yDbMask writeMask;   /* Start a write transaction on these databases */
2378   yDbMask cookieMask;  /* Bitmask of schema verified databases */
2379   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
2380   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
2381   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
2382   int regRoot;         /* Register holding root page number for new objects */
2383   int nMaxArg;         /* Max args passed to user function by sub-program */
2384   Token constraintName;/* Name of the constraint currently being parsed */
2385 #ifndef SQLITE_OMIT_SHARED_CACHE
2386   int nTableLock;        /* Number of locks in aTableLock */
2387   TableLock *aTableLock; /* Required table locks for shared-cache mode */
2388 #endif
2389   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
2390 
2391   /* Information used while coding trigger programs. */
2392   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
2393   Table *pTriggerTab;  /* Table triggers are being coded for */
2394   int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
2395   int addrSkipPK;      /* Address of instruction to skip PRIMARY KEY index */
2396   u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
2397   u32 oldmask;         /* Mask of old.* columns referenced */
2398   u32 newmask;         /* Mask of new.* columns referenced */
2399   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
2400   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
2401   u8 disableTriggers;  /* True to disable triggers */
2402 
2403   /* Above is constant between recursions.  Below is reset before and after
2404   ** each recursion */
2405 
2406   int nVar;                 /* Number of '?' variables seen in the SQL so far */
2407   int nzVar;                /* Number of available slots in azVar[] */
2408   u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
2409   u8 explain;               /* True if the EXPLAIN flag is found on the query */
2410 #ifndef SQLITE_OMIT_VIRTUALTABLE
2411   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
2412   int nVtabLock;            /* Number of virtual tables to lock */
2413 #endif
2414   int nAlias;               /* Number of aliased result set columns */
2415   int nHeight;              /* Expression tree height of current sub-select */
2416 #ifndef SQLITE_OMIT_EXPLAIN
2417   int iSelectId;            /* ID of current select for EXPLAIN output */
2418   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
2419 #endif
2420   char **azVar;             /* Pointers to names of parameters */
2421   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
2422   const char *zTail;        /* All SQL text past the last semicolon parsed */
2423   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
2424   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
2425   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
2426   Token sNameToken;         /* Token with unqualified schema object name */
2427   Token sLastToken;         /* The last token parsed */
2428 #ifndef SQLITE_OMIT_VIRTUALTABLE
2429   Token sArg;               /* Complete text of a module argument */
2430   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
2431 #endif
2432   Table *pZombieTab;        /* List of Table objects to delete after code gen */
2433   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
2434   With *pWith;              /* Current WITH clause, or NULL */
2435   u8 bFreeWith;             /* True if pWith should be freed with parser */
2436 };
2437 
2438 /*
2439 ** Return true if currently inside an sqlite3_declare_vtab() call.
2440 */
2441 #ifdef SQLITE_OMIT_VIRTUALTABLE
2442   #define IN_DECLARE_VTAB 0
2443 #else
2444   #define IN_DECLARE_VTAB (pParse->declareVtab)
2445 #endif
2446 
2447 /*
2448 ** An instance of the following structure can be declared on a stack and used
2449 ** to save the Parse.zAuthContext value so that it can be restored later.
2450 */
2451 struct AuthContext {
2452   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
2453   Parse *pParse;              /* The Parse structure */
2454 };
2455 
2456 /*
2457 ** Bitfield flags for P5 value in various opcodes.
2458 */
2459 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
2460 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
2461 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
2462 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
2463 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
2464 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
2465 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
2466 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
2467 #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
2468 #define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */
2469 #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
2470 
2471 /*
2472  * Each trigger present in the database schema is stored as an instance of
2473  * struct Trigger.
2474  *
2475  * Pointers to instances of struct Trigger are stored in two ways.
2476  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
2477  *    database). This allows Trigger structures to be retrieved by name.
2478  * 2. All triggers associated with a single table form a linked list, using the
2479  *    pNext member of struct Trigger. A pointer to the first element of the
2480  *    linked list is stored as the "pTrigger" member of the associated
2481  *    struct Table.
2482  *
2483  * The "step_list" member points to the first element of a linked list
2484  * containing the SQL statements specified as the trigger program.
2485  */
2486 struct Trigger {
2487   char *zName;            /* The name of the trigger                        */
2488   char *table;            /* The table or view to which the trigger applies */
2489   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
2490   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
2491   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
2492   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
2493                              the <column-list> is stored here */
2494   Schema *pSchema;        /* Schema containing the trigger */
2495   Schema *pTabSchema;     /* Schema containing the table */
2496   TriggerStep *step_list; /* Link list of trigger program steps             */
2497   Trigger *pNext;         /* Next trigger associated with the table */
2498 };
2499 
2500 /*
2501 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
2502 ** determine which.
2503 **
2504 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
2505 ** In that cases, the constants below can be ORed together.
2506 */
2507 #define TRIGGER_BEFORE  1
2508 #define TRIGGER_AFTER   2
2509 
2510 /*
2511  * An instance of struct TriggerStep is used to store a single SQL statement
2512  * that is a part of a trigger-program.
2513  *
2514  * Instances of struct TriggerStep are stored in a singly linked list (linked
2515  * using the "pNext" member) referenced by the "step_list" member of the
2516  * associated struct Trigger instance. The first element of the linked list is
2517  * the first step of the trigger-program.
2518  *
2519  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
2520  * "SELECT" statement. The meanings of the other members is determined by the
2521  * value of "op" as follows:
2522  *
2523  * (op == TK_INSERT)
2524  * orconf    -> stores the ON CONFLICT algorithm
2525  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
2526  *              this stores a pointer to the SELECT statement. Otherwise NULL.
2527  * target    -> A token holding the quoted name of the table to insert into.
2528  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
2529  *              this stores values to be inserted. Otherwise NULL.
2530  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
2531  *              statement, then this stores the column-names to be
2532  *              inserted into.
2533  *
2534  * (op == TK_DELETE)
2535  * target    -> A token holding the quoted name of the table to delete from.
2536  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
2537  *              Otherwise NULL.
2538  *
2539  * (op == TK_UPDATE)
2540  * target    -> A token holding the quoted name of the table to update rows of.
2541  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
2542  *              Otherwise NULL.
2543  * pExprList -> A list of the columns to update and the expressions to update
2544  *              them to. See sqlite3Update() documentation of "pChanges"
2545  *              argument.
2546  *
2547  */
2548 struct TriggerStep {
2549   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
2550   u8 orconf;           /* OE_Rollback etc. */
2551   Trigger *pTrig;      /* The trigger that this step is a part of */
2552   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
2553   Token target;        /* Target table for DELETE, UPDATE, INSERT */
2554   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
2555   ExprList *pExprList; /* SET clause for UPDATE. */
2556   IdList *pIdList;     /* Column names for INSERT */
2557   TriggerStep *pNext;  /* Next in the link-list */
2558   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
2559 };
2560 
2561 /*
2562 ** The following structure contains information used by the sqliteFix...
2563 ** routines as they walk the parse tree to make database references
2564 ** explicit.
2565 */
2566 typedef struct DbFixer DbFixer;
2567 struct DbFixer {
2568   Parse *pParse;      /* The parsing context.  Error messages written here */
2569   Schema *pSchema;    /* Fix items to this schema */
2570   int bVarOnly;       /* Check for variable references only */
2571   const char *zDb;    /* Make sure all objects are contained in this database */
2572   const char *zType;  /* Type of the container - used for error messages */
2573   const Token *pName; /* Name of the container - used for error messages */
2574 };
2575 
2576 /*
2577 ** An objected used to accumulate the text of a string where we
2578 ** do not necessarily know how big the string will be in the end.
2579 */
2580 struct StrAccum {
2581   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
2582   char *zBase;         /* A base allocation.  Not from malloc. */
2583   char *zText;         /* The string collected so far */
2584   int  nChar;          /* Length of the string so far */
2585   int  nAlloc;         /* Amount of space allocated in zText */
2586   int  mxAlloc;        /* Maximum allowed string length */
2587   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
2588   u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
2589 };
2590 #define STRACCUM_NOMEM   1
2591 #define STRACCUM_TOOBIG  2
2592 
2593 /*
2594 ** A pointer to this structure is used to communicate information
2595 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
2596 */
2597 typedef struct {
2598   sqlite3 *db;        /* The database being initialized */
2599   char **pzErrMsg;    /* Error message stored here */
2600   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
2601   int rc;             /* Result code stored here */
2602 } InitData;
2603 
2604 /*
2605 ** Structure containing global configuration data for the SQLite library.
2606 **
2607 ** This structure also contains some state information.
2608 */
2609 struct Sqlite3Config {
2610   int bMemstat;                     /* True to enable memory status */
2611   int bCoreMutex;                   /* True to enable core mutexing */
2612   int bFullMutex;                   /* True to enable full mutexing */
2613   int bOpenUri;                     /* True to interpret filenames as URIs */
2614   int bUseCis;                      /* Use covering indices for full-scans */
2615   int mxStrlen;                     /* Maximum string length */
2616   int neverCorrupt;                 /* Database is always well-formed */
2617   int szLookaside;                  /* Default lookaside buffer size */
2618   int nLookaside;                   /* Default lookaside buffer count */
2619   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
2620   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
2621   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
2622   void *pHeap;                      /* Heap storage space */
2623   int nHeap;                        /* Size of pHeap[] */
2624   int mnReq, mxReq;                 /* Min and max heap requests sizes */
2625   sqlite3_int64 szMmap;             /* mmap() space per open file */
2626   sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
2627   void *pScratch;                   /* Scratch memory */
2628   int szScratch;                    /* Size of each scratch buffer */
2629   int nScratch;                     /* Number of scratch buffers */
2630   void *pPage;                      /* Page cache memory */
2631   int szPage;                       /* Size of each page in pPage[] */
2632   int nPage;                        /* Number of pages in pPage[] */
2633   int mxParserStack;                /* maximum depth of the parser stack */
2634   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
2635   /* The above might be initialized to non-zero.  The following need to always
2636   ** initially be zero, however. */
2637   int isInit;                       /* True after initialization has finished */
2638   int inProgress;                   /* True while initialization in progress */
2639   int isMutexInit;                  /* True after mutexes are initialized */
2640   int isMallocInit;                 /* True after malloc is initialized */
2641   int isPCacheInit;                 /* True after malloc is initialized */
2642   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
2643   int nRefInitMutex;                /* Number of users of pInitMutex */
2644   void (*xLog)(void*,int,const char*); /* Function for logging */
2645   void *pLogArg;                       /* First argument to xLog() */
2646   int bLocaltimeFault;              /* True to fail localtime() calls */
2647 #ifdef SQLITE_ENABLE_SQLLOG
2648   void(*xSqllog)(void*,sqlite3*,const char*, int);
2649   void *pSqllogArg;
2650 #endif
2651 };
2652 
2653 /*
2654 ** This macro is used inside of assert() statements to indicate that
2655 ** the assert is only valid on a well-formed database.  Instead of:
2656 **
2657 **     assert( X );
2658 **
2659 ** One writes:
2660 **
2661 **     assert( X || CORRUPT_DB );
2662 **
2663 ** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
2664 ** that the database is definitely corrupt, only that it might be corrupt.
2665 ** For most test cases, CORRUPT_DB is set to false using a special
2666 ** sqlite3_test_control().  This enables assert() statements to prove
2667 ** things that are always true for well-formed databases.
2668 */
2669 #define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
2670 
2671 /*
2672 ** Context pointer passed down through the tree-walk.
2673 */
2674 struct Walker {
2675   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
2676   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
2677   void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
2678   Parse *pParse;                            /* Parser context.  */
2679   int walkerDepth;                          /* Number of subqueries */
2680   union {                                   /* Extra data for callback */
2681     NameContext *pNC;                          /* Naming context */
2682     int i;                                     /* Integer value */
2683     SrcList *pSrcList;                         /* FROM clause */
2684     struct SrcCount *pSrcCount;                /* Counting column references */
2685   } u;
2686 };
2687 
2688 /* Forward declarations */
2689 int sqlite3WalkExpr(Walker*, Expr*);
2690 int sqlite3WalkExprList(Walker*, ExprList*);
2691 int sqlite3WalkSelect(Walker*, Select*);
2692 int sqlite3WalkSelectExpr(Walker*, Select*);
2693 int sqlite3WalkSelectFrom(Walker*, Select*);
2694 
2695 /*
2696 ** Return code from the parse-tree walking primitives and their
2697 ** callbacks.
2698 */
2699 #define WRC_Continue    0   /* Continue down into children */
2700 #define WRC_Prune       1   /* Omit children but continue walking siblings */
2701 #define WRC_Abort       2   /* Abandon the tree walk */
2702 
2703 /*
2704 ** An instance of this structure represents a set of one or more CTEs
2705 ** (common table expressions) created by a single WITH clause.
2706 */
2707 struct With {
2708   int nCte;                       /* Number of CTEs in the WITH clause */
2709   With *pOuter;                   /* Containing WITH clause, or NULL */
2710   struct Cte {                    /* For each CTE in the WITH clause.... */
2711     char *zName;                    /* Name of this CTE */
2712     ExprList *pCols;                /* List of explicit column names, or NULL */
2713     Select *pSelect;                /* The definition of this CTE */
2714     const char *zErr;               /* Error message for circular references */
2715   } a[1];
2716 };
2717 
2718 /*
2719 ** Assuming zIn points to the first byte of a UTF-8 character,
2720 ** advance zIn to point to the first byte of the next UTF-8 character.
2721 */
2722 #define SQLITE_SKIP_UTF8(zIn) {                        \
2723   if( (*(zIn++))>=0xc0 ){                              \
2724     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
2725   }                                                    \
2726 }
2727 
2728 /*
2729 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
2730 ** the same name but without the _BKPT suffix.  These macros invoke
2731 ** routines that report the line-number on which the error originated
2732 ** using sqlite3_log().  The routines also provide a convenient place
2733 ** to set a debugger breakpoint.
2734 */
2735 int sqlite3CorruptError(int);
2736 int sqlite3MisuseError(int);
2737 int sqlite3CantopenError(int);
2738 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
2739 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
2740 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
2741 
2742 
2743 /*
2744 ** FTS4 is really an extension for FTS3.  It is enabled using the
2745 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
2746 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
2747 */
2748 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
2749 # define SQLITE_ENABLE_FTS3
2750 #endif
2751 
2752 /*
2753 ** The ctype.h header is needed for non-ASCII systems.  It is also
2754 ** needed by FTS3 when FTS3 is included in the amalgamation.
2755 */
2756 #if !defined(SQLITE_ASCII) || \
2757     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
2758 # include <ctype.h>
2759 #endif
2760 
2761 /*
2762 ** The following macros mimic the standard library functions toupper(),
2763 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
2764 ** sqlite versions only work for ASCII characters, regardless of locale.
2765 */
2766 #ifdef SQLITE_ASCII
2767 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
2768 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
2769 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
2770 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
2771 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
2772 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
2773 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
2774 #else
2775 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
2776 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
2777 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
2778 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
2779 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
2780 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
2781 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
2782 #endif
2783 
2784 /*
2785 ** Internal function prototypes
2786 */
2787 #define sqlite3StrICmp sqlite3_stricmp
2788 int sqlite3Strlen30(const char*);
2789 #define sqlite3StrNICmp sqlite3_strnicmp
2790 
2791 int sqlite3MallocInit(void);
2792 void sqlite3MallocEnd(void);
2793 void *sqlite3Malloc(int);
2794 void *sqlite3MallocZero(int);
2795 void *sqlite3DbMallocZero(sqlite3*, int);
2796 void *sqlite3DbMallocRaw(sqlite3*, int);
2797 char *sqlite3DbStrDup(sqlite3*,const char*);
2798 char *sqlite3DbStrNDup(sqlite3*,const char*, int);
2799 void *sqlite3Realloc(void*, int);
2800 void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
2801 void *sqlite3DbRealloc(sqlite3 *, void *, int);
2802 void sqlite3DbFree(sqlite3*, void*);
2803 int sqlite3MallocSize(void*);
2804 int sqlite3DbMallocSize(sqlite3*, void*);
2805 void *sqlite3ScratchMalloc(int);
2806 void sqlite3ScratchFree(void*);
2807 void *sqlite3PageMalloc(int);
2808 void sqlite3PageFree(void*);
2809 void sqlite3MemSetDefault(void);
2810 void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
2811 int sqlite3HeapNearlyFull(void);
2812 
2813 /*
2814 ** On systems with ample stack space and that support alloca(), make
2815 ** use of alloca() to obtain space for large automatic objects.  By default,
2816 ** obtain space from malloc().
2817 **
2818 ** The alloca() routine never returns NULL.  This will cause code paths
2819 ** that deal with sqlite3StackAlloc() failures to be unreachable.
2820 */
2821 #ifdef SQLITE_USE_ALLOCA
2822 # define sqlite3StackAllocRaw(D,N)   alloca(N)
2823 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
2824 # define sqlite3StackFree(D,P)
2825 #else
2826 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
2827 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
2828 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
2829 #endif
2830 
2831 #ifdef SQLITE_ENABLE_MEMSYS3
2832 const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
2833 #endif
2834 #ifdef SQLITE_ENABLE_MEMSYS5
2835 const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
2836 #endif
2837 
2838 
2839 #ifndef SQLITE_MUTEX_OMIT
2840   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
2841   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
2842   sqlite3_mutex *sqlite3MutexAlloc(int);
2843   int sqlite3MutexInit(void);
2844   int sqlite3MutexEnd(void);
2845 #endif
2846 
2847 int sqlite3StatusValue(int);
2848 void sqlite3StatusAdd(int, int);
2849 void sqlite3StatusSet(int, int);
2850 
2851 #ifndef SQLITE_OMIT_FLOATING_POINT
2852   int sqlite3IsNaN(double);
2853 #else
2854 # define sqlite3IsNaN(X)  0
2855 #endif
2856 
2857 /*
2858 ** An instance of the following structure holds information about SQL
2859 ** functions arguments that are the parameters to the printf() function.
2860 */
2861 struct PrintfArguments {
2862   int nArg;                /* Total number of arguments */
2863   int nUsed;               /* Number of arguments used so far */
2864   sqlite3_value **apArg;   /* The argument values */
2865 };
2866 
2867 #define SQLITE_PRINTF_INTERNAL 0x01
2868 #define SQLITE_PRINTF_SQLFUNC  0x02
2869 void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
2870 void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
2871 char *sqlite3MPrintf(sqlite3*,const char*, ...);
2872 char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
2873 char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
2874 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
2875   void sqlite3DebugPrintf(const char*, ...);
2876 #endif
2877 #if defined(SQLITE_TEST)
2878   void *sqlite3TestTextToPtr(const char*);
2879 #endif
2880 
2881 /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
2882 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
2883   void sqlite3ExplainBegin(Vdbe*);
2884   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
2885   void sqlite3ExplainNL(Vdbe*);
2886   void sqlite3ExplainPush(Vdbe*);
2887   void sqlite3ExplainPop(Vdbe*);
2888   void sqlite3ExplainFinish(Vdbe*);
2889   void sqlite3ExplainSelect(Vdbe*, Select*);
2890   void sqlite3ExplainExpr(Vdbe*, Expr*);
2891   void sqlite3ExplainExprList(Vdbe*, ExprList*);
2892   const char *sqlite3VdbeExplanation(Vdbe*);
2893 #else
2894 # define sqlite3ExplainBegin(X)
2895 # define sqlite3ExplainSelect(A,B)
2896 # define sqlite3ExplainExpr(A,B)
2897 # define sqlite3ExplainExprList(A,B)
2898 # define sqlite3ExplainFinish(X)
2899 # define sqlite3VdbeExplanation(X) 0
2900 #endif
2901 
2902 
2903 void sqlite3SetString(char **, sqlite3*, const char*, ...);
2904 void sqlite3ErrorMsg(Parse*, const char*, ...);
2905 int sqlite3Dequote(char*);
2906 int sqlite3KeywordCode(const unsigned char*, int);
2907 int sqlite3RunParser(Parse*, const char*, char **);
2908 void sqlite3FinishCoding(Parse*);
2909 int sqlite3GetTempReg(Parse*);
2910 void sqlite3ReleaseTempReg(Parse*,int);
2911 int sqlite3GetTempRange(Parse*,int);
2912 void sqlite3ReleaseTempRange(Parse*,int,int);
2913 void sqlite3ClearTempRegCache(Parse*);
2914 Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
2915 Expr *sqlite3Expr(sqlite3*,int,const char*);
2916 void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
2917 Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
2918 Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
2919 Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
2920 void sqlite3ExprAssignVarNumber(Parse*, Expr*);
2921 void sqlite3ExprDelete(sqlite3*, Expr*);
2922 ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
2923 void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
2924 void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
2925 void sqlite3ExprListDelete(sqlite3*, ExprList*);
2926 int sqlite3Init(sqlite3*, char**);
2927 int sqlite3InitCallback(void*, int, char**, char**);
2928 void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
2929 void sqlite3ResetAllSchemasOfConnection(sqlite3*);
2930 void sqlite3ResetOneSchema(sqlite3*,int);
2931 void sqlite3CollapseDatabaseArray(sqlite3*);
2932 void sqlite3BeginParse(Parse*,int);
2933 void sqlite3CommitInternalChanges(sqlite3*);
2934 Table *sqlite3ResultSetOfSelect(Parse*,Select*);
2935 void sqlite3OpenMasterTable(Parse *, int);
2936 Index *sqlite3PrimaryKeyIndex(Table*);
2937 i16 sqlite3ColumnOfIndex(Index*, i16);
2938 void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
2939 void sqlite3AddColumn(Parse*,Token*);
2940 void sqlite3AddNotNull(Parse*, int);
2941 void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
2942 void sqlite3AddCheckConstraint(Parse*, Expr*);
2943 void sqlite3AddColumnType(Parse*,Token*);
2944 void sqlite3AddDefaultValue(Parse*,ExprSpan*);
2945 void sqlite3AddCollateType(Parse*, Token*);
2946 void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
2947 int sqlite3ParseUri(const char*,const char*,unsigned int*,
2948                     sqlite3_vfs**,char**,char **);
2949 Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
2950 int sqlite3CodeOnce(Parse *);
2951 
2952 Bitvec *sqlite3BitvecCreate(u32);
2953 int sqlite3BitvecTest(Bitvec*, u32);
2954 int sqlite3BitvecSet(Bitvec*, u32);
2955 void sqlite3BitvecClear(Bitvec*, u32, void*);
2956 void sqlite3BitvecDestroy(Bitvec*);
2957 u32 sqlite3BitvecSize(Bitvec*);
2958 int sqlite3BitvecBuiltinTest(int,int*);
2959 
2960 RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
2961 void sqlite3RowSetClear(RowSet*);
2962 void sqlite3RowSetInsert(RowSet*, i64);
2963 int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
2964 int sqlite3RowSetNext(RowSet*, i64*);
2965 
2966 void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
2967 
2968 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
2969   int sqlite3ViewGetColumnNames(Parse*,Table*);
2970 #else
2971 # define sqlite3ViewGetColumnNames(A,B) 0
2972 #endif
2973 
2974 void sqlite3DropTable(Parse*, SrcList*, int, int);
2975 void sqlite3CodeDropTable(Parse*, Table*, int, int);
2976 void sqlite3DeleteTable(sqlite3*, Table*);
2977 #ifndef SQLITE_OMIT_AUTOINCREMENT
2978   void sqlite3AutoincrementBegin(Parse *pParse);
2979   void sqlite3AutoincrementEnd(Parse *pParse);
2980 #else
2981 # define sqlite3AutoincrementBegin(X)
2982 # define sqlite3AutoincrementEnd(X)
2983 #endif
2984 int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
2985 void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
2986 void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
2987 IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
2988 int sqlite3IdListIndex(IdList*,const char*);
2989 SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
2990 SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
2991 SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
2992                                       Token*, Select*, Expr*, IdList*);
2993 void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
2994 int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
2995 void sqlite3SrcListShiftJoinType(SrcList*);
2996 void sqlite3SrcListAssignCursors(Parse*, SrcList*);
2997 void sqlite3IdListDelete(sqlite3*, IdList*);
2998 void sqlite3SrcListDelete(sqlite3*, SrcList*);
2999 Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
3000 Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
3001                           Expr*, int, int);
3002 void sqlite3DropIndex(Parse*, SrcList*, int);
3003 int sqlite3Select(Parse*, Select*, SelectDest*);
3004 Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
3005                          Expr*,ExprList*,u16,Expr*,Expr*);
3006 void sqlite3SelectDelete(sqlite3*, Select*);
3007 Table *sqlite3SrcListLookup(Parse*, SrcList*);
3008 int sqlite3IsReadOnly(Parse*, Table*, int);
3009 void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
3010 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
3011 Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
3012 #endif
3013 void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
3014 void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
3015 WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
3016 void sqlite3WhereEnd(WhereInfo*);
3017 u64 sqlite3WhereOutputRowCount(WhereInfo*);
3018 int sqlite3WhereIsDistinct(WhereInfo*);
3019 int sqlite3WhereIsOrdered(WhereInfo*);
3020 int sqlite3WhereContinueLabel(WhereInfo*);
3021 int sqlite3WhereBreakLabel(WhereInfo*);
3022 int sqlite3WhereOkOnePass(WhereInfo*, int*);
3023 int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
3024 void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
3025 void sqlite3ExprCodeMove(Parse*, int, int, int);
3026 void sqlite3ExprCacheStore(Parse*, int, int, int);
3027 void sqlite3ExprCachePush(Parse*);
3028 void sqlite3ExprCachePop(Parse*, int);
3029 void sqlite3ExprCacheRemove(Parse*, int, int);
3030 void sqlite3ExprCacheClear(Parse*);
3031 void sqlite3ExprCacheAffinityChange(Parse*, int, int);
3032 int sqlite3ExprCode(Parse*, Expr*, int);
3033 void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
3034 int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
3035 int sqlite3ExprCodeTarget(Parse*, Expr*, int);
3036 int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
3037 int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
3038 #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
3039 #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
3040 void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
3041 void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
3042 Table *sqlite3FindTable(sqlite3*,const char*, const char*);
3043 Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
3044 Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
3045 Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
3046 void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
3047 void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
3048 void sqlite3Vacuum(Parse*);
3049 int sqlite3RunVacuum(char**, sqlite3*);
3050 char *sqlite3NameFromToken(sqlite3*, Token*);
3051 int sqlite3ExprCompare(Expr*, Expr*, int);
3052 int sqlite3ExprListCompare(ExprList*, ExprList*, int);
3053 int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
3054 void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
3055 void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
3056 int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
3057 Vdbe *sqlite3GetVdbe(Parse*);
3058 void sqlite3PrngSaveState(void);
3059 void sqlite3PrngRestoreState(void);
3060 void sqlite3RollbackAll(sqlite3*,int);
3061 void sqlite3CodeVerifySchema(Parse*, int);
3062 void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
3063 void sqlite3BeginTransaction(Parse*, int);
3064 void sqlite3CommitTransaction(Parse*);
3065 void sqlite3RollbackTransaction(Parse*);
3066 void sqlite3Savepoint(Parse*, int, Token*);
3067 void sqlite3CloseSavepoints(sqlite3 *);
3068 void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
3069 int sqlite3ExprIsConstant(Expr*);
3070 int sqlite3ExprIsConstantNotJoin(Expr*);
3071 int sqlite3ExprIsConstantOrFunction(Expr*);
3072 int sqlite3ExprIsInteger(Expr*, int*);
3073 int sqlite3ExprCanBeNull(const Expr*);
3074 void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
3075 int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
3076 int sqlite3IsRowid(const char*);
3077 void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
3078 void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
3079 int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
3080 void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
3081                                      u8,u8,int,int*);
3082 void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
3083 int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
3084 void sqlite3BeginWriteOperation(Parse*, int, int);
3085 void sqlite3MultiWrite(Parse*);
3086 void sqlite3MayAbort(Parse*);
3087 void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
3088 void sqlite3UniqueConstraint(Parse*, int, Index*);
3089 void sqlite3RowidConstraint(Parse*, int, Table*);
3090 Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
3091 ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
3092 SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
3093 IdList *sqlite3IdListDup(sqlite3*,IdList*);
3094 Select *sqlite3SelectDup(sqlite3*,Select*,int);
3095 void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
3096 FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
3097 void sqlite3RegisterBuiltinFunctions(sqlite3*);
3098 void sqlite3RegisterDateTimeFunctions(void);
3099 void sqlite3RegisterGlobalFunctions(void);
3100 int sqlite3SafetyCheckOk(sqlite3*);
3101 int sqlite3SafetyCheckSickOrOk(sqlite3*);
3102 void sqlite3ChangeCookie(Parse*, int);
3103 
3104 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
3105 void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
3106 #endif
3107 
3108 #ifndef SQLITE_OMIT_TRIGGER
3109   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
3110                            Expr*,int, int);
3111   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
3112   void sqlite3DropTrigger(Parse*, SrcList*, int);
3113   void sqlite3DropTriggerPtr(Parse*, Trigger*);
3114   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
3115   Trigger *sqlite3TriggerList(Parse *, Table *);
3116   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
3117                             int, int, int);
3118   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
3119   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
3120   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
3121   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
3122   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
3123                                         Select*,u8);
3124   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
3125   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
3126   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
3127   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
3128   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
3129 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
3130 #else
3131 # define sqlite3TriggersExist(B,C,D,E,F) 0
3132 # define sqlite3DeleteTrigger(A,B)
3133 # define sqlite3DropTriggerPtr(A,B)
3134 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
3135 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
3136 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
3137 # define sqlite3TriggerList(X, Y) 0
3138 # define sqlite3ParseToplevel(p) p
3139 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
3140 #endif
3141 
3142 int sqlite3JoinType(Parse*, Token*, Token*, Token*);
3143 void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
3144 void sqlite3DeferForeignKey(Parse*, int);
3145 #ifndef SQLITE_OMIT_AUTHORIZATION
3146   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
3147   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
3148   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
3149   void sqlite3AuthContextPop(AuthContext*);
3150   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
3151 #else
3152 # define sqlite3AuthRead(a,b,c,d)
3153 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
3154 # define sqlite3AuthContextPush(a,b,c)
3155 # define sqlite3AuthContextPop(a)  ((void)(a))
3156 #endif
3157 void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
3158 void sqlite3Detach(Parse*, Expr*);
3159 void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
3160 int sqlite3FixSrcList(DbFixer*, SrcList*);
3161 int sqlite3FixSelect(DbFixer*, Select*);
3162 int sqlite3FixExpr(DbFixer*, Expr*);
3163 int sqlite3FixExprList(DbFixer*, ExprList*);
3164 int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
3165 int sqlite3AtoF(const char *z, double*, int, u8);
3166 int sqlite3GetInt32(const char *, int*);
3167 int sqlite3Atoi(const char*);
3168 int sqlite3Utf16ByteLen(const void *pData, int nChar);
3169 int sqlite3Utf8CharLen(const char *pData, int nByte);
3170 u32 sqlite3Utf8Read(const u8**);
3171 LogEst sqlite3LogEst(u64);
3172 LogEst sqlite3LogEstAdd(LogEst,LogEst);
3173 #ifndef SQLITE_OMIT_VIRTUALTABLE
3174 LogEst sqlite3LogEstFromDouble(double);
3175 #endif
3176 u64 sqlite3LogEstToInt(LogEst);
3177 
3178 /*
3179 ** Routines to read and write variable-length integers.  These used to
3180 ** be defined locally, but now we use the varint routines in the util.c
3181 ** file.  Code should use the MACRO forms below, as the Varint32 versions
3182 ** are coded to assume the single byte case is already handled (which
3183 ** the MACRO form does).
3184 */
3185 int sqlite3PutVarint(unsigned char*, u64);
3186 int sqlite3PutVarint32(unsigned char*, u32);
3187 u8 sqlite3GetVarint(const unsigned char *, u64 *);
3188 u8 sqlite3GetVarint32(const unsigned char *, u32 *);
3189 int sqlite3VarintLen(u64 v);
3190 
3191 /*
3192 ** The header of a record consists of a sequence variable-length integers.
3193 ** These integers are almost always small and are encoded as a single byte.
3194 ** The following macros take advantage this fact to provide a fast encode
3195 ** and decode of the integers in a record header.  It is faster for the common
3196 ** case where the integer is a single byte.  It is a little slower when the
3197 ** integer is two or more bytes.  But overall it is faster.
3198 **
3199 ** The following expressions are equivalent:
3200 **
3201 **     x = sqlite3GetVarint32( A, &B );
3202 **     x = sqlite3PutVarint32( A, B );
3203 **
3204 **     x = getVarint32( A, B );
3205 **     x = putVarint32( A, B );
3206 **
3207 */
3208 #define getVarint32(A,B)  \
3209   (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
3210 #define putVarint32(A,B)  \
3211   (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
3212   sqlite3PutVarint32((A),(B)))
3213 #define getVarint    sqlite3GetVarint
3214 #define putVarint    sqlite3PutVarint
3215 
3216 
3217 const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
3218 void sqlite3TableAffinityStr(Vdbe *, Table *);
3219 char sqlite3CompareAffinity(Expr *pExpr, char aff2);
3220 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
3221 char sqlite3ExprAffinity(Expr *pExpr);
3222 int sqlite3Atoi64(const char*, i64*, int, u8);
3223 void sqlite3Error(sqlite3*, int, const char*,...);
3224 void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
3225 u8 sqlite3HexToInt(int h);
3226 int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
3227 
3228 #if defined(SQLITE_TEST)
3229 const char *sqlite3ErrName(int);
3230 #endif
3231 
3232 const char *sqlite3ErrStr(int);
3233 int sqlite3ReadSchema(Parse *pParse);
3234 CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
3235 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
3236 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
3237 Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
3238 Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
3239 Expr *sqlite3ExprSkipCollate(Expr*);
3240 int sqlite3CheckCollSeq(Parse *, CollSeq *);
3241 int sqlite3CheckObjectName(Parse *, const char *);
3242 void sqlite3VdbeSetChanges(sqlite3 *, int);
3243 int sqlite3AddInt64(i64*,i64);
3244 int sqlite3SubInt64(i64*,i64);
3245 int sqlite3MulInt64(i64*,i64);
3246 int sqlite3AbsInt32(int);
3247 #ifdef SQLITE_ENABLE_8_3_NAMES
3248 void sqlite3FileSuffix3(const char*, char*);
3249 #else
3250 # define sqlite3FileSuffix3(X,Y)
3251 #endif
3252 u8 sqlite3GetBoolean(const char *z,int);
3253 
3254 const void *sqlite3ValueText(sqlite3_value*, u8);
3255 int sqlite3ValueBytes(sqlite3_value*, u8);
3256 void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
3257                         void(*)(void*));
3258 void sqlite3ValueSetNull(sqlite3_value*);
3259 void sqlite3ValueFree(sqlite3_value*);
3260 sqlite3_value *sqlite3ValueNew(sqlite3 *);
3261 char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
3262 int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
3263 void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
3264 #ifndef SQLITE_AMALGAMATION
3265 extern const unsigned char sqlite3OpcodeProperty[];
3266 extern const unsigned char sqlite3UpperToLower[];
3267 extern const unsigned char sqlite3CtypeMap[];
3268 extern const Token sqlite3IntTokens[];
3269 extern SQLITE_WSD struct Sqlite3Config sqlite3Config;
3270 extern SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
3271 #ifndef SQLITE_OMIT_WSD
3272 extern int sqlite3PendingByte;
3273 #endif
3274 #endif
3275 void sqlite3RootPageMoved(sqlite3*, int, int, int);
3276 void sqlite3Reindex(Parse*, Token*, Token*);
3277 void sqlite3AlterFunctions(void);
3278 void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
3279 int sqlite3GetToken(const unsigned char *, int *);
3280 void sqlite3NestedParse(Parse*, const char*, ...);
3281 void sqlite3ExpirePreparedStatements(sqlite3*);
3282 int sqlite3CodeSubselect(Parse *, Expr *, int, int);
3283 void sqlite3SelectPrep(Parse*, Select*, NameContext*);
3284 int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
3285 int sqlite3ResolveExprNames(NameContext*, Expr*);
3286 void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
3287 void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
3288 int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
3289 void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
3290 void sqlite3AlterFinishAddColumn(Parse *, Token *);
3291 void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
3292 CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
3293 char sqlite3AffinityType(const char*, u8*);
3294 void sqlite3Analyze(Parse*, Token*, Token*);
3295 int sqlite3InvokeBusyHandler(BusyHandler*);
3296 int sqlite3FindDb(sqlite3*, Token*);
3297 int sqlite3FindDbName(sqlite3 *, const char *);
3298 int sqlite3AnalysisLoad(sqlite3*,int iDB);
3299 void sqlite3DeleteIndexSamples(sqlite3*,Index*);
3300 void sqlite3DefaultRowEst(Index*);
3301 void sqlite3RegisterLikeFunctions(sqlite3*, int);
3302 int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
3303 void sqlite3MinimumFileFormat(Parse*, int, int);
3304 void sqlite3SchemaClear(void *);
3305 Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
3306 int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
3307 KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
3308 void sqlite3KeyInfoUnref(KeyInfo*);
3309 KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
3310 KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
3311 #ifdef SQLITE_DEBUG
3312 int sqlite3KeyInfoIsWriteable(KeyInfo*);
3313 #endif
3314 int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
3315   void (*)(sqlite3_context*,int,sqlite3_value **),
3316   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
3317   FuncDestructor *pDestructor
3318 );
3319 int sqlite3ApiExit(sqlite3 *db, int);
3320 int sqlite3OpenTempDatabase(Parse *);
3321 
3322 void sqlite3StrAccumInit(StrAccum*, char*, int, int);
3323 void sqlite3StrAccumAppend(StrAccum*,const char*,int);
3324 void sqlite3StrAccumAppendAll(StrAccum*,const char*);
3325 void sqlite3AppendSpace(StrAccum*,int);
3326 char *sqlite3StrAccumFinish(StrAccum*);
3327 void sqlite3StrAccumReset(StrAccum*);
3328 void sqlite3SelectDestInit(SelectDest*,int,int);
3329 Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
3330 
3331 void sqlite3BackupRestart(sqlite3_backup *);
3332 void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
3333 
3334 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
3335 void sqlite3AnalyzeFunctions(void);
3336 int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
3337 void sqlite3Stat4ProbeFree(UnpackedRecord*);
3338 #endif
3339 
3340 /*
3341 ** The interface to the LEMON-generated parser
3342 */
3343 void *sqlite3ParserAlloc(void*(*)(size_t));
3344 void sqlite3ParserFree(void*, void(*)(void*));
3345 void sqlite3Parser(void*, int, Token, Parse*);
3346 #ifdef YYTRACKMAXSTACKDEPTH
3347   int sqlite3ParserStackPeak(void*);
3348 #endif
3349 
3350 void sqlite3AutoLoadExtensions(sqlite3*);
3351 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3352   void sqlite3CloseExtensions(sqlite3*);
3353 #else
3354 # define sqlite3CloseExtensions(X)
3355 #endif
3356 
3357 #ifndef SQLITE_OMIT_SHARED_CACHE
3358   void sqlite3TableLock(Parse *, int, int, u8, const char *);
3359 #else
3360   #define sqlite3TableLock(v,w,x,y,z)
3361 #endif
3362 
3363 #ifdef SQLITE_TEST
3364   int sqlite3Utf8To8(unsigned char*);
3365 #endif
3366 
3367 #ifdef SQLITE_OMIT_VIRTUALTABLE
3368 #  define sqlite3VtabClear(Y)
3369 #  define sqlite3VtabSync(X,Y) SQLITE_OK
3370 #  define sqlite3VtabRollback(X)
3371 #  define sqlite3VtabCommit(X)
3372 #  define sqlite3VtabInSync(db) 0
3373 #  define sqlite3VtabLock(X)
3374 #  define sqlite3VtabUnlock(X)
3375 #  define sqlite3VtabUnlockList(X)
3376 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
3377 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
3378 #else
3379    void sqlite3VtabClear(sqlite3 *db, Table*);
3380    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
3381    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
3382    int sqlite3VtabRollback(sqlite3 *db);
3383    int sqlite3VtabCommit(sqlite3 *db);
3384    void sqlite3VtabLock(VTable *);
3385    void sqlite3VtabUnlock(VTable *);
3386    void sqlite3VtabUnlockList(sqlite3*);
3387    int sqlite3VtabSavepoint(sqlite3 *, int, int);
3388    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
3389    VTable *sqlite3GetVTable(sqlite3*, Table*);
3390 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
3391 #endif
3392 void sqlite3VtabMakeWritable(Parse*,Table*);
3393 void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
3394 void sqlite3VtabFinishParse(Parse*, Token*);
3395 void sqlite3VtabArgInit(Parse*);
3396 void sqlite3VtabArgExtend(Parse*, Token*);
3397 int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
3398 int sqlite3VtabCallConnect(Parse*, Table*);
3399 int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
3400 int sqlite3VtabBegin(sqlite3 *, VTable *);
3401 FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
3402 void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
3403 sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
3404 int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
3405 int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
3406 void sqlite3ParserReset(Parse*);
3407 int sqlite3Reprepare(Vdbe*);
3408 void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
3409 CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
3410 int sqlite3TempInMemory(const sqlite3*);
3411 const char *sqlite3JournalModename(int);
3412 #ifndef SQLITE_OMIT_WAL
3413   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
3414   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
3415 #endif
3416 #ifndef SQLITE_OMIT_CTE
3417   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
3418   void sqlite3WithDelete(sqlite3*,With*);
3419   void sqlite3WithPush(Parse*, With*, u8);
3420 #else
3421 #define sqlite3WithPush(x,y,z)
3422 #define sqlite3WithDelete(x,y)
3423 #endif
3424 
3425 /* Declarations for functions in fkey.c. All of these are replaced by
3426 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
3427 ** key functionality is available. If OMIT_TRIGGER is defined but
3428 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
3429 ** this case foreign keys are parsed, but no other functionality is
3430 ** provided (enforcement of FK constraints requires the triggers sub-system).
3431 */
3432 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
3433   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
3434   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
3435   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
3436   int sqlite3FkRequired(Parse*, Table*, int*, int);
3437   u32 sqlite3FkOldmask(Parse*, Table*);
3438   FKey *sqlite3FkReferences(Table *);
3439 #else
3440   #define sqlite3FkActions(a,b,c,d,e,f)
3441   #define sqlite3FkCheck(a,b,c,d,e,f)
3442   #define sqlite3FkDropTable(a,b,c)
3443   #define sqlite3FkOldmask(a,b)         0
3444   #define sqlite3FkRequired(a,b,c,d)    0
3445 #endif
3446 #ifndef SQLITE_OMIT_FOREIGN_KEY
3447   void sqlite3FkDelete(sqlite3 *, Table*);
3448   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
3449 #else
3450   #define sqlite3FkDelete(a,b)
3451   #define sqlite3FkLocateIndex(a,b,c,d,e)
3452 #endif
3453 
3454 
3455 /*
3456 ** Available fault injectors.  Should be numbered beginning with 0.
3457 */
3458 #define SQLITE_FAULTINJECTOR_MALLOC     0
3459 #define SQLITE_FAULTINJECTOR_COUNT      1
3460 
3461 /*
3462 ** The interface to the code in fault.c used for identifying "benign"
3463 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
3464 ** is not defined.
3465 */
3466 #ifndef SQLITE_OMIT_BUILTIN_TEST
3467   void sqlite3BeginBenignMalloc(void);
3468   void sqlite3EndBenignMalloc(void);
3469 #else
3470   #define sqlite3BeginBenignMalloc()
3471   #define sqlite3EndBenignMalloc()
3472 #endif
3473 
3474 #define IN_INDEX_ROWID           1
3475 #define IN_INDEX_EPH             2
3476 #define IN_INDEX_INDEX_ASC       3
3477 #define IN_INDEX_INDEX_DESC      4
3478 int sqlite3FindInIndex(Parse *, Expr *, int*);
3479 
3480 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
3481   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
3482   int sqlite3JournalSize(sqlite3_vfs *);
3483   int sqlite3JournalCreate(sqlite3_file *);
3484   int sqlite3JournalExists(sqlite3_file *p);
3485 #else
3486   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
3487   #define sqlite3JournalExists(p) 1
3488 #endif
3489 
3490 void sqlite3MemJournalOpen(sqlite3_file *);
3491 int sqlite3MemJournalSize(void);
3492 int sqlite3IsMemJournal(sqlite3_file *);
3493 
3494 #if SQLITE_MAX_EXPR_DEPTH>0
3495   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
3496   int sqlite3SelectExprHeight(Select *);
3497   int sqlite3ExprCheckHeight(Parse*, int);
3498 #else
3499   #define sqlite3ExprSetHeight(x,y)
3500   #define sqlite3SelectExprHeight(x) 0
3501   #define sqlite3ExprCheckHeight(x,y)
3502 #endif
3503 
3504 u32 sqlite3Get4byte(const u8*);
3505 void sqlite3Put4byte(u8*, u32);
3506 
3507 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
3508   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
3509   void sqlite3ConnectionUnlocked(sqlite3 *db);
3510   void sqlite3ConnectionClosed(sqlite3 *db);
3511 #else
3512   #define sqlite3ConnectionBlocked(x,y)
3513   #define sqlite3ConnectionUnlocked(x)
3514   #define sqlite3ConnectionClosed(x)
3515 #endif
3516 
3517 #ifdef SQLITE_DEBUG
3518   void sqlite3ParserTrace(FILE*, char *);
3519 #endif
3520 
3521 /*
3522 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
3523 ** sqlite3IoTrace is a pointer to a printf-like routine used to
3524 ** print I/O tracing messages.
3525 */
3526 #ifdef SQLITE_ENABLE_IOTRACE
3527 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
3528   void sqlite3VdbeIOTraceSql(Vdbe*);
3529 SQLITE_EXTERN void (*sqlite3IoTrace)(const char*,...);
3530 #else
3531 # define IOTRACE(A)
3532 # define sqlite3VdbeIOTraceSql(X)
3533 #endif
3534 
3535 /*
3536 ** These routines are available for the mem2.c debugging memory allocator
3537 ** only.  They are used to verify that different "types" of memory
3538 ** allocations are properly tracked by the system.
3539 **
3540 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
3541 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
3542 ** a single bit set.
3543 **
3544 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
3545 ** argument match the type set by the previous sqlite3MemdebugSetType().
3546 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
3547 **
3548 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
3549 ** argument match the type set by the previous sqlite3MemdebugSetType().
3550 **
3551 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
3552 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
3553 ** it might have been allocated by lookaside, except the allocation was
3554 ** too large or lookaside was already full.  It is important to verify
3555 ** that allocations that might have been satisfied by lookaside are not
3556 ** passed back to non-lookaside free() routines.  Asserts such as the
3557 ** example above are placed on the non-lookaside free() routines to verify
3558 ** this constraint.
3559 **
3560 ** All of this is no-op for a production build.  It only comes into
3561 ** play when the SQLITE_MEMDEBUG compile-time option is used.
3562 */
3563 #ifdef SQLITE_MEMDEBUG
3564   void sqlite3MemdebugSetType(void*,u8);
3565   int sqlite3MemdebugHasType(void*,u8);
3566   int sqlite3MemdebugNoType(void*,u8);
3567 #else
3568 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
3569 # define sqlite3MemdebugHasType(X,Y)  1
3570 # define sqlite3MemdebugNoType(X,Y)   1
3571 #endif
3572 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
3573 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
3574 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
3575 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
3576 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
3577 
3578 #endif /* _SQLITEINT_H_ */
3579