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