000001  /*
000002  ** 2001 September 15
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  ** Internal interface definitions for SQLite.
000013  **
000014  */
000015  #ifndef SQLITEINT_H
000016  #define SQLITEINT_H
000017  
000018  /* Special Comments:
000019  **
000020  ** Some comments have special meaning to the tools that measure test
000021  ** coverage:
000022  **
000023  **    NO_TEST                     - The branches on this line are not
000024  **                                  measured by branch coverage.  This is
000025  **                                  used on lines of code that actually
000026  **                                  implement parts of coverage testing.
000027  **
000028  **    OPTIMIZATION-IF-TRUE        - This branch is allowed to alway be false
000029  **                                  and the correct answer is still obtained,
000030  **                                  though perhaps more slowly.
000031  **
000032  **    OPTIMIZATION-IF-FALSE       - This branch is allowed to alway be true
000033  **                                  and the correct answer is still obtained,
000034  **                                  though perhaps more slowly.
000035  **
000036  **    PREVENTS-HARMLESS-OVERREAD  - This branch prevents a buffer overread
000037  **                                  that would be harmless and undetectable
000038  **                                  if it did occur.  
000039  **
000040  ** In all cases, the special comment must be enclosed in the usual
000041  ** slash-asterisk...asterisk-slash comment marks, with no spaces between the 
000042  ** asterisks and the comment text.
000043  */
000044  
000045  /*
000046  ** Make sure the Tcl calling convention macro is defined.  This macro is
000047  ** only used by test code and Tcl integration code.
000048  */
000049  #ifndef SQLITE_TCLAPI
000050  #  define SQLITE_TCLAPI
000051  #endif
000052  
000053  /*
000054  ** Include the header file used to customize the compiler options for MSVC.
000055  ** This should be done first so that it can successfully prevent spurious
000056  ** compiler warnings due to subsequent content in this file and other files
000057  ** that are included by this file.
000058  */
000059  #include "msvc.h"
000060  
000061  /*
000062  ** Special setup for VxWorks
000063  */
000064  #include "vxworks.h"
000065  
000066  /*
000067  ** These #defines should enable >2GB file support on POSIX if the
000068  ** underlying operating system supports it.  If the OS lacks
000069  ** large file support, or if the OS is windows, these should be no-ops.
000070  **
000071  ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
000072  ** system #includes.  Hence, this block of code must be the very first
000073  ** code in all source files.
000074  **
000075  ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
000076  ** on the compiler command line.  This is necessary if you are compiling
000077  ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
000078  ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
000079  ** without this option, LFS is enable.  But LFS does not exist in the kernel
000080  ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
000081  ** portability you should omit LFS.
000082  **
000083  ** The previous paragraph was written in 2005.  (This paragraph is written
000084  ** on 2008-11-28.) These days, all Linux kernels support large files, so
000085  ** you should probably leave LFS enabled.  But some embedded platforms might
000086  ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
000087  **
000088  ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
000089  */
000090  #ifndef SQLITE_DISABLE_LFS
000091  # define _LARGE_FILE       1
000092  # ifndef _FILE_OFFSET_BITS
000093  #   define _FILE_OFFSET_BITS 64
000094  # endif
000095  # define _LARGEFILE_SOURCE 1
000096  #endif
000097  
000098  /* The GCC_VERSION and MSVC_VERSION macros are used to
000099  ** conditionally include optimizations for each of these compilers.  A
000100  ** value of 0 means that compiler is not being used.  The
000101  ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
000102  ** optimizations, and hence set all compiler macros to 0
000103  **
000104  ** There was once also a CLANG_VERSION macro.  However, we learn that the
000105  ** version numbers in clang are for "marketing" only and are inconsistent
000106  ** and unreliable.  Fortunately, all versions of clang also recognize the
000107  ** gcc version numbers and have reasonable settings for gcc version numbers,
000108  ** so the GCC_VERSION macro will be set to a correct non-zero value even
000109  ** when compiling with clang.
000110  */
000111  #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
000112  # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
000113  #else
000114  # define GCC_VERSION 0
000115  #endif
000116  #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
000117  # define MSVC_VERSION _MSC_VER
000118  #else
000119  # define MSVC_VERSION 0
000120  #endif
000121  
000122  /* Needed for various definitions... */
000123  #if defined(__GNUC__) && !defined(_GNU_SOURCE)
000124  # define _GNU_SOURCE
000125  #endif
000126  
000127  #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
000128  # define _BSD_SOURCE
000129  #endif
000130  
000131  /*
000132  ** For MinGW, check to see if we can include the header file containing its
000133  ** version information, among other things.  Normally, this internal MinGW
000134  ** header file would [only] be included automatically by other MinGW header
000135  ** files; however, the contained version information is now required by this
000136  ** header file to work around binary compatibility issues (see below) and
000137  ** this is the only known way to reliably obtain it.  This entire #if block
000138  ** would be completely unnecessary if there was any other way of detecting
000139  ** MinGW via their preprocessor (e.g. if they customized their GCC to define
000140  ** some MinGW-specific macros).  When compiling for MinGW, either the
000141  ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
000142  ** defined; otherwise, detection of conditions specific to MinGW will be
000143  ** disabled.
000144  */
000145  #if defined(_HAVE_MINGW_H)
000146  # include "mingw.h"
000147  #elif defined(_HAVE__MINGW_H)
000148  # include "_mingw.h"
000149  #endif
000150  
000151  /*
000152  ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
000153  ** define is required to maintain binary compatibility with the MSVC runtime
000154  ** library in use (e.g. for Windows XP).
000155  */
000156  #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
000157      defined(_WIN32) && !defined(_WIN64) && \
000158      defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
000159      defined(__MSVCRT__)
000160  # define _USE_32BIT_TIME_T
000161  #endif
000162  
000163  /* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
000164  ** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
000165  ** MinGW.
000166  */
000167  #include "sqlite3.h"
000168  
000169  /*
000170  ** Include the configuration header output by 'configure' if we're using the
000171  ** autoconf-based build
000172  */
000173  #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
000174  #include "config.h"
000175  #define SQLITECONFIG_H 1
000176  #endif
000177  
000178  #include "sqliteLimit.h"
000179  
000180  /* Disable nuisance warnings on Borland compilers */
000181  #if defined(__BORLANDC__)
000182  #pragma warn -rch /* unreachable code */
000183  #pragma warn -ccc /* Condition is always true or false */
000184  #pragma warn -aus /* Assigned value is never used */
000185  #pragma warn -csu /* Comparing signed and unsigned */
000186  #pragma warn -spa /* Suspicious pointer arithmetic */
000187  #endif
000188  
000189  /*
000190  ** Include standard header files as necessary
000191  */
000192  #ifdef HAVE_STDINT_H
000193  #include <stdint.h>
000194  #endif
000195  #ifdef HAVE_INTTYPES_H
000196  #include <inttypes.h>
000197  #endif
000198  
000199  /*
000200  ** The following macros are used to cast pointers to integers and
000201  ** integers to pointers.  The way you do this varies from one compiler
000202  ** to the next, so we have developed the following set of #if statements
000203  ** to generate appropriate macros for a wide range of compilers.
000204  **
000205  ** The correct "ANSI" way to do this is to use the intptr_t type.
000206  ** Unfortunately, that typedef is not available on all compilers, or
000207  ** if it is available, it requires an #include of specific headers
000208  ** that vary from one machine to the next.
000209  **
000210  ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
000211  ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
000212  ** So we have to define the macros in different ways depending on the
000213  ** compiler.
000214  */
000215  #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
000216  # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
000217  # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
000218  #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
000219  # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
000220  # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
000221  #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
000222  # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
000223  # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
000224  #else                          /* Generates a warning - but it always works */
000225  # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
000226  # define SQLITE_PTR_TO_INT(X)  ((int)(X))
000227  #endif
000228  
000229  /*
000230  ** A macro to hint to the compiler that a function should not be
000231  ** inlined.
000232  */
000233  #if defined(__GNUC__)
000234  #  define SQLITE_NOINLINE  __attribute__((noinline))
000235  #elif defined(_MSC_VER) && _MSC_VER>=1310
000236  #  define SQLITE_NOINLINE  __declspec(noinline)
000237  #else
000238  #  define SQLITE_NOINLINE
000239  #endif
000240  
000241  /*
000242  ** Make sure that the compiler intrinsics we desire are enabled when
000243  ** compiling with an appropriate version of MSVC unless prevented by
000244  ** the SQLITE_DISABLE_INTRINSIC define.
000245  */
000246  #if !defined(SQLITE_DISABLE_INTRINSIC)
000247  #  if defined(_MSC_VER) && _MSC_VER>=1400
000248  #    if !defined(_WIN32_WCE)
000249  #      include <intrin.h>
000250  #      pragma intrinsic(_byteswap_ushort)
000251  #      pragma intrinsic(_byteswap_ulong)
000252  #      pragma intrinsic(_byteswap_uint64)
000253  #      pragma intrinsic(_ReadWriteBarrier)
000254  #    else
000255  #      include <cmnintrin.h>
000256  #    endif
000257  #  endif
000258  #endif
000259  
000260  /*
000261  ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
000262  ** 0 means mutexes are permanently disable and the library is never
000263  ** threadsafe.  1 means the library is serialized which is the highest
000264  ** level of threadsafety.  2 means the library is multithreaded - multiple
000265  ** threads can use SQLite as long as no two threads try to use the same
000266  ** database connection at the same time.
000267  **
000268  ** Older versions of SQLite used an optional THREADSAFE macro.
000269  ** We support that for legacy.
000270  **
000271  ** To ensure that the correct value of "THREADSAFE" is reported when querying
000272  ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
000273  ** logic is partially replicated in ctime.c. If it is updated here, it should
000274  ** also be updated there.
000275  */
000276  #if !defined(SQLITE_THREADSAFE)
000277  # if defined(THREADSAFE)
000278  #   define SQLITE_THREADSAFE THREADSAFE
000279  # else
000280  #   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
000281  # endif
000282  #endif
000283  
000284  /*
000285  ** Powersafe overwrite is on by default.  But can be turned off using
000286  ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
000287  */
000288  #ifndef SQLITE_POWERSAFE_OVERWRITE
000289  # define SQLITE_POWERSAFE_OVERWRITE 1
000290  #endif
000291  
000292  /*
000293  ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
000294  ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
000295  ** which case memory allocation statistics are disabled by default.
000296  */
000297  #if !defined(SQLITE_DEFAULT_MEMSTATUS)
000298  # define SQLITE_DEFAULT_MEMSTATUS 1
000299  #endif
000300  
000301  /*
000302  ** Exactly one of the following macros must be defined in order to
000303  ** specify which memory allocation subsystem to use.
000304  **
000305  **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
000306  **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
000307  **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
000308  **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
000309  **
000310  ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
000311  ** assert() macro is enabled, each call into the Win32 native heap subsystem
000312  ** will cause HeapValidate to be called.  If heap validation should fail, an
000313  ** assertion will be triggered.
000314  **
000315  ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
000316  ** the default.
000317  */
000318  #if defined(SQLITE_SYSTEM_MALLOC) \
000319    + defined(SQLITE_WIN32_MALLOC) \
000320    + defined(SQLITE_ZERO_MALLOC) \
000321    + defined(SQLITE_MEMDEBUG)>1
000322  # error "Two or more of the following compile-time configuration options\
000323   are defined but at most one is allowed:\
000324   SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
000325   SQLITE_ZERO_MALLOC"
000326  #endif
000327  #if defined(SQLITE_SYSTEM_MALLOC) \
000328    + defined(SQLITE_WIN32_MALLOC) \
000329    + defined(SQLITE_ZERO_MALLOC) \
000330    + defined(SQLITE_MEMDEBUG)==0
000331  # define SQLITE_SYSTEM_MALLOC 1
000332  #endif
000333  
000334  /*
000335  ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
000336  ** sizes of memory allocations below this value where possible.
000337  */
000338  #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
000339  # define SQLITE_MALLOC_SOFT_LIMIT 1024
000340  #endif
000341  
000342  /*
000343  ** We need to define _XOPEN_SOURCE as follows in order to enable
000344  ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
000345  ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
000346  ** it.
000347  */
000348  #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
000349  #  define _XOPEN_SOURCE 600
000350  #endif
000351  
000352  /*
000353  ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
000354  ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
000355  ** make it true by defining or undefining NDEBUG.
000356  **
000357  ** Setting NDEBUG makes the code smaller and faster by disabling the
000358  ** assert() statements in the code.  So we want the default action
000359  ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
000360  ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
000361  ** feature.
000362  */
000363  #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
000364  # define NDEBUG 1
000365  #endif
000366  #if defined(NDEBUG) && defined(SQLITE_DEBUG)
000367  # undef NDEBUG
000368  #endif
000369  
000370  /*
000371  ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
000372  */
000373  #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
000374  # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
000375  #endif
000376  
000377  /*
000378  ** The testcase() macro is used to aid in coverage testing.  When
000379  ** doing coverage testing, the condition inside the argument to
000380  ** testcase() must be evaluated both true and false in order to
000381  ** get full branch coverage.  The testcase() macro is inserted
000382  ** to help ensure adequate test coverage in places where simple
000383  ** condition/decision coverage is inadequate.  For example, testcase()
000384  ** can be used to make sure boundary values are tested.  For
000385  ** bitmask tests, testcase() can be used to make sure each bit
000386  ** is significant and used at least once.  On switch statements
000387  ** where multiple cases go to the same block of code, testcase()
000388  ** can insure that all cases are evaluated.
000389  **
000390  */
000391  #ifdef SQLITE_COVERAGE_TEST
000392    void sqlite3Coverage(int);
000393  # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
000394  #else
000395  # define testcase(X)
000396  #endif
000397  
000398  /*
000399  ** The TESTONLY macro is used to enclose variable declarations or
000400  ** other bits of code that are needed to support the arguments
000401  ** within testcase() and assert() macros.
000402  */
000403  #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
000404  # define TESTONLY(X)  X
000405  #else
000406  # define TESTONLY(X)
000407  #endif
000408  
000409  /*
000410  ** Sometimes we need a small amount of code such as a variable initialization
000411  ** to setup for a later assert() statement.  We do not want this code to
000412  ** appear when assert() is disabled.  The following macro is therefore
000413  ** used to contain that setup code.  The "VVA" acronym stands for
000414  ** "Verification, Validation, and Accreditation".  In other words, the
000415  ** code within VVA_ONLY() will only run during verification processes.
000416  */
000417  #ifndef NDEBUG
000418  # define VVA_ONLY(X)  X
000419  #else
000420  # define VVA_ONLY(X)
000421  #endif
000422  
000423  /*
000424  ** The ALWAYS and NEVER macros surround boolean expressions which
000425  ** are intended to always be true or false, respectively.  Such
000426  ** expressions could be omitted from the code completely.  But they
000427  ** are included in a few cases in order to enhance the resilience
000428  ** of SQLite to unexpected behavior - to make the code "self-healing"
000429  ** or "ductile" rather than being "brittle" and crashing at the first
000430  ** hint of unplanned behavior.
000431  **
000432  ** In other words, ALWAYS and NEVER are added for defensive code.
000433  **
000434  ** When doing coverage testing ALWAYS and NEVER are hard-coded to
000435  ** be true and false so that the unreachable code they specify will
000436  ** not be counted as untested code.
000437  */
000438  #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
000439  # define ALWAYS(X)      (1)
000440  # define NEVER(X)       (0)
000441  #elif !defined(NDEBUG)
000442  # define ALWAYS(X)      ((X)?1:(assert(0),0))
000443  # define NEVER(X)       ((X)?(assert(0),1):0)
000444  #else
000445  # define ALWAYS(X)      (X)
000446  # define NEVER(X)       (X)
000447  #endif
000448  
000449  /*
000450  ** Some conditionals are optimizations only.  In other words, if the
000451  ** conditionals are replaced with a constant 1 (true) or 0 (false) then
000452  ** the correct answer is still obtained, though perhaps not as quickly.
000453  **
000454  ** The following macros mark these optimizations conditionals.
000455  */
000456  #if defined(SQLITE_MUTATION_TEST)
000457  # define OK_IF_ALWAYS_TRUE(X)  (1)
000458  # define OK_IF_ALWAYS_FALSE(X) (0)
000459  #else
000460  # define OK_IF_ALWAYS_TRUE(X)  (X)
000461  # define OK_IF_ALWAYS_FALSE(X) (X)
000462  #endif
000463  
000464  /*
000465  ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
000466  ** defined.  We need to defend against those failures when testing with
000467  ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
000468  ** during a normal build.  The following macro can be used to disable tests
000469  ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
000470  */
000471  #if defined(SQLITE_TEST_REALLOC_STRESS)
000472  # define ONLY_IF_REALLOC_STRESS(X)  (X)
000473  #elif !defined(NDEBUG)
000474  # define ONLY_IF_REALLOC_STRESS(X)  ((X)?(assert(0),1):0)
000475  #else
000476  # define ONLY_IF_REALLOC_STRESS(X)  (0)
000477  #endif
000478  
000479  /*
000480  ** Declarations used for tracing the operating system interfaces.
000481  */
000482  #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
000483      (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
000484    extern int sqlite3OSTrace;
000485  # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
000486  # define SQLITE_HAVE_OS_TRACE
000487  #else
000488  # define OSTRACE(X)
000489  # undef  SQLITE_HAVE_OS_TRACE
000490  #endif
000491  
000492  /*
000493  ** Is the sqlite3ErrName() function needed in the build?  Currently,
000494  ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
000495  ** OSTRACE is enabled), and by several "test*.c" files (which are
000496  ** compiled using SQLITE_TEST).
000497  */
000498  #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
000499      (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
000500  # define SQLITE_NEED_ERR_NAME
000501  #else
000502  # undef  SQLITE_NEED_ERR_NAME
000503  #endif
000504  
000505  /*
000506  ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
000507  */
000508  #ifdef SQLITE_OMIT_EXPLAIN
000509  # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
000510  #endif
000511  
000512  /*
000513  ** Return true (non-zero) if the input is an integer that is too large
000514  ** to fit in 32-bits.  This macro is used inside of various testcase()
000515  ** macros to verify that we have tested SQLite for large-file support.
000516  */
000517  #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
000518  
000519  /*
000520  ** The macro unlikely() is a hint that surrounds a boolean
000521  ** expression that is usually false.  Macro likely() surrounds
000522  ** a boolean expression that is usually true.  These hints could,
000523  ** in theory, be used by the compiler to generate better code, but
000524  ** currently they are just comments for human readers.
000525  */
000526  #define likely(X)    (X)
000527  #define unlikely(X)  (X)
000528  
000529  #include "hash.h"
000530  #include "parse.h"
000531  #include <stdio.h>
000532  #include <stdlib.h>
000533  #include <string.h>
000534  #include <assert.h>
000535  #include <stddef.h>
000536  
000537  /*
000538  ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
000539  ** This allows better measurements of where memcpy() is used when running
000540  ** cachegrind.  But this macro version of memcpy() is very slow so it
000541  ** should not be used in production.  This is a performance measurement
000542  ** hack only.
000543  */
000544  #ifdef SQLITE_INLINE_MEMCPY
000545  # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
000546                          int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
000547  #endif
000548  
000549  /*
000550  ** If compiling for a processor that lacks floating point support,
000551  ** substitute integer for floating-point
000552  */
000553  #ifdef SQLITE_OMIT_FLOATING_POINT
000554  # define double sqlite_int64
000555  # define float sqlite_int64
000556  # define LONGDOUBLE_TYPE sqlite_int64
000557  # ifndef SQLITE_BIG_DBL
000558  #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
000559  # endif
000560  # define SQLITE_OMIT_DATETIME_FUNCS 1
000561  # define SQLITE_OMIT_TRACE 1
000562  # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
000563  # undef SQLITE_HAVE_ISNAN
000564  #endif
000565  #ifndef SQLITE_BIG_DBL
000566  # define SQLITE_BIG_DBL (1e99)
000567  #endif
000568  
000569  /*
000570  ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
000571  ** afterward. Having this macro allows us to cause the C compiler
000572  ** to omit code used by TEMP tables without messy #ifndef statements.
000573  */
000574  #ifdef SQLITE_OMIT_TEMPDB
000575  #define OMIT_TEMPDB 1
000576  #else
000577  #define OMIT_TEMPDB 0
000578  #endif
000579  
000580  /*
000581  ** The "file format" number is an integer that is incremented whenever
000582  ** the VDBE-level file format changes.  The following macros define the
000583  ** the default file format for new databases and the maximum file format
000584  ** that the library can read.
000585  */
000586  #define SQLITE_MAX_FILE_FORMAT 4
000587  #ifndef SQLITE_DEFAULT_FILE_FORMAT
000588  # define SQLITE_DEFAULT_FILE_FORMAT 4
000589  #endif
000590  
000591  /*
000592  ** Determine whether triggers are recursive by default.  This can be
000593  ** changed at run-time using a pragma.
000594  */
000595  #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
000596  # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
000597  #endif
000598  
000599  /*
000600  ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
000601  ** on the command-line
000602  */
000603  #ifndef SQLITE_TEMP_STORE
000604  # define SQLITE_TEMP_STORE 1
000605  #endif
000606  
000607  /*
000608  ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
000609  ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
000610  ** to zero.
000611  */
000612  #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
000613  # undef SQLITE_MAX_WORKER_THREADS
000614  # define SQLITE_MAX_WORKER_THREADS 0
000615  #endif
000616  #ifndef SQLITE_MAX_WORKER_THREADS
000617  # define SQLITE_MAX_WORKER_THREADS 8
000618  #endif
000619  #ifndef SQLITE_DEFAULT_WORKER_THREADS
000620  # define SQLITE_DEFAULT_WORKER_THREADS 0
000621  #endif
000622  #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
000623  # undef SQLITE_MAX_WORKER_THREADS
000624  # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
000625  #endif
000626  
000627  /*
000628  ** The default initial allocation for the pagecache when using separate
000629  ** pagecaches for each database connection.  A positive number is the
000630  ** number of pages.  A negative number N translations means that a buffer
000631  ** of -1024*N bytes is allocated and used for as many pages as it will hold.
000632  **
000633  ** The default value of "20" was choosen to minimize the run-time of the
000634  ** speedtest1 test program with options: --shrink-memory --reprepare
000635  */
000636  #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
000637  # define SQLITE_DEFAULT_PCACHE_INITSZ 20
000638  #endif
000639  
000640  /*
000641  ** The compile-time options SQLITE_MMAP_READWRITE and 
000642  ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
000643  ** You must choose one or the other (or neither) but not both.
000644  */
000645  #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
000646  #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
000647  #endif
000648  
000649  /*
000650  ** GCC does not define the offsetof() macro so we'll have to do it
000651  ** ourselves.
000652  */
000653  #ifndef offsetof
000654  #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
000655  #endif
000656  
000657  /*
000658  ** Macros to compute minimum and maximum of two numbers.
000659  */
000660  #ifndef MIN
000661  # define MIN(A,B) ((A)<(B)?(A):(B))
000662  #endif
000663  #ifndef MAX
000664  # define MAX(A,B) ((A)>(B)?(A):(B))
000665  #endif
000666  
000667  /*
000668  ** Swap two objects of type TYPE.
000669  */
000670  #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
000671  
000672  /*
000673  ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
000674  ** not, there are still machines out there that use EBCDIC.)
000675  */
000676  #if 'A' == '\301'
000677  # define SQLITE_EBCDIC 1
000678  #else
000679  # define SQLITE_ASCII 1
000680  #endif
000681  
000682  /*
000683  ** Integers of known sizes.  These typedefs might change for architectures
000684  ** where the sizes very.  Preprocessor macros are available so that the
000685  ** types can be conveniently redefined at compile-type.  Like this:
000686  **
000687  **         cc '-DUINTPTR_TYPE=long long int' ...
000688  */
000689  #ifndef UINT32_TYPE
000690  # ifdef HAVE_UINT32_T
000691  #  define UINT32_TYPE uint32_t
000692  # else
000693  #  define UINT32_TYPE unsigned int
000694  # endif
000695  #endif
000696  #ifndef UINT16_TYPE
000697  # ifdef HAVE_UINT16_T
000698  #  define UINT16_TYPE uint16_t
000699  # else
000700  #  define UINT16_TYPE unsigned short int
000701  # endif
000702  #endif
000703  #ifndef INT16_TYPE
000704  # ifdef HAVE_INT16_T
000705  #  define INT16_TYPE int16_t
000706  # else
000707  #  define INT16_TYPE short int
000708  # endif
000709  #endif
000710  #ifndef UINT8_TYPE
000711  # ifdef HAVE_UINT8_T
000712  #  define UINT8_TYPE uint8_t
000713  # else
000714  #  define UINT8_TYPE unsigned char
000715  # endif
000716  #endif
000717  #ifndef INT8_TYPE
000718  # ifdef HAVE_INT8_T
000719  #  define INT8_TYPE int8_t
000720  # else
000721  #  define INT8_TYPE signed char
000722  # endif
000723  #endif
000724  #ifndef LONGDOUBLE_TYPE
000725  # define LONGDOUBLE_TYPE long double
000726  #endif
000727  typedef sqlite_int64 i64;          /* 8-byte signed integer */
000728  typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
000729  typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
000730  typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
000731  typedef INT16_TYPE i16;            /* 2-byte signed integer */
000732  typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
000733  typedef INT8_TYPE i8;              /* 1-byte signed integer */
000734  
000735  /*
000736  ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
000737  ** that can be stored in a u32 without loss of data.  The value
000738  ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
000739  ** have to specify the value in the less intuitive manner shown:
000740  */
000741  #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
000742  
000743  /*
000744  ** The datatype used to store estimates of the number of rows in a
000745  ** table or index.  This is an unsigned integer type.  For 99.9% of
000746  ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
000747  ** can be used at compile-time if desired.
000748  */
000749  #ifdef SQLITE_64BIT_STATS
000750   typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
000751  #else
000752   typedef u32 tRowcnt;    /* 32-bit is the default */
000753  #endif
000754  
000755  /*
000756  ** Estimated quantities used for query planning are stored as 16-bit
000757  ** logarithms.  For quantity X, the value stored is 10*log2(X).  This
000758  ** gives a possible range of values of approximately 1.0e986 to 1e-986.
000759  ** But the allowed values are "grainy".  Not every value is representable.
000760  ** For example, quantities 16 and 17 are both represented by a LogEst
000761  ** of 40.  However, since LogEst quantities are suppose to be estimates,
000762  ** not exact values, this imprecision is not a problem.
000763  **
000764  ** "LogEst" is short for "Logarithmic Estimate".
000765  **
000766  ** Examples:
000767  **      1 -> 0              20 -> 43          10000 -> 132
000768  **      2 -> 10             25 -> 46          25000 -> 146
000769  **      3 -> 16            100 -> 66        1000000 -> 199
000770  **      4 -> 20           1000 -> 99        1048576 -> 200
000771  **     10 -> 33           1024 -> 100    4294967296 -> 320
000772  **
000773  ** The LogEst can be negative to indicate fractional values.
000774  ** Examples:
000775  **
000776  **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
000777  */
000778  typedef INT16_TYPE LogEst;
000779  
000780  /*
000781  ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
000782  */
000783  #ifndef SQLITE_PTRSIZE
000784  # if defined(__SIZEOF_POINTER__)
000785  #   define SQLITE_PTRSIZE __SIZEOF_POINTER__
000786  # elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
000787         defined(_M_ARM)   || defined(__arm__)    || defined(__x86)
000788  #   define SQLITE_PTRSIZE 4
000789  # else
000790  #   define SQLITE_PTRSIZE 8
000791  # endif
000792  #endif
000793  
000794  /* The uptr type is an unsigned integer large enough to hold a pointer
000795  */
000796  #if defined(HAVE_STDINT_H)
000797    typedef uintptr_t uptr;
000798  #elif SQLITE_PTRSIZE==4
000799    typedef u32 uptr;
000800  #else
000801    typedef u64 uptr;
000802  #endif
000803  
000804  /*
000805  ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
000806  ** something between S (inclusive) and E (exclusive).
000807  **
000808  ** In other words, S is a buffer and E is a pointer to the first byte after
000809  ** the end of buffer S.  This macro returns true if P points to something
000810  ** contained within the buffer S.
000811  */
000812  #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
000813  
000814  
000815  /*
000816  ** Macros to determine whether the machine is big or little endian,
000817  ** and whether or not that determination is run-time or compile-time.
000818  **
000819  ** For best performance, an attempt is made to guess at the byte-order
000820  ** using C-preprocessor macros.  If that is unsuccessful, or if
000821  ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
000822  ** at run-time.
000823  */
000824  #ifndef SQLITE_BYTEORDER
000825  # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
000826       defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
000827       defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
000828       defined(__arm__)
000829  #   define SQLITE_BYTEORDER    1234
000830  # elif defined(sparc)    || defined(__ppc__)
000831  #   define SQLITE_BYTEORDER    4321
000832  # else
000833  #   define SQLITE_BYTEORDER 0
000834  # endif
000835  #endif
000836  #if SQLITE_BYTEORDER==4321
000837  # define SQLITE_BIGENDIAN    1
000838  # define SQLITE_LITTLEENDIAN 0
000839  # define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
000840  #elif SQLITE_BYTEORDER==1234
000841  # define SQLITE_BIGENDIAN    0
000842  # define SQLITE_LITTLEENDIAN 1
000843  # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
000844  #else
000845  # ifdef SQLITE_AMALGAMATION
000846    const int sqlite3one = 1;
000847  # else
000848    extern const int sqlite3one;
000849  # endif
000850  # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
000851  # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
000852  # define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
000853  #endif
000854  
000855  /*
000856  ** Constants for the largest and smallest possible 64-bit signed integers.
000857  ** These macros are designed to work correctly on both 32-bit and 64-bit
000858  ** compilers.
000859  */
000860  #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
000861  #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
000862  
000863  /*
000864  ** Round up a number to the next larger multiple of 8.  This is used
000865  ** to force 8-byte alignment on 64-bit architectures.
000866  */
000867  #define ROUND8(x)     (((x)+7)&~7)
000868  
000869  /*
000870  ** Round down to the nearest multiple of 8
000871  */
000872  #define ROUNDDOWN8(x) ((x)&~7)
000873  
000874  /*
000875  ** Assert that the pointer X is aligned to an 8-byte boundary.  This
000876  ** macro is used only within assert() to verify that the code gets
000877  ** all alignment restrictions correct.
000878  **
000879  ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
000880  ** underlying malloc() implementation might return us 4-byte aligned
000881  ** pointers.  In that case, only verify 4-byte alignment.
000882  */
000883  #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
000884  # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
000885  #else
000886  # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
000887  #endif
000888  
000889  /*
000890  ** Disable MMAP on platforms where it is known to not work
000891  */
000892  #if defined(__OpenBSD__) || defined(__QNXNTO__)
000893  # undef SQLITE_MAX_MMAP_SIZE
000894  # define SQLITE_MAX_MMAP_SIZE 0
000895  #endif
000896  
000897  /*
000898  ** Default maximum size of memory used by memory-mapped I/O in the VFS
000899  */
000900  #ifdef __APPLE__
000901  # include <TargetConditionals.h>
000902  #endif
000903  #ifndef SQLITE_MAX_MMAP_SIZE
000904  # if defined(__linux__) \
000905    || defined(_WIN32) \
000906    || (defined(__APPLE__) && defined(__MACH__)) \
000907    || defined(__sun) \
000908    || defined(__FreeBSD__) \
000909    || defined(__DragonFly__)
000910  #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
000911  # else
000912  #   define SQLITE_MAX_MMAP_SIZE 0
000913  # endif
000914  #endif
000915  
000916  /*
000917  ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
000918  ** default MMAP_SIZE is specified at compile-time, make sure that it does
000919  ** not exceed the maximum mmap size.
000920  */
000921  #ifndef SQLITE_DEFAULT_MMAP_SIZE
000922  # define SQLITE_DEFAULT_MMAP_SIZE 0
000923  #endif
000924  #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
000925  # undef SQLITE_DEFAULT_MMAP_SIZE
000926  # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
000927  #endif
000928  
000929  /*
000930  ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
000931  ** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
000932  ** define SQLITE_ENABLE_STAT3_OR_STAT4
000933  */
000934  #ifdef SQLITE_ENABLE_STAT4
000935  # undef SQLITE_ENABLE_STAT3
000936  # define SQLITE_ENABLE_STAT3_OR_STAT4 1
000937  #elif SQLITE_ENABLE_STAT3
000938  # define SQLITE_ENABLE_STAT3_OR_STAT4 1
000939  #elif SQLITE_ENABLE_STAT3_OR_STAT4
000940  # undef SQLITE_ENABLE_STAT3_OR_STAT4
000941  #endif
000942  
000943  /*
000944  ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
000945  ** the Select query generator tracing logic is turned on.
000946  */
000947  #if defined(SQLITE_ENABLE_SELECTTRACE)
000948  # define SELECTTRACE_ENABLED 1
000949  #else
000950  # define SELECTTRACE_ENABLED 0
000951  #endif
000952  
000953  /*
000954  ** An instance of the following structure is used to store the busy-handler
000955  ** callback for a given sqlite handle.
000956  **
000957  ** The sqlite.busyHandler member of the sqlite struct contains the busy
000958  ** callback for the database handle. Each pager opened via the sqlite
000959  ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
000960  ** callback is currently invoked only from within pager.c.
000961  */
000962  typedef struct BusyHandler BusyHandler;
000963  struct BusyHandler {
000964    int (*xFunc)(void *,int);  /* The busy callback */
000965    void *pArg;                /* First arg to busy callback */
000966    int nBusy;                 /* Incremented with each busy call */
000967  };
000968  
000969  /*
000970  ** Name of the master database table.  The master database table
000971  ** is a special table that holds the names and attributes of all
000972  ** user tables and indices.
000973  */
000974  #define MASTER_NAME       "sqlite_master"
000975  #define TEMP_MASTER_NAME  "sqlite_temp_master"
000976  
000977  /*
000978  ** The root-page of the master database table.
000979  */
000980  #define MASTER_ROOT       1
000981  
000982  /*
000983  ** The name of the schema table.
000984  */
000985  #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
000986  
000987  /*
000988  ** A convenience macro that returns the number of elements in
000989  ** an array.
000990  */
000991  #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
000992  
000993  /*
000994  ** Determine if the argument is a power of two
000995  */
000996  #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
000997  
000998  /*
000999  ** The following value as a destructor means to use sqlite3DbFree().
001000  ** The sqlite3DbFree() routine requires two parameters instead of the
001001  ** one parameter that destructors normally want.  So we have to introduce
001002  ** this magic value that the code knows to handle differently.  Any
001003  ** pointer will work here as long as it is distinct from SQLITE_STATIC
001004  ** and SQLITE_TRANSIENT.
001005  */
001006  #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
001007  
001008  /*
001009  ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
001010  ** not support Writable Static Data (WSD) such as global and static variables.
001011  ** All variables must either be on the stack or dynamically allocated from
001012  ** the heap.  When WSD is unsupported, the variable declarations scattered
001013  ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
001014  ** macro is used for this purpose.  And instead of referencing the variable
001015  ** directly, we use its constant as a key to lookup the run-time allocated
001016  ** buffer that holds real variable.  The constant is also the initializer
001017  ** for the run-time allocated buffer.
001018  **
001019  ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
001020  ** macros become no-ops and have zero performance impact.
001021  */
001022  #ifdef SQLITE_OMIT_WSD
001023    #define SQLITE_WSD const
001024    #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
001025    #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
001026    int sqlite3_wsd_init(int N, int J);
001027    void *sqlite3_wsd_find(void *K, int L);
001028  #else
001029    #define SQLITE_WSD
001030    #define GLOBAL(t,v) v
001031    #define sqlite3GlobalConfig sqlite3Config
001032  #endif
001033  
001034  /*
001035  ** The following macros are used to suppress compiler warnings and to
001036  ** make it clear to human readers when a function parameter is deliberately
001037  ** left unused within the body of a function. This usually happens when
001038  ** a function is called via a function pointer. For example the
001039  ** implementation of an SQL aggregate step callback may not use the
001040  ** parameter indicating the number of arguments passed to the aggregate,
001041  ** if it knows that this is enforced elsewhere.
001042  **
001043  ** When a function parameter is not used at all within the body of a function,
001044  ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
001045  ** However, these macros may also be used to suppress warnings related to
001046  ** parameters that may or may not be used depending on compilation options.
001047  ** For example those parameters only used in assert() statements. In these
001048  ** cases the parameters are named as per the usual conventions.
001049  */
001050  #define UNUSED_PARAMETER(x) (void)(x)
001051  #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
001052  
001053  /*
001054  ** Forward references to structures
001055  */
001056  typedef struct AggInfo AggInfo;
001057  typedef struct AuthContext AuthContext;
001058  typedef struct AutoincInfo AutoincInfo;
001059  typedef struct Bitvec Bitvec;
001060  typedef struct CollSeq CollSeq;
001061  typedef struct Column Column;
001062  typedef struct Db Db;
001063  typedef struct Schema Schema;
001064  typedef struct Expr Expr;
001065  typedef struct ExprList ExprList;
001066  typedef struct ExprSpan ExprSpan;
001067  typedef struct FKey FKey;
001068  typedef struct FuncDestructor FuncDestructor;
001069  typedef struct FuncDef FuncDef;
001070  typedef struct FuncDefHash FuncDefHash;
001071  typedef struct IdList IdList;
001072  typedef struct Index Index;
001073  typedef struct IndexSample IndexSample;
001074  typedef struct KeyClass KeyClass;
001075  typedef struct KeyInfo KeyInfo;
001076  typedef struct Lookaside Lookaside;
001077  typedef struct LookasideSlot LookasideSlot;
001078  typedef struct Module Module;
001079  typedef struct NameContext NameContext;
001080  typedef struct Parse Parse;
001081  typedef struct PreUpdate PreUpdate;
001082  typedef struct PrintfArguments PrintfArguments;
001083  typedef struct RowSet RowSet;
001084  typedef struct Savepoint Savepoint;
001085  typedef struct Select Select;
001086  typedef struct SQLiteThread SQLiteThread;
001087  typedef struct SelectDest SelectDest;
001088  typedef struct SrcList SrcList;
001089  typedef struct StrAccum StrAccum;
001090  typedef struct Table Table;
001091  typedef struct TableLock TableLock;
001092  typedef struct Token Token;
001093  typedef struct TreeView TreeView;
001094  typedef struct Trigger Trigger;
001095  typedef struct TriggerPrg TriggerPrg;
001096  typedef struct TriggerStep TriggerStep;
001097  typedef struct UnpackedRecord UnpackedRecord;
001098  typedef struct VTable VTable;
001099  typedef struct VtabCtx VtabCtx;
001100  typedef struct Walker Walker;
001101  typedef struct WhereInfo WhereInfo;
001102  typedef struct With With;
001103  
001104  /* A VList object records a mapping between parameters/variables/wildcards
001105  ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
001106  ** variable number associated with that parameter.  See the format description
001107  ** on the sqlite3VListAdd() routine for more information.  A VList is really
001108  ** just an array of integers.
001109  */
001110  typedef int VList;
001111  
001112  /*
001113  ** Defer sourcing vdbe.h and btree.h until after the "u8" and
001114  ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
001115  ** pointer types (i.e. FuncDef) defined above.
001116  */
001117  #include "btree.h"
001118  #include "vdbe.h"
001119  #include "pager.h"
001120  #include "pcache.h"
001121  #include "os.h"
001122  #include "mutex.h"
001123  
001124  /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
001125  ** synchronous setting to EXTRA.  It is no longer supported.
001126  */
001127  #ifdef SQLITE_EXTRA_DURABLE
001128  # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
001129  # define SQLITE_DEFAULT_SYNCHRONOUS 3
001130  #endif
001131  
001132  /*
001133  ** Default synchronous levels.
001134  **
001135  ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
001136  ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
001137  **
001138  **           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS
001139  **   OFF           1                         0
001140  **   NORMAL        2                         1
001141  **   FULL          3                         2
001142  **   EXTRA         4                         3
001143  **
001144  ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
001145  ** In other words, the zero-based numbers are used for all external interfaces
001146  ** and the one-based values are used internally.
001147  */
001148  #ifndef SQLITE_DEFAULT_SYNCHRONOUS
001149  # define SQLITE_DEFAULT_SYNCHRONOUS 2
001150  #endif
001151  #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
001152  # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
001153  #endif
001154  
001155  /*
001156  ** Each database file to be accessed by the system is an instance
001157  ** of the following structure.  There are normally two of these structures
001158  ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
001159  ** aDb[1] is the database file used to hold temporary tables.  Additional
001160  ** databases may be attached.
001161  */
001162  struct Db {
001163    char *zDbSName;      /* Name of this database. (schema name, not filename) */
001164    Btree *pBt;          /* The B*Tree structure for this database file */
001165    u8 safety_level;     /* How aggressive at syncing data to disk */
001166    u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */
001167    Schema *pSchema;     /* Pointer to database schema (possibly shared) */
001168  };
001169  
001170  /*
001171  ** An instance of the following structure stores a database schema.
001172  **
001173  ** Most Schema objects are associated with a Btree.  The exception is
001174  ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
001175  ** In shared cache mode, a single Schema object can be shared by multiple
001176  ** Btrees that refer to the same underlying BtShared object.
001177  **
001178  ** Schema objects are automatically deallocated when the last Btree that
001179  ** references them is destroyed.   The TEMP Schema is manually freed by
001180  ** sqlite3_close().
001181  *
001182  ** A thread must be holding a mutex on the corresponding Btree in order
001183  ** to access Schema content.  This implies that the thread must also be
001184  ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
001185  ** For a TEMP Schema, only the connection mutex is required.
001186  */
001187  struct Schema {
001188    int schema_cookie;   /* Database schema version number for this file */
001189    int iGeneration;     /* Generation counter.  Incremented with each change */
001190    Hash tblHash;        /* All tables indexed by name */
001191    Hash idxHash;        /* All (named) indices indexed by name */
001192    Hash trigHash;       /* All triggers indexed by name */
001193    Hash fkeyHash;       /* All foreign keys by referenced table name */
001194    Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
001195    u8 file_format;      /* Schema format version for this file */
001196    u8 enc;              /* Text encoding used by this database */
001197    u16 schemaFlags;     /* Flags associated with this schema */
001198    int cache_size;      /* Number of pages to use in the cache */
001199  };
001200  
001201  /*
001202  ** These macros can be used to test, set, or clear bits in the
001203  ** Db.pSchema->flags field.
001204  */
001205  #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
001206  #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
001207  #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
001208  #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
001209  
001210  /*
001211  ** Allowed values for the DB.pSchema->flags field.
001212  **
001213  ** The DB_SchemaLoaded flag is set after the database schema has been
001214  ** read into internal hash tables.
001215  **
001216  ** DB_UnresetViews means that one or more views have column names that
001217  ** have been filled out.  If the schema changes, these column names might
001218  ** changes and so the view will need to be reset.
001219  */
001220  #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
001221  #define DB_UnresetViews    0x0002  /* Some views have defined column names */
001222  #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
001223  #define DB_ResetWanted     0x0008  /* Reset the schema when nSchemaLock==0 */
001224  
001225  /*
001226  ** The number of different kinds of things that can be limited
001227  ** using the sqlite3_limit() interface.
001228  */
001229  #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
001230  
001231  /*
001232  ** Lookaside malloc is a set of fixed-size buffers that can be used
001233  ** to satisfy small transient memory allocation requests for objects
001234  ** associated with a particular database connection.  The use of
001235  ** lookaside malloc provides a significant performance enhancement
001236  ** (approx 10%) by avoiding numerous malloc/free requests while parsing
001237  ** SQL statements.
001238  **
001239  ** The Lookaside structure holds configuration information about the
001240  ** lookaside malloc subsystem.  Each available memory allocation in
001241  ** the lookaside subsystem is stored on a linked list of LookasideSlot
001242  ** objects.
001243  **
001244  ** Lookaside allocations are only allowed for objects that are associated
001245  ** with a particular database connection.  Hence, schema information cannot
001246  ** be stored in lookaside because in shared cache mode the schema information
001247  ** is shared by multiple database connections.  Therefore, while parsing
001248  ** schema information, the Lookaside.bEnabled flag is cleared so that
001249  ** lookaside allocations are not used to construct the schema objects.
001250  */
001251  struct Lookaside {
001252    u32 bDisable;           /* Only operate the lookaside when zero */
001253    u16 sz;                 /* Size of each buffer in bytes */
001254    u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
001255    u32 nSlot;              /* Number of lookaside slots allocated */
001256    u32 anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
001257    LookasideSlot *pInit;   /* List of buffers not previously used */
001258    LookasideSlot *pFree;   /* List of available buffers */
001259    void *pStart;           /* First byte of available memory space */
001260    void *pEnd;             /* First byte past end of available space */
001261  };
001262  struct LookasideSlot {
001263    LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
001264  };
001265  
001266  /*
001267  ** A hash table for built-in function definitions.  (Application-defined
001268  ** functions use a regular table table from hash.h.)
001269  **
001270  ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
001271  ** Collisions are on the FuncDef.u.pHash chain.
001272  */
001273  #define SQLITE_FUNC_HASH_SZ 23
001274  struct FuncDefHash {
001275    FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */
001276  };
001277  
001278  #ifdef SQLITE_USER_AUTHENTICATION
001279  /*
001280  ** Information held in the "sqlite3" database connection object and used
001281  ** to manage user authentication.
001282  */
001283  typedef struct sqlite3_userauth sqlite3_userauth;
001284  struct sqlite3_userauth {
001285    u8 authLevel;                 /* Current authentication level */
001286    int nAuthPW;                  /* Size of the zAuthPW in bytes */
001287    char *zAuthPW;                /* Password used to authenticate */
001288    char *zAuthUser;              /* User name used to authenticate */
001289  };
001290  
001291  /* Allowed values for sqlite3_userauth.authLevel */
001292  #define UAUTH_Unknown     0     /* Authentication not yet checked */
001293  #define UAUTH_Fail        1     /* User authentication failed */
001294  #define UAUTH_User        2     /* Authenticated as a normal user */
001295  #define UAUTH_Admin       3     /* Authenticated as an administrator */
001296  
001297  /* Functions used only by user authorization logic */
001298  int sqlite3UserAuthTable(const char*);
001299  int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
001300  void sqlite3UserAuthInit(sqlite3*);
001301  void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
001302  
001303  #endif /* SQLITE_USER_AUTHENTICATION */
001304  
001305  /*
001306  ** typedef for the authorization callback function.
001307  */
001308  #ifdef SQLITE_USER_AUTHENTICATION
001309    typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
001310                                 const char*, const char*);
001311  #else
001312    typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
001313                                 const char*);
001314  #endif
001315  
001316  #ifndef SQLITE_OMIT_DEPRECATED
001317  /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
001318  ** in the style of sqlite3_trace()
001319  */
001320  #define SQLITE_TRACE_LEGACY  0x80
001321  #else
001322  #define SQLITE_TRACE_LEGACY  0
001323  #endif /* SQLITE_OMIT_DEPRECATED */
001324  
001325  
001326  /*
001327  ** Each database connection is an instance of the following structure.
001328  */
001329  struct sqlite3 {
001330    sqlite3_vfs *pVfs;            /* OS Interface */
001331    struct Vdbe *pVdbe;           /* List of active virtual machines */
001332    CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
001333    sqlite3_mutex *mutex;         /* Connection mutex */
001334    Db *aDb;                      /* All backends */
001335    int nDb;                      /* Number of backends currently in use */
001336    u32 mDbFlags;                 /* flags recording internal state */
001337    u32 flags;                    /* flags settable by pragmas. See below */
001338    i64 lastRowid;                /* ROWID of most recent insert (see above) */
001339    i64 szMmap;                   /* Default mmap_size setting */
001340    u32 nSchemaLock;              /* Do not reset the schema when non-zero */
001341    unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
001342    int errCode;                  /* Most recent error code (SQLITE_*) */
001343    int errMask;                  /* & result codes with this before returning */
001344    int iSysErrno;                /* Errno value from last system error */
001345    u16 dbOptFlags;               /* Flags to enable/disable optimizations */
001346    u8 enc;                       /* Text encoding */
001347    u8 autoCommit;                /* The auto-commit flag. */
001348    u8 temp_store;                /* 1: file 2: memory 0: default */
001349    u8 mallocFailed;              /* True if we have seen a malloc failure */
001350    u8 bBenignMalloc;             /* Do not require OOMs if true */
001351    u8 dfltLockMode;              /* Default locking-mode for attached dbs */
001352    signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
001353    u8 suppressErr;               /* Do not issue error messages if true */
001354    u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
001355    u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
001356    u8 mTrace;                    /* zero or more SQLITE_TRACE flags */
001357    u8 skipBtreeMutex;            /* True if no shared-cache backends */
001358    u8 nSqlExec;                  /* Number of pending OP_SqlExec opcodes */
001359    int nextPagesize;             /* Pagesize after VACUUM if >0 */
001360    u32 magic;                    /* Magic number for detect library misuse */
001361    int nChange;                  /* Value returned by sqlite3_changes() */
001362    int nTotalChange;             /* Value returned by sqlite3_total_changes() */
001363    int aLimit[SQLITE_N_LIMIT];   /* Limits */
001364    int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
001365    struct sqlite3InitInfo {      /* Information used during initialization */
001366      int newTnum;                /* Rootpage of table being initialized */
001367      u8 iDb;                     /* Which db file is being initialized */
001368      u8 busy;                    /* TRUE if currently initializing */
001369      u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
001370      u8 imposterTable;           /* Building an imposter table */
001371    } init;
001372    int nVdbeActive;              /* Number of VDBEs currently running */
001373    int nVdbeRead;                /* Number of active VDBEs that read or write */
001374    int nVdbeWrite;               /* Number of active VDBEs that read and write */
001375    int nVdbeExec;                /* Number of nested calls to VdbeExec() */
001376    int nVDestroy;                /* Number of active OP_VDestroy operations */
001377    int nExtension;               /* Number of loaded extensions */
001378    void **aExtension;            /* Array of shared library handles */
001379    int (*xTrace)(u32,void*,void*,void*);     /* Trace function */
001380    void *pTraceArg;                          /* Argument to the trace function */
001381    void (*xProfile)(void*,const char*,u64);  /* Profiling function */
001382    void *pProfileArg;                        /* Argument to profile function */
001383    void *pCommitArg;                 /* Argument to xCommitCallback() */
001384    int (*xCommitCallback)(void*);    /* Invoked at every commit. */
001385    void *pRollbackArg;               /* Argument to xRollbackCallback() */
001386    void (*xRollbackCallback)(void*); /* Invoked at every commit. */
001387    void *pUpdateArg;
001388    void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
001389  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
001390    void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */
001391    void (*xPreUpdateCallback)(   /* Registered using sqlite3_preupdate_hook() */
001392      void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
001393    );
001394    PreUpdate *pPreUpdate;        /* Context for active pre-update callback */
001395  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
001396  #ifndef SQLITE_OMIT_WAL
001397    int (*xWalCallback)(void *, sqlite3 *, const char *, int);
001398    void *pWalArg;
001399  #endif
001400    void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
001401    void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
001402    void *pCollNeededArg;
001403    sqlite3_value *pErr;          /* Most recent error message */
001404    union {
001405      volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
001406      double notUsed1;            /* Spacer */
001407    } u1;
001408    Lookaside lookaside;          /* Lookaside malloc configuration */
001409  #ifndef SQLITE_OMIT_AUTHORIZATION
001410    sqlite3_xauth xAuth;          /* Access authorization function */
001411    void *pAuthArg;               /* 1st argument to the access auth function */
001412  #endif
001413  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
001414    int (*xProgress)(void *);     /* The progress callback */
001415    void *pProgressArg;           /* Argument to the progress callback */
001416    unsigned nProgressOps;        /* Number of opcodes for progress callback */
001417  #endif
001418  #ifndef SQLITE_OMIT_VIRTUALTABLE
001419    int nVTrans;                  /* Allocated size of aVTrans */
001420    Hash aModule;                 /* populated by sqlite3_create_module() */
001421    VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
001422    VTable **aVTrans;             /* Virtual tables with open transactions */
001423    VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
001424  #endif
001425    Hash aFunc;                   /* Hash table of connection functions */
001426    Hash aCollSeq;                /* All collating sequences */
001427    BusyHandler busyHandler;      /* Busy callback */
001428    Db aDbStatic[2];              /* Static space for the 2 default backends */
001429    Savepoint *pSavepoint;        /* List of active savepoints */
001430    int busyTimeout;              /* Busy handler timeout, in msec */
001431    int nSavepoint;               /* Number of non-transaction savepoints */
001432    int nStatement;               /* Number of nested statement-transactions  */
001433    i64 nDeferredCons;            /* Net deferred constraints this transaction. */
001434    i64 nDeferredImmCons;         /* Net deferred immediate constraints */
001435    int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
001436  #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
001437    /* The following variables are all protected by the STATIC_MASTER
001438    ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
001439    **
001440    ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
001441    ** unlock so that it can proceed.
001442    **
001443    ** When X.pBlockingConnection==Y, that means that something that X tried
001444    ** tried to do recently failed with an SQLITE_LOCKED error due to locks
001445    ** held by Y.
001446    */
001447    sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
001448    sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
001449    void *pUnlockArg;                     /* Argument to xUnlockNotify */
001450    void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
001451    sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
001452  #endif
001453  #ifdef SQLITE_USER_AUTHENTICATION
001454    sqlite3_userauth auth;        /* User authentication information */
001455  #endif
001456  };
001457  
001458  /*
001459  ** A macro to discover the encoding of a database.
001460  */
001461  #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
001462  #define ENC(db)        ((db)->enc)
001463  
001464  /*
001465  ** Possible values for the sqlite3.flags.
001466  **
001467  ** Value constraints (enforced via assert()):
001468  **      SQLITE_FullFSync     == PAGER_FULLFSYNC
001469  **      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
001470  **      SQLITE_CacheSpill    == PAGER_CACHE_SPILL
001471  */
001472  #define SQLITE_WriteSchema    0x00000001  /* OK to update SQLITE_MASTER */
001473  #define SQLITE_LegacyFileFmt  0x00000002  /* Create new databases in format 1 */
001474  #define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
001475  #define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */
001476  #define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */
001477  #define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
001478  #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
001479  #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
001480                                            /*   DELETE, or UPDATE and return */
001481                                            /*   the count using a callback. */
001482  #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
001483                                            /*   result set is empty */
001484  #define SQLITE_IgnoreChecks   0x00000200  /* Do not enforce check constraints */
001485  #define SQLITE_ReadUncommit   0x00000400  /* READ UNCOMMITTED in shared-cache */
001486  #define SQLITE_NoCkptOnClose  0x00000800  /* No checkpoint on close()/DETACH */
001487  #define SQLITE_ReverseOrder   0x00001000  /* Reverse unordered SELECTs */
001488  #define SQLITE_RecTriggers    0x00002000  /* Enable recursive triggers */
001489  #define SQLITE_ForeignKeys    0x00004000  /* Enforce foreign key constraints  */
001490  #define SQLITE_AutoIndex      0x00008000  /* Enable automatic indexes */
001491  #define SQLITE_LoadExtension  0x00010000  /* Enable load_extension */
001492  #define SQLITE_LoadExtFunc    0x00020000  /* Enable load_extension() SQL func */
001493  #define SQLITE_EnableTrigger  0x00040000  /* True to enable triggers */
001494  #define SQLITE_DeferFKs       0x00080000  /* Defer all FK constraints */
001495  #define SQLITE_QueryOnly      0x00100000  /* Disable database changes */
001496  #define SQLITE_CellSizeCk     0x00200000  /* Check btree cell sizes on load */
001497  #define SQLITE_Fts3Tokenizer  0x00400000  /* Enable fts3_tokenizer(2) */
001498  #define SQLITE_EnableQPSG     0x00800000  /* Query Planner Stability Guarantee */
001499  /* Flags used only if debugging */
001500  #ifdef SQLITE_DEBUG
001501  #define SQLITE_SqlTrace       0x08000000  /* Debug print SQL as it executes */
001502  #define SQLITE_VdbeListing    0x10000000  /* Debug listings of VDBE programs */
001503  #define SQLITE_VdbeTrace      0x20000000  /* True to trace VDBE execution */
001504  #define SQLITE_VdbeAddopTrace 0x40000000  /* Trace sqlite3VdbeAddOp() calls */
001505  #define SQLITE_VdbeEQP        0x80000000  /* Debug EXPLAIN QUERY PLAN */
001506  #endif
001507  
001508  /*
001509  ** Allowed values for sqlite3.mDbFlags
001510  */
001511  #define DBFLAG_SchemaChange   0x0001  /* Uncommitted Hash table changes */
001512  #define DBFLAG_PreferBuiltin  0x0002  /* Preference to built-in funcs */
001513  #define DBFLAG_Vacuum         0x0004  /* Currently in a VACUUM */
001514  
001515  /*
001516  ** Bits of the sqlite3.dbOptFlags field that are used by the
001517  ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
001518  ** selectively disable various optimizations.
001519  */
001520  #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
001521  #define SQLITE_ColumnCache    0x0002   /* Column cache */
001522  #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
001523  #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
001524  #define SQLITE_DistinctOpt    0x0010   /* DISTINCT using indexes */
001525  #define SQLITE_CoverIdxScan   0x0020   /* Covering index scans */
001526  #define SQLITE_OrderByIdxJoin 0x0040   /* ORDER BY of joins via index */
001527  #define SQLITE_Transitive     0x0080   /* Transitive constraints */
001528  #define SQLITE_OmitNoopJoin   0x0100   /* Omit unused tables in joins */
001529  #define SQLITE_CountOfView    0x0200   /* The count-of-view optimization */
001530  #define SQLITE_CursorHints    0x0400   /* Add OP_CursorHint opcodes */
001531  #define SQLITE_Stat34         0x0800   /* Use STAT3 or STAT4 data */
001532     /* TH3 expects the Stat34  ^^^^^^ value to be 0x0800.  Don't change it */
001533  #define SQLITE_AllOpts        0xffff   /* All optimizations */
001534  
001535  /*
001536  ** Macros for testing whether or not optimizations are enabled or disabled.
001537  */
001538  #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
001539  #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
001540  
001541  /*
001542  ** Return true if it OK to factor constant expressions into the initialization
001543  ** code. The argument is a Parse object for the code generator.
001544  */
001545  #define ConstFactorOk(P) ((P)->okConstFactor)
001546  
001547  /*
001548  ** Possible values for the sqlite.magic field.
001549  ** The numbers are obtained at random and have no special meaning, other
001550  ** than being distinct from one another.
001551  */
001552  #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
001553  #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
001554  #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
001555  #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
001556  #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
001557  #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
001558  
001559  /*
001560  ** Each SQL function is defined by an instance of the following
001561  ** structure.  For global built-in functions (ex: substr(), max(), count())
001562  ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
001563  ** For per-connection application-defined functions, a pointer to this
001564  ** structure is held in the db->aHash hash table.
001565  **
001566  ** The u.pHash field is used by the global built-ins.  The u.pDestructor
001567  ** field is used by per-connection app-def functions.
001568  */
001569  struct FuncDef {
001570    i8 nArg;             /* Number of arguments.  -1 means unlimited */
001571    u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
001572    void *pUserData;     /* User data parameter */
001573    FuncDef *pNext;      /* Next function with same name */
001574    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
001575    void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */
001576    const char *zName;   /* SQL name of the function. */
001577    union {
001578      FuncDef *pHash;      /* Next with a different name but the same hash */
001579      FuncDestructor *pDestructor;   /* Reference counted destructor function */
001580    } u;
001581  };
001582  
001583  /*
001584  ** This structure encapsulates a user-function destructor callback (as
001585  ** configured using create_function_v2()) and a reference counter. When
001586  ** create_function_v2() is called to create a function with a destructor,
001587  ** a single object of this type is allocated. FuncDestructor.nRef is set to
001588  ** the number of FuncDef objects created (either 1 or 3, depending on whether
001589  ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
001590  ** member of each of the new FuncDef objects is set to point to the allocated
001591  ** FuncDestructor.
001592  **
001593  ** Thereafter, when one of the FuncDef objects is deleted, the reference
001594  ** count on this object is decremented. When it reaches 0, the destructor
001595  ** is invoked and the FuncDestructor structure freed.
001596  */
001597  struct FuncDestructor {
001598    int nRef;
001599    void (*xDestroy)(void *);
001600    void *pUserData;
001601  };
001602  
001603  /*
001604  ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
001605  ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  And
001606  ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC.  There
001607  ** are assert() statements in the code to verify this.
001608  **
001609  ** Value constraints (enforced via assert()):
001610  **     SQLITE_FUNC_MINMAX    ==  NC_MinMaxAgg      == SF_MinMaxAgg
001611  **     SQLITE_FUNC_LENGTH    ==  OPFLAG_LENGTHARG
001612  **     SQLITE_FUNC_TYPEOF    ==  OPFLAG_TYPEOFARG
001613  **     SQLITE_FUNC_CONSTANT  ==  SQLITE_DETERMINISTIC from the API
001614  **     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API
001615  */
001616  #define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
001617  #define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */
001618  #define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */
001619  #define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */
001620  #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
001621  #define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */
001622  #define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */
001623  #define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */
001624  #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
001625  #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
001626  #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
001627  #define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
001628  #define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
001629                                      ** single query - might change over time */
001630  #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
001631  
001632  /*
001633  ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
001634  ** used to create the initializers for the FuncDef structures.
001635  **
001636  **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
001637  **     Used to create a scalar function definition of a function zName
001638  **     implemented by C function xFunc that accepts nArg arguments. The
001639  **     value passed as iArg is cast to a (void*) and made available
001640  **     as the user-data (sqlite3_user_data()) for the function. If
001641  **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
001642  **
001643  **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
001644  **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
001645  **
001646  **   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
001647  **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
001648  **     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions
001649  **     and functions like sqlite_version() that can change, but not during
001650  **     a single query.  The iArg is ignored.  The user-data is always set
001651  **     to a NULL pointer.  The bNC parameter is not used.
001652  **
001653  **   PURE_DATE(zName, nArg, iArg, bNC, xFunc)
001654  **     Used for "pure" date/time functions, this macro is like DFUNCTION
001655  **     except that it does set the SQLITE_FUNC_CONSTANT flags.  iArg is
001656  **     ignored and the user-data for these functions is set to an 
001657  **     arbitrary non-NULL pointer.  The bNC parameter is not used.
001658  **
001659  **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
001660  **     Used to create an aggregate function definition implemented by
001661  **     the C functions xStep and xFinal. The first four parameters
001662  **     are interpreted in the same way as the first 4 parameters to
001663  **     FUNCTION().
001664  **
001665  **   LIKEFUNC(zName, nArg, pArg, flags)
001666  **     Used to create a scalar function definition of a function zName
001667  **     that accepts nArg arguments and is implemented by a call to C
001668  **     function likeFunc. Argument pArg is cast to a (void *) and made
001669  **     available as the function user-data (sqlite3_user_data()). The
001670  **     FuncDef.flags variable is set to the value passed as the flags
001671  **     parameter.
001672  */
001673  #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
001674    {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
001675     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
001676  #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
001677    {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
001678     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
001679  #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
001680    {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
001681     0, 0, xFunc, 0, #zName, {0} }
001682  #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
001683    {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
001684     (void*)&sqlite3Config, 0, xFunc, 0, #zName, {0} }
001685  #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
001686    {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
001687     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
001688  #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
001689    {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
001690     pArg, 0, xFunc, 0, #zName, }
001691  #define LIKEFUNC(zName, nArg, arg, flags) \
001692    {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
001693     (void *)arg, 0, likeFunc, 0, #zName, {0} }
001694  #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
001695    {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
001696     SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
001697  #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
001698    {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
001699     SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
001700  
001701  /*
001702  ** All current savepoints are stored in a linked list starting at
001703  ** sqlite3.pSavepoint. The first element in the list is the most recently
001704  ** opened savepoint. Savepoints are added to the list by the vdbe
001705  ** OP_Savepoint instruction.
001706  */
001707  struct Savepoint {
001708    char *zName;                        /* Savepoint name (nul-terminated) */
001709    i64 nDeferredCons;                  /* Number of deferred fk violations */
001710    i64 nDeferredImmCons;               /* Number of deferred imm fk. */
001711    Savepoint *pNext;                   /* Parent savepoint (if any) */
001712  };
001713  
001714  /*
001715  ** The following are used as the second parameter to sqlite3Savepoint(),
001716  ** and as the P1 argument to the OP_Savepoint instruction.
001717  */
001718  #define SAVEPOINT_BEGIN      0
001719  #define SAVEPOINT_RELEASE    1
001720  #define SAVEPOINT_ROLLBACK   2
001721  
001722  
001723  /*
001724  ** Each SQLite module (virtual table definition) is defined by an
001725  ** instance of the following structure, stored in the sqlite3.aModule
001726  ** hash table.
001727  */
001728  struct Module {
001729    const sqlite3_module *pModule;       /* Callback pointers */
001730    const char *zName;                   /* Name passed to create_module() */
001731    void *pAux;                          /* pAux passed to create_module() */
001732    void (*xDestroy)(void *);            /* Module destructor function */
001733    Table *pEpoTab;                      /* Eponymous table for this module */
001734  };
001735  
001736  /*
001737  ** information about each column of an SQL table is held in an instance
001738  ** of this structure.
001739  */
001740  struct Column {
001741    char *zName;     /* Name of this column, \000, then the type */
001742    Expr *pDflt;     /* Default value of this column */
001743    char *zColl;     /* Collating sequence.  If NULL, use the default */
001744    u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
001745    char affinity;   /* One of the SQLITE_AFF_... values */
001746    u8 szEst;        /* Estimated size of value in this column. sizeof(INT)==1 */
001747    u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
001748  };
001749  
001750  /* Allowed values for Column.colFlags:
001751  */
001752  #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
001753  #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
001754  #define COLFLAG_HASTYPE  0x0004    /* Type name follows column name */
001755  
001756  /*
001757  ** A "Collating Sequence" is defined by an instance of the following
001758  ** structure. Conceptually, a collating sequence consists of a name and
001759  ** a comparison routine that defines the order of that sequence.
001760  **
001761  ** If CollSeq.xCmp is NULL, it means that the
001762  ** collating sequence is undefined.  Indices built on an undefined
001763  ** collating sequence may not be read or written.
001764  */
001765  struct CollSeq {
001766    char *zName;          /* Name of the collating sequence, UTF-8 encoded */
001767    u8 enc;               /* Text encoding handled by xCmp() */
001768    void *pUser;          /* First argument to xCmp() */
001769    int (*xCmp)(void*,int, const void*, int, const void*);
001770    void (*xDel)(void*);  /* Destructor for pUser */
001771  };
001772  
001773  /*
001774  ** A sort order can be either ASC or DESC.
001775  */
001776  #define SQLITE_SO_ASC       0  /* Sort in ascending order */
001777  #define SQLITE_SO_DESC      1  /* Sort in ascending order */
001778  #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
001779  
001780  /*
001781  ** Column affinity types.
001782  **
001783  ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
001784  ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
001785  ** the speed a little by numbering the values consecutively.
001786  **
001787  ** But rather than start with 0 or 1, we begin with 'A'.  That way,
001788  ** when multiple affinity types are concatenated into a string and
001789  ** used as the P4 operand, they will be more readable.
001790  **
001791  ** Note also that the numeric types are grouped together so that testing
001792  ** for a numeric type is a single comparison.  And the BLOB type is first.
001793  */
001794  #define SQLITE_AFF_BLOB     'A'
001795  #define SQLITE_AFF_TEXT     'B'
001796  #define SQLITE_AFF_NUMERIC  'C'
001797  #define SQLITE_AFF_INTEGER  'D'
001798  #define SQLITE_AFF_REAL     'E'
001799  
001800  #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
001801  
001802  /*
001803  ** The SQLITE_AFF_MASK values masks off the significant bits of an
001804  ** affinity value.
001805  */
001806  #define SQLITE_AFF_MASK     0x47
001807  
001808  /*
001809  ** Additional bit values that can be ORed with an affinity without
001810  ** changing the affinity.
001811  **
001812  ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
001813  ** It causes an assert() to fire if either operand to a comparison
001814  ** operator is NULL.  It is added to certain comparison operators to
001815  ** prove that the operands are always NOT NULL.
001816  */
001817  #define SQLITE_KEEPNULL     0x08  /* Used by vector == or <> */
001818  #define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
001819  #define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
001820  #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
001821  #define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
001822  
001823  /*
001824  ** An object of this type is created for each virtual table present in
001825  ** the database schema.
001826  **
001827  ** If the database schema is shared, then there is one instance of this
001828  ** structure for each database connection (sqlite3*) that uses the shared
001829  ** schema. This is because each database connection requires its own unique
001830  ** instance of the sqlite3_vtab* handle used to access the virtual table
001831  ** implementation. sqlite3_vtab* handles can not be shared between
001832  ** database connections, even when the rest of the in-memory database
001833  ** schema is shared, as the implementation often stores the database
001834  ** connection handle passed to it via the xConnect() or xCreate() method
001835  ** during initialization internally. This database connection handle may
001836  ** then be used by the virtual table implementation to access real tables
001837  ** within the database. So that they appear as part of the callers
001838  ** transaction, these accesses need to be made via the same database
001839  ** connection as that used to execute SQL operations on the virtual table.
001840  **
001841  ** All VTable objects that correspond to a single table in a shared
001842  ** database schema are initially stored in a linked-list pointed to by
001843  ** the Table.pVTable member variable of the corresponding Table object.
001844  ** When an sqlite3_prepare() operation is required to access the virtual
001845  ** table, it searches the list for the VTable that corresponds to the
001846  ** database connection doing the preparing so as to use the correct
001847  ** sqlite3_vtab* handle in the compiled query.
001848  **
001849  ** When an in-memory Table object is deleted (for example when the
001850  ** schema is being reloaded for some reason), the VTable objects are not
001851  ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
001852  ** immediately. Instead, they are moved from the Table.pVTable list to
001853  ** another linked list headed by the sqlite3.pDisconnect member of the
001854  ** corresponding sqlite3 structure. They are then deleted/xDisconnected
001855  ** next time a statement is prepared using said sqlite3*. This is done
001856  ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
001857  ** Refer to comments above function sqlite3VtabUnlockList() for an
001858  ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
001859  ** list without holding the corresponding sqlite3.mutex mutex.
001860  **
001861  ** The memory for objects of this type is always allocated by
001862  ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
001863  ** the first argument.
001864  */
001865  struct VTable {
001866    sqlite3 *db;              /* Database connection associated with this table */
001867    Module *pMod;             /* Pointer to module implementation */
001868    sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
001869    int nRef;                 /* Number of pointers to this structure */
001870    u8 bConstraint;           /* True if constraints are supported */
001871    int iSavepoint;           /* Depth of the SAVEPOINT stack */
001872    VTable *pNext;            /* Next in linked list (see above) */
001873  };
001874  
001875  /*
001876  ** The schema for each SQL table and view is represented in memory
001877  ** by an instance of the following structure.
001878  */
001879  struct Table {
001880    char *zName;         /* Name of the table or view */
001881    Column *aCol;        /* Information about each column */
001882    Index *pIndex;       /* List of SQL indexes on this table. */
001883    Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
001884    FKey *pFKey;         /* Linked list of all foreign keys in this table */
001885    char *zColAff;       /* String defining the affinity of each column */
001886    ExprList *pCheck;    /* All CHECK constraints */
001887                         /*   ... also used as column name list in a VIEW */
001888    int tnum;            /* Root BTree page for this table */
001889    u32 nTabRef;         /* Number of pointers to this Table */
001890    u32 tabFlags;        /* Mask of TF_* values */
001891    i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
001892    i16 nCol;            /* Number of columns in this table */
001893    LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
001894    LogEst szTabRow;     /* Estimated size of each table row in bytes */
001895  #ifdef SQLITE_ENABLE_COSTMULT
001896    LogEst costMult;     /* Cost multiplier for using this table */
001897  #endif
001898    u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
001899  #ifndef SQLITE_OMIT_ALTERTABLE
001900    int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
001901  #endif
001902  #ifndef SQLITE_OMIT_VIRTUALTABLE
001903    int nModuleArg;      /* Number of arguments to the module */
001904    char **azModuleArg;  /* 0: module 1: schema 2: vtab name 3...: args */
001905    VTable *pVTable;     /* List of VTable objects. */
001906  #endif
001907    Trigger *pTrigger;   /* List of triggers stored in pSchema */
001908    Schema *pSchema;     /* Schema that contains this table */
001909    Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
001910  };
001911  
001912  /*
001913  ** Allowed values for Table.tabFlags.
001914  **
001915  ** TF_OOOHidden applies to tables or view that have hidden columns that are
001916  ** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
001917  ** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
001918  ** the TF_OOOHidden attribute would apply in this case.  Such tables require
001919  ** special handling during INSERT processing.
001920  */
001921  #define TF_Readonly        0x0001    /* Read-only system table */
001922  #define TF_Ephemeral       0x0002    /* An ephemeral table */
001923  #define TF_HasPrimaryKey   0x0004    /* Table has a primary key */
001924  #define TF_Autoincrement   0x0008    /* Integer primary key is autoincrement */
001925  #define TF_HasStat1        0x0010    /* nRowLogEst set from sqlite_stat1 */
001926  #define TF_WithoutRowid    0x0020    /* No rowid.  PRIMARY KEY is the key */
001927  #define TF_NoVisibleRowid  0x0040    /* No user-visible "rowid" column */
001928  #define TF_OOOHidden       0x0080    /* Out-of-Order hidden columns */
001929  #define TF_StatsUsed       0x0100    /* Query planner decisions affected by
001930                                       ** Index.aiRowLogEst[] values */
001931  #define TF_HasNotNull      0x0200    /* Contains NOT NULL constraints */
001932  
001933  /*
001934  ** Test to see whether or not a table is a virtual table.  This is
001935  ** done as a macro so that it will be optimized out when virtual
001936  ** table support is omitted from the build.
001937  */
001938  #ifndef SQLITE_OMIT_VIRTUALTABLE
001939  #  define IsVirtual(X)      ((X)->nModuleArg)
001940  #else
001941  #  define IsVirtual(X)      0
001942  #endif
001943  
001944  /*
001945  ** Macros to determine if a column is hidden.  IsOrdinaryHiddenColumn()
001946  ** only works for non-virtual tables (ordinary tables and views) and is
001947  ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined.  The
001948  ** IsHiddenColumn() macro is general purpose.
001949  */
001950  #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
001951  #  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
001952  #  define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
001953  #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
001954  #  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
001955  #  define IsOrdinaryHiddenColumn(X) 0
001956  #else
001957  #  define IsHiddenColumn(X)         0
001958  #  define IsOrdinaryHiddenColumn(X) 0
001959  #endif
001960  
001961  
001962  /* Does the table have a rowid */
001963  #define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
001964  #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
001965  
001966  /*
001967  ** Each foreign key constraint is an instance of the following structure.
001968  **
001969  ** A foreign key is associated with two tables.  The "from" table is
001970  ** the table that contains the REFERENCES clause that creates the foreign
001971  ** key.  The "to" table is the table that is named in the REFERENCES clause.
001972  ** Consider this example:
001973  **
001974  **     CREATE TABLE ex1(
001975  **       a INTEGER PRIMARY KEY,
001976  **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
001977  **     );
001978  **
001979  ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
001980  ** Equivalent names:
001981  **
001982  **     from-table == child-table
001983  **       to-table == parent-table
001984  **
001985  ** Each REFERENCES clause generates an instance of the following structure
001986  ** which is attached to the from-table.  The to-table need not exist when
001987  ** the from-table is created.  The existence of the to-table is not checked.
001988  **
001989  ** The list of all parents for child Table X is held at X.pFKey.
001990  **
001991  ** A list of all children for a table named Z (which might not even exist)
001992  ** is held in Schema.fkeyHash with a hash key of Z.
001993  */
001994  struct FKey {
001995    Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
001996    FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
001997    char *zTo;        /* Name of table that the key points to (aka: Parent) */
001998    FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
001999    FKey *pPrevTo;    /* Previous with the same zTo */
002000    int nCol;         /* Number of columns in this key */
002001    /* EV: R-30323-21917 */
002002    u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
002003    u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
002004    Trigger *apTrigger[2];/* Triggers for aAction[] actions */
002005    struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
002006      int iFrom;            /* Index of column in pFrom */
002007      char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
002008    } aCol[1];            /* One entry for each of nCol columns */
002009  };
002010  
002011  /*
002012  ** SQLite supports many different ways to resolve a constraint
002013  ** error.  ROLLBACK processing means that a constraint violation
002014  ** causes the operation in process to fail and for the current transaction
002015  ** to be rolled back.  ABORT processing means the operation in process
002016  ** fails and any prior changes from that one operation are backed out,
002017  ** but the transaction is not rolled back.  FAIL processing means that
002018  ** the operation in progress stops and returns an error code.  But prior
002019  ** changes due to the same operation are not backed out and no rollback
002020  ** occurs.  IGNORE means that the particular row that caused the constraint
002021  ** error is not inserted or updated.  Processing continues and no error
002022  ** is returned.  REPLACE means that preexisting database rows that caused
002023  ** a UNIQUE constraint violation are removed so that the new insert or
002024  ** update can proceed.  Processing continues and no error is reported.
002025  **
002026  ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
002027  ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
002028  ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
002029  ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
002030  ** referenced table row is propagated into the row that holds the
002031  ** foreign key.
002032  **
002033  ** The following symbolic values are used to record which type
002034  ** of action to take.
002035  */
002036  #define OE_None     0   /* There is no constraint to check */
002037  #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
002038  #define OE_Abort    2   /* Back out changes but do no rollback transaction */
002039  #define OE_Fail     3   /* Stop the operation but leave all prior changes */
002040  #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
002041  #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
002042  
002043  #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
002044  #define OE_SetNull  7   /* Set the foreign key value to NULL */
002045  #define OE_SetDflt  8   /* Set the foreign key value to its default */
002046  #define OE_Cascade  9   /* Cascade the changes */
002047  
002048  #define OE_Default  10  /* Do whatever the default action is */
002049  
002050  
002051  /*
002052  ** An instance of the following structure is passed as the first
002053  ** argument to sqlite3VdbeKeyCompare and is used to control the
002054  ** comparison of the two index keys.
002055  **
002056  ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
002057  ** are nField slots for the columns of an index then one extra slot
002058  ** for the rowid at the end.
002059  */
002060  struct KeyInfo {
002061    u32 nRef;           /* Number of references to this KeyInfo object */
002062    u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
002063    u16 nKeyField;      /* Number of key columns in the index */
002064    u16 nAllField;      /* Total columns, including key plus others */
002065    sqlite3 *db;        /* The database connection */
002066    u8 *aSortOrder;     /* Sort order for each column. */
002067    CollSeq *aColl[1];  /* Collating sequence for each term of the key */
002068  };
002069  
002070  /*
002071  ** This object holds a record which has been parsed out into individual
002072  ** fields, for the purposes of doing a comparison.
002073  **
002074  ** A record is an object that contains one or more fields of data.
002075  ** Records are used to store the content of a table row and to store
002076  ** the key of an index.  A blob encoding of a record is created by
002077  ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
002078  ** OP_Column opcode.
002079  **
002080  ** An instance of this object serves as a "key" for doing a search on
002081  ** an index b+tree. The goal of the search is to find the entry that
002082  ** is closed to the key described by this object.  This object might hold
002083  ** just a prefix of the key.  The number of fields is given by
002084  ** pKeyInfo->nField.
002085  **
002086  ** The r1 and r2 fields are the values to return if this key is less than
002087  ** or greater than a key in the btree, respectively.  These are normally
002088  ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
002089  ** is in DESC order.
002090  **
002091  ** The key comparison functions actually return default_rc when they find
002092  ** an equals comparison.  default_rc can be -1, 0, or +1.  If there are
002093  ** multiple entries in the b-tree with the same key (when only looking
002094  ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
002095  ** cause the search to find the last match, or +1 to cause the search to
002096  ** find the first match.
002097  **
002098  ** The key comparison functions will set eqSeen to true if they ever
002099  ** get and equal results when comparing this structure to a b-tree record.
002100  ** When default_rc!=0, the search might end up on the record immediately
002101  ** before the first match or immediately after the last match.  The
002102  ** eqSeen field will indicate whether or not an exact match exists in the
002103  ** b-tree.
002104  */
002105  struct UnpackedRecord {
002106    KeyInfo *pKeyInfo;  /* Collation and sort-order information */
002107    Mem *aMem;          /* Values */
002108    u16 nField;         /* Number of entries in apMem[] */
002109    i8 default_rc;      /* Comparison result if keys are equal */
002110    u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
002111    i8 r1;              /* Value to return if (lhs < rhs) */
002112    i8 r2;              /* Value to return if (lhs > rhs) */
002113    u8 eqSeen;          /* True if an equality comparison has been seen */
002114  };
002115  
002116  
002117  /*
002118  ** Each SQL index is represented in memory by an
002119  ** instance of the following structure.
002120  **
002121  ** The columns of the table that are to be indexed are described
002122  ** by the aiColumn[] field of this structure.  For example, suppose
002123  ** we have the following table and index:
002124  **
002125  **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
002126  **     CREATE INDEX Ex2 ON Ex1(c3,c1);
002127  **
002128  ** In the Table structure describing Ex1, nCol==3 because there are
002129  ** three columns in the table.  In the Index structure describing
002130  ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
002131  ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
002132  ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
002133  ** The second column to be indexed (c1) has an index of 0 in
002134  ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
002135  **
002136  ** The Index.onError field determines whether or not the indexed columns
002137  ** must be unique and what to do if they are not.  When Index.onError=OE_None,
002138  ** it means this is not a unique index.  Otherwise it is a unique index
002139  ** and the value of Index.onError indicate the which conflict resolution
002140  ** algorithm to employ whenever an attempt is made to insert a non-unique
002141  ** element.
002142  **
002143  ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
002144  ** generate VDBE code (as opposed to parsing one read from an sqlite_master
002145  ** table as part of parsing an existing database schema), transient instances
002146  ** of this structure may be created. In this case the Index.tnum variable is
002147  ** used to store the address of a VDBE instruction, not a database page
002148  ** number (it cannot - the database page is not allocated until the VDBE
002149  ** program is executed). See convertToWithoutRowidTable() for details.
002150  */
002151  struct Index {
002152    char *zName;             /* Name of this index */
002153    i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
002154    LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
002155    Table *pTable;           /* The SQL table being indexed */
002156    char *zColAff;           /* String defining the affinity of each column */
002157    Index *pNext;            /* The next index associated with the same table */
002158    Schema *pSchema;         /* Schema containing this index */
002159    u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
002160    const char **azColl;     /* Array of collation sequence names for index */
002161    Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
002162    ExprList *aColExpr;      /* Column expressions */
002163    int tnum;                /* DB Page containing root of this index */
002164    LogEst szIdxRow;         /* Estimated average row size in bytes */
002165    u16 nKeyCol;             /* Number of columns forming the key */
002166    u16 nColumn;             /* Number of columns stored in the index */
002167    u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
002168    unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
002169    unsigned bUnordered:1;   /* Use this index for == or IN queries only */
002170    unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
002171    unsigned isResized:1;    /* True if resizeIndexObject() has been called */
002172    unsigned isCovering:1;   /* True if this is a covering index */
002173    unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
002174    unsigned hasStat1:1;     /* aiRowLogEst values come from sqlite_stat1 */
002175  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
002176    int nSample;             /* Number of elements in aSample[] */
002177    int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
002178    tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
002179    IndexSample *aSample;    /* Samples of the left-most key */
002180    tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
002181    tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
002182  #endif
002183  };
002184  
002185  /*
002186  ** Allowed values for Index.idxType
002187  */
002188  #define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
002189  #define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
002190  #define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
002191  
002192  /* Return true if index X is a PRIMARY KEY index */
002193  #define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
002194  
002195  /* Return true if index X is a UNIQUE index */
002196  #define IsUniqueIndex(X)      ((X)->onError!=OE_None)
002197  
002198  /* The Index.aiColumn[] values are normally positive integer.  But
002199  ** there are some negative values that have special meaning:
002200  */
002201  #define XN_ROWID     (-1)     /* Indexed column is the rowid */
002202  #define XN_EXPR      (-2)     /* Indexed column is an expression */
002203  
002204  /*
002205  ** Each sample stored in the sqlite_stat3 table is represented in memory
002206  ** using a structure of this type.  See documentation at the top of the
002207  ** analyze.c source file for additional information.
002208  */
002209  struct IndexSample {
002210    void *p;          /* Pointer to sampled record */
002211    int n;            /* Size of record in bytes */
002212    tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
002213    tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
002214    tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
002215  };
002216  
002217  /*
002218  ** Each token coming out of the lexer is an instance of
002219  ** this structure.  Tokens are also used as part of an expression.
002220  **
002221  ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
002222  ** may contain random values.  Do not make any assumptions about Token.dyn
002223  ** and Token.n when Token.z==0.
002224  */
002225  struct Token {
002226    const char *z;     /* Text of the token.  Not NULL-terminated! */
002227    unsigned int n;    /* Number of characters in this token */
002228  };
002229  
002230  /*
002231  ** An instance of this structure contains information needed to generate
002232  ** code for a SELECT that contains aggregate functions.
002233  **
002234  ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
002235  ** pointer to this structure.  The Expr.iColumn field is the index in
002236  ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
002237  ** code for that node.
002238  **
002239  ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
002240  ** original Select structure that describes the SELECT statement.  These
002241  ** fields do not need to be freed when deallocating the AggInfo structure.
002242  */
002243  struct AggInfo {
002244    u8 directMode;          /* Direct rendering mode means take data directly
002245                            ** from source tables rather than from accumulators */
002246    u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
002247                            ** than the source table */
002248    int sortingIdx;         /* Cursor number of the sorting index */
002249    int sortingIdxPTab;     /* Cursor number of pseudo-table */
002250    int nSortingColumn;     /* Number of columns in the sorting index */
002251    int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
002252    ExprList *pGroupBy;     /* The group by clause */
002253    struct AggInfo_col {    /* For each column used in source tables */
002254      Table *pTab;             /* Source table */
002255      int iTable;              /* Cursor number of the source table */
002256      int iColumn;             /* Column number within the source table */
002257      int iSorterColumn;       /* Column number in the sorting index */
002258      int iMem;                /* Memory location that acts as accumulator */
002259      Expr *pExpr;             /* The original expression */
002260    } *aCol;
002261    int nColumn;            /* Number of used entries in aCol[] */
002262    int nAccumulator;       /* Number of columns that show through to the output.
002263                            ** Additional columns are used only as parameters to
002264                            ** aggregate functions */
002265    struct AggInfo_func {   /* For each aggregate function */
002266      Expr *pExpr;             /* Expression encoding the function */
002267      FuncDef *pFunc;          /* The aggregate function implementation */
002268      int iMem;                /* Memory location that acts as accumulator */
002269      int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
002270    } *aFunc;
002271    int nFunc;              /* Number of entries in aFunc[] */
002272  };
002273  
002274  /*
002275  ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
002276  ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
002277  ** than 32767 we have to make it 32-bit.  16-bit is preferred because
002278  ** it uses less memory in the Expr object, which is a big memory user
002279  ** in systems with lots of prepared statements.  And few applications
002280  ** need more than about 10 or 20 variables.  But some extreme users want
002281  ** to have prepared statements with over 32767 variables, and for them
002282  ** the option is available (at compile-time).
002283  */
002284  #if SQLITE_MAX_VARIABLE_NUMBER<=32767
002285  typedef i16 ynVar;
002286  #else
002287  typedef int ynVar;
002288  #endif
002289  
002290  /*
002291  ** Each node of an expression in the parse tree is an instance
002292  ** of this structure.
002293  **
002294  ** Expr.op is the opcode. The integer parser token codes are reused
002295  ** as opcodes here. For example, the parser defines TK_GE to be an integer
002296  ** code representing the ">=" operator. This same integer code is reused
002297  ** to represent the greater-than-or-equal-to operator in the expression
002298  ** tree.
002299  **
002300  ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
002301  ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
002302  ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
002303  ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
002304  ** then Expr.token contains the name of the function.
002305  **
002306  ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
002307  ** binary operator. Either or both may be NULL.
002308  **
002309  ** Expr.x.pList is a list of arguments if the expression is an SQL function,
002310  ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
002311  ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
002312  ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
002313  ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
002314  ** valid.
002315  **
002316  ** An expression of the form ID or ID.ID refers to a column in a table.
002317  ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
002318  ** the integer cursor number of a VDBE cursor pointing to that table and
002319  ** Expr.iColumn is the column number for the specific column.  If the
002320  ** expression is used as a result in an aggregate SELECT, then the
002321  ** value is also stored in the Expr.iAgg column in the aggregate so that
002322  ** it can be accessed after all aggregates are computed.
002323  **
002324  ** If the expression is an unbound variable marker (a question mark
002325  ** character '?' in the original SQL) then the Expr.iTable holds the index
002326  ** number for that variable.
002327  **
002328  ** If the expression is a subquery then Expr.iColumn holds an integer
002329  ** register number containing the result of the subquery.  If the
002330  ** subquery gives a constant result, then iTable is -1.  If the subquery
002331  ** gives a different answer at different times during statement processing
002332  ** then iTable is the address of a subroutine that computes the subquery.
002333  **
002334  ** If the Expr is of type OP_Column, and the table it is selecting from
002335  ** is a disk table or the "old.*" pseudo-table, then pTab points to the
002336  ** corresponding table definition.
002337  **
002338  ** ALLOCATION NOTES:
002339  **
002340  ** Expr objects can use a lot of memory space in database schema.  To
002341  ** help reduce memory requirements, sometimes an Expr object will be
002342  ** truncated.  And to reduce the number of memory allocations, sometimes
002343  ** two or more Expr objects will be stored in a single memory allocation,
002344  ** together with Expr.zToken strings.
002345  **
002346  ** If the EP_Reduced and EP_TokenOnly flags are set when
002347  ** an Expr object is truncated.  When EP_Reduced is set, then all
002348  ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
002349  ** are contained within the same memory allocation.  Note, however, that
002350  ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
002351  ** allocated, regardless of whether or not EP_Reduced is set.
002352  */
002353  struct Expr {
002354    u8 op;                 /* Operation performed by this node */
002355    char affinity;         /* The affinity of the column or 0 if not a column */
002356    u32 flags;             /* Various flags.  EP_* See below */
002357    union {
002358      char *zToken;          /* Token value. Zero terminated and dequoted */
002359      int iValue;            /* Non-negative integer value if EP_IntValue */
002360    } u;
002361  
002362    /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
002363    ** space is allocated for the fields below this point. An attempt to
002364    ** access them will result in a segfault or malfunction.
002365    *********************************************************************/
002366  
002367    Expr *pLeft;           /* Left subnode */
002368    Expr *pRight;          /* Right subnode */
002369    union {
002370      ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
002371      Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
002372    } x;
002373  
002374    /* If the EP_Reduced flag is set in the Expr.flags mask, then no
002375    ** space is allocated for the fields below this point. An attempt to
002376    ** access them will result in a segfault or malfunction.
002377    *********************************************************************/
002378  
002379  #if SQLITE_MAX_EXPR_DEPTH>0
002380    int nHeight;           /* Height of the tree headed by this node */
002381  #endif
002382    int iTable;            /* TK_COLUMN: cursor number of table holding column
002383                           ** TK_REGISTER: register number
002384                           ** TK_TRIGGER: 1 -> new, 0 -> old
002385                           ** EP_Unlikely:  134217728 times likelihood
002386                           ** TK_SELECT: 1st register of result vector */
002387    ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
002388                           ** TK_VARIABLE: variable number (always >= 1).
002389                           ** TK_SELECT_COLUMN: column of the result vector */
002390    i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
002391    i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
002392    u8 op2;                /* TK_REGISTER: original value of Expr.op
002393                           ** TK_COLUMN: the value of p5 for OP_Column
002394                           ** TK_AGG_FUNCTION: nesting depth */
002395    AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
002396    Table *pTab;           /* Table for TK_COLUMN expressions.  Can be NULL
002397                           ** for a column of an index on an expression */
002398  };
002399  
002400  /*
002401  ** The following are the meanings of bits in the Expr.flags field.
002402  */
002403  #define EP_FromJoin  0x000001 /* Originates in ON/USING clause of outer join */
002404  #define EP_Agg       0x000002 /* Contains one or more aggregate functions */
002405                    /* 0x000004 // available for use */
002406                    /* 0x000008 // available for use */
002407  #define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
002408  #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
002409  #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
002410  #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
002411  #define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
002412  #define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
002413  #define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
002414  #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
002415  #define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
002416  #define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
002417  #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
002418  #define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
002419  #define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
002420  #define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
002421  #define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
002422  #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
002423  #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
002424  #define EP_Subquery  0x200000 /* Tree contains a TK_SELECT operator */
002425  #define EP_Alias     0x400000 /* Is an alias for a result set column */
002426  #define EP_Leaf      0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
002427  
002428  /*
002429  ** Combinations of two or more EP_* flags
002430  */
002431  #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
002432  
002433  /*
002434  ** These macros can be used to test, set, or clear bits in the
002435  ** Expr.flags field.
002436  */
002437  #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
002438  #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
002439  #define ExprSetProperty(E,P)     (E)->flags|=(P)
002440  #define ExprClearProperty(E,P)   (E)->flags&=~(P)
002441  
002442  /* The ExprSetVVAProperty() macro is used for Verification, Validation,
002443  ** and Accreditation only.  It works like ExprSetProperty() during VVA
002444  ** processes but is a no-op for delivery.
002445  */
002446  #ifdef SQLITE_DEBUG
002447  # define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
002448  #else
002449  # define ExprSetVVAProperty(E,P)
002450  #endif
002451  
002452  /*
002453  ** Macros to determine the number of bytes required by a normal Expr
002454  ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
002455  ** and an Expr struct with the EP_TokenOnly flag set.
002456  */
002457  #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
002458  #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
002459  #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
002460  
002461  /*
002462  ** Flags passed to the sqlite3ExprDup() function. See the header comment
002463  ** above sqlite3ExprDup() for details.
002464  */
002465  #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
002466  
002467  /*
002468  ** A list of expressions.  Each expression may optionally have a
002469  ** name.  An expr/name combination can be used in several ways, such
002470  ** as the list of "expr AS ID" fields following a "SELECT" or in the
002471  ** list of "ID = expr" items in an UPDATE.  A list of expressions can
002472  ** also be used as the argument to a function, in which case the a.zName
002473  ** field is not used.
002474  **
002475  ** By default the Expr.zSpan field holds a human-readable description of
002476  ** the expression that is used in the generation of error messages and
002477  ** column labels.  In this case, Expr.zSpan is typically the text of a
002478  ** column expression as it exists in a SELECT statement.  However, if
002479  ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
002480  ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
002481  ** form is used for name resolution with nested FROM clauses.
002482  */
002483  struct ExprList {
002484    int nExpr;             /* Number of expressions on the list */
002485    struct ExprList_item { /* For each expression in the list */
002486      Expr *pExpr;            /* The parse tree for this expression */
002487      char *zName;            /* Token associated with this expression */
002488      char *zSpan;            /* Original text of the expression */
002489      u8 sortOrder;           /* 1 for DESC or 0 for ASC */
002490      unsigned done :1;       /* A flag to indicate when processing is finished */
002491      unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
002492      unsigned reusable :1;   /* Constant expression is reusable */
002493      union {
002494        struct {
002495          u16 iOrderByCol;      /* For ORDER BY, column number in result set */
002496          u16 iAlias;           /* Index into Parse.aAlias[] for zName */
002497        } x;
002498        int iConstExprReg;      /* Register in which Expr value is cached */
002499      } u;
002500    } a[1];                  /* One slot for each expression in the list */
002501  };
002502  
002503  /*
002504  ** An instance of this structure is used by the parser to record both
002505  ** the parse tree for an expression and the span of input text for an
002506  ** expression.
002507  */
002508  struct ExprSpan {
002509    Expr *pExpr;          /* The expression parse tree */
002510    const char *zStart;   /* First character of input text */
002511    const char *zEnd;     /* One character past the end of input text */
002512  };
002513  
002514  /*
002515  ** An instance of this structure can hold a simple list of identifiers,
002516  ** such as the list "a,b,c" in the following statements:
002517  **
002518  **      INSERT INTO t(a,b,c) VALUES ...;
002519  **      CREATE INDEX idx ON t(a,b,c);
002520  **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
002521  **
002522  ** The IdList.a.idx field is used when the IdList represents the list of
002523  ** column names after a table name in an INSERT statement.  In the statement
002524  **
002525  **     INSERT INTO t(a,b,c) ...
002526  **
002527  ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
002528  */
002529  struct IdList {
002530    struct IdList_item {
002531      char *zName;      /* Name of the identifier */
002532      int idx;          /* Index in some Table.aCol[] of a column named zName */
002533    } *a;
002534    int nId;         /* Number of identifiers on the list */
002535  };
002536  
002537  /*
002538  ** The bitmask datatype defined below is used for various optimizations.
002539  **
002540  ** Changing this from a 64-bit to a 32-bit type limits the number of
002541  ** tables in a join to 32 instead of 64.  But it also reduces the size
002542  ** of the library by 738 bytes on ix86.
002543  */
002544  #ifdef SQLITE_BITMASK_TYPE
002545    typedef SQLITE_BITMASK_TYPE Bitmask;
002546  #else
002547    typedef u64 Bitmask;
002548  #endif
002549  
002550  /*
002551  ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
002552  */
002553  #define BMS  ((int)(sizeof(Bitmask)*8))
002554  
002555  /*
002556  ** A bit in a Bitmask
002557  */
002558  #define MASKBIT(n)   (((Bitmask)1)<<(n))
002559  #define MASKBIT32(n) (((unsigned int)1)<<(n))
002560  #define ALLBITS      ((Bitmask)-1)
002561  
002562  /*
002563  ** The following structure describes the FROM clause of a SELECT statement.
002564  ** Each table or subquery in the FROM clause is a separate element of
002565  ** the SrcList.a[] array.
002566  **
002567  ** With the addition of multiple database support, the following structure
002568  ** can also be used to describe a particular table such as the table that
002569  ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
002570  ** such a table must be a simple name: ID.  But in SQLite, the table can
002571  ** now be identified by a database name, a dot, then the table name: ID.ID.
002572  **
002573  ** The jointype starts out showing the join type between the current table
002574  ** and the next table on the list.  The parser builds the list this way.
002575  ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
002576  ** jointype expresses the join between the table and the previous table.
002577  **
002578  ** In the colUsed field, the high-order bit (bit 63) is set if the table
002579  ** contains more than 63 columns and the 64-th or later column is used.
002580  */
002581  struct SrcList {
002582    int nSrc;        /* Number of tables or subqueries in the FROM clause */
002583    u32 nAlloc;      /* Number of entries allocated in a[] below */
002584    struct SrcList_item {
002585      Schema *pSchema;  /* Schema to which this item is fixed */
002586      char *zDatabase;  /* Name of database holding this table */
002587      char *zName;      /* Name of the table */
002588      char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
002589      Table *pTab;      /* An SQL table corresponding to zName */
002590      Select *pSelect;  /* A SELECT statement used in place of a table name */
002591      int addrFillSub;  /* Address of subroutine to manifest a subquery */
002592      int regReturn;    /* Register holding return address of addrFillSub */
002593      int regResult;    /* Registers holding results of a co-routine */
002594      struct {
002595        u8 jointype;      /* Type of join between this table and the previous */
002596        unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
002597        unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
002598        unsigned isTabFunc :1;     /* True if table-valued-function syntax */
002599        unsigned isCorrelated :1;  /* True if sub-query is correlated */
002600        unsigned viaCoroutine :1;  /* Implemented as a co-routine */
002601        unsigned isRecursive :1;   /* True for recursive reference in WITH */
002602      } fg;
002603  #ifndef SQLITE_OMIT_EXPLAIN
002604      u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
002605  #endif
002606      int iCursor;      /* The VDBE cursor number used to access this table */
002607      Expr *pOn;        /* The ON clause of a join */
002608      IdList *pUsing;   /* The USING clause of a join */
002609      Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
002610      union {
002611        char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
002612        ExprList *pFuncArg;  /* Arguments to table-valued-function */
002613      } u1;
002614      Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
002615    } a[1];             /* One entry for each identifier on the list */
002616  };
002617  
002618  /*
002619  ** Permitted values of the SrcList.a.jointype field
002620  */
002621  #define JT_INNER     0x0001    /* Any kind of inner or cross join */
002622  #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
002623  #define JT_NATURAL   0x0004    /* True for a "natural" join */
002624  #define JT_LEFT      0x0008    /* Left outer join */
002625  #define JT_RIGHT     0x0010    /* Right outer join */
002626  #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
002627  #define JT_ERROR     0x0040    /* unknown or unsupported join type */
002628  
002629  
002630  /*
002631  ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
002632  ** and the WhereInfo.wctrlFlags member.
002633  **
002634  ** Value constraints (enforced via assert()):
002635  **     WHERE_USE_LIMIT  == SF_FixedLimit
002636  */
002637  #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
002638  #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
002639  #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
002640  #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
002641  #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
002642  #define WHERE_DUPLICATES_OK    0x0010 /* Ok to return a row more than once */
002643  #define WHERE_OR_SUBCLAUSE     0x0020 /* Processing a sub-WHERE as part of
002644                                        ** the OR optimization  */
002645  #define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */
002646  #define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
002647  #define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
002648  #define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
002649  #define WHERE_SEEK_TABLE       0x0400 /* Do not defer seeks on main table */
002650  #define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
002651  #define WHERE_SEEK_UNIQ_TABLE  0x1000 /* Do not defer seeks if unique */
002652                          /*     0x2000    not currently used */
002653  #define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
002654                          /*     0x8000    not currently used */
002655  
002656  /* Allowed return values from sqlite3WhereIsDistinct()
002657  */
002658  #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
002659  #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
002660  #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
002661  #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
002662  
002663  /*
002664  ** A NameContext defines a context in which to resolve table and column
002665  ** names.  The context consists of a list of tables (the pSrcList) field and
002666  ** a list of named expression (pEList).  The named expression list may
002667  ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
002668  ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
002669  ** pEList corresponds to the result set of a SELECT and is NULL for
002670  ** other statements.
002671  **
002672  ** NameContexts can be nested.  When resolving names, the inner-most
002673  ** context is searched first.  If no match is found, the next outer
002674  ** context is checked.  If there is still no match, the next context
002675  ** is checked.  This process continues until either a match is found
002676  ** or all contexts are check.  When a match is found, the nRef member of
002677  ** the context containing the match is incremented.
002678  **
002679  ** Each subquery gets a new NameContext.  The pNext field points to the
002680  ** NameContext in the parent query.  Thus the process of scanning the
002681  ** NameContext list corresponds to searching through successively outer
002682  ** subqueries looking for a match.
002683  */
002684  struct NameContext {
002685    Parse *pParse;       /* The parser */
002686    SrcList *pSrcList;   /* One or more tables used to resolve names */
002687    ExprList *pEList;    /* Optional list of result-set columns */
002688    AggInfo *pAggInfo;   /* Information about aggregates at this level */
002689    NameContext *pNext;  /* Next outer name context.  NULL for outermost */
002690    int nRef;            /* Number of names resolved by this context */
002691    int nErr;            /* Number of errors encountered while resolving names */
002692    u16 ncFlags;         /* Zero or more NC_* flags defined below */
002693  };
002694  
002695  /*
002696  ** Allowed values for the NameContext, ncFlags field.
002697  **
002698  ** Value constraints (all checked via assert()):
002699  **    NC_HasAgg    == SF_HasAgg
002700  **    NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
002701  **
002702  */
002703  #define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
002704  #define NC_PartIdx   0x0002  /* True if resolving a partial index WHERE */
002705  #define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
002706  #define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
002707  #define NC_HasAgg    0x0010  /* One or more aggregate functions seen */
002708  #define NC_IdxExpr   0x0020  /* True if resolving columns of CREATE INDEX */
002709  #define NC_VarSelect 0x0040  /* A correlated subquery has been seen */
002710  #define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
002711  
002712  /*
002713  ** An instance of the following structure contains all information
002714  ** needed to generate code for a single SELECT statement.
002715  **
002716  ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
002717  ** If there is a LIMIT clause, the parser sets nLimit to the value of the
002718  ** limit and nOffset to the value of the offset (or 0 if there is not
002719  ** offset).  But later on, nLimit and nOffset become the memory locations
002720  ** in the VDBE that record the limit and offset counters.
002721  **
002722  ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
002723  ** These addresses must be stored so that we can go back and fill in
002724  ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
002725  ** the number of columns in P2 can be computed at the same time
002726  ** as the OP_OpenEphm instruction is coded because not
002727  ** enough information about the compound query is known at that point.
002728  ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
002729  ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
002730  ** sequences for the ORDER BY clause.
002731  */
002732  struct Select {
002733    ExprList *pEList;      /* The fields of the result */
002734    u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
002735    LogEst nSelectRow;     /* Estimated number of result rows */
002736    u32 selFlags;          /* Various SF_* values */
002737    int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
002738  #if SELECTTRACE_ENABLED
002739    char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
002740  #endif
002741    int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
002742    SrcList *pSrc;         /* The FROM clause */
002743    Expr *pWhere;          /* The WHERE clause */
002744    ExprList *pGroupBy;    /* The GROUP BY clause */
002745    Expr *pHaving;         /* The HAVING clause */
002746    ExprList *pOrderBy;    /* The ORDER BY clause */
002747    Select *pPrior;        /* Prior select in a compound select statement */
002748    Select *pNext;         /* Next select to the left in a compound */
002749    Expr *pLimit;          /* LIMIT expression. NULL means not used. */
002750    Expr *pOffset;         /* OFFSET expression. NULL means not used. */
002751    With *pWith;           /* WITH clause attached to this select. Or NULL. */
002752  };
002753  
002754  /*
002755  ** Allowed values for Select.selFlags.  The "SF" prefix stands for
002756  ** "Select Flag".
002757  **
002758  ** Value constraints (all checked via assert())
002759  **     SF_HasAgg     == NC_HasAgg
002760  **     SF_MinMaxAgg  == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
002761  **     SF_FixedLimit == WHERE_USE_LIMIT
002762  */
002763  #define SF_Distinct       0x00001  /* Output should be DISTINCT */
002764  #define SF_All            0x00002  /* Includes the ALL keyword */
002765  #define SF_Resolved       0x00004  /* Identifiers have been resolved */
002766  #define SF_Aggregate      0x00008  /* Contains agg functions or a GROUP BY */
002767  #define SF_HasAgg         0x00010  /* Contains aggregate functions */
002768  #define SF_UsesEphemeral  0x00020  /* Uses the OpenEphemeral opcode */
002769  #define SF_Expanded       0x00040  /* sqlite3SelectExpand() called on this */
002770  #define SF_HasTypeInfo    0x00080  /* FROM subqueries have Table metadata */
002771  #define SF_Compound       0x00100  /* Part of a compound query */
002772  #define SF_Values         0x00200  /* Synthesized from VALUES clause */
002773  #define SF_MultiValue     0x00400  /* Single VALUES term with multiple rows */
002774  #define SF_NestedFrom     0x00800  /* Part of a parenthesized FROM clause */
002775  #define SF_MinMaxAgg      0x01000  /* Aggregate containing min() or max() */
002776  #define SF_Recursive      0x02000  /* The recursive part of a recursive CTE */
002777  #define SF_FixedLimit     0x04000  /* nSelectRow set by a constant LIMIT */
002778  #define SF_MaybeConvert   0x08000  /* Need convertCompoundSelectToSubquery() */
002779  #define SF_Converted      0x10000  /* By convertCompoundSelectToSubquery() */
002780  #define SF_IncludeHidden  0x20000  /* Include hidden columns in output */
002781  
002782  
002783  /*
002784  ** The results of a SELECT can be distributed in several ways, as defined
002785  ** by one of the following macros.  The "SRT" prefix means "SELECT Result
002786  ** Type".
002787  **
002788  **     SRT_Union       Store results as a key in a temporary index
002789  **                     identified by pDest->iSDParm.
002790  **
002791  **     SRT_Except      Remove results from the temporary index pDest->iSDParm.
002792  **
002793  **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
002794  **                     set is not empty.
002795  **
002796  **     SRT_Discard     Throw the results away.  This is used by SELECT
002797  **                     statements within triggers whose only purpose is
002798  **                     the side-effects of functions.
002799  **
002800  ** All of the above are free to ignore their ORDER BY clause. Those that
002801  ** follow must honor the ORDER BY clause.
002802  **
002803  **     SRT_Output      Generate a row of output (using the OP_ResultRow
002804  **                     opcode) for each row in the result set.
002805  **
002806  **     SRT_Mem         Only valid if the result is a single column.
002807  **                     Store the first column of the first result row
002808  **                     in register pDest->iSDParm then abandon the rest
002809  **                     of the query.  This destination implies "LIMIT 1".
002810  **
002811  **     SRT_Set         The result must be a single column.  Store each
002812  **                     row of result as the key in table pDest->iSDParm.
002813  **                     Apply the affinity pDest->affSdst before storing
002814  **                     results.  Used to implement "IN (SELECT ...)".
002815  **
002816  **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
002817  **                     the result there. The cursor is left open after
002818  **                     returning.  This is like SRT_Table except that
002819  **                     this destination uses OP_OpenEphemeral to create
002820  **                     the table first.
002821  **
002822  **     SRT_Coroutine   Generate a co-routine that returns a new row of
002823  **                     results each time it is invoked.  The entry point
002824  **                     of the co-routine is stored in register pDest->iSDParm
002825  **                     and the result row is stored in pDest->nDest registers
002826  **                     starting with pDest->iSdst.
002827  **
002828  **     SRT_Table       Store results in temporary table pDest->iSDParm.
002829  **     SRT_Fifo        This is like SRT_EphemTab except that the table
002830  **                     is assumed to already be open.  SRT_Fifo has
002831  **                     the additional property of being able to ignore
002832  **                     the ORDER BY clause.
002833  **
002834  **     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
002835  **                     But also use temporary table pDest->iSDParm+1 as
002836  **                     a record of all prior results and ignore any duplicate
002837  **                     rows.  Name means:  "Distinct Fifo".
002838  **
002839  **     SRT_Queue       Store results in priority queue pDest->iSDParm (really
002840  **                     an index).  Append a sequence number so that all entries
002841  **                     are distinct.
002842  **
002843  **     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
002844  **                     the same record has never been stored before.  The
002845  **                     index at pDest->iSDParm+1 hold all prior stores.
002846  */
002847  #define SRT_Union        1  /* Store result as keys in an index */
002848  #define SRT_Except       2  /* Remove result from a UNION index */
002849  #define SRT_Exists       3  /* Store 1 if the result is not empty */
002850  #define SRT_Discard      4  /* Do not save the results anywhere */
002851  #define SRT_Fifo         5  /* Store result as data with an automatic rowid */
002852  #define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
002853  #define SRT_Queue        7  /* Store result in an queue */
002854  #define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
002855  
002856  /* The ORDER BY clause is ignored for all of the above */
002857  #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
002858  
002859  #define SRT_Output       9  /* Output each row of result */
002860  #define SRT_Mem         10  /* Store result in a memory cell */
002861  #define SRT_Set         11  /* Store results as keys in an index */
002862  #define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
002863  #define SRT_Coroutine   13  /* Generate a single row of result */
002864  #define SRT_Table       14  /* Store result as data with an automatic rowid */
002865  
002866  /*
002867  ** An instance of this object describes where to put of the results of
002868  ** a SELECT statement.
002869  */
002870  struct SelectDest {
002871    u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
002872    int iSDParm;         /* A parameter used by the eDest disposal method */
002873    int iSdst;           /* Base register where results are written */
002874    int nSdst;           /* Number of registers allocated */
002875    char *zAffSdst;      /* Affinity used when eDest==SRT_Set */
002876    ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
002877  };
002878  
002879  /*
002880  ** During code generation of statements that do inserts into AUTOINCREMENT
002881  ** tables, the following information is attached to the Table.u.autoInc.p
002882  ** pointer of each autoincrement table to record some side information that
002883  ** the code generator needs.  We have to keep per-table autoincrement
002884  ** information in case inserts are done within triggers.  Triggers do not
002885  ** normally coordinate their activities, but we do need to coordinate the
002886  ** loading and saving of autoincrement information.
002887  */
002888  struct AutoincInfo {
002889    AutoincInfo *pNext;   /* Next info block in a list of them all */
002890    Table *pTab;          /* Table this info block refers to */
002891    int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
002892    int regCtr;           /* Memory register holding the rowid counter */
002893  };
002894  
002895  /*
002896  ** Size of the column cache
002897  */
002898  #ifndef SQLITE_N_COLCACHE
002899  # define SQLITE_N_COLCACHE 10
002900  #endif
002901  
002902  /*
002903  ** At least one instance of the following structure is created for each
002904  ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
002905  ** statement. All such objects are stored in the linked list headed at
002906  ** Parse.pTriggerPrg and deleted once statement compilation has been
002907  ** completed.
002908  **
002909  ** A Vdbe sub-program that implements the body and WHEN clause of trigger
002910  ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
002911  ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
002912  ** The Parse.pTriggerPrg list never contains two entries with the same
002913  ** values for both pTrigger and orconf.
002914  **
002915  ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
002916  ** accessed (or set to 0 for triggers fired as a result of INSERT
002917  ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
002918  ** a mask of new.* columns used by the program.
002919  */
002920  struct TriggerPrg {
002921    Trigger *pTrigger;      /* Trigger this program was coded from */
002922    TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
002923    SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
002924    int orconf;             /* Default ON CONFLICT policy */
002925    u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
002926  };
002927  
002928  /*
002929  ** The yDbMask datatype for the bitmask of all attached databases.
002930  */
002931  #if SQLITE_MAX_ATTACHED>30
002932    typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
002933  # define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
002934  # define DbMaskZero(M)      memset((M),0,sizeof(M))
002935  # define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
002936  # define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
002937  # define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
002938  #else
002939    typedef unsigned int yDbMask;
002940  # define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
002941  # define DbMaskZero(M)      (M)=0
002942  # define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
002943  # define DbMaskAllZero(M)   (M)==0
002944  # define DbMaskNonZero(M)   (M)!=0
002945  #endif
002946  
002947  /*
002948  ** An SQL parser context.  A copy of this structure is passed through
002949  ** the parser and down into all the parser action routine in order to
002950  ** carry around information that is global to the entire parse.
002951  **
002952  ** The structure is divided into two parts.  When the parser and code
002953  ** generate call themselves recursively, the first part of the structure
002954  ** is constant but the second part is reset at the beginning and end of
002955  ** each recursion.
002956  **
002957  ** The nTableLock and aTableLock variables are only used if the shared-cache
002958  ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
002959  ** used to store the set of table-locks required by the statement being
002960  ** compiled. Function sqlite3TableLock() is used to add entries to the
002961  ** list.
002962  */
002963  struct Parse {
002964    sqlite3 *db;         /* The main database structure */
002965    char *zErrMsg;       /* An error message */
002966    Vdbe *pVdbe;         /* An engine for executing database bytecode */
002967    int rc;              /* Return code from execution */
002968    u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
002969    u8 checkSchema;      /* Causes schema cookie check after an error */
002970    u8 nested;           /* Number of nested calls to the parser/code generator */
002971    u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
002972    u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
002973    u8 mayAbort;         /* True if statement may throw an ABORT exception */
002974    u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
002975    u8 okConstFactor;    /* OK to factor out constants */
002976    u8 disableLookaside; /* Number of times lookaside has been disabled */
002977    u8 nColCache;        /* Number of entries in aColCache[] */
002978    int nRangeReg;       /* Size of the temporary register block */
002979    int iRangeReg;       /* First register in temporary register block */
002980    int nErr;            /* Number of errors seen */
002981    int nTab;            /* Number of previously allocated VDBE cursors */
002982    int nMem;            /* Number of memory cells used so far */
002983    int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
002984    int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */
002985    int iSelfTab;        /* Table for associated with an index on expr, or negative
002986                         ** of the base register during check-constraint eval */
002987    int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
002988    int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
002989    int nLabel;          /* Number of labels used */
002990    int *aLabel;         /* Space to hold the labels */
002991    ExprList *pConstExpr;/* Constant expressions */
002992    Token constraintName;/* Name of the constraint currently being parsed */
002993    yDbMask writeMask;   /* Start a write transaction on these databases */
002994    yDbMask cookieMask;  /* Bitmask of schema verified databases */
002995    int regRowid;        /* Register holding rowid of CREATE TABLE entry */
002996    int regRoot;         /* Register holding root page number for new objects */
002997    int nMaxArg;         /* Max args passed to user function by sub-program */
002998  #if SELECTTRACE_ENABLED
002999    int nSelect;         /* Number of SELECT statements seen */
003000    int nSelectIndent;   /* How far to indent SELECTTRACE() output */
003001  #endif
003002  #ifndef SQLITE_OMIT_SHARED_CACHE
003003    int nTableLock;        /* Number of locks in aTableLock */
003004    TableLock *aTableLock; /* Required table locks for shared-cache mode */
003005  #endif
003006    AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
003007    Parse *pToplevel;    /* Parse structure for main program (or NULL) */
003008    Table *pTriggerTab;  /* Table triggers are being coded for */
003009    int addrCrTab;       /* Address of OP_CreateBtree opcode on CREATE TABLE */
003010    u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
003011    u32 oldmask;         /* Mask of old.* columns referenced */
003012    u32 newmask;         /* Mask of new.* columns referenced */
003013    u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
003014    u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
003015    u8 disableTriggers;  /* True to disable triggers */
003016  
003017    /**************************************************************************
003018    ** Fields above must be initialized to zero.  The fields that follow,
003019    ** down to the beginning of the recursive section, do not need to be
003020    ** initialized as they will be set before being used.  The boundary is
003021    ** determined by offsetof(Parse,aColCache).
003022    **************************************************************************/
003023  
003024    struct yColCache {
003025      int iTable;           /* Table cursor number */
003026      i16 iColumn;          /* Table column number */
003027      u8 tempReg;           /* iReg is a temp register that needs to be freed */
003028      int iLevel;           /* Nesting level */
003029      int iReg;             /* Reg with value of this column. 0 means none. */
003030      int lru;              /* Least recently used entry has the smallest value */
003031    } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
003032    int aTempReg[8];        /* Holding area for temporary registers */
003033    Token sNameToken;       /* Token with unqualified schema object name */
003034  
003035    /************************************************************************
003036    ** Above is constant between recursions.  Below is reset before and after
003037    ** each recursion.  The boundary between these two regions is determined
003038    ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
003039    ** first field in the recursive region.
003040    ************************************************************************/
003041  
003042    Token sLastToken;       /* The last token parsed */
003043    ynVar nVar;               /* Number of '?' variables seen in the SQL so far */
003044    u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
003045    u8 explain;               /* True if the EXPLAIN flag is found on the query */
003046  #ifndef SQLITE_OMIT_VIRTUALTABLE
003047    u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
003048    int nVtabLock;            /* Number of virtual tables to lock */
003049  #endif
003050    int nHeight;              /* Expression tree height of current sub-select */
003051  #ifndef SQLITE_OMIT_EXPLAIN
003052    int iSelectId;            /* ID of current select for EXPLAIN output */
003053    int iNextSelectId;        /* Next available select ID for EXPLAIN output */
003054  #endif
003055    VList *pVList;            /* Mapping between variable names and numbers */
003056    Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
003057    const char *zTail;        /* All SQL text past the last semicolon parsed */
003058    Table *pNewTable;         /* A table being constructed by CREATE TABLE */
003059    Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
003060    const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
003061  #ifndef SQLITE_OMIT_VIRTUALTABLE
003062    Token sArg;               /* Complete text of a module argument */
003063    Table **apVtabLock;       /* Pointer to virtual tables needing locking */
003064  #endif
003065    Table *pZombieTab;        /* List of Table objects to delete after code gen */
003066    TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
003067    With *pWith;              /* Current WITH clause, or NULL */
003068    With *pWithToFree;        /* Free this WITH object at the end of the parse */
003069  };
003070  
003071  /*
003072  ** Sizes and pointers of various parts of the Parse object.
003073  */
003074  #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
003075  #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken)    /* Recursive part */
003076  #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
003077  #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ)  /* Pointer to tail */
003078  
003079  /*
003080  ** Return true if currently inside an sqlite3_declare_vtab() call.
003081  */
003082  #ifdef SQLITE_OMIT_VIRTUALTABLE
003083    #define IN_DECLARE_VTAB 0
003084  #else
003085    #define IN_DECLARE_VTAB (pParse->declareVtab)
003086  #endif
003087  
003088  /*
003089  ** An instance of the following structure can be declared on a stack and used
003090  ** to save the Parse.zAuthContext value so that it can be restored later.
003091  */
003092  struct AuthContext {
003093    const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
003094    Parse *pParse;              /* The Parse structure */
003095  };
003096  
003097  /*
003098  ** Bitfield flags for P5 value in various opcodes.
003099  **
003100  ** Value constraints (enforced via assert()):
003101  **    OPFLAG_LENGTHARG    == SQLITE_FUNC_LENGTH
003102  **    OPFLAG_TYPEOFARG    == SQLITE_FUNC_TYPEOF
003103  **    OPFLAG_BULKCSR      == BTREE_BULKLOAD
003104  **    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ
003105  **    OPFLAG_FORDELETE    == BTREE_FORDELETE
003106  **    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
003107  **    OPFLAG_AUXDELETE    == BTREE_AUXDELETE
003108  */
003109  #define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */
003110                                       /* Also used in P2 (not P5) of OP_Delete */
003111  #define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
003112  #define OPFLAG_LASTROWID     0x20    /* Set to update db->lastRowid */
003113  #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
003114  #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
003115  #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
003116  #define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */
003117  #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
003118  #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
003119  #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
003120  #define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
003121  #define OPFLAG_FORDELETE     0x08    /* OP_Open should use BTREE_FORDELETE */
003122  #define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */
003123  #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
003124  #define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete/Insert: save cursor pos */
003125  #define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */
003126  
003127  /*
003128   * Each trigger present in the database schema is stored as an instance of
003129   * struct Trigger.
003130   *
003131   * Pointers to instances of struct Trigger are stored in two ways.
003132   * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
003133   *    database). This allows Trigger structures to be retrieved by name.
003134   * 2. All triggers associated with a single table form a linked list, using the
003135   *    pNext member of struct Trigger. A pointer to the first element of the
003136   *    linked list is stored as the "pTrigger" member of the associated
003137   *    struct Table.
003138   *
003139   * The "step_list" member points to the first element of a linked list
003140   * containing the SQL statements specified as the trigger program.
003141   */
003142  struct Trigger {
003143    char *zName;            /* The name of the trigger                        */
003144    char *table;            /* The table or view to which the trigger applies */
003145    u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
003146    u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
003147    Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
003148    IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
003149                               the <column-list> is stored here */
003150    Schema *pSchema;        /* Schema containing the trigger */
003151    Schema *pTabSchema;     /* Schema containing the table */
003152    TriggerStep *step_list; /* Link list of trigger program steps             */
003153    Trigger *pNext;         /* Next trigger associated with the table */
003154  };
003155  
003156  /*
003157  ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
003158  ** determine which.
003159  **
003160  ** If there are multiple triggers, you might of some BEFORE and some AFTER.
003161  ** In that cases, the constants below can be ORed together.
003162  */
003163  #define TRIGGER_BEFORE  1
003164  #define TRIGGER_AFTER   2
003165  
003166  /*
003167   * An instance of struct TriggerStep is used to store a single SQL statement
003168   * that is a part of a trigger-program.
003169   *
003170   * Instances of struct TriggerStep are stored in a singly linked list (linked
003171   * using the "pNext" member) referenced by the "step_list" member of the
003172   * associated struct Trigger instance. The first element of the linked list is
003173   * the first step of the trigger-program.
003174   *
003175   * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
003176   * "SELECT" statement. The meanings of the other members is determined by the
003177   * value of "op" as follows:
003178   *
003179   * (op == TK_INSERT)
003180   * orconf    -> stores the ON CONFLICT algorithm
003181   * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
003182   *              this stores a pointer to the SELECT statement. Otherwise NULL.
003183   * zTarget   -> Dequoted name of the table to insert into.
003184   * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
003185   *              this stores values to be inserted. Otherwise NULL.
003186   * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
003187   *              statement, then this stores the column-names to be
003188   *              inserted into.
003189   *
003190   * (op == TK_DELETE)
003191   * zTarget   -> Dequoted name of the table to delete from.
003192   * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
003193   *              Otherwise NULL.
003194   *
003195   * (op == TK_UPDATE)
003196   * zTarget   -> Dequoted name of the table to update.
003197   * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
003198   *              Otherwise NULL.
003199   * pExprList -> A list of the columns to update and the expressions to update
003200   *              them to. See sqlite3Update() documentation of "pChanges"
003201   *              argument.
003202   *
003203   */
003204  struct TriggerStep {
003205    u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
003206    u8 orconf;           /* OE_Rollback etc. */
003207    Trigger *pTrig;      /* The trigger that this step is a part of */
003208    Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
003209    char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
003210    Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
003211    ExprList *pExprList; /* SET clause for UPDATE. */
003212    IdList *pIdList;     /* Column names for INSERT */
003213    TriggerStep *pNext;  /* Next in the link-list */
003214    TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
003215  };
003216  
003217  /*
003218  ** The following structure contains information used by the sqliteFix...
003219  ** routines as they walk the parse tree to make database references
003220  ** explicit.
003221  */
003222  typedef struct DbFixer DbFixer;
003223  struct DbFixer {
003224    Parse *pParse;      /* The parsing context.  Error messages written here */
003225    Schema *pSchema;    /* Fix items to this schema */
003226    int bVarOnly;       /* Check for variable references only */
003227    const char *zDb;    /* Make sure all objects are contained in this database */
003228    const char *zType;  /* Type of the container - used for error messages */
003229    const Token *pName; /* Name of the container - used for error messages */
003230  };
003231  
003232  /*
003233  ** An objected used to accumulate the text of a string where we
003234  ** do not necessarily know how big the string will be in the end.
003235  */
003236  struct StrAccum {
003237    sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
003238    char *zText;         /* The string collected so far */
003239    u32  nAlloc;         /* Amount of space allocated in zText */
003240    u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
003241    u32  nChar;          /* Length of the string so far */
003242    u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
003243    u8   printfFlags;    /* SQLITE_PRINTF flags below */
003244  };
003245  #define STRACCUM_NOMEM   1
003246  #define STRACCUM_TOOBIG  2
003247  #define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */
003248  #define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */
003249  #define SQLITE_PRINTF_MALLOCED 0x04  /* True if xText is allocated space */
003250  
003251  #define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
003252  
003253  
003254  /*
003255  ** A pointer to this structure is used to communicate information
003256  ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
003257  */
003258  typedef struct {
003259    sqlite3 *db;        /* The database being initialized */
003260    char **pzErrMsg;    /* Error message stored here */
003261    int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
003262    int rc;             /* Result code stored here */
003263  } InitData;
003264  
003265  /*
003266  ** Structure containing global configuration data for the SQLite library.
003267  **
003268  ** This structure also contains some state information.
003269  */
003270  struct Sqlite3Config {
003271    int bMemstat;                     /* True to enable memory status */
003272    int bCoreMutex;                   /* True to enable core mutexing */
003273    int bFullMutex;                   /* True to enable full mutexing */
003274    int bOpenUri;                     /* True to interpret filenames as URIs */
003275    int bUseCis;                      /* Use covering indices for full-scans */
003276    int bSmallMalloc;                 /* Avoid large memory allocations if true */
003277    int mxStrlen;                     /* Maximum string length */
003278    int neverCorrupt;                 /* Database is always well-formed */
003279    int szLookaside;                  /* Default lookaside buffer size */
003280    int nLookaside;                   /* Default lookaside buffer count */
003281    int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */
003282    sqlite3_mem_methods m;            /* Low-level memory allocation interface */
003283    sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
003284    sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
003285    void *pHeap;                      /* Heap storage space */
003286    int nHeap;                        /* Size of pHeap[] */
003287    int mnReq, mxReq;                 /* Min and max heap requests sizes */
003288    sqlite3_int64 szMmap;             /* mmap() space per open file */
003289    sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
003290    void *pPage;                      /* Page cache memory */
003291    int szPage;                       /* Size of each page in pPage[] */
003292    int nPage;                        /* Number of pages in pPage[] */
003293    int mxParserStack;                /* maximum depth of the parser stack */
003294    int sharedCacheEnabled;           /* true if shared-cache mode enabled */
003295    u32 szPma;                        /* Maximum Sorter PMA size */
003296    /* The above might be initialized to non-zero.  The following need to always
003297    ** initially be zero, however. */
003298    int isInit;                       /* True after initialization has finished */
003299    int inProgress;                   /* True while initialization in progress */
003300    int isMutexInit;                  /* True after mutexes are initialized */
003301    int isMallocInit;                 /* True after malloc is initialized */
003302    int isPCacheInit;                 /* True after malloc is initialized */
003303    int nRefInitMutex;                /* Number of users of pInitMutex */
003304    sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
003305    void (*xLog)(void*,int,const char*); /* Function for logging */
003306    void *pLogArg;                       /* First argument to xLog() */
003307  #ifdef SQLITE_ENABLE_SQLLOG
003308    void(*xSqllog)(void*,sqlite3*,const char*, int);
003309    void *pSqllogArg;
003310  #endif
003311  #ifdef SQLITE_VDBE_COVERAGE
003312    /* The following callback (if not NULL) is invoked on every VDBE branch
003313    ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
003314    */
003315    void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
003316    void *pVdbeBranchArg;                                     /* 1st argument */
003317  #endif
003318  #ifndef SQLITE_UNTESTABLE
003319    int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
003320  #endif
003321    int bLocaltimeFault;              /* True to fail localtime() calls */
003322    int iOnceResetThreshold;          /* When to reset OP_Once counters */
003323  };
003324  
003325  /*
003326  ** This macro is used inside of assert() statements to indicate that
003327  ** the assert is only valid on a well-formed database.  Instead of:
003328  **
003329  **     assert( X );
003330  **
003331  ** One writes:
003332  **
003333  **     assert( X || CORRUPT_DB );
003334  **
003335  ** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
003336  ** that the database is definitely corrupt, only that it might be corrupt.
003337  ** For most test cases, CORRUPT_DB is set to false using a special
003338  ** sqlite3_test_control().  This enables assert() statements to prove
003339  ** things that are always true for well-formed databases.
003340  */
003341  #define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
003342  
003343  /*
003344  ** Context pointer passed down through the tree-walk.
003345  */
003346  struct Walker {
003347    Parse *pParse;                            /* Parser context.  */
003348    int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
003349    int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
003350    void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
003351    int walkerDepth;                          /* Number of subqueries */
003352    u8 eCode;                                 /* A small processing code */
003353    union {                                   /* Extra data for callback */
003354      NameContext *pNC;                         /* Naming context */
003355      int n;                                    /* A counter */
003356      int iCur;                                 /* A cursor number */
003357      SrcList *pSrcList;                        /* FROM clause */
003358      struct SrcCount *pSrcCount;               /* Counting column references */
003359      struct CCurHint *pCCurHint;               /* Used by codeCursorHint() */
003360      int *aiCol;                               /* array of column indexes */
003361      struct IdxCover *pIdxCover;               /* Check for index coverage */
003362      struct IdxExprTrans *pIdxTrans;           /* Convert indexed expr to column */
003363      ExprList *pGroupBy;                       /* GROUP BY clause */
003364      struct HavingToWhereCtx *pHavingCtx;      /* HAVING to WHERE clause ctx */
003365    } u;
003366  };
003367  
003368  /* Forward declarations */
003369  int sqlite3WalkExpr(Walker*, Expr*);
003370  int sqlite3WalkExprList(Walker*, ExprList*);
003371  int sqlite3WalkSelect(Walker*, Select*);
003372  int sqlite3WalkSelectExpr(Walker*, Select*);
003373  int sqlite3WalkSelectFrom(Walker*, Select*);
003374  int sqlite3ExprWalkNoop(Walker*, Expr*);
003375  int sqlite3SelectWalkNoop(Walker*, Select*);
003376  int sqlite3SelectWalkFail(Walker*, Select*);
003377  #ifdef SQLITE_DEBUG
003378  void sqlite3SelectWalkAssert2(Walker*, Select*);
003379  #endif
003380  
003381  /*
003382  ** Return code from the parse-tree walking primitives and their
003383  ** callbacks.
003384  */
003385  #define WRC_Continue    0   /* Continue down into children */
003386  #define WRC_Prune       1   /* Omit children but continue walking siblings */
003387  #define WRC_Abort       2   /* Abandon the tree walk */
003388  
003389  /*
003390  ** An instance of this structure represents a set of one or more CTEs
003391  ** (common table expressions) created by a single WITH clause.
003392  */
003393  struct With {
003394    int nCte;                       /* Number of CTEs in the WITH clause */
003395    With *pOuter;                   /* Containing WITH clause, or NULL */
003396    struct Cte {                    /* For each CTE in the WITH clause.... */
003397      char *zName;                    /* Name of this CTE */
003398      ExprList *pCols;                /* List of explicit column names, or NULL */
003399      Select *pSelect;                /* The definition of this CTE */
003400      const char *zCteErr;            /* Error message for circular references */
003401    } a[1];
003402  };
003403  
003404  #ifdef SQLITE_DEBUG
003405  /*
003406  ** An instance of the TreeView object is used for printing the content of
003407  ** data structures on sqlite3DebugPrintf() using a tree-like view.
003408  */
003409  struct TreeView {
003410    int iLevel;             /* Which level of the tree we are on */
003411    u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
003412  };
003413  #endif /* SQLITE_DEBUG */
003414  
003415  /*
003416  ** Assuming zIn points to the first byte of a UTF-8 character,
003417  ** advance zIn to point to the first byte of the next UTF-8 character.
003418  */
003419  #define SQLITE_SKIP_UTF8(zIn) {                        \
003420    if( (*(zIn++))>=0xc0 ){                              \
003421      while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
003422    }                                                    \
003423  }
003424  
003425  /*
003426  ** The SQLITE_*_BKPT macros are substitutes for the error codes with
003427  ** the same name but without the _BKPT suffix.  These macros invoke
003428  ** routines that report the line-number on which the error originated
003429  ** using sqlite3_log().  The routines also provide a convenient place
003430  ** to set a debugger breakpoint.
003431  */
003432  int sqlite3CorruptError(int);
003433  int sqlite3MisuseError(int);
003434  int sqlite3CantopenError(int);
003435  #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
003436  #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
003437  #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
003438  #ifdef SQLITE_DEBUG
003439    int sqlite3NomemError(int);
003440    int sqlite3IoerrnomemError(int);
003441    int sqlite3CorruptPgnoError(int,Pgno);
003442  # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
003443  # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
003444  # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
003445  #else
003446  # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
003447  # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
003448  # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
003449  #endif
003450  
003451  /*
003452  ** FTS3 and FTS4 both require virtual table support
003453  */
003454  #if defined(SQLITE_OMIT_VIRTUALTABLE)
003455  # undef SQLITE_ENABLE_FTS3
003456  # undef SQLITE_ENABLE_FTS4
003457  #endif
003458  
003459  /*
003460  ** FTS4 is really an extension for FTS3.  It is enabled using the
003461  ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
003462  ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
003463  */
003464  #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
003465  # define SQLITE_ENABLE_FTS3 1
003466  #endif
003467  
003468  /*
003469  ** The ctype.h header is needed for non-ASCII systems.  It is also
003470  ** needed by FTS3 when FTS3 is included in the amalgamation.
003471  */
003472  #if !defined(SQLITE_ASCII) || \
003473      (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
003474  # include <ctype.h>
003475  #endif
003476  
003477  /*
003478  ** The following macros mimic the standard library functions toupper(),
003479  ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
003480  ** sqlite versions only work for ASCII characters, regardless of locale.
003481  */
003482  #ifdef SQLITE_ASCII
003483  # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
003484  # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
003485  # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
003486  # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
003487  # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
003488  # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
003489  # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
003490  # define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
003491  #else
003492  # define sqlite3Toupper(x)   toupper((unsigned char)(x))
003493  # define sqlite3Isspace(x)   isspace((unsigned char)(x))
003494  # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
003495  # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
003496  # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
003497  # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
003498  # define sqlite3Tolower(x)   tolower((unsigned char)(x))
003499  # define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
003500  #endif
003501  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
003502  int sqlite3IsIdChar(u8);
003503  #endif
003504  
003505  /*
003506  ** Internal function prototypes
003507  */
003508  int sqlite3StrICmp(const char*,const char*);
003509  int sqlite3Strlen30(const char*);
003510  char *sqlite3ColumnType(Column*,char*);
003511  #define sqlite3StrNICmp sqlite3_strnicmp
003512  
003513  int sqlite3MallocInit(void);
003514  void sqlite3MallocEnd(void);
003515  void *sqlite3Malloc(u64);
003516  void *sqlite3MallocZero(u64);
003517  void *sqlite3DbMallocZero(sqlite3*, u64);
003518  void *sqlite3DbMallocRaw(sqlite3*, u64);
003519  void *sqlite3DbMallocRawNN(sqlite3*, u64);
003520  char *sqlite3DbStrDup(sqlite3*,const char*);
003521  char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
003522  void *sqlite3Realloc(void*, u64);
003523  void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
003524  void *sqlite3DbRealloc(sqlite3 *, void *, u64);
003525  void sqlite3DbFree(sqlite3*, void*);
003526  void sqlite3DbFreeNN(sqlite3*, void*);
003527  int sqlite3MallocSize(void*);
003528  int sqlite3DbMallocSize(sqlite3*, void*);
003529  void *sqlite3PageMalloc(int);
003530  void sqlite3PageFree(void*);
003531  void sqlite3MemSetDefault(void);
003532  #ifndef SQLITE_UNTESTABLE
003533  void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
003534  #endif
003535  int sqlite3HeapNearlyFull(void);
003536  
003537  /*
003538  ** On systems with ample stack space and that support alloca(), make
003539  ** use of alloca() to obtain space for large automatic objects.  By default,
003540  ** obtain space from malloc().
003541  **
003542  ** The alloca() routine never returns NULL.  This will cause code paths
003543  ** that deal with sqlite3StackAlloc() failures to be unreachable.
003544  */
003545  #ifdef SQLITE_USE_ALLOCA
003546  # define sqlite3StackAllocRaw(D,N)   alloca(N)
003547  # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
003548  # define sqlite3StackFree(D,P)
003549  #else
003550  # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
003551  # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
003552  # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
003553  #endif
003554  
003555  /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together.  If they
003556  ** are, disable MEMSYS3
003557  */
003558  #ifdef SQLITE_ENABLE_MEMSYS5
003559  const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
003560  #undef SQLITE_ENABLE_MEMSYS3
003561  #endif
003562  #ifdef SQLITE_ENABLE_MEMSYS3
003563  const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
003564  #endif
003565  
003566  
003567  #ifndef SQLITE_MUTEX_OMIT
003568    sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
003569    sqlite3_mutex_methods const *sqlite3NoopMutex(void);
003570    sqlite3_mutex *sqlite3MutexAlloc(int);
003571    int sqlite3MutexInit(void);
003572    int sqlite3MutexEnd(void);
003573  #endif
003574  #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
003575    void sqlite3MemoryBarrier(void);
003576  #else
003577  # define sqlite3MemoryBarrier()
003578  #endif
003579  
003580  sqlite3_int64 sqlite3StatusValue(int);
003581  void sqlite3StatusUp(int, int);
003582  void sqlite3StatusDown(int, int);
003583  void sqlite3StatusHighwater(int, int);
003584  int sqlite3LookasideUsed(sqlite3*,int*);
003585  
003586  /* Access to mutexes used by sqlite3_status() */
003587  sqlite3_mutex *sqlite3Pcache1Mutex(void);
003588  sqlite3_mutex *sqlite3MallocMutex(void);
003589  
003590  #ifndef SQLITE_OMIT_FLOATING_POINT
003591    int sqlite3IsNaN(double);
003592  #else
003593  # define sqlite3IsNaN(X)  0
003594  #endif
003595  
003596  /*
003597  ** An instance of the following structure holds information about SQL
003598  ** functions arguments that are the parameters to the printf() function.
003599  */
003600  struct PrintfArguments {
003601    int nArg;                /* Total number of arguments */
003602    int nUsed;               /* Number of arguments used so far */
003603    sqlite3_value **apArg;   /* The argument values */
003604  };
003605  
003606  void sqlite3VXPrintf(StrAccum*, const char*, va_list);
003607  void sqlite3XPrintf(StrAccum*, const char*, ...);
003608  char *sqlite3MPrintf(sqlite3*,const char*, ...);
003609  char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
003610  #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
003611    void sqlite3DebugPrintf(const char*, ...);
003612  #endif
003613  #if defined(SQLITE_TEST)
003614    void *sqlite3TestTextToPtr(const char*);
003615  #endif
003616  
003617  #if defined(SQLITE_DEBUG)
003618    void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
003619    void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
003620    void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
003621    void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
003622    void sqlite3TreeViewWith(TreeView*, const With*, u8);
003623  #endif
003624  
003625  
003626  void sqlite3SetString(char **, sqlite3*, const char*);
003627  void sqlite3ErrorMsg(Parse*, const char*, ...);
003628  void sqlite3Dequote(char*);
003629  void sqlite3TokenInit(Token*,char*);
003630  int sqlite3KeywordCode(const unsigned char*, int);
003631  int sqlite3RunParser(Parse*, const char*, char **);
003632  void sqlite3FinishCoding(Parse*);
003633  int sqlite3GetTempReg(Parse*);
003634  void sqlite3ReleaseTempReg(Parse*,int);
003635  int sqlite3GetTempRange(Parse*,int);
003636  void sqlite3ReleaseTempRange(Parse*,int,int);
003637  void sqlite3ClearTempRegCache(Parse*);
003638  #ifdef SQLITE_DEBUG
003639  int sqlite3NoTempsInRange(Parse*,int,int);
003640  #endif
003641  Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
003642  Expr *sqlite3Expr(sqlite3*,int,const char*);
003643  void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
003644  Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
003645  void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
003646  Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
003647  Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
003648  void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
003649  void sqlite3ExprDelete(sqlite3*, Expr*);
003650  ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
003651  ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
003652  void sqlite3ExprListSetSortOrder(ExprList*,int);
003653  void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
003654  void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
003655  void sqlite3ExprListDelete(sqlite3*, ExprList*);
003656  u32 sqlite3ExprListFlags(const ExprList*);
003657  int sqlite3Init(sqlite3*, char**);
003658  int sqlite3InitCallback(void*, int, char**, char**);
003659  void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
003660  #ifndef SQLITE_OMIT_VIRTUALTABLE
003661  Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
003662  #endif
003663  void sqlite3ResetAllSchemasOfConnection(sqlite3*);
003664  void sqlite3ResetOneSchema(sqlite3*,int);
003665  void sqlite3CollapseDatabaseArray(sqlite3*);
003666  void sqlite3CommitInternalChanges(sqlite3*);
003667  void sqlite3DeleteColumnNames(sqlite3*,Table*);
003668  int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
003669  void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
003670  Table *sqlite3ResultSetOfSelect(Parse*,Select*);
003671  void sqlite3OpenMasterTable(Parse *, int);
003672  Index *sqlite3PrimaryKeyIndex(Table*);
003673  i16 sqlite3ColumnOfIndex(Index*, i16);
003674  void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
003675  #if SQLITE_ENABLE_HIDDEN_COLUMNS
003676    void sqlite3ColumnPropertiesFromName(Table*, Column*);
003677  #else
003678  # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
003679  #endif
003680  void sqlite3AddColumn(Parse*,Token*,Token*);
003681  void sqlite3AddNotNull(Parse*, int);
003682  void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
003683  void sqlite3AddCheckConstraint(Parse*, Expr*);
003684  void sqlite3AddDefaultValue(Parse*,ExprSpan*);
003685  void sqlite3AddCollateType(Parse*, Token*);
003686  void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
003687  int sqlite3ParseUri(const char*,const char*,unsigned int*,
003688                      sqlite3_vfs**,char**,char **);
003689  Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
003690  
003691  #ifdef SQLITE_UNTESTABLE
003692  # define sqlite3FaultSim(X) SQLITE_OK
003693  #else
003694    int sqlite3FaultSim(int);
003695  #endif
003696  
003697  Bitvec *sqlite3BitvecCreate(u32);
003698  int sqlite3BitvecTest(Bitvec*, u32);
003699  int sqlite3BitvecTestNotNull(Bitvec*, u32);
003700  int sqlite3BitvecSet(Bitvec*, u32);
003701  void sqlite3BitvecClear(Bitvec*, u32, void*);
003702  void sqlite3BitvecDestroy(Bitvec*);
003703  u32 sqlite3BitvecSize(Bitvec*);
003704  #ifndef SQLITE_UNTESTABLE
003705  int sqlite3BitvecBuiltinTest(int,int*);
003706  #endif
003707  
003708  RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
003709  void sqlite3RowSetClear(RowSet*);
003710  void sqlite3RowSetInsert(RowSet*, i64);
003711  int sqlite3RowSetTest(RowSet*, int iBatch, i64);
003712  int sqlite3RowSetNext(RowSet*, i64*);
003713  
003714  void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
003715  
003716  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
003717    int sqlite3ViewGetColumnNames(Parse*,Table*);
003718  #else
003719  # define sqlite3ViewGetColumnNames(A,B) 0
003720  #endif
003721  
003722  #if SQLITE_MAX_ATTACHED>30
003723    int sqlite3DbMaskAllZero(yDbMask);
003724  #endif
003725  void sqlite3DropTable(Parse*, SrcList*, int, int);
003726  void sqlite3CodeDropTable(Parse*, Table*, int, int);
003727  void sqlite3DeleteTable(sqlite3*, Table*);
003728  #ifndef SQLITE_OMIT_AUTOINCREMENT
003729    void sqlite3AutoincrementBegin(Parse *pParse);
003730    void sqlite3AutoincrementEnd(Parse *pParse);
003731  #else
003732  # define sqlite3AutoincrementBegin(X)
003733  # define sqlite3AutoincrementEnd(X)
003734  #endif
003735  void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
003736  void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
003737  IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
003738  int sqlite3IdListIndex(IdList*,const char*);
003739  SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
003740  SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
003741  SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
003742                                        Token*, Select*, Expr*, IdList*);
003743  void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
003744  void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
003745  int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
003746  void sqlite3SrcListShiftJoinType(SrcList*);
003747  void sqlite3SrcListAssignCursors(Parse*, SrcList*);
003748  void sqlite3IdListDelete(sqlite3*, IdList*);
003749  void sqlite3SrcListDelete(sqlite3*, SrcList*);
003750  Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
003751  void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
003752                            Expr*, int, int, u8);
003753  void sqlite3DropIndex(Parse*, SrcList*, int);
003754  int sqlite3Select(Parse*, Select*, SelectDest*);
003755  Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
003756                           Expr*,ExprList*,u32,Expr*,Expr*);
003757  void sqlite3SelectDelete(sqlite3*, Select*);
003758  Table *sqlite3SrcListLookup(Parse*, SrcList*);
003759  int sqlite3IsReadOnly(Parse*, Table*, int);
003760  void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
003761  #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
003762  Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
003763  #endif
003764  void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
003765  void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
003766  WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
003767  void sqlite3WhereEnd(WhereInfo*);
003768  LogEst sqlite3WhereOutputRowCount(WhereInfo*);
003769  int sqlite3WhereIsDistinct(WhereInfo*);
003770  int sqlite3WhereIsOrdered(WhereInfo*);
003771  int sqlite3WhereOrderedInnerLoop(WhereInfo*);
003772  int sqlite3WhereIsSorted(WhereInfo*);
003773  int sqlite3WhereContinueLabel(WhereInfo*);
003774  int sqlite3WhereBreakLabel(WhereInfo*);
003775  int sqlite3WhereOkOnePass(WhereInfo*, int*);
003776  #define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
003777  #define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
003778  #define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
003779  void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
003780  int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
003781  void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
003782  void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
003783  void sqlite3ExprCodeMove(Parse*, int, int, int);
003784  void sqlite3ExprCacheStore(Parse*, int, int, int);
003785  void sqlite3ExprCachePush(Parse*);
003786  void sqlite3ExprCachePop(Parse*);
003787  void sqlite3ExprCacheRemove(Parse*, int, int);
003788  void sqlite3ExprCacheClear(Parse*);
003789  void sqlite3ExprCacheAffinityChange(Parse*, int, int);
003790  void sqlite3ExprCode(Parse*, Expr*, int);
003791  void sqlite3ExprCodeCopy(Parse*, Expr*, int);
003792  void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
003793  int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
003794  int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
003795  int sqlite3ExprCodeTarget(Parse*, Expr*, int);
003796  void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
003797  int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
003798  #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
003799  #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
003800  #define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */
003801  #define SQLITE_ECEL_OMITREF  0x08  /* Omit if ExprList.u.x.iOrderByCol */
003802  void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
003803  void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
003804  void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
003805  Table *sqlite3FindTable(sqlite3*,const char*, const char*);
003806  #define LOCATE_VIEW    0x01
003807  #define LOCATE_NOERR   0x02
003808  Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
003809  Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
003810  Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
003811  void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
003812  void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
003813  void sqlite3Vacuum(Parse*,Token*);
003814  int sqlite3RunVacuum(char**, sqlite3*, int);
003815  char *sqlite3NameFromToken(sqlite3*, Token*);
003816  int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
003817  int sqlite3ExprCompareSkip(Expr*, Expr*, int);
003818  int sqlite3ExprListCompare(ExprList*, ExprList*, int);
003819  int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
003820  void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
003821  void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
003822  int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
003823  int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
003824  Vdbe *sqlite3GetVdbe(Parse*);
003825  #ifndef SQLITE_UNTESTABLE
003826  void sqlite3PrngSaveState(void);
003827  void sqlite3PrngRestoreState(void);
003828  #endif
003829  void sqlite3RollbackAll(sqlite3*,int);
003830  void sqlite3CodeVerifySchema(Parse*, int);
003831  void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
003832  void sqlite3BeginTransaction(Parse*, int);
003833  void sqlite3EndTransaction(Parse*,int);
003834  void sqlite3Savepoint(Parse*, int, Token*);
003835  void sqlite3CloseSavepoints(sqlite3 *);
003836  void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
003837  int sqlite3ExprIsConstant(Expr*);
003838  int sqlite3ExprIsConstantNotJoin(Expr*);
003839  int sqlite3ExprIsConstantOrFunction(Expr*, u8);
003840  int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
003841  int sqlite3ExprIsTableConstant(Expr*,int);
003842  #ifdef SQLITE_ENABLE_CURSOR_HINTS
003843  int sqlite3ExprContainsSubquery(Expr*);
003844  #endif
003845  int sqlite3ExprIsInteger(Expr*, int*);
003846  int sqlite3ExprCanBeNull(const Expr*);
003847  int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
003848  int sqlite3IsRowid(const char*);
003849  void sqlite3GenerateRowDelete(
003850      Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
003851  void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
003852  int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
003853  void sqlite3ResolvePartIdxLabel(Parse*,int);
003854  void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
003855                                       u8,u8,int,int*,int*);
003856  #ifdef SQLITE_ENABLE_NULL_TRIM
003857    void sqlite3SetMakeRecordP5(Vdbe*,Table*);
003858  #else
003859  # define sqlite3SetMakeRecordP5(A,B)
003860  #endif
003861  void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
003862  int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
003863  void sqlite3BeginWriteOperation(Parse*, int, int);
003864  void sqlite3MultiWrite(Parse*);
003865  void sqlite3MayAbort(Parse*);
003866  void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
003867  void sqlite3UniqueConstraint(Parse*, int, Index*);
003868  void sqlite3RowidConstraint(Parse*, int, Table*);
003869  Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
003870  ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
003871  SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
003872  IdList *sqlite3IdListDup(sqlite3*,IdList*);
003873  Select *sqlite3SelectDup(sqlite3*,Select*,int);
003874  #if SELECTTRACE_ENABLED
003875  void sqlite3SelectSetName(Select*,const char*);
003876  #else
003877  # define sqlite3SelectSetName(A,B)
003878  #endif
003879  void sqlite3InsertBuiltinFuncs(FuncDef*,int);
003880  FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
003881  void sqlite3RegisterBuiltinFunctions(void);
003882  void sqlite3RegisterDateTimeFunctions(void);
003883  void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
003884  int sqlite3SafetyCheckOk(sqlite3*);
003885  int sqlite3SafetyCheckSickOrOk(sqlite3*);
003886  void sqlite3ChangeCookie(Parse*, int);
003887  
003888  #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
003889  void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
003890  #endif
003891  
003892  #ifndef SQLITE_OMIT_TRIGGER
003893    void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
003894                             Expr*,int, int);
003895    void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
003896    void sqlite3DropTrigger(Parse*, SrcList*, int);
003897    void sqlite3DropTriggerPtr(Parse*, Trigger*);
003898    Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
003899    Trigger *sqlite3TriggerList(Parse *, Table *);
003900    void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
003901                              int, int, int);
003902    void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
003903    void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
003904    void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
003905    TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
003906    TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
003907                                          Select*,u8);
003908    TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
003909    TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
003910    void sqlite3DeleteTrigger(sqlite3*, Trigger*);
003911    void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
003912    u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
003913  # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
003914  # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
003915  #else
003916  # define sqlite3TriggersExist(B,C,D,E,F) 0
003917  # define sqlite3DeleteTrigger(A,B)
003918  # define sqlite3DropTriggerPtr(A,B)
003919  # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
003920  # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
003921  # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
003922  # define sqlite3TriggerList(X, Y) 0
003923  # define sqlite3ParseToplevel(p) p
003924  # define sqlite3IsToplevel(p) 1
003925  # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
003926  #endif
003927  
003928  int sqlite3JoinType(Parse*, Token*, Token*, Token*);
003929  void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
003930  void sqlite3DeferForeignKey(Parse*, int);
003931  #ifndef SQLITE_OMIT_AUTHORIZATION
003932    void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
003933    int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
003934    void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
003935    void sqlite3AuthContextPop(AuthContext*);
003936    int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
003937  #else
003938  # define sqlite3AuthRead(a,b,c,d)
003939  # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
003940  # define sqlite3AuthContextPush(a,b,c)
003941  # define sqlite3AuthContextPop(a)  ((void)(a))
003942  #endif
003943  void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
003944  void sqlite3Detach(Parse*, Expr*);
003945  void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
003946  int sqlite3FixSrcList(DbFixer*, SrcList*);
003947  int sqlite3FixSelect(DbFixer*, Select*);
003948  int sqlite3FixExpr(DbFixer*, Expr*);
003949  int sqlite3FixExprList(DbFixer*, ExprList*);
003950  int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
003951  int sqlite3AtoF(const char *z, double*, int, u8);
003952  int sqlite3GetInt32(const char *, int*);
003953  int sqlite3Atoi(const char*);
003954  #ifndef SQLITE_OMIT_UTF16
003955  int sqlite3Utf16ByteLen(const void *pData, int nChar);
003956  #endif
003957  int sqlite3Utf8CharLen(const char *pData, int nByte);
003958  u32 sqlite3Utf8Read(const u8**);
003959  LogEst sqlite3LogEst(u64);
003960  LogEst sqlite3LogEstAdd(LogEst,LogEst);
003961  #ifndef SQLITE_OMIT_VIRTUALTABLE
003962  LogEst sqlite3LogEstFromDouble(double);
003963  #endif
003964  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
003965      defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
003966      defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
003967  u64 sqlite3LogEstToInt(LogEst);
003968  #endif
003969  VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
003970  const char *sqlite3VListNumToName(VList*,int);
003971  int sqlite3VListNameToNum(VList*,const char*,int);
003972  
003973  /*
003974  ** Routines to read and write variable-length integers.  These used to
003975  ** be defined locally, but now we use the varint routines in the util.c
003976  ** file.
003977  */
003978  int sqlite3PutVarint(unsigned char*, u64);
003979  u8 sqlite3GetVarint(const unsigned char *, u64 *);
003980  u8 sqlite3GetVarint32(const unsigned char *, u32 *);
003981  int sqlite3VarintLen(u64 v);
003982  
003983  /*
003984  ** The common case is for a varint to be a single byte.  They following
003985  ** macros handle the common case without a procedure call, but then call
003986  ** the procedure for larger varints.
003987  */
003988  #define getVarint32(A,B)  \
003989    (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
003990  #define putVarint32(A,B)  \
003991    (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
003992    sqlite3PutVarint((A),(B)))
003993  #define getVarint    sqlite3GetVarint
003994  #define putVarint    sqlite3PutVarint
003995  
003996  
003997  const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
003998  void sqlite3TableAffinity(Vdbe*, Table*, int);
003999  char sqlite3CompareAffinity(Expr *pExpr, char aff2);
004000  int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
004001  char sqlite3TableColumnAffinity(Table*,int);
004002  char sqlite3ExprAffinity(Expr *pExpr);
004003  int sqlite3Atoi64(const char*, i64*, int, u8);
004004  int sqlite3DecOrHexToI64(const char*, i64*);
004005  void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
004006  void sqlite3Error(sqlite3*,int);
004007  void sqlite3SystemError(sqlite3*,int);
004008  void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
004009  u8 sqlite3HexToInt(int h);
004010  int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
004011  
004012  #if defined(SQLITE_NEED_ERR_NAME)
004013  const char *sqlite3ErrName(int);
004014  #endif
004015  
004016  const char *sqlite3ErrStr(int);
004017  int sqlite3ReadSchema(Parse *pParse);
004018  CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
004019  CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
004020  CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
004021  CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
004022  int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
004023  Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
004024  Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
004025  Expr *sqlite3ExprSkipCollate(Expr*);
004026  int sqlite3CheckCollSeq(Parse *, CollSeq *);
004027  int sqlite3CheckObjectName(Parse *, const char *);
004028  void sqlite3VdbeSetChanges(sqlite3 *, int);
004029  int sqlite3AddInt64(i64*,i64);
004030  int sqlite3SubInt64(i64*,i64);
004031  int sqlite3MulInt64(i64*,i64);
004032  int sqlite3AbsInt32(int);
004033  #ifdef SQLITE_ENABLE_8_3_NAMES
004034  void sqlite3FileSuffix3(const char*, char*);
004035  #else
004036  # define sqlite3FileSuffix3(X,Y)
004037  #endif
004038  u8 sqlite3GetBoolean(const char *z,u8);
004039  
004040  const void *sqlite3ValueText(sqlite3_value*, u8);
004041  int sqlite3ValueBytes(sqlite3_value*, u8);
004042  void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
004043                          void(*)(void*));
004044  void sqlite3ValueSetNull(sqlite3_value*);
004045  void sqlite3ValueFree(sqlite3_value*);
004046  sqlite3_value *sqlite3ValueNew(sqlite3 *);
004047  #ifndef SQLITE_OMIT_UTF16
004048  char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
004049  #endif
004050  int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
004051  void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
004052  #ifndef SQLITE_AMALGAMATION
004053  extern const unsigned char sqlite3OpcodeProperty[];
004054  extern const char sqlite3StrBINARY[];
004055  extern const unsigned char sqlite3UpperToLower[];
004056  extern const unsigned char sqlite3CtypeMap[];
004057  extern const Token sqlite3IntTokens[];
004058  extern SQLITE_WSD struct Sqlite3Config sqlite3Config;
004059  extern FuncDefHash sqlite3BuiltinFunctions;
004060  #ifndef SQLITE_OMIT_WSD
004061  extern int sqlite3PendingByte;
004062  #endif
004063  #endif
004064  void sqlite3RootPageMoved(sqlite3*, int, int, int);
004065  void sqlite3Reindex(Parse*, Token*, Token*);
004066  void sqlite3AlterFunctions(void);
004067  void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
004068  int sqlite3GetToken(const unsigned char *, int *);
004069  void sqlite3NestedParse(Parse*, const char*, ...);
004070  void sqlite3ExpirePreparedStatements(sqlite3*);
004071  int sqlite3CodeSubselect(Parse*, Expr *, int, int);
004072  void sqlite3SelectPrep(Parse*, Select*, NameContext*);
004073  void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
004074  int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
004075  int sqlite3ResolveExprNames(NameContext*, Expr*);
004076  int sqlite3ResolveExprListNames(NameContext*, ExprList*);
004077  void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
004078  void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
004079  int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
004080  void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
004081  void sqlite3AlterFinishAddColumn(Parse *, Token *);
004082  void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
004083  CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
004084  char sqlite3AffinityType(const char*, u8*);
004085  void sqlite3Analyze(Parse*, Token*, Token*);
004086  int sqlite3InvokeBusyHandler(BusyHandler*);
004087  int sqlite3FindDb(sqlite3*, Token*);
004088  int sqlite3FindDbName(sqlite3 *, const char *);
004089  int sqlite3AnalysisLoad(sqlite3*,int iDB);
004090  void sqlite3DeleteIndexSamples(sqlite3*,Index*);
004091  void sqlite3DefaultRowEst(Index*);
004092  void sqlite3RegisterLikeFunctions(sqlite3*, int);
004093  int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
004094  void sqlite3SchemaClear(void *);
004095  Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
004096  int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
004097  KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
004098  void sqlite3KeyInfoUnref(KeyInfo*);
004099  KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
004100  KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
004101  #ifdef SQLITE_DEBUG
004102  int sqlite3KeyInfoIsWriteable(KeyInfo*);
004103  #endif
004104  int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
004105    void (*)(sqlite3_context*,int,sqlite3_value **),
004106    void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
004107    FuncDestructor *pDestructor
004108  );
004109  void sqlite3OomFault(sqlite3*);
004110  void sqlite3OomClear(sqlite3*);
004111  int sqlite3ApiExit(sqlite3 *db, int);
004112  int sqlite3OpenTempDatabase(Parse *);
004113  
004114  void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
004115  void sqlite3StrAccumAppend(StrAccum*,const char*,int);
004116  void sqlite3StrAccumAppendAll(StrAccum*,const char*);
004117  void sqlite3AppendChar(StrAccum*,int,char);
004118  char *sqlite3StrAccumFinish(StrAccum*);
004119  void sqlite3StrAccumReset(StrAccum*);
004120  void sqlite3SelectDestInit(SelectDest*,int,int);
004121  Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
004122  
004123  void sqlite3BackupRestart(sqlite3_backup *);
004124  void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
004125  
004126  #ifndef SQLITE_OMIT_SUBQUERY
004127  int sqlite3ExprCheckIN(Parse*, Expr*);
004128  #else
004129  # define sqlite3ExprCheckIN(x,y) SQLITE_OK
004130  #endif
004131  
004132  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
004133  void sqlite3AnalyzeFunctions(void);
004134  int sqlite3Stat4ProbeSetValue(
004135      Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
004136  int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
004137  void sqlite3Stat4ProbeFree(UnpackedRecord*);
004138  int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
004139  char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
004140  #endif
004141  
004142  /*
004143  ** The interface to the LEMON-generated parser
004144  */
004145  #ifndef SQLITE_AMALGAMATION
004146    void *sqlite3ParserAlloc(void*(*)(u64));
004147    void sqlite3ParserFree(void*, void(*)(void*));
004148  #endif
004149  void sqlite3Parser(void*, int, Token, Parse*);
004150  #ifdef YYTRACKMAXSTACKDEPTH
004151    int sqlite3ParserStackPeak(void*);
004152  #endif
004153  
004154  void sqlite3AutoLoadExtensions(sqlite3*);
004155  #ifndef SQLITE_OMIT_LOAD_EXTENSION
004156    void sqlite3CloseExtensions(sqlite3*);
004157  #else
004158  # define sqlite3CloseExtensions(X)
004159  #endif
004160  
004161  #ifndef SQLITE_OMIT_SHARED_CACHE
004162    void sqlite3TableLock(Parse *, int, int, u8, const char *);
004163  #else
004164    #define sqlite3TableLock(v,w,x,y,z)
004165  #endif
004166  
004167  #ifdef SQLITE_TEST
004168    int sqlite3Utf8To8(unsigned char*);
004169  #endif
004170  
004171  #ifdef SQLITE_OMIT_VIRTUALTABLE
004172  #  define sqlite3VtabClear(Y)
004173  #  define sqlite3VtabSync(X,Y) SQLITE_OK
004174  #  define sqlite3VtabRollback(X)
004175  #  define sqlite3VtabCommit(X)
004176  #  define sqlite3VtabInSync(db) 0
004177  #  define sqlite3VtabLock(X)
004178  #  define sqlite3VtabUnlock(X)
004179  #  define sqlite3VtabUnlockList(X)
004180  #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
004181  #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
004182  #else
004183     void sqlite3VtabClear(sqlite3 *db, Table*);
004184     void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
004185     int sqlite3VtabSync(sqlite3 *db, Vdbe*);
004186     int sqlite3VtabRollback(sqlite3 *db);
004187     int sqlite3VtabCommit(sqlite3 *db);
004188     void sqlite3VtabLock(VTable *);
004189     void sqlite3VtabUnlock(VTable *);
004190     void sqlite3VtabUnlockList(sqlite3*);
004191     int sqlite3VtabSavepoint(sqlite3 *, int, int);
004192     void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
004193     VTable *sqlite3GetVTable(sqlite3*, Table*);
004194     Module *sqlite3VtabCreateModule(
004195       sqlite3*,
004196       const char*,
004197       const sqlite3_module*,
004198       void*,
004199       void(*)(void*)
004200     );
004201  #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
004202  #endif
004203  int sqlite3VtabEponymousTableInit(Parse*,Module*);
004204  void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
004205  void sqlite3VtabMakeWritable(Parse*,Table*);
004206  void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
004207  void sqlite3VtabFinishParse(Parse*, Token*);
004208  void sqlite3VtabArgInit(Parse*);
004209  void sqlite3VtabArgExtend(Parse*, Token*);
004210  int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
004211  int sqlite3VtabCallConnect(Parse*, Table*);
004212  int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
004213  int sqlite3VtabBegin(sqlite3 *, VTable *);
004214  FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
004215  void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
004216  sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
004217  int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
004218  int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
004219  void sqlite3ParserReset(Parse*);
004220  int sqlite3Reprepare(Vdbe*);
004221  void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
004222  CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
004223  int sqlite3TempInMemory(const sqlite3*);
004224  const char *sqlite3JournalModename(int);
004225  #ifndef SQLITE_OMIT_WAL
004226    int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
004227    int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
004228  #endif
004229  #ifndef SQLITE_OMIT_CTE
004230    With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
004231    void sqlite3WithDelete(sqlite3*,With*);
004232    void sqlite3WithPush(Parse*, With*, u8);
004233  #else
004234  #define sqlite3WithPush(x,y,z)
004235  #define sqlite3WithDelete(x,y)
004236  #endif
004237  
004238  /* Declarations for functions in fkey.c. All of these are replaced by
004239  ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
004240  ** key functionality is available. If OMIT_TRIGGER is defined but
004241  ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
004242  ** this case foreign keys are parsed, but no other functionality is
004243  ** provided (enforcement of FK constraints requires the triggers sub-system).
004244  */
004245  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
004246    void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
004247    void sqlite3FkDropTable(Parse*, SrcList *, Table*);
004248    void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
004249    int sqlite3FkRequired(Parse*, Table*, int*, int);
004250    u32 sqlite3FkOldmask(Parse*, Table*);
004251    FKey *sqlite3FkReferences(Table *);
004252  #else
004253    #define sqlite3FkActions(a,b,c,d,e,f)
004254    #define sqlite3FkCheck(a,b,c,d,e,f)
004255    #define sqlite3FkDropTable(a,b,c)
004256    #define sqlite3FkOldmask(a,b)         0
004257    #define sqlite3FkRequired(a,b,c,d)    0
004258    #define sqlite3FkReferences(a)        0
004259  #endif
004260  #ifndef SQLITE_OMIT_FOREIGN_KEY
004261    void sqlite3FkDelete(sqlite3 *, Table*);
004262    int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
004263  #else
004264    #define sqlite3FkDelete(a,b)
004265    #define sqlite3FkLocateIndex(a,b,c,d,e)
004266  #endif
004267  
004268  
004269  /*
004270  ** Available fault injectors.  Should be numbered beginning with 0.
004271  */
004272  #define SQLITE_FAULTINJECTOR_MALLOC     0
004273  #define SQLITE_FAULTINJECTOR_COUNT      1
004274  
004275  /*
004276  ** The interface to the code in fault.c used for identifying "benign"
004277  ** malloc failures. This is only present if SQLITE_UNTESTABLE
004278  ** is not defined.
004279  */
004280  #ifndef SQLITE_UNTESTABLE
004281    void sqlite3BeginBenignMalloc(void);
004282    void sqlite3EndBenignMalloc(void);
004283  #else
004284    #define sqlite3BeginBenignMalloc()
004285    #define sqlite3EndBenignMalloc()
004286  #endif
004287  
004288  /*
004289  ** Allowed return values from sqlite3FindInIndex()
004290  */
004291  #define IN_INDEX_ROWID        1   /* Search the rowid of the table */
004292  #define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
004293  #define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
004294  #define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
004295  #define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
004296  /*
004297  ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
004298  */
004299  #define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
004300  #define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
004301  #define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
004302  int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
004303  
004304  int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
004305  int sqlite3JournalSize(sqlite3_vfs *);
004306  #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
004307   || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
004308    int sqlite3JournalCreate(sqlite3_file *);
004309  #endif
004310  
004311  int sqlite3JournalIsInMemory(sqlite3_file *p);
004312  void sqlite3MemJournalOpen(sqlite3_file *);
004313  
004314  void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
004315  #if SQLITE_MAX_EXPR_DEPTH>0
004316    int sqlite3SelectExprHeight(Select *);
004317    int sqlite3ExprCheckHeight(Parse*, int);
004318  #else
004319    #define sqlite3SelectExprHeight(x) 0
004320    #define sqlite3ExprCheckHeight(x,y)
004321  #endif
004322  
004323  u32 sqlite3Get4byte(const u8*);
004324  void sqlite3Put4byte(u8*, u32);
004325  
004326  #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
004327    void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
004328    void sqlite3ConnectionUnlocked(sqlite3 *db);
004329    void sqlite3ConnectionClosed(sqlite3 *db);
004330  #else
004331    #define sqlite3ConnectionBlocked(x,y)
004332    #define sqlite3ConnectionUnlocked(x)
004333    #define sqlite3ConnectionClosed(x)
004334  #endif
004335  
004336  #ifdef SQLITE_DEBUG
004337    void sqlite3ParserTrace(FILE*, char *);
004338  #endif
004339  
004340  /*
004341  ** If the SQLITE_ENABLE IOTRACE exists then the global variable
004342  ** sqlite3IoTrace is a pointer to a printf-like routine used to
004343  ** print I/O tracing messages.
004344  */
004345  #ifdef SQLITE_ENABLE_IOTRACE
004346  # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
004347    void sqlite3VdbeIOTraceSql(Vdbe*);
004348  SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
004349  #else
004350  # define IOTRACE(A)
004351  # define sqlite3VdbeIOTraceSql(X)
004352  #endif
004353  
004354  /*
004355  ** These routines are available for the mem2.c debugging memory allocator
004356  ** only.  They are used to verify that different "types" of memory
004357  ** allocations are properly tracked by the system.
004358  **
004359  ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
004360  ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
004361  ** a single bit set.
004362  **
004363  ** sqlite3MemdebugHasType() returns true if any of the bits in its second
004364  ** argument match the type set by the previous sqlite3MemdebugSetType().
004365  ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
004366  **
004367  ** sqlite3MemdebugNoType() returns true if none of the bits in its second
004368  ** argument match the type set by the previous sqlite3MemdebugSetType().
004369  **
004370  ** Perhaps the most important point is the difference between MEMTYPE_HEAP
004371  ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
004372  ** it might have been allocated by lookaside, except the allocation was
004373  ** too large or lookaside was already full.  It is important to verify
004374  ** that allocations that might have been satisfied by lookaside are not
004375  ** passed back to non-lookaside free() routines.  Asserts such as the
004376  ** example above are placed on the non-lookaside free() routines to verify
004377  ** this constraint.
004378  **
004379  ** All of this is no-op for a production build.  It only comes into
004380  ** play when the SQLITE_MEMDEBUG compile-time option is used.
004381  */
004382  #ifdef SQLITE_MEMDEBUG
004383    void sqlite3MemdebugSetType(void*,u8);
004384    int sqlite3MemdebugHasType(void*,u8);
004385    int sqlite3MemdebugNoType(void*,u8);
004386  #else
004387  # define sqlite3MemdebugSetType(X,Y)  /* no-op */
004388  # define sqlite3MemdebugHasType(X,Y)  1
004389  # define sqlite3MemdebugNoType(X,Y)   1
004390  #endif
004391  #define MEMTYPE_HEAP       0x01  /* General heap allocations */
004392  #define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
004393  #define MEMTYPE_PCACHE     0x04  /* Page cache allocations */
004394  
004395  /*
004396  ** Threading interface
004397  */
004398  #if SQLITE_MAX_WORKER_THREADS>0
004399  int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
004400  int sqlite3ThreadJoin(SQLiteThread*, void**);
004401  #endif
004402  
004403  #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
004404  int sqlite3DbpageRegister(sqlite3*);
004405  #endif
004406  #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
004407  int sqlite3DbstatRegister(sqlite3*);
004408  #endif
004409  
004410  int sqlite3ExprVectorSize(Expr *pExpr);
004411  int sqlite3ExprIsVector(Expr *pExpr);
004412  Expr *sqlite3VectorFieldSubexpr(Expr*, int);
004413  Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
004414  void sqlite3VectorErrorMsg(Parse*, Expr*);
004415  
004416  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
004417  const char **sqlite3CompileOptions(int *pnOpt);
004418  #endif
004419  
004420  #endif /* SQLITEINT_H */