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