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 always 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 always 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  /*
000123  ** Some C99 functions in "math.h" are only present for MSVC when its version
000124  ** is associated with Visual Studio 2013 or higher.
000125  */
000126  #ifndef SQLITE_HAVE_C99_MATH_FUNCS
000127  # if MSVC_VERSION==0 || MSVC_VERSION>=1800
000128  #  define SQLITE_HAVE_C99_MATH_FUNCS (1)
000129  # else
000130  #  define SQLITE_HAVE_C99_MATH_FUNCS (0)
000131  # endif
000132  #endif
000133  
000134  /* Needed for various definitions... */
000135  #if defined(__GNUC__) && !defined(_GNU_SOURCE)
000136  # define _GNU_SOURCE
000137  #endif
000138  
000139  #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
000140  # define _BSD_SOURCE
000141  #endif
000142  
000143  /*
000144  ** Macro to disable warnings about missing "break" at the end of a "case".
000145  */
000146  #if GCC_VERSION>=7000000
000147  # define deliberate_fall_through __attribute__((fallthrough));
000148  #else
000149  # define deliberate_fall_through
000150  #endif
000151  
000152  /*
000153  ** For MinGW, check to see if we can include the header file containing its
000154  ** version information, among other things.  Normally, this internal MinGW
000155  ** header file would [only] be included automatically by other MinGW header
000156  ** files; however, the contained version information is now required by this
000157  ** header file to work around binary compatibility issues (see below) and
000158  ** this is the only known way to reliably obtain it.  This entire #if block
000159  ** would be completely unnecessary if there was any other way of detecting
000160  ** MinGW via their preprocessor (e.g. if they customized their GCC to define
000161  ** some MinGW-specific macros).  When compiling for MinGW, either the
000162  ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
000163  ** defined; otherwise, detection of conditions specific to MinGW will be
000164  ** disabled.
000165  */
000166  #if defined(_HAVE_MINGW_H)
000167  # include "mingw.h"
000168  #elif defined(_HAVE__MINGW_H)
000169  # include "_mingw.h"
000170  #endif
000171  
000172  /*
000173  ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
000174  ** define is required to maintain binary compatibility with the MSVC runtime
000175  ** library in use (e.g. for Windows XP).
000176  */
000177  #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
000178      defined(_WIN32) && !defined(_WIN64) && \
000179      defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
000180      defined(__MSVCRT__)
000181  # define _USE_32BIT_TIME_T
000182  #endif
000183  
000184  /* Optionally #include a user-defined header, whereby compilation options
000185  ** may be set prior to where they take effect, but after platform setup.
000186  ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
000187  ** file.
000188  */
000189  #ifdef SQLITE_CUSTOM_INCLUDE
000190  # define INC_STRINGIFY_(f) #f
000191  # define INC_STRINGIFY(f) INC_STRINGIFY_(f)
000192  # include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
000193  #endif
000194  
000195  /* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
000196  ** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
000197  ** MinGW.
000198  */
000199  #include "sqlite3.h"
000200  
000201  /*
000202  ** Reuse the STATIC_LRU for mutex access to sqlite3_temp_directory.
000203  */
000204  #define SQLITE_MUTEX_STATIC_TEMPDIR SQLITE_MUTEX_STATIC_VFS1
000205  
000206  /*
000207  ** Include the configuration header output by 'configure' if we're using the
000208  ** autoconf-based build
000209  */
000210  #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
000211  #include "sqlite_cfg.h"
000212  #define SQLITECONFIG_H 1
000213  #endif
000214  
000215  #include "sqliteLimit.h"
000216  
000217  /* Disable nuisance warnings on Borland compilers */
000218  #if defined(__BORLANDC__)
000219  #pragma warn -rch /* unreachable code */
000220  #pragma warn -ccc /* Condition is always true or false */
000221  #pragma warn -aus /* Assigned value is never used */
000222  #pragma warn -csu /* Comparing signed and unsigned */
000223  #pragma warn -spa /* Suspicious pointer arithmetic */
000224  #endif
000225  
000226  /*
000227  ** A few places in the code require atomic load/store of aligned
000228  ** integer values.
000229  */
000230  #ifndef __has_extension
000231  # define __has_extension(x) 0     /* compatibility with non-clang compilers */
000232  #endif
000233  #if GCC_VERSION>=4007000 || __has_extension(c_atomic)
000234  # define SQLITE_ATOMIC_INTRINSICS 1
000235  # define AtomicLoad(PTR)       __atomic_load_n((PTR),__ATOMIC_RELAXED)
000236  # define AtomicStore(PTR,VAL)  __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
000237  #else
000238  # define SQLITE_ATOMIC_INTRINSICS 0
000239  # define AtomicLoad(PTR)       (*(PTR))
000240  # define AtomicStore(PTR,VAL)  (*(PTR) = (VAL))
000241  #endif
000242  
000243  /*
000244  ** Include standard header files as necessary
000245  */
000246  #ifdef HAVE_STDINT_H
000247  #include <stdint.h>
000248  #endif
000249  #ifdef HAVE_INTTYPES_H
000250  #include <inttypes.h>
000251  #endif
000252  
000253  /*
000254  ** The following macros are used to cast pointers to integers and
000255  ** integers to pointers.  The way you do this varies from one compiler
000256  ** to the next, so we have developed the following set of #if statements
000257  ** to generate appropriate macros for a wide range of compilers.
000258  **
000259  ** The correct "ANSI" way to do this is to use the intptr_t type.
000260  ** Unfortunately, that typedef is not available on all compilers, or
000261  ** if it is available, it requires an #include of specific headers
000262  ** that vary from one machine to the next.
000263  **
000264  ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
000265  ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
000266  ** So we have to define the macros in different ways depending on the
000267  ** compiler.
000268  */
000269  #if defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
000270  # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
000271  # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
000272  #elif defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
000273  # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
000274  # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
000275  #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
000276  # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
000277  # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
000278  #else                          /* Generates a warning - but it always works */
000279  # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
000280  # define SQLITE_PTR_TO_INT(X)  ((int)(X))
000281  #endif
000282  
000283  /*
000284  ** Macros to hint to the compiler that a function should or should not be
000285  ** inlined.
000286  */
000287  #if defined(__GNUC__)
000288  #  define SQLITE_NOINLINE  __attribute__((noinline))
000289  #  define SQLITE_INLINE    __attribute__((always_inline)) inline
000290  #elif defined(_MSC_VER) && _MSC_VER>=1310
000291  #  define SQLITE_NOINLINE  __declspec(noinline)
000292  #  define SQLITE_INLINE    __forceinline
000293  #else
000294  #  define SQLITE_NOINLINE
000295  #  define SQLITE_INLINE
000296  #endif
000297  #if defined(SQLITE_COVERAGE_TEST) || defined(__STRICT_ANSI__)
000298  # undef SQLITE_INLINE
000299  # define SQLITE_INLINE
000300  #endif
000301  
000302  /*
000303  ** Make sure that the compiler intrinsics we desire are enabled when
000304  ** compiling with an appropriate version of MSVC unless prevented by
000305  ** the SQLITE_DISABLE_INTRINSIC define.
000306  */
000307  #if !defined(SQLITE_DISABLE_INTRINSIC)
000308  #  if defined(_MSC_VER) && _MSC_VER>=1400
000309  #    if !defined(_WIN32_WCE)
000310  #      include <intrin.h>
000311  #      pragma intrinsic(_byteswap_ushort)
000312  #      pragma intrinsic(_byteswap_ulong)
000313  #      pragma intrinsic(_byteswap_uint64)
000314  #      pragma intrinsic(_ReadWriteBarrier)
000315  #    else
000316  #      include <cmnintrin.h>
000317  #    endif
000318  #  endif
000319  #endif
000320  
000321  /*
000322  ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
000323  ** 0 means mutexes are permanently disable and the library is never
000324  ** threadsafe.  1 means the library is serialized which is the highest
000325  ** level of threadsafety.  2 means the library is multithreaded - multiple
000326  ** threads can use SQLite as long as no two threads try to use the same
000327  ** database connection at the same time.
000328  **
000329  ** Older versions of SQLite used an optional THREADSAFE macro.
000330  ** We support that for legacy.
000331  **
000332  ** To ensure that the correct value of "THREADSAFE" is reported when querying
000333  ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
000334  ** logic is partially replicated in ctime.c. If it is updated here, it should
000335  ** also be updated there.
000336  */
000337  #if !defined(SQLITE_THREADSAFE)
000338  # if defined(THREADSAFE)
000339  #   define SQLITE_THREADSAFE THREADSAFE
000340  # else
000341  #   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
000342  # endif
000343  #endif
000344  
000345  /*
000346  ** Powersafe overwrite is on by default.  But can be turned off using
000347  ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
000348  */
000349  #ifndef SQLITE_POWERSAFE_OVERWRITE
000350  # define SQLITE_POWERSAFE_OVERWRITE 1
000351  #endif
000352  
000353  /*
000354  ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
000355  ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
000356  ** which case memory allocation statistics are disabled by default.
000357  */
000358  #if !defined(SQLITE_DEFAULT_MEMSTATUS)
000359  # define SQLITE_DEFAULT_MEMSTATUS 1
000360  #endif
000361  
000362  /*
000363  ** Exactly one of the following macros must be defined in order to
000364  ** specify which memory allocation subsystem to use.
000365  **
000366  **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
000367  **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
000368  **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
000369  **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
000370  **
000371  ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
000372  ** assert() macro is enabled, each call into the Win32 native heap subsystem
000373  ** will cause HeapValidate to be called.  If heap validation should fail, an
000374  ** assertion will be triggered.
000375  **
000376  ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
000377  ** the default.
000378  */
000379  #if defined(SQLITE_SYSTEM_MALLOC) \
000380    + defined(SQLITE_WIN32_MALLOC) \
000381    + defined(SQLITE_ZERO_MALLOC) \
000382    + defined(SQLITE_MEMDEBUG)>1
000383  # error "Two or more of the following compile-time configuration options\
000384   are defined but at most one is allowed:\
000385   SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
000386   SQLITE_ZERO_MALLOC"
000387  #endif
000388  #if defined(SQLITE_SYSTEM_MALLOC) \
000389    + defined(SQLITE_WIN32_MALLOC) \
000390    + defined(SQLITE_ZERO_MALLOC) \
000391    + defined(SQLITE_MEMDEBUG)==0
000392  # define SQLITE_SYSTEM_MALLOC 1
000393  #endif
000394  
000395  /*
000396  ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
000397  ** sizes of memory allocations below this value where possible.
000398  */
000399  #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
000400  # define SQLITE_MALLOC_SOFT_LIMIT 1024
000401  #endif
000402  
000403  /*
000404  ** We need to define _XOPEN_SOURCE as follows in order to enable
000405  ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
000406  ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
000407  ** it.
000408  */
000409  #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
000410  #  define _XOPEN_SOURCE 600
000411  #endif
000412  
000413  /*
000414  ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
000415  ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
000416  ** make it true by defining or undefining NDEBUG.
000417  **
000418  ** Setting NDEBUG makes the code smaller and faster by disabling the
000419  ** assert() statements in the code.  So we want the default action
000420  ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
000421  ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
000422  ** feature.
000423  */
000424  #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
000425  # define NDEBUG 1
000426  #endif
000427  #if defined(NDEBUG) && defined(SQLITE_DEBUG)
000428  # undef NDEBUG
000429  #endif
000430  
000431  /*
000432  ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
000433  */
000434  #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
000435  # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
000436  #endif
000437  
000438  /*
000439  ** The testcase() macro is used to aid in coverage testing.  When
000440  ** doing coverage testing, the condition inside the argument to
000441  ** testcase() must be evaluated both true and false in order to
000442  ** get full branch coverage.  The testcase() macro is inserted
000443  ** to help ensure adequate test coverage in places where simple
000444  ** condition/decision coverage is inadequate.  For example, testcase()
000445  ** can be used to make sure boundary values are tested.  For
000446  ** bitmask tests, testcase() can be used to make sure each bit
000447  ** is significant and used at least once.  On switch statements
000448  ** where multiple cases go to the same block of code, testcase()
000449  ** can insure that all cases are evaluated.
000450  */
000451  #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
000452  # ifndef SQLITE_AMALGAMATION
000453      extern unsigned int sqlite3CoverageCounter;
000454  # endif
000455  # define testcase(X)  if( X ){ sqlite3CoverageCounter += (unsigned)__LINE__; }
000456  #else
000457  # define testcase(X)
000458  #endif
000459  
000460  /*
000461  ** The TESTONLY macro is used to enclose variable declarations or
000462  ** other bits of code that are needed to support the arguments
000463  ** within testcase() and assert() macros.
000464  */
000465  #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
000466  # define TESTONLY(X)  X
000467  #else
000468  # define TESTONLY(X)
000469  #endif
000470  
000471  /*
000472  ** Sometimes we need a small amount of code such as a variable initialization
000473  ** to setup for a later assert() statement.  We do not want this code to
000474  ** appear when assert() is disabled.  The following macro is therefore
000475  ** used to contain that setup code.  The "VVA" acronym stands for
000476  ** "Verification, Validation, and Accreditation".  In other words, the
000477  ** code within VVA_ONLY() will only run during verification processes.
000478  */
000479  #ifndef NDEBUG
000480  # define VVA_ONLY(X)  X
000481  #else
000482  # define VVA_ONLY(X)
000483  #endif
000484  
000485  /*
000486  ** Disable ALWAYS() and NEVER() (make them pass-throughs) for coverage
000487  ** and mutation testing
000488  */
000489  #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
000490  # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS  1
000491  #endif
000492  
000493  /*
000494  ** The ALWAYS and NEVER macros surround boolean expressions which
000495  ** are intended to always be true or false, respectively.  Such
000496  ** expressions could be omitted from the code completely.  But they
000497  ** are included in a few cases in order to enhance the resilience
000498  ** of SQLite to unexpected behavior - to make the code "self-healing"
000499  ** or "ductile" rather than being "brittle" and crashing at the first
000500  ** hint of unplanned behavior.
000501  **
000502  ** In other words, ALWAYS and NEVER are added for defensive code.
000503  **
000504  ** When doing coverage testing ALWAYS and NEVER are hard-coded to
000505  ** be true and false so that the unreachable code they specify will
000506  ** not be counted as untested code.
000507  */
000508  #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
000509  # define ALWAYS(X)      (1)
000510  # define NEVER(X)       (0)
000511  #elif !defined(NDEBUG)
000512  # define ALWAYS(X)      ((X)?1:(assert(0),0))
000513  # define NEVER(X)       ((X)?(assert(0),1):0)
000514  #else
000515  # define ALWAYS(X)      (X)
000516  # define NEVER(X)       (X)
000517  #endif
000518  
000519  /*
000520  ** Some conditionals are optimizations only.  In other words, if the
000521  ** conditionals are replaced with a constant 1 (true) or 0 (false) then
000522  ** the correct answer is still obtained, though perhaps not as quickly.
000523  **
000524  ** The following macros mark these optimizations conditionals.
000525  */
000526  #if defined(SQLITE_MUTATION_TEST)
000527  # define OK_IF_ALWAYS_TRUE(X)  (1)
000528  # define OK_IF_ALWAYS_FALSE(X) (0)
000529  #else
000530  # define OK_IF_ALWAYS_TRUE(X)  (X)
000531  # define OK_IF_ALWAYS_FALSE(X) (X)
000532  #endif
000533  
000534  /*
000535  ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
000536  ** defined.  We need to defend against those failures when testing with
000537  ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
000538  ** during a normal build.  The following macro can be used to disable tests
000539  ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
000540  */
000541  #if defined(SQLITE_TEST_REALLOC_STRESS)
000542  # define ONLY_IF_REALLOC_STRESS(X)  (X)
000543  #elif !defined(NDEBUG)
000544  # define ONLY_IF_REALLOC_STRESS(X)  ((X)?(assert(0),1):0)
000545  #else
000546  # define ONLY_IF_REALLOC_STRESS(X)  (0)
000547  #endif
000548  
000549  /*
000550  ** Declarations used for tracing the operating system interfaces.
000551  */
000552  #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
000553      (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
000554    extern int sqlite3OSTrace;
000555  # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
000556  # define SQLITE_HAVE_OS_TRACE
000557  #else
000558  # define OSTRACE(X)
000559  # undef  SQLITE_HAVE_OS_TRACE
000560  #endif
000561  
000562  /*
000563  ** Is the sqlite3ErrName() function needed in the build?  Currently,
000564  ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
000565  ** OSTRACE is enabled), and by several "test*.c" files (which are
000566  ** compiled using SQLITE_TEST).
000567  */
000568  #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
000569      (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
000570  # define SQLITE_NEED_ERR_NAME
000571  #else
000572  # undef  SQLITE_NEED_ERR_NAME
000573  #endif
000574  
000575  /*
000576  ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
000577  */
000578  #ifdef SQLITE_OMIT_EXPLAIN
000579  # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
000580  #endif
000581  
000582  /*
000583  ** SQLITE_OMIT_VIRTUALTABLE implies SQLITE_OMIT_ALTERTABLE
000584  */
000585  #if defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_ALTERTABLE)
000586  # define SQLITE_OMIT_ALTERTABLE
000587  #endif
000588  
000589  /*
000590  ** Return true (non-zero) if the input is an integer that is too large
000591  ** to fit in 32-bits.  This macro is used inside of various testcase()
000592  ** macros to verify that we have tested SQLite for large-file support.
000593  */
000594  #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
000595  
000596  /*
000597  ** The macro unlikely() is a hint that surrounds a boolean
000598  ** expression that is usually false.  Macro likely() surrounds
000599  ** a boolean expression that is usually true.  These hints could,
000600  ** in theory, be used by the compiler to generate better code, but
000601  ** currently they are just comments for human readers.
000602  */
000603  #define likely(X)    (X)
000604  #define unlikely(X)  (X)
000605  
000606  #include "hash.h"
000607  #include "parse.h"
000608  #include <stdio.h>
000609  #include <stdlib.h>
000610  #include <string.h>
000611  #include <assert.h>
000612  #include <stddef.h>
000613  
000614  /*
000615  ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
000616  ** This allows better measurements of where memcpy() is used when running
000617  ** cachegrind.  But this macro version of memcpy() is very slow so it
000618  ** should not be used in production.  This is a performance measurement
000619  ** hack only.
000620  */
000621  #ifdef SQLITE_INLINE_MEMCPY
000622  # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
000623                          int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
000624  #endif
000625  
000626  /*
000627  ** If compiling for a processor that lacks floating point support,
000628  ** substitute integer for floating-point
000629  */
000630  #ifdef SQLITE_OMIT_FLOATING_POINT
000631  # define double sqlite_int64
000632  # define float sqlite_int64
000633  # define LONGDOUBLE_TYPE sqlite_int64
000634  # ifndef SQLITE_BIG_DBL
000635  #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
000636  # endif
000637  # define SQLITE_OMIT_DATETIME_FUNCS 1
000638  # define SQLITE_OMIT_TRACE 1
000639  # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
000640  # undef SQLITE_HAVE_ISNAN
000641  #endif
000642  #ifndef SQLITE_BIG_DBL
000643  # define SQLITE_BIG_DBL (1e99)
000644  #endif
000645  
000646  /*
000647  ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
000648  ** afterward. Having this macro allows us to cause the C compiler
000649  ** to omit code used by TEMP tables without messy #ifndef statements.
000650  */
000651  #ifdef SQLITE_OMIT_TEMPDB
000652  #define OMIT_TEMPDB 1
000653  #else
000654  #define OMIT_TEMPDB 0
000655  #endif
000656  
000657  /*
000658  ** The "file format" number is an integer that is incremented whenever
000659  ** the VDBE-level file format changes.  The following macros define the
000660  ** the default file format for new databases and the maximum file format
000661  ** that the library can read.
000662  */
000663  #define SQLITE_MAX_FILE_FORMAT 4
000664  #ifndef SQLITE_DEFAULT_FILE_FORMAT
000665  # define SQLITE_DEFAULT_FILE_FORMAT 4
000666  #endif
000667  
000668  /*
000669  ** Determine whether triggers are recursive by default.  This can be
000670  ** changed at run-time using a pragma.
000671  */
000672  #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
000673  # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
000674  #endif
000675  
000676  /*
000677  ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
000678  ** on the command-line
000679  */
000680  #ifndef SQLITE_TEMP_STORE
000681  # define SQLITE_TEMP_STORE 1
000682  #endif
000683  
000684  /*
000685  ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
000686  ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
000687  ** to zero.
000688  */
000689  #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
000690  # undef SQLITE_MAX_WORKER_THREADS
000691  # define SQLITE_MAX_WORKER_THREADS 0
000692  #endif
000693  #ifndef SQLITE_MAX_WORKER_THREADS
000694  # define SQLITE_MAX_WORKER_THREADS 8
000695  #endif
000696  #ifndef SQLITE_DEFAULT_WORKER_THREADS
000697  # define SQLITE_DEFAULT_WORKER_THREADS 0
000698  #endif
000699  #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
000700  # undef SQLITE_MAX_WORKER_THREADS
000701  # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
000702  #endif
000703  
000704  /*
000705  ** The default initial allocation for the pagecache when using separate
000706  ** pagecaches for each database connection.  A positive number is the
000707  ** number of pages.  A negative number N translations means that a buffer
000708  ** of -1024*N bytes is allocated and used for as many pages as it will hold.
000709  **
000710  ** The default value of "20" was chosen to minimize the run-time of the
000711  ** speedtest1 test program with options: --shrink-memory --reprepare
000712  */
000713  #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
000714  # define SQLITE_DEFAULT_PCACHE_INITSZ 20
000715  #endif
000716  
000717  /*
000718  ** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
000719  */
000720  #ifndef SQLITE_DEFAULT_SORTERREF_SIZE
000721  # define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff
000722  #endif
000723  
000724  /*
000725  ** The compile-time options SQLITE_MMAP_READWRITE and
000726  ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
000727  ** You must choose one or the other (or neither) but not both.
000728  */
000729  #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
000730  #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
000731  #endif
000732  
000733  /*
000734  ** GCC does not define the offsetof() macro so we'll have to do it
000735  ** ourselves.
000736  */
000737  #ifndef offsetof
000738  #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
000739  #endif
000740  
000741  /*
000742  ** Macros to compute minimum and maximum of two numbers.
000743  */
000744  #ifndef MIN
000745  # define MIN(A,B) ((A)<(B)?(A):(B))
000746  #endif
000747  #ifndef MAX
000748  # define MAX(A,B) ((A)>(B)?(A):(B))
000749  #endif
000750  
000751  /*
000752  ** Swap two objects of type TYPE.
000753  */
000754  #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
000755  
000756  /*
000757  ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
000758  ** not, there are still machines out there that use EBCDIC.)
000759  */
000760  #if 'A' == '\301'
000761  # define SQLITE_EBCDIC 1
000762  #else
000763  # define SQLITE_ASCII 1
000764  #endif
000765  
000766  /*
000767  ** Integers of known sizes.  These typedefs might change for architectures
000768  ** where the sizes very.  Preprocessor macros are available so that the
000769  ** types can be conveniently redefined at compile-type.  Like this:
000770  **
000771  **         cc '-DUINTPTR_TYPE=long long int' ...
000772  */
000773  #ifndef UINT32_TYPE
000774  # ifdef HAVE_UINT32_T
000775  #  define UINT32_TYPE uint32_t
000776  # else
000777  #  define UINT32_TYPE unsigned int
000778  # endif
000779  #endif
000780  #ifndef UINT16_TYPE
000781  # ifdef HAVE_UINT16_T
000782  #  define UINT16_TYPE uint16_t
000783  # else
000784  #  define UINT16_TYPE unsigned short int
000785  # endif
000786  #endif
000787  #ifndef INT16_TYPE
000788  # ifdef HAVE_INT16_T
000789  #  define INT16_TYPE int16_t
000790  # else
000791  #  define INT16_TYPE short int
000792  # endif
000793  #endif
000794  #ifndef UINT8_TYPE
000795  # ifdef HAVE_UINT8_T
000796  #  define UINT8_TYPE uint8_t
000797  # else
000798  #  define UINT8_TYPE unsigned char
000799  # endif
000800  #endif
000801  #ifndef INT8_TYPE
000802  # ifdef HAVE_INT8_T
000803  #  define INT8_TYPE int8_t
000804  # else
000805  #  define INT8_TYPE signed char
000806  # endif
000807  #endif
000808  #ifndef LONGDOUBLE_TYPE
000809  # define LONGDOUBLE_TYPE long double
000810  #endif
000811  typedef sqlite_int64 i64;          /* 8-byte signed integer */
000812  typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
000813  typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
000814  typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
000815  typedef INT16_TYPE i16;            /* 2-byte signed integer */
000816  typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
000817  typedef INT8_TYPE i8;              /* 1-byte signed integer */
000818  
000819  /*
000820  ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
000821  ** that can be stored in a u32 without loss of data.  The value
000822  ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
000823  ** have to specify the value in the less intuitive manner shown:
000824  */
000825  #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
000826  
000827  /*
000828  ** The datatype used to store estimates of the number of rows in a
000829  ** table or index.
000830  */
000831  typedef u64 tRowcnt;
000832  
000833  /*
000834  ** Estimated quantities used for query planning are stored as 16-bit
000835  ** logarithms.  For quantity X, the value stored is 10*log2(X).  This
000836  ** gives a possible range of values of approximately 1.0e986 to 1e-986.
000837  ** But the allowed values are "grainy".  Not every value is representable.
000838  ** For example, quantities 16 and 17 are both represented by a LogEst
000839  ** of 40.  However, since LogEst quantities are suppose to be estimates,
000840  ** not exact values, this imprecision is not a problem.
000841  **
000842  ** "LogEst" is short for "Logarithmic Estimate".
000843  **
000844  ** Examples:
000845  **      1 -> 0              20 -> 43          10000 -> 132
000846  **      2 -> 10             25 -> 46          25000 -> 146
000847  **      3 -> 16            100 -> 66        1000000 -> 199
000848  **      4 -> 20           1000 -> 99        1048576 -> 200
000849  **     10 -> 33           1024 -> 100    4294967296 -> 320
000850  **
000851  ** The LogEst can be negative to indicate fractional values.
000852  ** Examples:
000853  **
000854  **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
000855  */
000856  typedef INT16_TYPE LogEst;
000857  
000858  /*
000859  ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
000860  */
000861  #ifndef SQLITE_PTRSIZE
000862  # if defined(__SIZEOF_POINTER__)
000863  #   define SQLITE_PTRSIZE __SIZEOF_POINTER__
000864  # elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
000865         defined(_M_ARM)   || defined(__arm__)    || defined(__x86)   ||    \
000866        (defined(__APPLE__) && defined(__POWERPC__)) ||                     \
000867        (defined(__TOS_AIX__) && !defined(__64BIT__))
000868  #   define SQLITE_PTRSIZE 4
000869  # else
000870  #   define SQLITE_PTRSIZE 8
000871  # endif
000872  #endif
000873  
000874  /* The uptr type is an unsigned integer large enough to hold a pointer
000875  */
000876  #if defined(HAVE_STDINT_H)
000877    typedef uintptr_t uptr;
000878  #elif SQLITE_PTRSIZE==4
000879    typedef u32 uptr;
000880  #else
000881    typedef u64 uptr;
000882  #endif
000883  
000884  /*
000885  ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
000886  ** something between S (inclusive) and E (exclusive).
000887  **
000888  ** In other words, S is a buffer and E is a pointer to the first byte after
000889  ** the end of buffer S.  This macro returns true if P points to something
000890  ** contained within the buffer S.
000891  */
000892  #define SQLITE_WITHIN(P,S,E)   (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
000893  
000894  /*
000895  ** P is one byte past the end of a large buffer. Return true if a span of bytes
000896  ** between S..E crosses the end of that buffer.  In other words, return true
000897  ** if the sub-buffer S..E-1 overflows the buffer whose last byte is P-1.
000898  **
000899  ** S is the start of the span.  E is one byte past the end of end of span.
000900  **
000901  **                        P
000902  **     |-----------------|                FALSE
000903  **               |-------|
000904  **               S        E
000905  **
000906  **                        P
000907  **     |-----------------|
000908  **                    |-------|           TRUE
000909  **                    S        E
000910  **
000911  **                        P
000912  **     |-----------------|               
000913  **                        |-------|       FALSE
000914  **                        S        E
000915  */
000916  #define SQLITE_OVERFLOW(P,S,E) (((uptr)(S)<(uptr)(P))&&((uptr)(E)>(uptr)(P)))
000917  
000918  /*
000919  ** Macros to determine whether the machine is big or little endian,
000920  ** and whether or not that determination is run-time or compile-time.
000921  **
000922  ** For best performance, an attempt is made to guess at the byte-order
000923  ** using C-preprocessor macros.  If that is unsuccessful, or if
000924  ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
000925  ** at run-time.
000926  */
000927  #ifndef SQLITE_BYTEORDER
000928  # if defined(i386)      || defined(__i386__)      || defined(_M_IX86) ||    \
000929       defined(__x86_64)  || defined(__x86_64__)    || defined(_M_X64)  ||    \
000930       defined(_M_AMD64)  || defined(_M_ARM)        || defined(__x86)   ||    \
000931       defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
000932  #   define SQLITE_BYTEORDER    1234
000933  # elif defined(sparc)     || defined(__ppc__) || \
000934         defined(__ARMEB__) || defined(__AARCH64EB__)
000935  #   define SQLITE_BYTEORDER    4321
000936  # else
000937  #   define SQLITE_BYTEORDER 0
000938  # endif
000939  #endif
000940  #if SQLITE_BYTEORDER==4321
000941  # define SQLITE_BIGENDIAN    1
000942  # define SQLITE_LITTLEENDIAN 0
000943  # define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
000944  #elif SQLITE_BYTEORDER==1234
000945  # define SQLITE_BIGENDIAN    0
000946  # define SQLITE_LITTLEENDIAN 1
000947  # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
000948  #else
000949  # ifdef SQLITE_AMALGAMATION
000950    const int sqlite3one = 1;
000951  # else
000952    extern const int sqlite3one;
000953  # endif
000954  # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
000955  # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
000956  # define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
000957  #endif
000958  
000959  /*
000960  ** Constants for the largest and smallest possible 64-bit signed integers.
000961  ** These macros are designed to work correctly on both 32-bit and 64-bit
000962  ** compilers.
000963  */
000964  #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
000965  #define LARGEST_UINT64 (0xffffffff|(((u64)0xffffffff)<<32))
000966  #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
000967  
000968  /*
000969  ** Round up a number to the next larger multiple of 8.  This is used
000970  ** to force 8-byte alignment on 64-bit architectures.
000971  **
000972  ** ROUND8() always does the rounding, for any argument.
000973  **
000974  ** ROUND8P() assumes that the argument is already an integer number of
000975  ** pointers in size, and so it is a no-op on systems where the pointer
000976  ** size is 8.
000977  */
000978  #define ROUND8(x)     (((x)+7)&~7)
000979  #if SQLITE_PTRSIZE==8
000980  # define ROUND8P(x)   (x)
000981  #else
000982  # define ROUND8P(x)   (((x)+7)&~7)
000983  #endif
000984  
000985  /*
000986  ** Round down to the nearest multiple of 8
000987  */
000988  #define ROUNDDOWN8(x) ((x)&~7)
000989  
000990  /*
000991  ** Assert that the pointer X is aligned to an 8-byte boundary.  This
000992  ** macro is used only within assert() to verify that the code gets
000993  ** all alignment restrictions correct.
000994  **
000995  ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
000996  ** underlying malloc() implementation might return us 4-byte aligned
000997  ** pointers.  In that case, only verify 4-byte alignment.
000998  */
000999  #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
001000  # define EIGHT_BYTE_ALIGNMENT(X)   ((((uptr)(X) - (uptr)0)&3)==0)
001001  #else
001002  # define EIGHT_BYTE_ALIGNMENT(X)   ((((uptr)(X) - (uptr)0)&7)==0)
001003  #endif
001004  
001005  /*
001006  ** Disable MMAP on platforms where it is known to not work
001007  */
001008  #if defined(__OpenBSD__) || defined(__QNXNTO__)
001009  # undef SQLITE_MAX_MMAP_SIZE
001010  # define SQLITE_MAX_MMAP_SIZE 0
001011  #endif
001012  
001013  /*
001014  ** Default maximum size of memory used by memory-mapped I/O in the VFS
001015  */
001016  #ifdef __APPLE__
001017  # include <TargetConditionals.h>
001018  #endif
001019  #ifndef SQLITE_MAX_MMAP_SIZE
001020  # if defined(__linux__) \
001021    || defined(_WIN32) \
001022    || (defined(__APPLE__) && defined(__MACH__)) \
001023    || defined(__sun) \
001024    || defined(__FreeBSD__) \
001025    || defined(__DragonFly__)
001026  #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
001027  # else
001028  #   define SQLITE_MAX_MMAP_SIZE 0
001029  # endif
001030  #endif
001031  
001032  /*
001033  ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
001034  ** default MMAP_SIZE is specified at compile-time, make sure that it does
001035  ** not exceed the maximum mmap size.
001036  */
001037  #ifndef SQLITE_DEFAULT_MMAP_SIZE
001038  # define SQLITE_DEFAULT_MMAP_SIZE 0
001039  #endif
001040  #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
001041  # undef SQLITE_DEFAULT_MMAP_SIZE
001042  # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
001043  #endif
001044  
001045  /*
001046  ** TREETRACE_ENABLED will be either 1 or 0 depending on whether or not
001047  ** the Abstract Syntax Tree tracing logic is turned on.
001048  */
001049  #if !defined(SQLITE_AMALGAMATION)
001050  extern u32 sqlite3TreeTrace;
001051  #endif
001052  #if defined(SQLITE_DEBUG) \
001053      && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_SELECTTRACE) \
001054                               || defined(SQLITE_ENABLE_TREETRACE))
001055  # define TREETRACE_ENABLED 1
001056  # define TREETRACE(K,P,S,X)  \
001057    if(sqlite3TreeTrace&(K))   \
001058      sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
001059      sqlite3DebugPrintf X
001060  #else
001061  # define TREETRACE(K,P,S,X)
001062  # define TREETRACE_ENABLED 0
001063  #endif
001064  
001065  /* TREETRACE flag meanings:
001066  **
001067  **   0x00000001     Beginning and end of SELECT processing
001068  **   0x00000002     WHERE clause processing
001069  **   0x00000004     Query flattener
001070  **   0x00000008     Result-set wildcard expansion
001071  **   0x00000010     Query name resolution
001072  **   0x00000020     Aggregate analysis
001073  **   0x00000040     Window functions
001074  **   0x00000080     Generated column names
001075  **   0x00000100     Move HAVING terms into WHERE
001076  **   0x00000200     Count-of-view optimization
001077  **   0x00000400     Compound SELECT processing
001078  **   0x00000800     Drop superfluous ORDER BY
001079  **   0x00001000     LEFT JOIN simplifies to JOIN
001080  **   0x00002000     Constant propagation
001081  **   0x00004000     Push-down optimization
001082  **   0x00008000     After all FROM-clause analysis
001083  **   0x00010000     Beginning of DELETE/INSERT/UPDATE processing
001084  **   0x00020000     Transform DISTINCT into GROUP BY
001085  **   0x00040000     SELECT tree dump after all code has been generated
001086  */
001087  
001088  /*
001089  ** Macros for "wheretrace"
001090  */
001091  extern u32 sqlite3WhereTrace;
001092  #if defined(SQLITE_DEBUG) \
001093      && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
001094  # define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
001095  # define WHERETRACE_ENABLED 1
001096  #else
001097  # define WHERETRACE(K,X)
001098  #endif
001099  
001100  /*
001101  ** Bits for the sqlite3WhereTrace mask:
001102  **
001103  ** (---any--)   Top-level block structure
001104  ** 0x-------F   High-level debug messages
001105  ** 0x----FFF-   More detail
001106  ** 0xFFFF----   Low-level debug messages
001107  **
001108  ** 0x00000001   Code generation
001109  ** 0x00000002   Solver
001110  ** 0x00000004   Solver costs
001111  ** 0x00000008   WhereLoop inserts
001112  **
001113  ** 0x00000010   Display sqlite3_index_info xBestIndex calls
001114  ** 0x00000020   Range an equality scan metrics
001115  ** 0x00000040   IN operator decisions
001116  ** 0x00000080   WhereLoop cost adjustements
001117  ** 0x00000100
001118  ** 0x00000200   Covering index decisions
001119  ** 0x00000400   OR optimization
001120  ** 0x00000800   Index scanner
001121  ** 0x00001000   More details associated with code generation
001122  ** 0x00002000
001123  ** 0x00004000   Show all WHERE terms at key points
001124  ** 0x00008000   Show the full SELECT statement at key places
001125  **
001126  ** 0x00010000   Show more detail when printing WHERE terms
001127  ** 0x00020000   Show WHERE terms returned from whereScanNext()
001128  */
001129  
001130  
001131  /*
001132  ** An instance of the following structure is used to store the busy-handler
001133  ** callback for a given sqlite handle.
001134  **
001135  ** The sqlite.busyHandler member of the sqlite struct contains the busy
001136  ** callback for the database handle. Each pager opened via the sqlite
001137  ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
001138  ** callback is currently invoked only from within pager.c.
001139  */
001140  typedef struct BusyHandler BusyHandler;
001141  struct BusyHandler {
001142    int (*xBusyHandler)(void *,int);  /* The busy callback */
001143    void *pBusyArg;                   /* First arg to busy callback */
001144    int nBusy;                        /* Incremented with each busy call */
001145  };
001146  
001147  /*
001148  ** Name of table that holds the database schema.
001149  **
001150  ** The PREFERRED names are used wherever possible.  But LEGACY is also
001151  ** used for backwards compatibility.
001152  **
001153  **  1.  Queries can use either the PREFERRED or the LEGACY names
001154  **  2.  The sqlite3_set_authorizer() callback uses the LEGACY name
001155  **  3.  The PRAGMA table_list statement uses the PREFERRED name
001156  **
001157  ** The LEGACY names are stored in the internal symbol hash table
001158  ** in support of (2).  Names are translated using sqlite3PreferredTableName()
001159  ** for (3).  The sqlite3FindTable() function takes care of translating
001160  ** names for (1).
001161  **
001162  ** Note that "sqlite_temp_schema" can also be called "temp.sqlite_schema".
001163  */
001164  #define LEGACY_SCHEMA_TABLE          "sqlite_master"
001165  #define LEGACY_TEMP_SCHEMA_TABLE     "sqlite_temp_master"
001166  #define PREFERRED_SCHEMA_TABLE       "sqlite_schema"
001167  #define PREFERRED_TEMP_SCHEMA_TABLE  "sqlite_temp_schema"
001168  
001169  
001170  /*
001171  ** The root-page of the schema table.
001172  */
001173  #define SCHEMA_ROOT    1
001174  
001175  /*
001176  ** The name of the schema table.  The name is different for TEMP.
001177  */
001178  #define SCHEMA_TABLE(x) \
001179      ((!OMIT_TEMPDB)&&(x==1)?LEGACY_TEMP_SCHEMA_TABLE:LEGACY_SCHEMA_TABLE)
001180  
001181  /*
001182  ** A convenience macro that returns the number of elements in
001183  ** an array.
001184  */
001185  #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
001186  
001187  /*
001188  ** Determine if the argument is a power of two
001189  */
001190  #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
001191  
001192  /*
001193  ** The following value as a destructor means to use sqlite3DbFree().
001194  ** The sqlite3DbFree() routine requires two parameters instead of the
001195  ** one parameter that destructors normally want.  So we have to introduce
001196  ** this magic value that the code knows to handle differently.  Any
001197  ** pointer will work here as long as it is distinct from SQLITE_STATIC
001198  ** and SQLITE_TRANSIENT.
001199  */
001200  #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3OomClear)
001201  
001202  /*
001203  ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
001204  ** not support Writable Static Data (WSD) such as global and static variables.
001205  ** All variables must either be on the stack or dynamically allocated from
001206  ** the heap.  When WSD is unsupported, the variable declarations scattered
001207  ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
001208  ** macro is used for this purpose.  And instead of referencing the variable
001209  ** directly, we use its constant as a key to lookup the run-time allocated
001210  ** buffer that holds real variable.  The constant is also the initializer
001211  ** for the run-time allocated buffer.
001212  **
001213  ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
001214  ** macros become no-ops and have zero performance impact.
001215  */
001216  #ifdef SQLITE_OMIT_WSD
001217    #define SQLITE_WSD const
001218    #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
001219    #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
001220    int sqlite3_wsd_init(int N, int J);
001221    void *sqlite3_wsd_find(void *K, int L);
001222  #else
001223    #define SQLITE_WSD
001224    #define GLOBAL(t,v) v
001225    #define sqlite3GlobalConfig sqlite3Config
001226  #endif
001227  
001228  /*
001229  ** The following macros are used to suppress compiler warnings and to
001230  ** make it clear to human readers when a function parameter is deliberately
001231  ** left unused within the body of a function. This usually happens when
001232  ** a function is called via a function pointer. For example the
001233  ** implementation of an SQL aggregate step callback may not use the
001234  ** parameter indicating the number of arguments passed to the aggregate,
001235  ** if it knows that this is enforced elsewhere.
001236  **
001237  ** When a function parameter is not used at all within the body of a function,
001238  ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
001239  ** However, these macros may also be used to suppress warnings related to
001240  ** parameters that may or may not be used depending on compilation options.
001241  ** For example those parameters only used in assert() statements. In these
001242  ** cases the parameters are named as per the usual conventions.
001243  */
001244  #define UNUSED_PARAMETER(x) (void)(x)
001245  #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
001246  
001247  /*
001248  ** Forward references to structures
001249  */
001250  typedef struct AggInfo AggInfo;
001251  typedef struct AuthContext AuthContext;
001252  typedef struct AutoincInfo AutoincInfo;
001253  typedef struct Bitvec Bitvec;
001254  typedef struct CollSeq CollSeq;
001255  typedef struct Column Column;
001256  typedef struct Cte Cte;
001257  typedef struct CteUse CteUse;
001258  typedef struct Db Db;
001259  typedef struct DbFixer DbFixer;
001260  typedef struct Schema Schema;
001261  typedef struct Expr Expr;
001262  typedef struct ExprList ExprList;
001263  typedef struct FKey FKey;
001264  typedef struct FpDecode FpDecode;
001265  typedef struct FuncDestructor FuncDestructor;
001266  typedef struct FuncDef FuncDef;
001267  typedef struct FuncDefHash FuncDefHash;
001268  typedef struct IdList IdList;
001269  typedef struct Index Index;
001270  typedef struct IndexedExpr IndexedExpr;
001271  typedef struct IndexSample IndexSample;
001272  typedef struct KeyClass KeyClass;
001273  typedef struct KeyInfo KeyInfo;
001274  typedef struct Lookaside Lookaside;
001275  typedef struct LookasideSlot LookasideSlot;
001276  typedef struct Module Module;
001277  typedef struct NameContext NameContext;
001278  typedef struct OnOrUsing OnOrUsing;
001279  typedef struct Parse Parse;
001280  typedef struct ParseCleanup ParseCleanup;
001281  typedef struct PreUpdate PreUpdate;
001282  typedef struct PrintfArguments PrintfArguments;
001283  typedef struct RCStr RCStr;
001284  typedef struct RenameToken RenameToken;
001285  typedef struct Returning Returning;
001286  typedef struct RowSet RowSet;
001287  typedef struct Savepoint Savepoint;
001288  typedef struct Select Select;
001289  typedef struct SQLiteThread SQLiteThread;
001290  typedef struct SelectDest SelectDest;
001291  typedef struct SrcItem SrcItem;
001292  typedef struct SrcList SrcList;
001293  typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
001294  typedef struct Table Table;
001295  typedef struct TableLock TableLock;
001296  typedef struct Token Token;
001297  typedef struct TreeView TreeView;
001298  typedef struct Trigger Trigger;
001299  typedef struct TriggerPrg TriggerPrg;
001300  typedef struct TriggerStep TriggerStep;
001301  typedef struct UnpackedRecord UnpackedRecord;
001302  typedef struct Upsert Upsert;
001303  typedef struct VTable VTable;
001304  typedef struct VtabCtx VtabCtx;
001305  typedef struct Walker Walker;
001306  typedef struct WhereInfo WhereInfo;
001307  typedef struct Window Window;
001308  typedef struct With With;
001309  
001310  
001311  /*
001312  ** The bitmask datatype defined below is used for various optimizations.
001313  **
001314  ** Changing this from a 64-bit to a 32-bit type limits the number of
001315  ** tables in a join to 32 instead of 64.  But it also reduces the size
001316  ** of the library by 738 bytes on ix86.
001317  */
001318  #ifdef SQLITE_BITMASK_TYPE
001319    typedef SQLITE_BITMASK_TYPE Bitmask;
001320  #else
001321    typedef u64 Bitmask;
001322  #endif
001323  
001324  /*
001325  ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
001326  */
001327  #define BMS  ((int)(sizeof(Bitmask)*8))
001328  
001329  /*
001330  ** A bit in a Bitmask
001331  */
001332  #define MASKBIT(n)    (((Bitmask)1)<<(n))
001333  #define MASKBIT64(n)  (((u64)1)<<(n))
001334  #define MASKBIT32(n)  (((unsigned int)1)<<(n))
001335  #define SMASKBIT32(n) ((n)<=31?((unsigned int)1)<<(n):0)
001336  #define ALLBITS       ((Bitmask)-1)
001337  #define TOPBIT        (((Bitmask)1)<<(BMS-1))
001338  
001339  /* A VList object records a mapping between parameters/variables/wildcards
001340  ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
001341  ** variable number associated with that parameter.  See the format description
001342  ** on the sqlite3VListAdd() routine for more information.  A VList is really
001343  ** just an array of integers.
001344  */
001345  typedef int VList;
001346  
001347  /*
001348  ** Defer sourcing vdbe.h and btree.h until after the "u8" and
001349  ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
001350  ** pointer types (i.e. FuncDef) defined above.
001351  */
001352  #include "os.h"
001353  #include "pager.h"
001354  #include "btree.h"
001355  #include "vdbe.h"
001356  #include "pcache.h"
001357  #include "mutex.h"
001358  
001359  /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
001360  ** synchronous setting to EXTRA.  It is no longer supported.
001361  */
001362  #ifdef SQLITE_EXTRA_DURABLE
001363  # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
001364  # define SQLITE_DEFAULT_SYNCHRONOUS 3
001365  #endif
001366  
001367  /*
001368  ** Default synchronous levels.
001369  **
001370  ** Note that (for historical reasons) the PAGER_SYNCHRONOUS_* macros differ
001371  ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
001372  **
001373  **           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS
001374  **   OFF           1                         0
001375  **   NORMAL        2                         1
001376  **   FULL          3                         2
001377  **   EXTRA         4                         3
001378  **
001379  ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
001380  ** In other words, the zero-based numbers are used for all external interfaces
001381  ** and the one-based values are used internally.
001382  */
001383  #ifndef SQLITE_DEFAULT_SYNCHRONOUS
001384  # define SQLITE_DEFAULT_SYNCHRONOUS 2
001385  #endif
001386  #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
001387  # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
001388  #endif
001389  
001390  /*
001391  ** Each database file to be accessed by the system is an instance
001392  ** of the following structure.  There are normally two of these structures
001393  ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
001394  ** aDb[1] is the database file used to hold temporary tables.  Additional
001395  ** databases may be attached.
001396  */
001397  struct Db {
001398    char *zDbSName;      /* Name of this database. (schema name, not filename) */
001399    Btree *pBt;          /* The B*Tree structure for this database file */
001400    u8 safety_level;     /* How aggressive at syncing data to disk */
001401    u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */
001402    Schema *pSchema;     /* Pointer to database schema (possibly shared) */
001403  };
001404  
001405  /*
001406  ** An instance of the following structure stores a database schema.
001407  **
001408  ** Most Schema objects are associated with a Btree.  The exception is
001409  ** the Schema for the TEMP database (sqlite3.aDb[1]) which is free-standing.
001410  ** In shared cache mode, a single Schema object can be shared by multiple
001411  ** Btrees that refer to the same underlying BtShared object.
001412  **
001413  ** Schema objects are automatically deallocated when the last Btree that
001414  ** references them is destroyed.   The TEMP Schema is manually freed by
001415  ** sqlite3_close().
001416  *
001417  ** A thread must be holding a mutex on the corresponding Btree in order
001418  ** to access Schema content.  This implies that the thread must also be
001419  ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
001420  ** For a TEMP Schema, only the connection mutex is required.
001421  */
001422  struct Schema {
001423    int schema_cookie;   /* Database schema version number for this file */
001424    int iGeneration;     /* Generation counter.  Incremented with each change */
001425    Hash tblHash;        /* All tables indexed by name */
001426    Hash idxHash;        /* All (named) indices indexed by name */
001427    Hash trigHash;       /* All triggers indexed by name */
001428    Hash fkeyHash;       /* All foreign keys by referenced table name */
001429    Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
001430    u8 file_format;      /* Schema format version for this file */
001431    u8 enc;              /* Text encoding used by this database */
001432    u16 schemaFlags;     /* Flags associated with this schema */
001433    int cache_size;      /* Number of pages to use in the cache */
001434  };
001435  
001436  /*
001437  ** These macros can be used to test, set, or clear bits in the
001438  ** Db.pSchema->flags field.
001439  */
001440  #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
001441  #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
001442  #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
001443  #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
001444  
001445  /*
001446  ** Allowed values for the DB.pSchema->flags field.
001447  **
001448  ** The DB_SchemaLoaded flag is set after the database schema has been
001449  ** read into internal hash tables.
001450  **
001451  ** DB_UnresetViews means that one or more views have column names that
001452  ** have been filled out.  If the schema changes, these column names might
001453  ** changes and so the view will need to be reset.
001454  */
001455  #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
001456  #define DB_UnresetViews    0x0002  /* Some views have defined column names */
001457  #define DB_ResetWanted     0x0008  /* Reset the schema when nSchemaLock==0 */
001458  
001459  /*
001460  ** The number of different kinds of things that can be limited
001461  ** using the sqlite3_limit() interface.
001462  */
001463  #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
001464  
001465  /*
001466  ** Lookaside malloc is a set of fixed-size buffers that can be used
001467  ** to satisfy small transient memory allocation requests for objects
001468  ** associated with a particular database connection.  The use of
001469  ** lookaside malloc provides a significant performance enhancement
001470  ** (approx 10%) by avoiding numerous malloc/free requests while parsing
001471  ** SQL statements.
001472  **
001473  ** The Lookaside structure holds configuration information about the
001474  ** lookaside malloc subsystem.  Each available memory allocation in
001475  ** the lookaside subsystem is stored on a linked list of LookasideSlot
001476  ** objects.
001477  **
001478  ** Lookaside allocations are only allowed for objects that are associated
001479  ** with a particular database connection.  Hence, schema information cannot
001480  ** be stored in lookaside because in shared cache mode the schema information
001481  ** is shared by multiple database connections.  Therefore, while parsing
001482  ** schema information, the Lookaside.bEnabled flag is cleared so that
001483  ** lookaside allocations are not used to construct the schema objects.
001484  **
001485  ** New lookaside allocations are only allowed if bDisable==0.  When
001486  ** bDisable is greater than zero, sz is set to zero which effectively
001487  ** disables lookaside without adding a new test for the bDisable flag
001488  ** in a performance-critical path.  sz should be set by to szTrue whenever
001489  ** bDisable changes back to zero.
001490  **
001491  ** Lookaside buffers are initially held on the pInit list.  As they are
001492  ** used and freed, they are added back to the pFree list.  New allocations
001493  ** come off of pFree first, then pInit as a fallback.  This dual-list
001494  ** allows use to compute a high-water mark - the maximum number of allocations
001495  ** outstanding at any point in the past - by subtracting the number of
001496  ** allocations on the pInit list from the total number of allocations.
001497  **
001498  ** Enhancement on 2019-12-12:  Two-size-lookaside
001499  ** The default lookaside configuration is 100 slots of 1200 bytes each.
001500  ** The larger slot sizes are important for performance, but they waste
001501  ** a lot of space, as most lookaside allocations are less than 128 bytes.
001502  ** The two-size-lookaside enhancement breaks up the lookaside allocation
001503  ** into two pools:  One of 128-byte slots and the other of the default size
001504  ** (1200-byte) slots.   Allocations are filled from the small-pool first,
001505  ** failing over to the full-size pool if that does not work.  Thus more
001506  ** lookaside slots are available while also using less memory.
001507  ** This enhancement can be omitted by compiling with
001508  ** SQLITE_OMIT_TWOSIZE_LOOKASIDE.
001509  */
001510  struct Lookaside {
001511    u32 bDisable;           /* Only operate the lookaside when zero */
001512    u16 sz;                 /* Size of each buffer in bytes */
001513    u16 szTrue;             /* True value of sz, even if disabled */
001514    u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
001515    u32 nSlot;              /* Number of lookaside slots allocated */
001516    u32 anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
001517    LookasideSlot *pInit;   /* List of buffers not previously used */
001518    LookasideSlot *pFree;   /* List of available buffers */
001519  #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
001520    LookasideSlot *pSmallInit; /* List of small buffers not previously used */
001521    LookasideSlot *pSmallFree; /* List of available small buffers */
001522    void *pMiddle;          /* First byte past end of full-size buffers and
001523                            ** the first byte of LOOKASIDE_SMALL buffers */
001524  #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
001525    void *pStart;           /* First byte of available memory space */
001526    void *pEnd;             /* First byte past end of available space */
001527    void *pTrueEnd;         /* True value of pEnd, when db->pnBytesFreed!=0 */
001528  };
001529  struct LookasideSlot {
001530    LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
001531  };
001532  
001533  #define DisableLookaside  db->lookaside.bDisable++;db->lookaside.sz=0
001534  #define EnableLookaside   db->lookaside.bDisable--;\
001535     db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue
001536  
001537  /* Size of the smaller allocations in two-size lookaside */
001538  #ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
001539  #  define LOOKASIDE_SMALL           0
001540  #else
001541  #  define LOOKASIDE_SMALL         128
001542  #endif
001543  
001544  /*
001545  ** A hash table for built-in function definitions.  (Application-defined
001546  ** functions use a regular table table from hash.h.)
001547  **
001548  ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
001549  ** Collisions are on the FuncDef.u.pHash chain.  Use the SQLITE_FUNC_HASH()
001550  ** macro to compute a hash on the function name.
001551  */
001552  #define SQLITE_FUNC_HASH_SZ 23
001553  struct FuncDefHash {
001554    FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */
001555  };
001556  #define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)
001557  
001558  #ifdef SQLITE_USER_AUTHENTICATION
001559  /*
001560  ** Information held in the "sqlite3" database connection object and used
001561  ** to manage user authentication.
001562  */
001563  typedef struct sqlite3_userauth sqlite3_userauth;
001564  struct sqlite3_userauth {
001565    u8 authLevel;                 /* Current authentication level */
001566    int nAuthPW;                  /* Size of the zAuthPW in bytes */
001567    char *zAuthPW;                /* Password used to authenticate */
001568    char *zAuthUser;              /* User name used to authenticate */
001569  };
001570  
001571  /* Allowed values for sqlite3_userauth.authLevel */
001572  #define UAUTH_Unknown     0     /* Authentication not yet checked */
001573  #define UAUTH_Fail        1     /* User authentication failed */
001574  #define UAUTH_User        2     /* Authenticated as a normal user */
001575  #define UAUTH_Admin       3     /* Authenticated as an administrator */
001576  
001577  /* Functions used only by user authorization logic */
001578  int sqlite3UserAuthTable(const char*);
001579  int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
001580  void sqlite3UserAuthInit(sqlite3*);
001581  void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
001582  
001583  #endif /* SQLITE_USER_AUTHENTICATION */
001584  
001585  /*
001586  ** typedef for the authorization callback function.
001587  */
001588  #ifdef SQLITE_USER_AUTHENTICATION
001589    typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
001590                                 const char*, const char*);
001591  #else
001592    typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
001593                                 const char*);
001594  #endif
001595  
001596  #ifndef SQLITE_OMIT_DEPRECATED
001597  /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
001598  ** in the style of sqlite3_trace()
001599  */
001600  #define SQLITE_TRACE_LEGACY          0x40     /* Use the legacy xTrace */
001601  #define SQLITE_TRACE_XPROFILE        0x80     /* Use the legacy xProfile */
001602  #else
001603  #define SQLITE_TRACE_LEGACY          0
001604  #define SQLITE_TRACE_XPROFILE        0
001605  #endif /* SQLITE_OMIT_DEPRECATED */
001606  #define SQLITE_TRACE_NONLEGACY_MASK  0x0f     /* Normal flags */
001607  
001608  /*
001609  ** Maximum number of sqlite3.aDb[] entries.  This is the number of attached
001610  ** databases plus 2 for "main" and "temp".
001611  */
001612  #define SQLITE_MAX_DB (SQLITE_MAX_ATTACHED+2)
001613  
001614  /*
001615  ** Each database connection is an instance of the following structure.
001616  */
001617  struct sqlite3 {
001618    sqlite3_vfs *pVfs;            /* OS Interface */
001619    struct Vdbe *pVdbe;           /* List of active virtual machines */
001620    CollSeq *pDfltColl;           /* BINARY collseq for the database encoding */
001621    sqlite3_mutex *mutex;         /* Connection mutex */
001622    Db *aDb;                      /* All backends */
001623    int nDb;                      /* Number of backends currently in use */
001624    u32 mDbFlags;                 /* flags recording internal state */
001625    u64 flags;                    /* flags settable by pragmas. See below */
001626    i64 lastRowid;                /* ROWID of most recent insert (see above) */
001627    i64 szMmap;                   /* Default mmap_size setting */
001628    u32 nSchemaLock;              /* Do not reset the schema when non-zero */
001629    unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
001630    int errCode;                  /* Most recent error code (SQLITE_*) */
001631    int errByteOffset;            /* Byte offset of error in SQL statement */
001632    int errMask;                  /* & result codes with this before returning */
001633    int iSysErrno;                /* Errno value from last system error */
001634    u32 dbOptFlags;               /* Flags to enable/disable optimizations */
001635    u8 enc;                       /* Text encoding */
001636    u8 autoCommit;                /* The auto-commit flag. */
001637    u8 temp_store;                /* 1: file 2: memory 0: default */
001638    u8 mallocFailed;              /* True if we have seen a malloc failure */
001639    u8 bBenignMalloc;             /* Do not require OOMs if true */
001640    u8 dfltLockMode;              /* Default locking-mode for attached dbs */
001641    signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
001642    u8 suppressErr;               /* Do not issue error messages if true */
001643    u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
001644    u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
001645    u8 mTrace;                    /* zero or more SQLITE_TRACE flags */
001646    u8 noSharedCache;             /* True if no shared-cache backends */
001647    u8 nSqlExec;                  /* Number of pending OP_SqlExec opcodes */
001648    u8 eOpenState;                /* Current condition of the connection */
001649    int nextPagesize;             /* Pagesize after VACUUM if >0 */
001650    i64 nChange;                  /* Value returned by sqlite3_changes() */
001651    i64 nTotalChange;             /* Value returned by sqlite3_total_changes() */
001652    int aLimit[SQLITE_N_LIMIT];   /* Limits */
001653    int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
001654    struct sqlite3InitInfo {      /* Information used during initialization */
001655      Pgno newTnum;               /* Rootpage of table being initialized */
001656      u8 iDb;                     /* Which db file is being initialized */
001657      u8 busy;                    /* TRUE if currently initializing */
001658      unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
001659      unsigned imposterTable : 1; /* Building an imposter table */
001660      unsigned reopenMemdb : 1;   /* ATTACH is really a reopen using MemDB */
001661      const char **azInit;        /* "type", "name", and "tbl_name" columns */
001662    } init;
001663    int nVdbeActive;              /* Number of VDBEs currently running */
001664    int nVdbeRead;                /* Number of active VDBEs that read or write */
001665    int nVdbeWrite;               /* Number of active VDBEs that read and write */
001666    int nVdbeExec;                /* Number of nested calls to VdbeExec() */
001667    int nVDestroy;                /* Number of active OP_VDestroy operations */
001668    int nExtension;               /* Number of loaded extensions */
001669    void **aExtension;            /* Array of shared library handles */
001670    union {
001671      void (*xLegacy)(void*,const char*);   /* mTrace==SQLITE_TRACE_LEGACY */
001672      int (*xV2)(u32,void*,void*,void*);    /* All other mTrace values */
001673    } trace;
001674    void *pTraceArg;                        /* Argument to the trace function */
001675  #ifndef SQLITE_OMIT_DEPRECATED
001676    void (*xProfile)(void*,const char*,u64);  /* Profiling function */
001677    void *pProfileArg;                        /* Argument to profile function */
001678  #endif
001679    void *pCommitArg;                 /* Argument to xCommitCallback() */
001680    int (*xCommitCallback)(void*);    /* Invoked at every commit. */
001681    void *pRollbackArg;               /* Argument to xRollbackCallback() */
001682    void (*xRollbackCallback)(void*); /* Invoked at every commit. */
001683    void *pUpdateArg;
001684    void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
001685    void *pAutovacPagesArg;           /* Client argument to autovac_pages */
001686    void (*xAutovacDestr)(void*);     /* Destructor for pAutovacPAgesArg */
001687    unsigned int (*xAutovacPages)(void*,const char*,u32,u32,u32);
001688    Parse *pParse;                /* Current parse */
001689  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
001690    void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */
001691    void (*xPreUpdateCallback)(   /* Registered using sqlite3_preupdate_hook() */
001692      void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
001693    );
001694    PreUpdate *pPreUpdate;        /* Context for active pre-update callback */
001695  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
001696  #ifndef SQLITE_OMIT_WAL
001697    int (*xWalCallback)(void *, sqlite3 *, const char *, int);
001698    void *pWalArg;
001699  #endif
001700    void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
001701    void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
001702    void *pCollNeededArg;
001703    sqlite3_value *pErr;          /* Most recent error message */
001704    union {
001705      volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
001706      double notUsed1;            /* Spacer */
001707    } u1;
001708    Lookaside lookaside;          /* Lookaside malloc configuration */
001709  #ifndef SQLITE_OMIT_AUTHORIZATION
001710    sqlite3_xauth xAuth;          /* Access authorization function */
001711    void *pAuthArg;               /* 1st argument to the access auth function */
001712  #endif
001713  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
001714    int (*xProgress)(void *);     /* The progress callback */
001715    void *pProgressArg;           /* Argument to the progress callback */
001716    unsigned nProgressOps;        /* Number of opcodes for progress callback */
001717  #endif
001718  #ifndef SQLITE_OMIT_VIRTUALTABLE
001719    int nVTrans;                  /* Allocated size of aVTrans */
001720    Hash aModule;                 /* populated by sqlite3_create_module() */
001721    VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
001722    VTable **aVTrans;             /* Virtual tables with open transactions */
001723    VTable *pDisconnect;          /* Disconnect these in next sqlite3_prepare() */
001724  #endif
001725    Hash aFunc;                   /* Hash table of connection functions */
001726    Hash aCollSeq;                /* All collating sequences */
001727    BusyHandler busyHandler;      /* Busy callback */
001728    Db aDbStatic[2];              /* Static space for the 2 default backends */
001729    Savepoint *pSavepoint;        /* List of active savepoints */
001730    int nAnalysisLimit;           /* Number of index rows to ANALYZE */
001731    int busyTimeout;              /* Busy handler timeout, in msec */
001732    int nSavepoint;               /* Number of non-transaction savepoints */
001733    int nStatement;               /* Number of nested statement-transactions  */
001734    i64 nDeferredCons;            /* Net deferred constraints this transaction. */
001735    i64 nDeferredImmCons;         /* Net deferred immediate constraints */
001736    int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
001737  #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
001738    /* The following variables are all protected by the STATIC_MAIN
001739    ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
001740    **
001741    ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
001742    ** unlock so that it can proceed.
001743    **
001744    ** When X.pBlockingConnection==Y, that means that something that X tried
001745    ** tried to do recently failed with an SQLITE_LOCKED error due to locks
001746    ** held by Y.
001747    */
001748    sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
001749    sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
001750    void *pUnlockArg;                     /* Argument to xUnlockNotify */
001751    void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
001752    sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
001753  #endif
001754  #ifdef SQLITE_USER_AUTHENTICATION
001755    sqlite3_userauth auth;        /* User authentication information */
001756  #endif
001757  };
001758  
001759  /*
001760  ** A macro to discover the encoding of a database.
001761  */
001762  #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
001763  #define ENC(db)        ((db)->enc)
001764  
001765  /*
001766  ** A u64 constant where the lower 32 bits are all zeros.  Only the
001767  ** upper 32 bits are included in the argument.  Necessary because some
001768  ** C-compilers still do not accept LL integer literals.
001769  */
001770  #define HI(X)  ((u64)(X)<<32)
001771  
001772  /*
001773  ** Possible values for the sqlite3.flags.
001774  **
001775  ** Value constraints (enforced via assert()):
001776  **      SQLITE_FullFSync     == PAGER_FULLFSYNC
001777  **      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
001778  **      SQLITE_CacheSpill    == PAGER_CACHE_SPILL
001779  */
001780  #define SQLITE_WriteSchema    0x00000001  /* OK to update SQLITE_SCHEMA */
001781  #define SQLITE_LegacyFileFmt  0x00000002  /* Create new databases in format 1 */
001782  #define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
001783  #define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */
001784  #define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */
001785  #define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
001786  #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
001787  #define SQLITE_TrustedSchema  0x00000080  /* Allow unsafe functions and
001788                                            ** vtabs in the schema definition */
001789  #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
001790                                            /*   result set is empty */
001791  #define SQLITE_IgnoreChecks   0x00000200  /* Do not enforce check constraints */
001792  #define SQLITE_StmtScanStatus 0x00000400  /* Enable stmt_scanstats() counters */
001793  #define SQLITE_NoCkptOnClose  0x00000800  /* No checkpoint on close()/DETACH */
001794  #define SQLITE_ReverseOrder   0x00001000  /* Reverse unordered SELECTs */
001795  #define SQLITE_RecTriggers    0x00002000  /* Enable recursive triggers */
001796  #define SQLITE_ForeignKeys    0x00004000  /* Enforce foreign key constraints  */
001797  #define SQLITE_AutoIndex      0x00008000  /* Enable automatic indexes */
001798  #define SQLITE_LoadExtension  0x00010000  /* Enable load_extension */
001799  #define SQLITE_LoadExtFunc    0x00020000  /* Enable load_extension() SQL func */
001800  #define SQLITE_EnableTrigger  0x00040000  /* True to enable triggers */
001801  #define SQLITE_DeferFKs       0x00080000  /* Defer all FK constraints */
001802  #define SQLITE_QueryOnly      0x00100000  /* Disable database changes */
001803  #define SQLITE_CellSizeCk     0x00200000  /* Check btree cell sizes on load */
001804  #define SQLITE_Fts3Tokenizer  0x00400000  /* Enable fts3_tokenizer(2) */
001805  #define SQLITE_EnableQPSG     0x00800000  /* Query Planner Stability Guarantee*/
001806  #define SQLITE_TriggerEQP     0x01000000  /* Show trigger EXPLAIN QUERY PLAN */
001807  #define SQLITE_ResetDatabase  0x02000000  /* Reset the database */
001808  #define SQLITE_LegacyAlter    0x04000000  /* Legacy ALTER TABLE behaviour */
001809  #define SQLITE_NoSchemaError  0x08000000  /* Do not report schema parse errors*/
001810  #define SQLITE_Defensive      0x10000000  /* Input SQL is likely hostile */
001811  #define SQLITE_DqsDDL         0x20000000  /* dbl-quoted strings allowed in DDL*/
001812  #define SQLITE_DqsDML         0x40000000  /* dbl-quoted strings allowed in DML*/
001813  #define SQLITE_EnableView     0x80000000  /* Enable the use of views */
001814  #define SQLITE_CountRows      HI(0x00001) /* Count rows changed by INSERT, */
001815                                            /*   DELETE, or UPDATE and return */
001816                                            /*   the count using a callback. */
001817  #define SQLITE_CorruptRdOnly  HI(0x00002) /* Prohibit writes due to error */
001818  #define SQLITE_ReadUncommit   HI(0x00004) /* READ UNCOMMITTED in shared-cache */
001819  
001820  /* Flags used only if debugging */
001821  #ifdef SQLITE_DEBUG
001822  #define SQLITE_SqlTrace       HI(0x0100000) /* Debug print SQL as it executes */
001823  #define SQLITE_VdbeListing    HI(0x0200000) /* Debug listings of VDBE progs */
001824  #define SQLITE_VdbeTrace      HI(0x0400000) /* True to trace VDBE execution */
001825  #define SQLITE_VdbeAddopTrace HI(0x0800000) /* Trace sqlite3VdbeAddOp() calls */
001826  #define SQLITE_VdbeEQP        HI(0x1000000) /* Debug EXPLAIN QUERY PLAN */
001827  #define SQLITE_ParserTrace    HI(0x2000000) /* PRAGMA parser_trace=ON */
001828  #endif
001829  
001830  /*
001831  ** Allowed values for sqlite3.mDbFlags
001832  */
001833  #define DBFLAG_SchemaChange   0x0001  /* Uncommitted Hash table changes */
001834  #define DBFLAG_PreferBuiltin  0x0002  /* Preference to built-in funcs */
001835  #define DBFLAG_Vacuum         0x0004  /* Currently in a VACUUM */
001836  #define DBFLAG_VacuumInto     0x0008  /* Currently running VACUUM INTO */
001837  #define DBFLAG_SchemaKnownOk  0x0010  /* Schema is known to be valid */
001838  #define DBFLAG_InternalFunc   0x0020  /* Allow use of internal functions */
001839  #define DBFLAG_EncodingFixed  0x0040  /* No longer possible to change enc. */
001840  
001841  /*
001842  ** Bits of the sqlite3.dbOptFlags field that are used by the
001843  ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
001844  ** selectively disable various optimizations.
001845  */
001846  #define SQLITE_QueryFlattener 0x00000001 /* Query flattening */
001847  #define SQLITE_WindowFunc     0x00000002 /* Use xInverse for window functions */
001848  #define SQLITE_GroupByOrder   0x00000004 /* GROUPBY cover of ORDERBY */
001849  #define SQLITE_FactorOutConst 0x00000008 /* Constant factoring */
001850  #define SQLITE_DistinctOpt    0x00000010 /* DISTINCT using indexes */
001851  #define SQLITE_CoverIdxScan   0x00000020 /* Covering index scans */
001852  #define SQLITE_OrderByIdxJoin 0x00000040 /* ORDER BY of joins via index */
001853  #define SQLITE_Transitive     0x00000080 /* Transitive constraints */
001854  #define SQLITE_OmitNoopJoin   0x00000100 /* Omit unused tables in joins */
001855  #define SQLITE_CountOfView    0x00000200 /* The count-of-view optimization */
001856  #define SQLITE_CursorHints    0x00000400 /* Add OP_CursorHint opcodes */
001857  #define SQLITE_Stat4          0x00000800 /* Use STAT4 data */
001858     /* TH3 expects this value  ^^^^^^^^^^ to be 0x0000800. Don't change it */
001859  #define SQLITE_PushDown       0x00001000 /* The push-down optimization */
001860  #define SQLITE_SimplifyJoin   0x00002000 /* Convert LEFT JOIN to JOIN */
001861  #define SQLITE_SkipScan       0x00004000 /* Skip-scans */
001862  #define SQLITE_PropagateConst 0x00008000 /* The constant propagation opt */
001863  #define SQLITE_MinMaxOpt      0x00010000 /* The min/max optimization */
001864  #define SQLITE_SeekScan       0x00020000 /* The OP_SeekScan optimization */
001865  #define SQLITE_OmitOrderBy    0x00040000 /* Omit pointless ORDER BY */
001866     /* TH3 expects this value  ^^^^^^^^^^ to be 0x40000. Coordinate any change */
001867  #define SQLITE_BloomFilter    0x00080000 /* Use a Bloom filter on searches */
001868  #define SQLITE_BloomPulldown  0x00100000 /* Run Bloom filters early */
001869  #define SQLITE_BalancedMerge  0x00200000 /* Balance multi-way merges */
001870  #define SQLITE_ReleaseReg     0x00400000 /* Use OP_ReleaseReg for testing */
001871  #define SQLITE_FlttnUnionAll  0x00800000 /* Disable the UNION ALL flattener */
001872     /* TH3 expects this value  ^^^^^^^^^^ See flatten04.test */
001873  #define SQLITE_IndexedExpr    0x01000000 /* Pull exprs from index when able */
001874  #define SQLITE_Coroutines     0x02000000 /* Co-routines for subqueries */
001875  #define SQLITE_NullUnusedCols 0x04000000 /* NULL unused columns in subqueries */
001876  #define SQLITE_OnePass        0x08000000 /* Single-pass DELETE and UPDATE */
001877  #define SQLITE_AllOpts        0xffffffff /* All optimizations */
001878  
001879  /*
001880  ** Macros for testing whether or not optimizations are enabled or disabled.
001881  */
001882  #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
001883  #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
001884  
001885  /*
001886  ** Return true if it OK to factor constant expressions into the initialization
001887  ** code. The argument is a Parse object for the code generator.
001888  */
001889  #define ConstFactorOk(P) ((P)->okConstFactor)
001890  
001891  /* Possible values for the sqlite3.eOpenState field.
001892  ** The numbers are randomly selected such that a minimum of three bits must
001893  ** change to convert any number to another or to zero
001894  */
001895  #define SQLITE_STATE_OPEN     0x76  /* Database is open */
001896  #define SQLITE_STATE_CLOSED   0xce  /* Database is closed */
001897  #define SQLITE_STATE_SICK     0xba  /* Error and awaiting close */
001898  #define SQLITE_STATE_BUSY     0x6d  /* Database currently in use */
001899  #define SQLITE_STATE_ERROR    0xd5  /* An SQLITE_MISUSE error occurred */
001900  #define SQLITE_STATE_ZOMBIE   0xa7  /* Close with last statement close */
001901  
001902  /*
001903  ** Each SQL function is defined by an instance of the following
001904  ** structure.  For global built-in functions (ex: substr(), max(), count())
001905  ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
001906  ** For per-connection application-defined functions, a pointer to this
001907  ** structure is held in the db->aHash hash table.
001908  **
001909  ** The u.pHash field is used by the global built-ins.  The u.pDestructor
001910  ** field is used by per-connection app-def functions.
001911  */
001912  struct FuncDef {
001913    i8 nArg;             /* Number of arguments.  -1 means unlimited */
001914    u32 funcFlags;       /* Some combination of SQLITE_FUNC_* */
001915    void *pUserData;     /* User data parameter */
001916    FuncDef *pNext;      /* Next function with same name */
001917    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
001918    void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */
001919    void (*xValue)(sqlite3_context*);                     /* Current agg value */
001920    void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
001921    const char *zName;   /* SQL name of the function. */
001922    union {
001923      FuncDef *pHash;      /* Next with a different name but the same hash */
001924      FuncDestructor *pDestructor;   /* Reference counted destructor function */
001925    } u; /* pHash if SQLITE_FUNC_BUILTIN, pDestructor otherwise */
001926  };
001927  
001928  /*
001929  ** This structure encapsulates a user-function destructor callback (as
001930  ** configured using create_function_v2()) and a reference counter. When
001931  ** create_function_v2() is called to create a function with a destructor,
001932  ** a single object of this type is allocated. FuncDestructor.nRef is set to
001933  ** the number of FuncDef objects created (either 1 or 3, depending on whether
001934  ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
001935  ** member of each of the new FuncDef objects is set to point to the allocated
001936  ** FuncDestructor.
001937  **
001938  ** Thereafter, when one of the FuncDef objects is deleted, the reference
001939  ** count on this object is decremented. When it reaches 0, the destructor
001940  ** is invoked and the FuncDestructor structure freed.
001941  */
001942  struct FuncDestructor {
001943    int nRef;
001944    void (*xDestroy)(void *);
001945    void *pUserData;
001946  };
001947  
001948  /*
001949  ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
001950  ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  And
001951  ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC.  There
001952  ** are assert() statements in the code to verify this.
001953  **
001954  ** Value constraints (enforced via assert()):
001955  **     SQLITE_FUNC_MINMAX      ==  NC_MinMaxAgg      == SF_MinMaxAgg
001956  **     SQLITE_FUNC_ANYORDER    ==  NC_OrderAgg       == SF_OrderByReqd
001957  **     SQLITE_FUNC_LENGTH      ==  OPFLAG_LENGTHARG
001958  **     SQLITE_FUNC_TYPEOF      ==  OPFLAG_TYPEOFARG
001959  **     SQLITE_FUNC_BYTELEN     ==  OPFLAG_BYTELENARG
001960  **     SQLITE_FUNC_CONSTANT    ==  SQLITE_DETERMINISTIC from the API
001961  **     SQLITE_FUNC_DIRECT      ==  SQLITE_DIRECTONLY from the API
001962  **     SQLITE_FUNC_UNSAFE      ==  SQLITE_INNOCUOUS  -- opposite meanings!!!
001963  **     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API
001964  **
001965  ** Note that even though SQLITE_FUNC_UNSAFE and SQLITE_INNOCUOUS have the
001966  ** same bit value, their meanings are inverted.  SQLITE_FUNC_UNSAFE is
001967  ** used internally and if set means that the function has side effects.
001968  ** SQLITE_INNOCUOUS is used by application code and means "not unsafe".
001969  ** See multiple instances of tag-20230109-1.
001970  */
001971  #define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
001972  #define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */
001973  #define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */
001974  #define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */
001975  #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
001976  #define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */
001977  #define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */
001978  #define SQLITE_FUNC_BYTELEN  0x00c0 /* Built-in octet_length() function */
001979  #define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */
001980  /*                           0x0200 -- available for reuse */
001981  #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
001982  #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
001983  #define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
001984  #define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
001985                                      ** single query - might change over time */
001986  #define SQLITE_FUNC_TEST     0x4000 /* Built-in testing functions */
001987  /*                           0x8000 -- available for reuse */
001988  #define SQLITE_FUNC_WINDOW   0x00010000 /* Built-in window-only function */
001989  #define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
001990  #define SQLITE_FUNC_DIRECT   0x00080000 /* Not for use in TRIGGERs or VIEWs */
001991  #define SQLITE_FUNC_SUBTYPE  0x00100000 /* Result likely to have sub-type */
001992  #define SQLITE_FUNC_UNSAFE   0x00200000 /* Function has side effects */
001993  #define SQLITE_FUNC_INLINE   0x00400000 /* Functions implemented in-line */
001994  #define SQLITE_FUNC_BUILTIN  0x00800000 /* This is a built-in function */
001995  #define SQLITE_FUNC_ANYORDER 0x08000000 /* count/min/max aggregate */
001996  
001997  /* Identifier numbers for each in-line function */
001998  #define INLINEFUNC_coalesce             0
001999  #define INLINEFUNC_implies_nonnull_row  1
002000  #define INLINEFUNC_expr_implies_expr    2
002001  #define INLINEFUNC_expr_compare         3
002002  #define INLINEFUNC_affinity             4
002003  #define INLINEFUNC_iif                  5
002004  #define INLINEFUNC_sqlite_offset        6
002005  #define INLINEFUNC_unlikely            99  /* Default case */
002006  
002007  /*
002008  ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
002009  ** used to create the initializers for the FuncDef structures.
002010  **
002011  **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
002012  **     Used to create a scalar function definition of a function zName
002013  **     implemented by C function xFunc that accepts nArg arguments. The
002014  **     value passed as iArg is cast to a (void*) and made available
002015  **     as the user-data (sqlite3_user_data()) for the function. If
002016  **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
002017  **
002018  **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
002019  **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
002020  **
002021  **   SFUNCTION(zName, nArg, iArg, bNC, xFunc)
002022  **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
002023  **     adds the SQLITE_DIRECTONLY flag.
002024  **
002025  **   INLINE_FUNC(zName, nArg, iFuncId, mFlags)
002026  **     zName is the name of a function that is implemented by in-line
002027  **     byte code rather than by the usual callbacks. The iFuncId
002028  **     parameter determines the function id.  The mFlags parameter is
002029  **     optional SQLITE_FUNC_ flags for this function.
002030  **
002031  **   TEST_FUNC(zName, nArg, iFuncId, mFlags)
002032  **     zName is the name of a test-only function implemented by in-line
002033  **     byte code rather than by the usual callbacks. The iFuncId
002034  **     parameter determines the function id.  The mFlags parameter is
002035  **     optional SQLITE_FUNC_ flags for this function.
002036  **
002037  **   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
002038  **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
002039  **     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions
002040  **     and functions like sqlite_version() that can change, but not during
002041  **     a single query.  The iArg is ignored.  The user-data is always set
002042  **     to a NULL pointer.  The bNC parameter is not used.
002043  **
002044  **   MFUNCTION(zName, nArg, xPtr, xFunc)
002045  **     For math-library functions.  xPtr is an arbitrary pointer.
002046  **
002047  **   PURE_DATE(zName, nArg, iArg, bNC, xFunc)
002048  **     Used for "pure" date/time functions, this macro is like DFUNCTION
002049  **     except that it does set the SQLITE_FUNC_CONSTANT flags.  iArg is
002050  **     ignored and the user-data for these functions is set to an
002051  **     arbitrary non-NULL pointer.  The bNC parameter is not used.
002052  **
002053  **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
002054  **     Used to create an aggregate function definition implemented by
002055  **     the C functions xStep and xFinal. The first four parameters
002056  **     are interpreted in the same way as the first 4 parameters to
002057  **     FUNCTION().
002058  **
002059  **   WAGGREGATE(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
002060  **     Used to create an aggregate function definition implemented by
002061  **     the C functions xStep and xFinal. The first four parameters
002062  **     are interpreted in the same way as the first 4 parameters to
002063  **     FUNCTION().
002064  **
002065  **   LIKEFUNC(zName, nArg, pArg, flags)
002066  **     Used to create a scalar function definition of a function zName
002067  **     that accepts nArg arguments and is implemented by a call to C
002068  **     function likeFunc. Argument pArg is cast to a (void *) and made
002069  **     available as the function user-data (sqlite3_user_data()). The
002070  **     FuncDef.flags variable is set to the value passed as the flags
002071  **     parameter.
002072  */
002073  #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
002074    {nArg, SQLITE_FUNC_BUILTIN|\
002075     SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
002076     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
002077  #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
002078    {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
002079     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
002080  #define SFUNCTION(zName, nArg, iArg, bNC, xFunc) \
002081    {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \
002082     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
002083  #define MFUNCTION(zName, nArg, xPtr, xFunc) \
002084    {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8, \
002085     xPtr, 0, xFunc, 0, 0, 0, #zName, {0} }
002086  #define JFUNCTION(zName, nArg, iArg, xFunc) \
002087    {nArg, SQLITE_FUNC_BUILTIN|SQLITE_DETERMINISTIC|\
002088     SQLITE_FUNC_CONSTANT|SQLITE_UTF8, \
002089     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
002090  #define INLINE_FUNC(zName, nArg, iArg, mFlags) \
002091    {nArg, SQLITE_FUNC_BUILTIN|\
002092     SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
002093     SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
002094  #define TEST_FUNC(zName, nArg, iArg, mFlags) \
002095    {nArg, SQLITE_FUNC_BUILTIN|\
002096           SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \
002097           SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
002098     SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
002099  #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
002100    {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
002101     0, 0, xFunc, 0, 0, 0, #zName, {0} }
002102  #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
002103    {nArg, SQLITE_FUNC_BUILTIN|\
002104           SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
002105     (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
002106  #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
002107    {nArg, SQLITE_FUNC_BUILTIN|\
002108     SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
002109     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
002110  #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
002111    {nArg, SQLITE_FUNC_BUILTIN|\
002112     SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
002113     pArg, 0, xFunc, 0, 0, 0, #zName, }
002114  #define LIKEFUNC(zName, nArg, arg, flags) \
002115    {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
002116     (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
002117  #define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
002118    {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
002119     SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
002120  #define INTERNAL_FUNCTION(zName, nArg, xFunc) \
002121    {nArg, SQLITE_FUNC_BUILTIN|\
002122     SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
002123     0, 0, xFunc, 0, 0, 0, #zName, {0} }
002124  
002125  
002126  /*
002127  ** All current savepoints are stored in a linked list starting at
002128  ** sqlite3.pSavepoint. The first element in the list is the most recently
002129  ** opened savepoint. Savepoints are added to the list by the vdbe
002130  ** OP_Savepoint instruction.
002131  */
002132  struct Savepoint {
002133    char *zName;                        /* Savepoint name (nul-terminated) */
002134    i64 nDeferredCons;                  /* Number of deferred fk violations */
002135    i64 nDeferredImmCons;               /* Number of deferred imm fk. */
002136    Savepoint *pNext;                   /* Parent savepoint (if any) */
002137  };
002138  
002139  /*
002140  ** The following are used as the second parameter to sqlite3Savepoint(),
002141  ** and as the P1 argument to the OP_Savepoint instruction.
002142  */
002143  #define SAVEPOINT_BEGIN      0
002144  #define SAVEPOINT_RELEASE    1
002145  #define SAVEPOINT_ROLLBACK   2
002146  
002147  
002148  /*
002149  ** Each SQLite module (virtual table definition) is defined by an
002150  ** instance of the following structure, stored in the sqlite3.aModule
002151  ** hash table.
002152  */
002153  struct Module {
002154    const sqlite3_module *pModule;       /* Callback pointers */
002155    const char *zName;                   /* Name passed to create_module() */
002156    int nRefModule;                      /* Number of pointers to this object */
002157    void *pAux;                          /* pAux passed to create_module() */
002158    void (*xDestroy)(void *);            /* Module destructor function */
002159    Table *pEpoTab;                      /* Eponymous table for this module */
002160  };
002161  
002162  /*
002163  ** Information about each column of an SQL table is held in an instance
002164  ** of the Column structure, in the Table.aCol[] array.
002165  **
002166  ** Definitions:
002167  **
002168  **   "table column index"     This is the index of the column in the
002169  **                            Table.aCol[] array, and also the index of
002170  **                            the column in the original CREATE TABLE stmt.
002171  **
002172  **   "storage column index"   This is the index of the column in the
002173  **                            record BLOB generated by the OP_MakeRecord
002174  **                            opcode.  The storage column index is less than
002175  **                            or equal to the table column index.  It is
002176  **                            equal if and only if there are no VIRTUAL
002177  **                            columns to the left.
002178  **
002179  ** Notes on zCnName:
002180  ** The zCnName field stores the name of the column, the datatype of the
002181  ** column, and the collating sequence for the column, in that order, all in
002182  ** a single allocation.  Each string is 0x00 terminated.  The datatype
002183  ** is only included if the COLFLAG_HASTYPE bit of colFlags is set and the
002184  ** collating sequence name is only included if the COLFLAG_HASCOLL bit is
002185  ** set.
002186  */
002187  struct Column {
002188    char *zCnName;        /* Name of this column */
002189    unsigned notNull :4;  /* An OE_ code for handling a NOT NULL constraint */
002190    unsigned eCType :4;   /* One of the standard types */
002191    char affinity;        /* One of the SQLITE_AFF_... values */
002192    u8 szEst;             /* Est size of value in this column. sizeof(INT)==1 */
002193    u8 hName;             /* Column name hash for faster lookup */
002194    u16 iDflt;            /* 1-based index of DEFAULT.  0 means "none" */
002195    u16 colFlags;         /* Boolean properties.  See COLFLAG_ defines below */
002196  };
002197  
002198  /* Allowed values for Column.eCType.
002199  **
002200  ** Values must match entries in the global constant arrays
002201  ** sqlite3StdTypeLen[] and sqlite3StdType[].  Each value is one more
002202  ** than the offset into these arrays for the corresponding name.
002203  ** Adjust the SQLITE_N_STDTYPE value if adding or removing entries.
002204  */
002205  #define COLTYPE_CUSTOM      0   /* Type appended to zName */
002206  #define COLTYPE_ANY         1
002207  #define COLTYPE_BLOB        2
002208  #define COLTYPE_INT         3
002209  #define COLTYPE_INTEGER     4
002210  #define COLTYPE_REAL        5
002211  #define COLTYPE_TEXT        6
002212  #define SQLITE_N_STDTYPE    6  /* Number of standard types */
002213  
002214  /* Allowed values for Column.colFlags.
002215  **
002216  ** Constraints:
002217  **         TF_HasVirtual == COLFLAG_VIRTUAL
002218  **         TF_HasStored  == COLFLAG_STORED
002219  **         TF_HasHidden  == COLFLAG_HIDDEN
002220  */
002221  #define COLFLAG_PRIMKEY   0x0001   /* Column is part of the primary key */
002222  #define COLFLAG_HIDDEN    0x0002   /* A hidden column in a virtual table */
002223  #define COLFLAG_HASTYPE   0x0004   /* Type name follows column name */
002224  #define COLFLAG_UNIQUE    0x0008   /* Column def contains "UNIQUE" or "PK" */
002225  #define COLFLAG_SORTERREF 0x0010   /* Use sorter-refs with this column */
002226  #define COLFLAG_VIRTUAL   0x0020   /* GENERATED ALWAYS AS ... VIRTUAL */
002227  #define COLFLAG_STORED    0x0040   /* GENERATED ALWAYS AS ... STORED */
002228  #define COLFLAG_NOTAVAIL  0x0080   /* STORED column not yet calculated */
002229  #define COLFLAG_BUSY      0x0100   /* Blocks recursion on GENERATED columns */
002230  #define COLFLAG_HASCOLL   0x0200   /* Has collating sequence name in zCnName */
002231  #define COLFLAG_NOEXPAND  0x0400   /* Omit this column when expanding "*" */
002232  #define COLFLAG_GENERATED 0x0060   /* Combo: _STORED, _VIRTUAL */
002233  #define COLFLAG_NOINSERT  0x0062   /* Combo: _HIDDEN, _STORED, _VIRTUAL */
002234  
002235  /*
002236  ** A "Collating Sequence" is defined by an instance of the following
002237  ** structure. Conceptually, a collating sequence consists of a name and
002238  ** a comparison routine that defines the order of that sequence.
002239  **
002240  ** If CollSeq.xCmp is NULL, it means that the
002241  ** collating sequence is undefined.  Indices built on an undefined
002242  ** collating sequence may not be read or written.
002243  */
002244  struct CollSeq {
002245    char *zName;          /* Name of the collating sequence, UTF-8 encoded */
002246    u8 enc;               /* Text encoding handled by xCmp() */
002247    void *pUser;          /* First argument to xCmp() */
002248    int (*xCmp)(void*,int, const void*, int, const void*);
002249    void (*xDel)(void*);  /* Destructor for pUser */
002250  };
002251  
002252  /*
002253  ** A sort order can be either ASC or DESC.
002254  */
002255  #define SQLITE_SO_ASC       0  /* Sort in ascending order */
002256  #define SQLITE_SO_DESC      1  /* Sort in ascending order */
002257  #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
002258  
002259  /*
002260  ** Column affinity types.
002261  **
002262  ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
002263  ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
002264  ** the speed a little by numbering the values consecutively.
002265  **
002266  ** But rather than start with 0 or 1, we begin with 'A'.  That way,
002267  ** when multiple affinity types are concatenated into a string and
002268  ** used as the P4 operand, they will be more readable.
002269  **
002270  ** Note also that the numeric types are grouped together so that testing
002271  ** for a numeric type is a single comparison.  And the BLOB type is first.
002272  */
002273  #define SQLITE_AFF_NONE     0x40  /* '@' */
002274  #define SQLITE_AFF_BLOB     0x41  /* 'A' */
002275  #define SQLITE_AFF_TEXT     0x42  /* 'B' */
002276  #define SQLITE_AFF_NUMERIC  0x43  /* 'C' */
002277  #define SQLITE_AFF_INTEGER  0x44  /* 'D' */
002278  #define SQLITE_AFF_REAL     0x45  /* 'E' */
002279  #define SQLITE_AFF_FLEXNUM  0x46  /* 'F' */
002280  
002281  #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
002282  
002283  /*
002284  ** The SQLITE_AFF_MASK values masks off the significant bits of an
002285  ** affinity value.
002286  */
002287  #define SQLITE_AFF_MASK     0x47
002288  
002289  /*
002290  ** Additional bit values that can be ORed with an affinity without
002291  ** changing the affinity.
002292  **
002293  ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
002294  ** It causes an assert() to fire if either operand to a comparison
002295  ** operator is NULL.  It is added to certain comparison operators to
002296  ** prove that the operands are always NOT NULL.
002297  */
002298  #define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
002299  #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
002300  #define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
002301  
002302  /*
002303  ** An object of this type is created for each virtual table present in
002304  ** the database schema.
002305  **
002306  ** If the database schema is shared, then there is one instance of this
002307  ** structure for each database connection (sqlite3*) that uses the shared
002308  ** schema. This is because each database connection requires its own unique
002309  ** instance of the sqlite3_vtab* handle used to access the virtual table
002310  ** implementation. sqlite3_vtab* handles can not be shared between
002311  ** database connections, even when the rest of the in-memory database
002312  ** schema is shared, as the implementation often stores the database
002313  ** connection handle passed to it via the xConnect() or xCreate() method
002314  ** during initialization internally. This database connection handle may
002315  ** then be used by the virtual table implementation to access real tables
002316  ** within the database. So that they appear as part of the callers
002317  ** transaction, these accesses need to be made via the same database
002318  ** connection as that used to execute SQL operations on the virtual table.
002319  **
002320  ** All VTable objects that correspond to a single table in a shared
002321  ** database schema are initially stored in a linked-list pointed to by
002322  ** the Table.pVTable member variable of the corresponding Table object.
002323  ** When an sqlite3_prepare() operation is required to access the virtual
002324  ** table, it searches the list for the VTable that corresponds to the
002325  ** database connection doing the preparing so as to use the correct
002326  ** sqlite3_vtab* handle in the compiled query.
002327  **
002328  ** When an in-memory Table object is deleted (for example when the
002329  ** schema is being reloaded for some reason), the VTable objects are not
002330  ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
002331  ** immediately. Instead, they are moved from the Table.pVTable list to
002332  ** another linked list headed by the sqlite3.pDisconnect member of the
002333  ** corresponding sqlite3 structure. They are then deleted/xDisconnected
002334  ** next time a statement is prepared using said sqlite3*. This is done
002335  ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
002336  ** Refer to comments above function sqlite3VtabUnlockList() for an
002337  ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
002338  ** list without holding the corresponding sqlite3.mutex mutex.
002339  **
002340  ** The memory for objects of this type is always allocated by
002341  ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
002342  ** the first argument.
002343  */
002344  struct VTable {
002345    sqlite3 *db;              /* Database connection associated with this table */
002346    Module *pMod;             /* Pointer to module implementation */
002347    sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
002348    int nRef;                 /* Number of pointers to this structure */
002349    u8 bConstraint;           /* True if constraints are supported */
002350    u8 bAllSchemas;           /* True if might use any attached schema */
002351    u8 eVtabRisk;             /* Riskiness of allowing hacker access */
002352    int iSavepoint;           /* Depth of the SAVEPOINT stack */
002353    VTable *pNext;            /* Next in linked list (see above) */
002354  };
002355  
002356  /* Allowed values for VTable.eVtabRisk
002357  */
002358  #define SQLITE_VTABRISK_Low          0
002359  #define SQLITE_VTABRISK_Normal       1
002360  #define SQLITE_VTABRISK_High         2
002361  
002362  /*
002363  ** The schema for each SQL table, virtual table, and view is represented
002364  ** in memory by an instance of the following structure.
002365  */
002366  struct Table {
002367    char *zName;         /* Name of the table or view */
002368    Column *aCol;        /* Information about each column */
002369    Index *pIndex;       /* List of SQL indexes on this table. */
002370    char *zColAff;       /* String defining the affinity of each column */
002371    ExprList *pCheck;    /* All CHECK constraints */
002372                         /*   ... also used as column name list in a VIEW */
002373    Pgno tnum;           /* Root BTree page for this table */
002374    u32 nTabRef;         /* Number of pointers to this Table */
002375    u32 tabFlags;        /* Mask of TF_* values */
002376    i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
002377    i16 nCol;            /* Number of columns in this table */
002378    i16 nNVCol;          /* Number of columns that are not VIRTUAL */
002379    LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
002380    LogEst szTabRow;     /* Estimated size of each table row in bytes */
002381  #ifdef SQLITE_ENABLE_COSTMULT
002382    LogEst costMult;     /* Cost multiplier for using this table */
002383  #endif
002384    u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
002385    u8 eTabType;         /* 0: normal, 1: virtual, 2: view */
002386    union {
002387      struct {             /* Used by ordinary tables: */
002388        int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
002389        FKey *pFKey;         /* Linked list of all foreign keys in this table */
002390        ExprList *pDfltList; /* DEFAULT clauses on various columns.
002391                             ** Or the AS clause for generated columns. */
002392      } tab;
002393      struct {             /* Used by views: */
002394        Select *pSelect;     /* View definition */
002395      } view;
002396      struct {             /* Used by virtual tables only: */
002397        int nArg;            /* Number of arguments to the module */
002398        char **azArg;        /* 0: module 1: schema 2: vtab name 3...: args */
002399        VTable *p;           /* List of VTable objects. */
002400      } vtab;
002401    } u;
002402    Trigger *pTrigger;   /* List of triggers on this object */
002403    Schema *pSchema;     /* Schema that contains this table */
002404  };
002405  
002406  /*
002407  ** Allowed values for Table.tabFlags.
002408  **
002409  ** TF_OOOHidden applies to tables or view that have hidden columns that are
002410  ** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
002411  ** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
002412  ** the TF_OOOHidden attribute would apply in this case.  Such tables require
002413  ** special handling during INSERT processing. The "OOO" means "Out Of Order".
002414  **
002415  ** Constraints:
002416  **
002417  **         TF_HasVirtual == COLFLAG_VIRTUAL
002418  **         TF_HasStored  == COLFLAG_STORED
002419  **         TF_HasHidden  == COLFLAG_HIDDEN
002420  */
002421  #define TF_Readonly       0x00000001 /* Read-only system table */
002422  #define TF_HasHidden      0x00000002 /* Has one or more hidden columns */
002423  #define TF_HasPrimaryKey  0x00000004 /* Table has a primary key */
002424  #define TF_Autoincrement  0x00000008 /* Integer primary key is autoincrement */
002425  #define TF_HasStat1       0x00000010 /* nRowLogEst set from sqlite_stat1 */
002426  #define TF_HasVirtual     0x00000020 /* Has one or more VIRTUAL columns */
002427  #define TF_HasStored      0x00000040 /* Has one or more STORED columns */
002428  #define TF_HasGenerated   0x00000060 /* Combo: HasVirtual + HasStored */
002429  #define TF_WithoutRowid   0x00000080 /* No rowid.  PRIMARY KEY is the key */
002430  #define TF_StatsUsed      0x00000100 /* Query planner decisions affected by
002431                                       ** Index.aiRowLogEst[] values */
002432  #define TF_NoVisibleRowid 0x00000200 /* No user-visible "rowid" column */
002433  #define TF_OOOHidden      0x00000400 /* Out-of-Order hidden columns */
002434  #define TF_HasNotNull     0x00000800 /* Contains NOT NULL constraints */
002435  #define TF_Shadow         0x00001000 /* True for a shadow table */
002436  #define TF_HasStat4       0x00002000 /* STAT4 info available for this table */
002437  #define TF_Ephemeral      0x00004000 /* An ephemeral table */
002438  #define TF_Eponymous      0x00008000 /* An eponymous virtual table */
002439  #define TF_Strict         0x00010000 /* STRICT mode */
002440  
002441  /*
002442  ** Allowed values for Table.eTabType
002443  */
002444  #define TABTYP_NORM      0     /* Ordinary table */
002445  #define TABTYP_VTAB      1     /* Virtual table */
002446  #define TABTYP_VIEW      2     /* A view */
002447  
002448  #define IsView(X)           ((X)->eTabType==TABTYP_VIEW)
002449  #define IsOrdinaryTable(X)  ((X)->eTabType==TABTYP_NORM)
002450  
002451  /*
002452  ** Test to see whether or not a table is a virtual table.  This is
002453  ** done as a macro so that it will be optimized out when virtual
002454  ** table support is omitted from the build.
002455  */
002456  #ifndef SQLITE_OMIT_VIRTUALTABLE
002457  #  define IsVirtual(X)      ((X)->eTabType==TABTYP_VTAB)
002458  #  define ExprIsVtab(X)  \
002459     ((X)->op==TK_COLUMN && (X)->y.pTab->eTabType==TABTYP_VTAB)
002460  #else
002461  #  define IsVirtual(X)      0
002462  #  define ExprIsVtab(X)     0
002463  #endif
002464  
002465  /*
002466  ** Macros to determine if a column is hidden.  IsOrdinaryHiddenColumn()
002467  ** only works for non-virtual tables (ordinary tables and views) and is
002468  ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined.  The
002469  ** IsHiddenColumn() macro is general purpose.
002470  */
002471  #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
002472  #  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
002473  #  define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
002474  #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
002475  #  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
002476  #  define IsOrdinaryHiddenColumn(X) 0
002477  #else
002478  #  define IsHiddenColumn(X)         0
002479  #  define IsOrdinaryHiddenColumn(X) 0
002480  #endif
002481  
002482  
002483  /* Does the table have a rowid */
002484  #define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
002485  #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
002486  
002487  /*
002488  ** Each foreign key constraint is an instance of the following structure.
002489  **
002490  ** A foreign key is associated with two tables.  The "from" table is
002491  ** the table that contains the REFERENCES clause that creates the foreign
002492  ** key.  The "to" table is the table that is named in the REFERENCES clause.
002493  ** Consider this example:
002494  **
002495  **     CREATE TABLE ex1(
002496  **       a INTEGER PRIMARY KEY,
002497  **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
002498  **     );
002499  **
002500  ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
002501  ** Equivalent names:
002502  **
002503  **     from-table == child-table
002504  **       to-table == parent-table
002505  **
002506  ** Each REFERENCES clause generates an instance of the following structure
002507  ** which is attached to the from-table.  The to-table need not exist when
002508  ** the from-table is created.  The existence of the to-table is not checked.
002509  **
002510  ** The list of all parents for child Table X is held at X.pFKey.
002511  **
002512  ** A list of all children for a table named Z (which might not even exist)
002513  ** is held in Schema.fkeyHash with a hash key of Z.
002514  */
002515  struct FKey {
002516    Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
002517    FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
002518    char *zTo;        /* Name of table that the key points to (aka: Parent) */
002519    FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
002520    FKey *pPrevTo;    /* Previous with the same zTo */
002521    int nCol;         /* Number of columns in this key */
002522    /* EV: R-30323-21917 */
002523    u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
002524    u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
002525    Trigger *apTrigger[2];/* Triggers for aAction[] actions */
002526    struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
002527      int iFrom;            /* Index of column in pFrom */
002528      char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
002529    } aCol[1];            /* One entry for each of nCol columns */
002530  };
002531  
002532  /*
002533  ** SQLite supports many different ways to resolve a constraint
002534  ** error.  ROLLBACK processing means that a constraint violation
002535  ** causes the operation in process to fail and for the current transaction
002536  ** to be rolled back.  ABORT processing means the operation in process
002537  ** fails and any prior changes from that one operation are backed out,
002538  ** but the transaction is not rolled back.  FAIL processing means that
002539  ** the operation in progress stops and returns an error code.  But prior
002540  ** changes due to the same operation are not backed out and no rollback
002541  ** occurs.  IGNORE means that the particular row that caused the constraint
002542  ** error is not inserted or updated.  Processing continues and no error
002543  ** is returned.  REPLACE means that preexisting database rows that caused
002544  ** a UNIQUE constraint violation are removed so that the new insert or
002545  ** update can proceed.  Processing continues and no error is reported.
002546  ** UPDATE applies to insert operations only and means that the insert
002547  ** is omitted and the DO UPDATE clause of an upsert is run instead.
002548  **
002549  ** RESTRICT, SETNULL, SETDFLT, and CASCADE actions apply only to foreign keys.
002550  ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
002551  ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
002552  ** key is set to NULL.  SETDFLT means that the foreign key is set
002553  ** to its default value.  CASCADE means that a DELETE or UPDATE of the
002554  ** referenced table row is propagated into the row that holds the
002555  ** foreign key.
002556  **
002557  ** The OE_Default value is a place holder that means to use whatever
002558  ** conflict resolution algorithm is required from context.
002559  **
002560  ** The following symbolic values are used to record which type
002561  ** of conflict resolution action to take.
002562  */
002563  #define OE_None     0   /* There is no constraint to check */
002564  #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
002565  #define OE_Abort    2   /* Back out changes but do no rollback transaction */
002566  #define OE_Fail     3   /* Stop the operation but leave all prior changes */
002567  #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
002568  #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
002569  #define OE_Update   6   /* Process as a DO UPDATE in an upsert */
002570  #define OE_Restrict 7   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
002571  #define OE_SetNull  8   /* Set the foreign key value to NULL */
002572  #define OE_SetDflt  9   /* Set the foreign key value to its default */
002573  #define OE_Cascade  10  /* Cascade the changes */
002574  #define OE_Default  11  /* Do whatever the default action is */
002575  
002576  
002577  /*
002578  ** An instance of the following structure is passed as the first
002579  ** argument to sqlite3VdbeKeyCompare and is used to control the
002580  ** comparison of the two index keys.
002581  **
002582  ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
002583  ** are nField slots for the columns of an index then one extra slot
002584  ** for the rowid at the end.
002585  */
002586  struct KeyInfo {
002587    u32 nRef;           /* Number of references to this KeyInfo object */
002588    u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
002589    u16 nKeyField;      /* Number of key columns in the index */
002590    u16 nAllField;      /* Total columns, including key plus others */
002591    sqlite3 *db;        /* The database connection */
002592    u8 *aSortFlags;     /* Sort order for each column. */
002593    CollSeq *aColl[1];  /* Collating sequence for each term of the key */
002594  };
002595  
002596  /*
002597  ** Allowed bit values for entries in the KeyInfo.aSortFlags[] array.
002598  */
002599  #define KEYINFO_ORDER_DESC    0x01    /* DESC sort order */
002600  #define KEYINFO_ORDER_BIGNULL 0x02    /* NULL is larger than any other value */
002601  
002602  /*
002603  ** This object holds a record which has been parsed out into individual
002604  ** fields, for the purposes of doing a comparison.
002605  **
002606  ** A record is an object that contains one or more fields of data.
002607  ** Records are used to store the content of a table row and to store
002608  ** the key of an index.  A blob encoding of a record is created by
002609  ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
002610  ** OP_Column opcode.
002611  **
002612  ** An instance of this object serves as a "key" for doing a search on
002613  ** an index b+tree. The goal of the search is to find the entry that
002614  ** is closed to the key described by this object.  This object might hold
002615  ** just a prefix of the key.  The number of fields is given by
002616  ** pKeyInfo->nField.
002617  **
002618  ** The r1 and r2 fields are the values to return if this key is less than
002619  ** or greater than a key in the btree, respectively.  These are normally
002620  ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
002621  ** is in DESC order.
002622  **
002623  ** The key comparison functions actually return default_rc when they find
002624  ** an equals comparison.  default_rc can be -1, 0, or +1.  If there are
002625  ** multiple entries in the b-tree with the same key (when only looking
002626  ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
002627  ** cause the search to find the last match, or +1 to cause the search to
002628  ** find the first match.
002629  **
002630  ** The key comparison functions will set eqSeen to true if they ever
002631  ** get and equal results when comparing this structure to a b-tree record.
002632  ** When default_rc!=0, the search might end up on the record immediately
002633  ** before the first match or immediately after the last match.  The
002634  ** eqSeen field will indicate whether or not an exact match exists in the
002635  ** b-tree.
002636  */
002637  struct UnpackedRecord {
002638    KeyInfo *pKeyInfo;  /* Collation and sort-order information */
002639    Mem *aMem;          /* Values */
002640    union {
002641      char *z;            /* Cache of aMem[0].z for vdbeRecordCompareString() */
002642      i64 i;              /* Cache of aMem[0].u.i for vdbeRecordCompareInt() */
002643    } u;
002644    int n;              /* Cache of aMem[0].n used by vdbeRecordCompareString() */
002645    u16 nField;         /* Number of entries in apMem[] */
002646    i8 default_rc;      /* Comparison result if keys are equal */
002647    u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
002648    i8 r1;              /* Value to return if (lhs < rhs) */
002649    i8 r2;              /* Value to return if (lhs > rhs) */
002650    u8 eqSeen;          /* True if an equality comparison has been seen */
002651  };
002652  
002653  
002654  /*
002655  ** Each SQL index is represented in memory by an
002656  ** instance of the following structure.
002657  **
002658  ** The columns of the table that are to be indexed are described
002659  ** by the aiColumn[] field of this structure.  For example, suppose
002660  ** we have the following table and index:
002661  **
002662  **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
002663  **     CREATE INDEX Ex2 ON Ex1(c3,c1);
002664  **
002665  ** In the Table structure describing Ex1, nCol==3 because there are
002666  ** three columns in the table.  In the Index structure describing
002667  ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
002668  ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
002669  ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
002670  ** The second column to be indexed (c1) has an index of 0 in
002671  ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
002672  **
002673  ** The Index.onError field determines whether or not the indexed columns
002674  ** must be unique and what to do if they are not.  When Index.onError=OE_None,
002675  ** it means this is not a unique index.  Otherwise it is a unique index
002676  ** and the value of Index.onError indicates which conflict resolution
002677  ** algorithm to employ when an attempt is made to insert a non-unique
002678  ** element.
002679  **
002680  ** The colNotIdxed bitmask is used in combination with SrcItem.colUsed
002681  ** for a fast test to see if an index can serve as a covering index.
002682  ** colNotIdxed has a 1 bit for every column of the original table that
002683  ** is *not* available in the index.  Thus the expression
002684  ** "colUsed & colNotIdxed" will be non-zero if the index is not a
002685  ** covering index.  The most significant bit of of colNotIdxed will always
002686  ** be true (note-20221022-a).  If a column beyond the 63rd column of the
002687  ** table is used, the "colUsed & colNotIdxed" test will always be non-zero
002688  ** and we have to assume either that the index is not covering, or use
002689  ** an alternative (slower) algorithm to determine whether or not
002690  ** the index is covering.
002691  **
002692  ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
002693  ** generate VDBE code (as opposed to parsing one read from an sqlite_schema
002694  ** table as part of parsing an existing database schema), transient instances
002695  ** of this structure may be created. In this case the Index.tnum variable is
002696  ** used to store the address of a VDBE instruction, not a database page
002697  ** number (it cannot - the database page is not allocated until the VDBE
002698  ** program is executed). See convertToWithoutRowidTable() for details.
002699  */
002700  struct Index {
002701    char *zName;             /* Name of this index */
002702    i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
002703    LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
002704    Table *pTable;           /* The SQL table being indexed */
002705    char *zColAff;           /* String defining the affinity of each column */
002706    Index *pNext;            /* The next index associated with the same table */
002707    Schema *pSchema;         /* Schema containing this index */
002708    u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
002709    const char **azColl;     /* Array of collation sequence names for index */
002710    Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
002711    ExprList *aColExpr;      /* Column expressions */
002712    Pgno tnum;               /* DB Page containing root of this index */
002713    LogEst szIdxRow;         /* Estimated average row size in bytes */
002714    u16 nKeyCol;             /* Number of columns forming the key */
002715    u16 nColumn;             /* Number of columns stored in the index */
002716    u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
002717    unsigned idxType:2;      /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */
002718    unsigned bUnordered:1;   /* Use this index for == or IN queries only */
002719    unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
002720    unsigned isResized:1;    /* True if resizeIndexObject() has been called */
002721    unsigned isCovering:1;   /* True if this is a covering index */
002722    unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
002723    unsigned hasStat1:1;     /* aiRowLogEst values come from sqlite_stat1 */
002724    unsigned bNoQuery:1;     /* Do not use this index to optimize queries */
002725    unsigned bAscKeyBug:1;   /* True if the bba7b69f9849b5bf bug applies */
002726    unsigned bHasVCol:1;     /* Index references one or more VIRTUAL columns */
002727    unsigned bHasExpr:1;     /* Index contains an expression, either a literal
002728                             ** expression, or a reference to a VIRTUAL column */
002729  #ifdef SQLITE_ENABLE_STAT4
002730    int nSample;             /* Number of elements in aSample[] */
002731    int mxSample;            /* Number of slots allocated to aSample[] */
002732    int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
002733    tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
002734    IndexSample *aSample;    /* Samples of the left-most key */
002735    tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
002736    tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
002737  #endif
002738    Bitmask colNotIdxed;     /* Unindexed columns in pTab */
002739  };
002740  
002741  /*
002742  ** Allowed values for Index.idxType
002743  */
002744  #define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
002745  #define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
002746  #define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
002747  #define SQLITE_IDXTYPE_IPK         3   /* INTEGER PRIMARY KEY index */
002748  
002749  /* Return true if index X is a PRIMARY KEY index */
002750  #define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
002751  
002752  /* Return true if index X is a UNIQUE index */
002753  #define IsUniqueIndex(X)      ((X)->onError!=OE_None)
002754  
002755  /* The Index.aiColumn[] values are normally positive integer.  But
002756  ** there are some negative values that have special meaning:
002757  */
002758  #define XN_ROWID     (-1)     /* Indexed column is the rowid */
002759  #define XN_EXPR      (-2)     /* Indexed column is an expression */
002760  
002761  /*
002762  ** Each sample stored in the sqlite_stat4 table is represented in memory
002763  ** using a structure of this type.  See documentation at the top of the
002764  ** analyze.c source file for additional information.
002765  */
002766  struct IndexSample {
002767    void *p;          /* Pointer to sampled record */
002768    int n;            /* Size of record in bytes */
002769    tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
002770    tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
002771    tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
002772  };
002773  
002774  /*
002775  ** Possible values to use within the flags argument to sqlite3GetToken().
002776  */
002777  #define SQLITE_TOKEN_QUOTED    0x1 /* Token is a quoted identifier. */
002778  #define SQLITE_TOKEN_KEYWORD   0x2 /* Token is a keyword. */
002779  
002780  /*
002781  ** Each token coming out of the lexer is an instance of
002782  ** this structure.  Tokens are also used as part of an expression.
002783  **
002784  ** The memory that "z" points to is owned by other objects.  Take care
002785  ** that the owner of the "z" string does not deallocate the string before
002786  ** the Token goes out of scope!  Very often, the "z" points to some place
002787  ** in the middle of the Parse.zSql text.  But it might also point to a
002788  ** static string.
002789  */
002790  struct Token {
002791    const char *z;     /* Text of the token.  Not NULL-terminated! */
002792    unsigned int n;    /* Number of characters in this token */
002793  };
002794  
002795  /*
002796  ** An instance of this structure contains information needed to generate
002797  ** code for a SELECT that contains aggregate functions.
002798  **
002799  ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
002800  ** pointer to this structure.  The Expr.iAgg field is the index in
002801  ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
002802  ** code for that node.
002803  **
002804  ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
002805  ** original Select structure that describes the SELECT statement.  These
002806  ** fields do not need to be freed when deallocating the AggInfo structure.
002807  */
002808  struct AggInfo {
002809    u8 directMode;          /* Direct rendering mode means take data directly
002810                            ** from source tables rather than from accumulators */
002811    u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
002812                            ** than the source table */
002813    u16 nSortingColumn;     /* Number of columns in the sorting index */
002814    int sortingIdx;         /* Cursor number of the sorting index */
002815    int sortingIdxPTab;     /* Cursor number of pseudo-table */
002816    int iFirstReg;          /* First register in range for aCol[] and aFunc[] */
002817    ExprList *pGroupBy;     /* The group by clause */
002818    struct AggInfo_col {    /* For each column used in source tables */
002819      Table *pTab;             /* Source table */
002820      Expr *pCExpr;            /* The original expression */
002821      int iTable;              /* Cursor number of the source table */
002822      i16 iColumn;             /* Column number within the source table */
002823      i16 iSorterColumn;       /* Column number in the sorting index */
002824    } *aCol;
002825    int nColumn;            /* Number of used entries in aCol[] */
002826    int nAccumulator;       /* Number of columns that show through to the output.
002827                            ** Additional columns are used only as parameters to
002828                            ** aggregate functions */
002829    struct AggInfo_func {   /* For each aggregate function */
002830      Expr *pFExpr;            /* Expression encoding the function */
002831      FuncDef *pFunc;          /* The aggregate function implementation */
002832      int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
002833      int iDistAddr;           /* Address of OP_OpenEphemeral */
002834    } *aFunc;
002835    int nFunc;              /* Number of entries in aFunc[] */
002836    u32 selId;              /* Select to which this AggInfo belongs */
002837  #ifdef SQLITE_DEBUG
002838    Select *pSelect;        /* SELECT statement that this AggInfo supports */
002839  #endif
002840  };
002841  
002842  /*
002843  ** Macros to compute aCol[] and aFunc[] register numbers.
002844  **
002845  ** These macros should not be used prior to the call to
002846  ** assignAggregateRegisters() that computes the value of pAggInfo->iFirstReg.
002847  ** The assert()s that are part of this macro verify that constraint.
002848  */
002849  #define AggInfoColumnReg(A,I)  (assert((A)->iFirstReg),(A)->iFirstReg+(I))
002850  #define AggInfoFuncReg(A,I)    \
002851                        (assert((A)->iFirstReg),(A)->iFirstReg+(A)->nColumn+(I))
002852  
002853  /*
002854  ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
002855  ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
002856  ** than 32767 we have to make it 32-bit.  16-bit is preferred because
002857  ** it uses less memory in the Expr object, which is a big memory user
002858  ** in systems with lots of prepared statements.  And few applications
002859  ** need more than about 10 or 20 variables.  But some extreme users want
002860  ** to have prepared statements with over 32766 variables, and for them
002861  ** the option is available (at compile-time).
002862  */
002863  #if SQLITE_MAX_VARIABLE_NUMBER<32767
002864  typedef i16 ynVar;
002865  #else
002866  typedef int ynVar;
002867  #endif
002868  
002869  /*
002870  ** Each node of an expression in the parse tree is an instance
002871  ** of this structure.
002872  **
002873  ** Expr.op is the opcode. The integer parser token codes are reused
002874  ** as opcodes here. For example, the parser defines TK_GE to be an integer
002875  ** code representing the ">=" operator. This same integer code is reused
002876  ** to represent the greater-than-or-equal-to operator in the expression
002877  ** tree.
002878  **
002879  ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
002880  ** or TK_STRING), then Expr.u.zToken contains the text of the SQL literal. If
002881  ** the expression is a variable (TK_VARIABLE), then Expr.u.zToken contains the
002882  ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
002883  ** then Expr.u.zToken contains the name of the function.
002884  **
002885  ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
002886  ** binary operator. Either or both may be NULL.
002887  **
002888  ** Expr.x.pList is a list of arguments if the expression is an SQL function,
002889  ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
002890  ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
002891  ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
002892  ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
002893  ** valid.
002894  **
002895  ** An expression of the form ID or ID.ID refers to a column in a table.
002896  ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
002897  ** the integer cursor number of a VDBE cursor pointing to that table and
002898  ** Expr.iColumn is the column number for the specific column.  If the
002899  ** expression is used as a result in an aggregate SELECT, then the
002900  ** value is also stored in the Expr.iAgg column in the aggregate so that
002901  ** it can be accessed after all aggregates are computed.
002902  **
002903  ** If the expression is an unbound variable marker (a question mark
002904  ** character '?' in the original SQL) then the Expr.iTable holds the index
002905  ** number for that variable.
002906  **
002907  ** If the expression is a subquery then Expr.iColumn holds an integer
002908  ** register number containing the result of the subquery.  If the
002909  ** subquery gives a constant result, then iTable is -1.  If the subquery
002910  ** gives a different answer at different times during statement processing
002911  ** then iTable is the address of a subroutine that computes the subquery.
002912  **
002913  ** If the Expr is of type OP_Column, and the table it is selecting from
002914  ** is a disk table or the "old.*" pseudo-table, then pTab points to the
002915  ** corresponding table definition.
002916  **
002917  ** ALLOCATION NOTES:
002918  **
002919  ** Expr objects can use a lot of memory space in database schema.  To
002920  ** help reduce memory requirements, sometimes an Expr object will be
002921  ** truncated.  And to reduce the number of memory allocations, sometimes
002922  ** two or more Expr objects will be stored in a single memory allocation,
002923  ** together with Expr.u.zToken strings.
002924  **
002925  ** If the EP_Reduced and EP_TokenOnly flags are set when
002926  ** an Expr object is truncated.  When EP_Reduced is set, then all
002927  ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
002928  ** are contained within the same memory allocation.  Note, however, that
002929  ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
002930  ** allocated, regardless of whether or not EP_Reduced is set.
002931  */
002932  struct Expr {
002933    u8 op;                 /* Operation performed by this node */
002934    char affExpr;          /* affinity, or RAISE type */
002935    u8 op2;                /* TK_REGISTER/TK_TRUTH: original value of Expr.op
002936                           ** TK_COLUMN: the value of p5 for OP_Column
002937                           ** TK_AGG_FUNCTION: nesting depth
002938                           ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */
002939  #ifdef SQLITE_DEBUG
002940    u8 vvaFlags;           /* Verification flags. */
002941  #endif
002942    u32 flags;             /* Various flags.  EP_* See below */
002943    union {
002944      char *zToken;          /* Token value. Zero terminated and dequoted */
002945      int iValue;            /* Non-negative integer value if EP_IntValue */
002946    } u;
002947  
002948    /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
002949    ** space is allocated for the fields below this point. An attempt to
002950    ** access them will result in a segfault or malfunction.
002951    *********************************************************************/
002952  
002953    Expr *pLeft;           /* Left subnode */
002954    Expr *pRight;          /* Right subnode */
002955    union {
002956      ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
002957      Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
002958    } x;
002959  
002960    /* If the EP_Reduced flag is set in the Expr.flags mask, then no
002961    ** space is allocated for the fields below this point. An attempt to
002962    ** access them will result in a segfault or malfunction.
002963    *********************************************************************/
002964  
002965  #if SQLITE_MAX_EXPR_DEPTH>0
002966    int nHeight;           /* Height of the tree headed by this node */
002967  #endif
002968    int iTable;            /* TK_COLUMN: cursor number of table holding column
002969                           ** TK_REGISTER: register number
002970                           ** TK_TRIGGER: 1 -> new, 0 -> old
002971                           ** EP_Unlikely:  134217728 times likelihood
002972                           ** TK_IN: ephemeral table holding RHS
002973                           ** TK_SELECT_COLUMN: Number of columns on the LHS
002974                           ** TK_SELECT: 1st register of result vector */
002975    ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
002976                           ** TK_VARIABLE: variable number (always >= 1).
002977                           ** TK_SELECT_COLUMN: column of the result vector */
002978    i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
002979    union {
002980      int iJoin;             /* If EP_OuterON or EP_InnerON, the right table */
002981      int iOfst;             /* else: start of token from start of statement */
002982    } w;
002983    AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
002984    union {
002985      Table *pTab;           /* TK_COLUMN: Table containing column. Can be NULL
002986                             ** for a column of an index on an expression */
002987      Window *pWin;          /* EP_WinFunc: Window/Filter defn for a function */
002988      struct {               /* TK_IN, TK_SELECT, and TK_EXISTS */
002989        int iAddr;             /* Subroutine entry address */
002990        int regReturn;         /* Register used to hold return address */
002991      } sub;
002992    } y;
002993  };
002994  
002995  /* The following are the meanings of bits in the Expr.flags field.
002996  ** Value restrictions:
002997  **
002998  **          EP_Agg == NC_HasAgg == SF_HasAgg
002999  **          EP_Win == NC_HasWin
003000  */
003001  #define EP_OuterON    0x000001 /* Originates in ON/USING clause of outer join */
003002  #define EP_InnerON    0x000002 /* Originates in ON/USING of an inner join */
003003  #define EP_Distinct   0x000004 /* Aggregate function with DISTINCT keyword */
003004  #define EP_HasFunc    0x000008 /* Contains one or more functions of any kind */
003005  #define EP_Agg        0x000010 /* Contains one or more aggregate functions */
003006  #define EP_FixedCol   0x000020 /* TK_Column with a known fixed value */
003007  #define EP_VarSelect  0x000040 /* pSelect is correlated, not constant */
003008  #define EP_DblQuoted  0x000080 /* token.z was originally in "..." */
003009  #define EP_InfixFunc  0x000100 /* True for an infix function: LIKE, GLOB, etc */
003010  #define EP_Collate    0x000200 /* Tree contains a TK_COLLATE operator */
003011  #define EP_Commuted   0x000400 /* Comparison operator has been commuted */
003012  #define EP_IntValue   0x000800 /* Integer value contained in u.iValue */
003013  #define EP_xIsSelect  0x001000 /* x.pSelect is valid (otherwise x.pList is) */
003014  #define EP_Skip       0x002000 /* Operator does not contribute to affinity */
003015  #define EP_Reduced    0x004000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
003016  #define EP_Win        0x008000 /* Contains window functions */
003017  #define EP_TokenOnly  0x010000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
003018                     /* 0x020000 // Available for reuse */
003019  #define EP_IfNullRow  0x040000 /* The TK_IF_NULL_ROW opcode */
003020  #define EP_Unlikely   0x080000 /* unlikely() or likelihood() function */
003021  #define EP_ConstFunc  0x100000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
003022  #define EP_CanBeNull  0x200000 /* Can be null despite NOT NULL constraint */
003023  #define EP_Subquery   0x400000 /* Tree contains a TK_SELECT operator */
003024  #define EP_Leaf       0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
003025  #define EP_WinFunc   0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
003026  #define EP_Subrtn    0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
003027  #define EP_Quoted    0x4000000 /* TK_ID was originally quoted */
003028  #define EP_Static    0x8000000 /* Held in memory not obtained from malloc() */
003029  #define EP_IsTrue   0x10000000 /* Always has boolean value of TRUE */
003030  #define EP_IsFalse  0x20000000 /* Always has boolean value of FALSE */
003031  #define EP_FromDDL  0x40000000 /* Originates from sqlite_schema */
003032                 /*   0x80000000 // Available */
003033  
003034  /* The EP_Propagate mask is a set of properties that automatically propagate
003035  ** upwards into parent nodes.
003036  */
003037  #define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
003038  
003039  /* Macros can be used to test, set, or clear bits in the
003040  ** Expr.flags field.
003041  */
003042  #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
003043  #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
003044  #define ExprSetProperty(E,P)     (E)->flags|=(P)
003045  #define ExprClearProperty(E,P)   (E)->flags&=~(P)
003046  #define ExprAlwaysTrue(E)   (((E)->flags&(EP_OuterON|EP_IsTrue))==EP_IsTrue)
003047  #define ExprAlwaysFalse(E)  (((E)->flags&(EP_OuterON|EP_IsFalse))==EP_IsFalse)
003048  
003049  /* Macros used to ensure that the correct members of unions are accessed
003050  ** in Expr.
003051  */
003052  #define ExprUseUToken(E)    (((E)->flags&EP_IntValue)==0)
003053  #define ExprUseUValue(E)    (((E)->flags&EP_IntValue)!=0)
003054  #define ExprUseWOfst(E)     (((E)->flags&(EP_InnerON|EP_OuterON))==0)
003055  #define ExprUseWJoin(E)     (((E)->flags&(EP_InnerON|EP_OuterON))!=0)
003056  #define ExprUseXList(E)     (((E)->flags&EP_xIsSelect)==0)
003057  #define ExprUseXSelect(E)   (((E)->flags&EP_xIsSelect)!=0)
003058  #define ExprUseYTab(E)      (((E)->flags&(EP_WinFunc|EP_Subrtn))==0)
003059  #define ExprUseYWin(E)      (((E)->flags&EP_WinFunc)!=0)
003060  #define ExprUseYSub(E)      (((E)->flags&EP_Subrtn)!=0)
003061  
003062  /* Flags for use with Expr.vvaFlags
003063  */
003064  #define EP_NoReduce   0x01  /* Cannot EXPRDUP_REDUCE this Expr */
003065  #define EP_Immutable  0x02  /* Do not change this Expr node */
003066  
003067  /* The ExprSetVVAProperty() macro is used for Verification, Validation,
003068  ** and Accreditation only.  It works like ExprSetProperty() during VVA
003069  ** processes but is a no-op for delivery.
003070  */
003071  #ifdef SQLITE_DEBUG
003072  # define ExprSetVVAProperty(E,P)   (E)->vvaFlags|=(P)
003073  # define ExprHasVVAProperty(E,P)   (((E)->vvaFlags&(P))!=0)
003074  # define ExprClearVVAProperties(E) (E)->vvaFlags = 0
003075  #else
003076  # define ExprSetVVAProperty(E,P)
003077  # define ExprHasVVAProperty(E,P)   0
003078  # define ExprClearVVAProperties(E)
003079  #endif
003080  
003081  /*
003082  ** Macros to determine the number of bytes required by a normal Expr
003083  ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
003084  ** and an Expr struct with the EP_TokenOnly flag set.
003085  */
003086  #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
003087  #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
003088  #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
003089  
003090  /*
003091  ** Flags passed to the sqlite3ExprDup() function. See the header comment
003092  ** above sqlite3ExprDup() for details.
003093  */
003094  #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
003095  
003096  /*
003097  ** True if the expression passed as an argument was a function with
003098  ** an OVER() clause (a window function).
003099  */
003100  #ifdef SQLITE_OMIT_WINDOWFUNC
003101  # define IsWindowFunc(p) 0
003102  #else
003103  # define IsWindowFunc(p) ( \
003104      ExprHasProperty((p), EP_WinFunc) && p->y.pWin->eFrmType!=TK_FILTER \
003105   )
003106  #endif
003107  
003108  /*
003109  ** A list of expressions.  Each expression may optionally have a
003110  ** name.  An expr/name combination can be used in several ways, such
003111  ** as the list of "expr AS ID" fields following a "SELECT" or in the
003112  ** list of "ID = expr" items in an UPDATE.  A list of expressions can
003113  ** also be used as the argument to a function, in which case the a.zName
003114  ** field is not used.
003115  **
003116  ** In order to try to keep memory usage down, the Expr.a.zEName field
003117  ** is used for multiple purposes:
003118  **
003119  **     eEName          Usage
003120  **    ----------       -------------------------
003121  **    ENAME_NAME       (1) the AS of result set column
003122  **                     (2) COLUMN= of an UPDATE
003123  **
003124  **    ENAME_TAB        DB.TABLE.NAME used to resolve names
003125  **                     of subqueries
003126  **
003127  **    ENAME_SPAN       Text of the original result set
003128  **                     expression.
003129  */
003130  struct ExprList {
003131    int nExpr;             /* Number of expressions on the list */
003132    int nAlloc;            /* Number of a[] slots allocated */
003133    struct ExprList_item { /* For each expression in the list */
003134      Expr *pExpr;            /* The parse tree for this expression */
003135      char *zEName;           /* Token associated with this expression */
003136      struct {
003137        u8 sortFlags;           /* Mask of KEYINFO_ORDER_* flags */
003138        unsigned eEName :2;     /* Meaning of zEName */
003139        unsigned done :1;       /* Indicates when processing is finished */
003140        unsigned reusable :1;   /* Constant expression is reusable */
003141        unsigned bSorterRef :1; /* Defer evaluation until after sorting */
003142        unsigned bNulls :1;     /* True if explicit "NULLS FIRST/LAST" */
003143        unsigned bUsed :1;      /* This column used in a SF_NestedFrom subquery */
003144        unsigned bUsingTerm:1;  /* Term from the USING clause of a NestedFrom */
003145        unsigned bNoExpand: 1;  /* Term is an auxiliary in NestedFrom and should
003146                                ** not be expanded by "*" in parent queries */
003147      } fg;
003148      union {
003149        struct {             /* Used by any ExprList other than Parse.pConsExpr */
003150          u16 iOrderByCol;      /* For ORDER BY, column number in result set */
003151          u16 iAlias;           /* Index into Parse.aAlias[] for zName */
003152        } x;
003153        int iConstExprReg;   /* Register in which Expr value is cached. Used only
003154                             ** by Parse.pConstExpr */
003155      } u;
003156    } a[1];                  /* One slot for each expression in the list */
003157  };
003158  
003159  /*
003160  ** Allowed values for Expr.a.eEName
003161  */
003162  #define ENAME_NAME  0       /* The AS clause of a result set */
003163  #define ENAME_SPAN  1       /* Complete text of the result set expression */
003164  #define ENAME_TAB   2       /* "DB.TABLE.NAME" for the result set */
003165  
003166  /*
003167  ** An instance of this structure can hold a simple list of identifiers,
003168  ** such as the list "a,b,c" in the following statements:
003169  **
003170  **      INSERT INTO t(a,b,c) VALUES ...;
003171  **      CREATE INDEX idx ON t(a,b,c);
003172  **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
003173  **
003174  ** The IdList.a.idx field is used when the IdList represents the list of
003175  ** column names after a table name in an INSERT statement.  In the statement
003176  **
003177  **     INSERT INTO t(a,b,c) ...
003178  **
003179  ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
003180  */
003181  struct IdList {
003182    int nId;         /* Number of identifiers on the list */
003183    u8 eU4;          /* Which element of a.u4 is valid */
003184    struct IdList_item {
003185      char *zName;      /* Name of the identifier */
003186      union {
003187        int idx;          /* Index in some Table.aCol[] of a column named zName */
003188        Expr *pExpr;      /* Expr to implement a USING variable -- NOT USED */
003189      } u4;
003190    } a[1];
003191  };
003192  
003193  /*
003194  ** Allowed values for IdList.eType, which determines which value of the a.u4
003195  ** is valid.
003196  */
003197  #define EU4_NONE   0   /* Does not use IdList.a.u4 */
003198  #define EU4_IDX    1   /* Uses IdList.a.u4.idx */
003199  #define EU4_EXPR   2   /* Uses IdList.a.u4.pExpr -- NOT CURRENTLY USED */
003200  
003201  /*
003202  ** The SrcItem object represents a single term in the FROM clause of a query.
003203  ** The SrcList object is mostly an array of SrcItems.
003204  **
003205  ** The jointype starts out showing the join type between the current table
003206  ** and the next table on the list.  The parser builds the list this way.
003207  ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
003208  ** jointype expresses the join between the table and the previous table.
003209  **
003210  ** In the colUsed field, the high-order bit (bit 63) is set if the table
003211  ** contains more than 63 columns and the 64-th or later column is used.
003212  **
003213  ** Union member validity:
003214  **
003215  **    u1.zIndexedBy          fg.isIndexedBy && !fg.isTabFunc
003216  **    u1.pFuncArg            fg.isTabFunc   && !fg.isIndexedBy
003217  **    u2.pIBIndex            fg.isIndexedBy && !fg.isCte
003218  **    u2.pCteUse             fg.isCte       && !fg.isIndexedBy
003219  */
003220  struct SrcItem {
003221    Schema *pSchema;  /* Schema to which this item is fixed */
003222    char *zDatabase;  /* Name of database holding this table */
003223    char *zName;      /* Name of the table */
003224    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
003225    Table *pTab;      /* An SQL table corresponding to zName */
003226    Select *pSelect;  /* A SELECT statement used in place of a table name */
003227    int addrFillSub;  /* Address of subroutine to manifest a subquery */
003228    int regReturn;    /* Register holding return address of addrFillSub */
003229    int regResult;    /* Registers holding results of a co-routine */
003230    struct {
003231      u8 jointype;      /* Type of join between this table and the previous */
003232      unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
003233      unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
003234      unsigned isTabFunc :1;     /* True if table-valued-function syntax */
003235      unsigned isCorrelated :1;  /* True if sub-query is correlated */
003236      unsigned isMaterialized:1; /* This is a materialized view */
003237      unsigned viaCoroutine :1;  /* Implemented as a co-routine */
003238      unsigned isRecursive :1;   /* True for recursive reference in WITH */
003239      unsigned fromDDL :1;       /* Comes from sqlite_schema */
003240      unsigned isCte :1;         /* This is a CTE */
003241      unsigned notCte :1;        /* This item may not match a CTE */
003242      unsigned isUsing :1;       /* u3.pUsing is valid */
003243      unsigned isOn :1;          /* u3.pOn was once valid and non-NULL */
003244      unsigned isSynthUsing :1;  /* u3.pUsing is synthesized from NATURAL */
003245      unsigned isNestedFrom :1;  /* pSelect is a SF_NestedFrom subquery */
003246    } fg;
003247    int iCursor;      /* The VDBE cursor number used to access this table */
003248    union {
003249      Expr *pOn;        /* fg.isUsing==0 =>  The ON clause of a join */
003250      IdList *pUsing;   /* fg.isUsing==1 =>  The USING clause of a join */
003251    } u3;
003252    Bitmask colUsed;  /* Bit N set if column N used. Details above for N>62 */
003253    union {
003254      char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
003255      ExprList *pFuncArg;  /* Arguments to table-valued-function */
003256    } u1;
003257    union {
003258      Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
003259      CteUse *pCteUse;  /* CTE Usage info when fg.isCte is true */
003260    } u2;
003261  };
003262  
003263  /*
003264  ** The OnOrUsing object represents either an ON clause or a USING clause.
003265  ** It can never be both at the same time, but it can be neither.
003266  */
003267  struct OnOrUsing {
003268    Expr *pOn;         /* The ON clause of a join */
003269    IdList *pUsing;    /* The USING clause of a join */
003270  };
003271  
003272  /*
003273  ** This object represents one or more tables that are the source of
003274  ** content for an SQL statement.  For example, a single SrcList object
003275  ** is used to hold the FROM clause of a SELECT statement.  SrcList also
003276  ** represents the target tables for DELETE, INSERT, and UPDATE statements.
003277  **
003278  */
003279  struct SrcList {
003280    int nSrc;        /* Number of tables or subqueries in the FROM clause */
003281    u32 nAlloc;      /* Number of entries allocated in a[] below */
003282    SrcItem a[1];    /* One entry for each identifier on the list */
003283  };
003284  
003285  /*
003286  ** Permitted values of the SrcList.a.jointype field
003287  */
003288  #define JT_INNER     0x01    /* Any kind of inner or cross join */
003289  #define JT_CROSS     0x02    /* Explicit use of the CROSS keyword */
003290  #define JT_NATURAL   0x04    /* True for a "natural" join */
003291  #define JT_LEFT      0x08    /* Left outer join */
003292  #define JT_RIGHT     0x10    /* Right outer join */
003293  #define JT_OUTER     0x20    /* The "OUTER" keyword is present */
003294  #define JT_LTORJ     0x40    /* One of the LEFT operands of a RIGHT JOIN
003295                               ** Mnemonic: Left Table Of Right Join */
003296  #define JT_ERROR     0x80    /* unknown or unsupported join type */
003297  
003298  /*
003299  ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
003300  ** and the WhereInfo.wctrlFlags member.
003301  **
003302  ** Value constraints (enforced via assert()):
003303  **     WHERE_USE_LIMIT  == SF_FixedLimit
003304  */
003305  #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
003306  #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
003307  #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
003308  #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
003309  #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
003310  #define WHERE_DUPLICATES_OK    0x0010 /* Ok to return a row more than once */
003311  #define WHERE_OR_SUBCLAUSE     0x0020 /* Processing a sub-WHERE as part of
003312                                        ** the OR optimization  */
003313  #define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */
003314  #define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
003315  #define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
003316  #define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
003317  #define WHERE_AGG_DISTINCT     0x0400 /* Query is "SELECT agg(DISTINCT ...)" */
003318  #define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
003319  #define WHERE_RIGHT_JOIN       0x1000 /* Processing a RIGHT JOIN */
003320                          /*     0x2000    not currently used */
003321  #define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
003322                          /*     0x8000    not currently used */
003323  
003324  /* Allowed return values from sqlite3WhereIsDistinct()
003325  */
003326  #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
003327  #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
003328  #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
003329  #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
003330  
003331  /*
003332  ** A NameContext defines a context in which to resolve table and column
003333  ** names.  The context consists of a list of tables (the pSrcList) field and
003334  ** a list of named expression (pEList).  The named expression list may
003335  ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
003336  ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
003337  ** pEList corresponds to the result set of a SELECT and is NULL for
003338  ** other statements.
003339  **
003340  ** NameContexts can be nested.  When resolving names, the inner-most
003341  ** context is searched first.  If no match is found, the next outer
003342  ** context is checked.  If there is still no match, the next context
003343  ** is checked.  This process continues until either a match is found
003344  ** or all contexts are check.  When a match is found, the nRef member of
003345  ** the context containing the match is incremented.
003346  **
003347  ** Each subquery gets a new NameContext.  The pNext field points to the
003348  ** NameContext in the parent query.  Thus the process of scanning the
003349  ** NameContext list corresponds to searching through successively outer
003350  ** subqueries looking for a match.
003351  */
003352  struct NameContext {
003353    Parse *pParse;       /* The parser */
003354    SrcList *pSrcList;   /* One or more tables used to resolve names */
003355    union {
003356      ExprList *pEList;    /* Optional list of result-set columns */
003357      AggInfo *pAggInfo;   /* Information about aggregates at this level */
003358      Upsert *pUpsert;     /* ON CONFLICT clause information from an upsert */
003359      int iBaseReg;        /* For TK_REGISTER when parsing RETURNING */
003360    } uNC;
003361    NameContext *pNext;  /* Next outer name context.  NULL for outermost */
003362    int nRef;            /* Number of names resolved by this context */
003363    int nNcErr;          /* Number of errors encountered while resolving names */
003364    int ncFlags;         /* Zero or more NC_* flags defined below */
003365    Select *pWinSelect;  /* SELECT statement for any window functions */
003366  };
003367  
003368  /*
003369  ** Allowed values for the NameContext, ncFlags field.
003370  **
003371  ** Value constraints (all checked via assert()):
003372  **    NC_HasAgg    == SF_HasAgg       == EP_Agg
003373  **    NC_MinMaxAgg == SF_MinMaxAgg    == SQLITE_FUNC_MINMAX
003374  **    NC_OrderAgg  == SF_OrderByReqd  == SQLITE_FUNC_ANYORDER
003375  **    NC_HasWin    == EP_Win
003376  **
003377  */
003378  #define NC_AllowAgg  0x000001 /* Aggregate functions are allowed here */
003379  #define NC_PartIdx   0x000002 /* True if resolving a partial index WHERE */
003380  #define NC_IsCheck   0x000004 /* True if resolving a CHECK constraint */
003381  #define NC_GenCol    0x000008 /* True for a GENERATED ALWAYS AS clause */
003382  #define NC_HasAgg    0x000010 /* One or more aggregate functions seen */
003383  #define NC_IdxExpr   0x000020 /* True if resolving columns of CREATE INDEX */
003384  #define NC_SelfRef   0x00002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
003385  #define NC_Subquery  0x000040 /* A subquery has been seen */
003386  #define NC_UEList    0x000080 /* True if uNC.pEList is used */
003387  #define NC_UAggInfo  0x000100 /* True if uNC.pAggInfo is used */
003388  #define NC_UUpsert   0x000200 /* True if uNC.pUpsert is used */
003389  #define NC_UBaseReg  0x000400 /* True if uNC.iBaseReg is used */
003390  #define NC_MinMaxAgg 0x001000 /* min/max aggregates seen.  See note above */
003391  #define NC_Complex   0x002000 /* True if a function or subquery seen */
003392  #define NC_AllowWin  0x004000 /* Window functions are allowed here */
003393  #define NC_HasWin    0x008000 /* One or more window functions seen */
003394  #define NC_IsDDL     0x010000 /* Resolving names in a CREATE statement */
003395  #define NC_InAggFunc 0x020000 /* True if analyzing arguments to an agg func */
003396  #define NC_FromDDL   0x040000 /* SQL text comes from sqlite_schema */
003397  #define NC_NoSelect  0x080000 /* Do not descend into sub-selects */
003398  #define NC_OrderAgg 0x8000000 /* Has an aggregate other than count/min/max */
003399  
003400  /*
003401  ** An instance of the following object describes a single ON CONFLICT
003402  ** clause in an upsert.
003403  **
003404  ** The pUpsertTarget field is only set if the ON CONFLICT clause includes
003405  ** conflict-target clause.  (In "ON CONFLICT(a,b)" the "(a,b)" is the
003406  ** conflict-target clause.)  The pUpsertTargetWhere is the optional
003407  ** WHERE clause used to identify partial unique indexes.
003408  **
003409  ** pUpsertSet is the list of column=expr terms of the UPDATE statement.
003410  ** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING.  The
003411  ** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
003412  ** WHERE clause is omitted.
003413  */
003414  struct Upsert {
003415    ExprList *pUpsertTarget;  /* Optional description of conflict target */
003416    Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
003417    ExprList *pUpsertSet;     /* The SET clause from an ON CONFLICT UPDATE */
003418    Expr *pUpsertWhere;       /* WHERE clause for the ON CONFLICT UPDATE */
003419    Upsert *pNextUpsert;      /* Next ON CONFLICT clause in the list */
003420    u8 isDoUpdate;            /* True for DO UPDATE.  False for DO NOTHING */
003421    /* Above this point is the parse tree for the ON CONFLICT clauses.
003422    ** The next group of fields stores intermediate data. */
003423    void *pToFree;            /* Free memory when deleting the Upsert object */
003424    /* All fields above are owned by the Upsert object and must be freed
003425    ** when the Upsert is destroyed.  The fields below are used to transfer
003426    ** information from the INSERT processing down into the UPDATE processing
003427    ** while generating code.  The fields below are owned by the INSERT
003428    ** statement and will be freed by INSERT processing. */
003429    Index *pUpsertIdx;        /* UNIQUE constraint specified by pUpsertTarget */
003430    SrcList *pUpsertSrc;      /* Table to be updated */
003431    int regData;              /* First register holding array of VALUES */
003432    int iDataCur;             /* Index of the data cursor */
003433    int iIdxCur;              /* Index of the first index cursor */
003434  };
003435  
003436  /*
003437  ** An instance of the following structure contains all information
003438  ** needed to generate code for a single SELECT statement.
003439  **
003440  ** See the header comment on the computeLimitRegisters() routine for a
003441  ** detailed description of the meaning of the iLimit and iOffset fields.
003442  **
003443  ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
003444  ** These addresses must be stored so that we can go back and fill in
003445  ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
003446  ** the number of columns in P2 can be computed at the same time
003447  ** as the OP_OpenEphm instruction is coded because not
003448  ** enough information about the compound query is known at that point.
003449  ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
003450  ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
003451  ** sequences for the ORDER BY clause.
003452  */
003453  struct Select {
003454    u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
003455    LogEst nSelectRow;     /* Estimated number of result rows */
003456    u32 selFlags;          /* Various SF_* values */
003457    int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
003458    u32 selId;             /* Unique identifier number for this SELECT */
003459    int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
003460    ExprList *pEList;      /* The fields of the result */
003461    SrcList *pSrc;         /* The FROM clause */
003462    Expr *pWhere;          /* The WHERE clause */
003463    ExprList *pGroupBy;    /* The GROUP BY clause */
003464    Expr *pHaving;         /* The HAVING clause */
003465    ExprList *pOrderBy;    /* The ORDER BY clause */
003466    Select *pPrior;        /* Prior select in a compound select statement */
003467    Select *pNext;         /* Next select to the left in a compound */
003468    Expr *pLimit;          /* LIMIT expression. NULL means not used. */
003469    With *pWith;           /* WITH clause attached to this select. Or NULL. */
003470  #ifndef SQLITE_OMIT_WINDOWFUNC
003471    Window *pWin;          /* List of window functions */
003472    Window *pWinDefn;      /* List of named window definitions */
003473  #endif
003474  };
003475  
003476  /*
003477  ** Allowed values for Select.selFlags.  The "SF" prefix stands for
003478  ** "Select Flag".
003479  **
003480  ** Value constraints (all checked via assert())
003481  **     SF_HasAgg      == NC_HasAgg
003482  **     SF_MinMaxAgg   == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
003483  **     SF_OrderByReqd == NC_OrderAgg      == SQLITE_FUNC_ANYORDER
003484  **     SF_FixedLimit  == WHERE_USE_LIMIT
003485  */
003486  #define SF_Distinct      0x0000001 /* Output should be DISTINCT */
003487  #define SF_All           0x0000002 /* Includes the ALL keyword */
003488  #define SF_Resolved      0x0000004 /* Identifiers have been resolved */
003489  #define SF_Aggregate     0x0000008 /* Contains agg functions or a GROUP BY */
003490  #define SF_HasAgg        0x0000010 /* Contains aggregate functions */
003491  #define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */
003492  #define SF_Expanded      0x0000040 /* sqlite3SelectExpand() called on this */
003493  #define SF_HasTypeInfo   0x0000080 /* FROM subqueries have Table metadata */
003494  #define SF_Compound      0x0000100 /* Part of a compound query */
003495  #define SF_Values        0x0000200 /* Synthesized from VALUES clause */
003496  #define SF_MultiValue    0x0000400 /* Single VALUES term with multiple rows */
003497  #define SF_NestedFrom    0x0000800 /* Part of a parenthesized FROM clause */
003498  #define SF_MinMaxAgg     0x0001000 /* Aggregate containing min() or max() */
003499  #define SF_Recursive     0x0002000 /* The recursive part of a recursive CTE */
003500  #define SF_FixedLimit    0x0004000 /* nSelectRow set by a constant LIMIT */
003501  #define SF_MaybeConvert  0x0008000 /* Need convertCompoundSelectToSubquery() */
003502  #define SF_Converted     0x0010000 /* By convertCompoundSelectToSubquery() */
003503  #define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */
003504  #define SF_ComplexResult 0x0040000 /* Result contains subquery or function */
003505  #define SF_WhereBegin    0x0080000 /* Really a WhereBegin() call.  Debug Only */
003506  #define SF_WinRewrite    0x0100000 /* Window function rewrite accomplished */
003507  #define SF_View          0x0200000 /* SELECT statement is a view */
003508  #define SF_NoopOrderBy   0x0400000 /* ORDER BY is ignored for this query */
003509  #define SF_UFSrcCheck    0x0800000 /* Check pSrc as required by UPDATE...FROM */
003510  #define SF_PushDown      0x1000000 /* SELECT has be modified by push-down opt */
003511  #define SF_MultiPart     0x2000000 /* Has multiple incompatible PARTITIONs */
003512  #define SF_CopyCte       0x4000000 /* SELECT statement is a copy of a CTE */
003513  #define SF_OrderByReqd   0x8000000 /* The ORDER BY clause may not be omitted */
003514  #define SF_UpdateFrom   0x10000000 /* Query originates with UPDATE FROM */
003515  
003516  /* True if S exists and has SF_NestedFrom */
003517  #define IsNestedFrom(S) ((S)!=0 && ((S)->selFlags&SF_NestedFrom)!=0)
003518  
003519  /*
003520  ** The results of a SELECT can be distributed in several ways, as defined
003521  ** by one of the following macros.  The "SRT" prefix means "SELECT Result
003522  ** Type".
003523  **
003524  **     SRT_Union       Store results as a key in a temporary index
003525  **                     identified by pDest->iSDParm.
003526  **
003527  **     SRT_Except      Remove results from the temporary index pDest->iSDParm.
003528  **
003529  **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
003530  **                     set is not empty.
003531  **
003532  **     SRT_Discard     Throw the results away.  This is used by SELECT
003533  **                     statements within triggers whose only purpose is
003534  **                     the side-effects of functions.
003535  **
003536  **     SRT_Output      Generate a row of output (using the OP_ResultRow
003537  **                     opcode) for each row in the result set.
003538  **
003539  **     SRT_Mem         Only valid if the result is a single column.
003540  **                     Store the first column of the first result row
003541  **                     in register pDest->iSDParm then abandon the rest
003542  **                     of the query.  This destination implies "LIMIT 1".
003543  **
003544  **     SRT_Set         The result must be a single column.  Store each
003545  **                     row of result as the key in table pDest->iSDParm.
003546  **                     Apply the affinity pDest->affSdst before storing
003547  **                     results.  Used to implement "IN (SELECT ...)".
003548  **
003549  **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
003550  **                     the result there. The cursor is left open after
003551  **                     returning.  This is like SRT_Table except that
003552  **                     this destination uses OP_OpenEphemeral to create
003553  **                     the table first.
003554  **
003555  **     SRT_Coroutine   Generate a co-routine that returns a new row of
003556  **                     results each time it is invoked.  The entry point
003557  **                     of the co-routine is stored in register pDest->iSDParm
003558  **                     and the result row is stored in pDest->nDest registers
003559  **                     starting with pDest->iSdst.
003560  **
003561  **     SRT_Table       Store results in temporary table pDest->iSDParm.
003562  **     SRT_Fifo        This is like SRT_EphemTab except that the table
003563  **                     is assumed to already be open.  SRT_Fifo has
003564  **                     the additional property of being able to ignore
003565  **                     the ORDER BY clause.
003566  **
003567  **     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
003568  **                     But also use temporary table pDest->iSDParm+1 as
003569  **                     a record of all prior results and ignore any duplicate
003570  **                     rows.  Name means:  "Distinct Fifo".
003571  **
003572  **     SRT_Queue       Store results in priority queue pDest->iSDParm (really
003573  **                     an index).  Append a sequence number so that all entries
003574  **                     are distinct.
003575  **
003576  **     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
003577  **                     the same record has never been stored before.  The
003578  **                     index at pDest->iSDParm+1 hold all prior stores.
003579  **
003580  **     SRT_Upfrom      Store results in the temporary table already opened by
003581  **                     pDest->iSDParm. If (pDest->iSDParm<0), then the temp
003582  **                     table is an intkey table - in this case the first
003583  **                     column returned by the SELECT is used as the integer
003584  **                     key. If (pDest->iSDParm>0), then the table is an index
003585  **                     table. (pDest->iSDParm) is the number of key columns in
003586  **                     each index record in this case.
003587  */
003588  #define SRT_Union        1  /* Store result as keys in an index */
003589  #define SRT_Except       2  /* Remove result from a UNION index */
003590  #define SRT_Exists       3  /* Store 1 if the result is not empty */
003591  #define SRT_Discard      4  /* Do not save the results anywhere */
003592  #define SRT_DistFifo     5  /* Like SRT_Fifo, but unique results only */
003593  #define SRT_DistQueue    6  /* Like SRT_Queue, but unique results only */
003594  
003595  /* The DISTINCT clause is ignored for all of the above.  Not that
003596  ** IgnorableDistinct() implies IgnorableOrderby() */
003597  #define IgnorableDistinct(X) ((X->eDest)<=SRT_DistQueue)
003598  
003599  #define SRT_Queue        7  /* Store result in an queue */
003600  #define SRT_Fifo         8  /* Store result as data with an automatic rowid */
003601  
003602  /* The ORDER BY clause is ignored for all of the above */
003603  #define IgnorableOrderby(X) ((X->eDest)<=SRT_Fifo)
003604  
003605  #define SRT_Output       9  /* Output each row of result */
003606  #define SRT_Mem         10  /* Store result in a memory cell */
003607  #define SRT_Set         11  /* Store results as keys in an index */
003608  #define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
003609  #define SRT_Coroutine   13  /* Generate a single row of result */
003610  #define SRT_Table       14  /* Store result as data with an automatic rowid */
003611  #define SRT_Upfrom      15  /* Store result as data with rowid */
003612  
003613  /*
003614  ** An instance of this object describes where to put of the results of
003615  ** a SELECT statement.
003616  */
003617  struct SelectDest {
003618    u8 eDest;            /* How to dispose of the results.  One of SRT_* above. */
003619    int iSDParm;         /* A parameter used by the eDest disposal method */
003620    int iSDParm2;        /* A second parameter for the eDest disposal method */
003621    int iSdst;           /* Base register where results are written */
003622    int nSdst;           /* Number of registers allocated */
003623    char *zAffSdst;      /* Affinity used for SRT_Set */
003624    ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
003625  };
003626  
003627  /*
003628  ** During code generation of statements that do inserts into AUTOINCREMENT
003629  ** tables, the following information is attached to the Table.u.autoInc.p
003630  ** pointer of each autoincrement table to record some side information that
003631  ** the code generator needs.  We have to keep per-table autoincrement
003632  ** information in case inserts are done within triggers.  Triggers do not
003633  ** normally coordinate their activities, but we do need to coordinate the
003634  ** loading and saving of autoincrement information.
003635  */
003636  struct AutoincInfo {
003637    AutoincInfo *pNext;   /* Next info block in a list of them all */
003638    Table *pTab;          /* Table this info block refers to */
003639    int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
003640    int regCtr;           /* Memory register holding the rowid counter */
003641  };
003642  
003643  /*
003644  ** At least one instance of the following structure is created for each
003645  ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
003646  ** statement. All such objects are stored in the linked list headed at
003647  ** Parse.pTriggerPrg and deleted once statement compilation has been
003648  ** completed.
003649  **
003650  ** A Vdbe sub-program that implements the body and WHEN clause of trigger
003651  ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
003652  ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
003653  ** The Parse.pTriggerPrg list never contains two entries with the same
003654  ** values for both pTrigger and orconf.
003655  **
003656  ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
003657  ** accessed (or set to 0 for triggers fired as a result of INSERT
003658  ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
003659  ** a mask of new.* columns used by the program.
003660  */
003661  struct TriggerPrg {
003662    Trigger *pTrigger;      /* Trigger this program was coded from */
003663    TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
003664    SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
003665    int orconf;             /* Default ON CONFLICT policy */
003666    u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
003667  };
003668  
003669  /*
003670  ** The yDbMask datatype for the bitmask of all attached databases.
003671  */
003672  #if SQLITE_MAX_ATTACHED>30
003673    typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
003674  # define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
003675  # define DbMaskZero(M)      memset((M),0,sizeof(M))
003676  # define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
003677  # define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
003678  # define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
003679  #else
003680    typedef unsigned int yDbMask;
003681  # define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
003682  # define DbMaskZero(M)      ((M)=0)
003683  # define DbMaskSet(M,I)     ((M)|=(((yDbMask)1)<<(I)))
003684  # define DbMaskAllZero(M)   ((M)==0)
003685  # define DbMaskNonZero(M)   ((M)!=0)
003686  #endif
003687  
003688  /*
003689  ** For each index X that has as one of its arguments either an expression
003690  ** or the name of a virtual generated column, and if X is in scope such that
003691  ** the value of the expression can simply be read from the index, then
003692  ** there is an instance of this object on the Parse.pIdxExpr list.
003693  **
003694  ** During code generation, while generating code to evaluate expressions,
003695  ** this list is consulted and if a matching expression is found, the value
003696  ** is read from the index rather than being recomputed.
003697  */
003698  struct IndexedExpr {
003699    Expr *pExpr;            /* The expression contained in the index */
003700    int iDataCur;           /* The data cursor associated with the index */
003701    int iIdxCur;            /* The index cursor */
003702    int iIdxCol;            /* The index column that contains value of pExpr */
003703    u8 bMaybeNullRow;       /* True if we need an OP_IfNullRow check */
003704    u8 aff;                 /* Affinity of the pExpr expression */
003705    IndexedExpr *pIENext;   /* Next in a list of all indexed expressions */
003706  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
003707    const char *zIdxName;   /* Name of index, used only for bytecode comments */
003708  #endif
003709  };
003710  
003711  /*
003712  ** An instance of the ParseCleanup object specifies an operation that
003713  ** should be performed after parsing to deallocation resources obtained
003714  ** during the parse and which are no longer needed.
003715  */
003716  struct ParseCleanup {
003717    ParseCleanup *pNext;               /* Next cleanup task */
003718    void *pPtr;                        /* Pointer to object to deallocate */
003719    void (*xCleanup)(sqlite3*,void*);  /* Deallocation routine */
003720  };
003721  
003722  /*
003723  ** An SQL parser context.  A copy of this structure is passed through
003724  ** the parser and down into all the parser action routine in order to
003725  ** carry around information that is global to the entire parse.
003726  **
003727  ** The structure is divided into two parts.  When the parser and code
003728  ** generate call themselves recursively, the first part of the structure
003729  ** is constant but the second part is reset at the beginning and end of
003730  ** each recursion.
003731  **
003732  ** The nTableLock and aTableLock variables are only used if the shared-cache
003733  ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
003734  ** used to store the set of table-locks required by the statement being
003735  ** compiled. Function sqlite3TableLock() is used to add entries to the
003736  ** list.
003737  */
003738  struct Parse {
003739    sqlite3 *db;         /* The main database structure */
003740    char *zErrMsg;       /* An error message */
003741    Vdbe *pVdbe;         /* An engine for executing database bytecode */
003742    int rc;              /* Return code from execution */
003743    u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
003744    u8 checkSchema;      /* Causes schema cookie check after an error */
003745    u8 nested;           /* Number of nested calls to the parser/code generator */
003746    u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
003747    u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
003748    u8 mayAbort;         /* True if statement may throw an ABORT exception */
003749    u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
003750    u8 okConstFactor;    /* OK to factor out constants */
003751    u8 disableLookaside; /* Number of times lookaside has been disabled */
003752    u8 prepFlags;        /* SQLITE_PREPARE_* flags */
003753    u8 withinRJSubrtn;   /* Nesting level for RIGHT JOIN body subroutines */
003754  #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
003755    u8 earlyCleanup;     /* OOM inside sqlite3ParserAddCleanup() */
003756  #endif
003757  #ifdef SQLITE_DEBUG
003758    u8 ifNotExists;      /* Might be true if IF NOT EXISTS.  Assert()s only */
003759  #endif
003760    int nRangeReg;       /* Size of the temporary register block */
003761    int iRangeReg;       /* First register in temporary register block */
003762    int nErr;            /* Number of errors seen */
003763    int nTab;            /* Number of previously allocated VDBE cursors */
003764    int nMem;            /* Number of memory cells used so far */
003765    int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */
003766    int iSelfTab;        /* Table associated with an index on expr, or negative
003767                         ** of the base register during check-constraint eval */
003768    int nLabel;          /* The *negative* of the number of labels used */
003769    int nLabelAlloc;     /* Number of slots in aLabel */
003770    int *aLabel;         /* Space to hold the labels */
003771    ExprList *pConstExpr;/* Constant expressions */
003772    IndexedExpr *pIdxEpr;/* List of expressions used by active indexes */
003773    Token constraintName;/* Name of the constraint currently being parsed */
003774    yDbMask writeMask;   /* Start a write transaction on these databases */
003775    yDbMask cookieMask;  /* Bitmask of schema verified databases */
003776    int regRowid;        /* Register holding rowid of CREATE TABLE entry */
003777    int regRoot;         /* Register holding root page number for new objects */
003778    int nMaxArg;         /* Max args passed to user function by sub-program */
003779    int nSelect;         /* Number of SELECT stmts. Counter for Select.selId */
003780  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
003781    u32 nProgressSteps;  /* xProgress steps taken during sqlite3_prepare() */
003782  #endif
003783  #ifndef SQLITE_OMIT_SHARED_CACHE
003784    int nTableLock;        /* Number of locks in aTableLock */
003785    TableLock *aTableLock; /* Required table locks for shared-cache mode */
003786  #endif
003787    AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
003788    Parse *pToplevel;    /* Parse structure for main program (or NULL) */
003789    Table *pTriggerTab;  /* Table triggers are being coded for */
003790    TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
003791    ParseCleanup *pCleanup;   /* List of cleanup operations to run after parse */
003792    union {
003793      int addrCrTab;         /* Address of OP_CreateBtree on CREATE TABLE */
003794      Returning *pReturning; /* The RETURNING clause */
003795    } u1;
003796    u32 oldmask;         /* Mask of old.* columns referenced */
003797    u32 newmask;         /* Mask of new.* columns referenced */
003798    LogEst nQueryLoop;   /* Est number of iterations of a query (10*log2(N)) */
003799    u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
003800    u8 bReturning;       /* Coding a RETURNING trigger */
003801    u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
003802    u8 disableTriggers;  /* True to disable triggers */
003803  
003804    /**************************************************************************
003805    ** Fields above must be initialized to zero.  The fields that follow,
003806    ** down to the beginning of the recursive section, do not need to be
003807    ** initialized as they will be set before being used.  The boundary is
003808    ** determined by offsetof(Parse,aTempReg).
003809    **************************************************************************/
003810  
003811    int aTempReg[8];        /* Holding area for temporary registers */
003812    Parse *pOuterParse;     /* Outer Parse object when nested */
003813    Token sNameToken;       /* Token with unqualified schema object name */
003814  
003815    /************************************************************************
003816    ** Above is constant between recursions.  Below is reset before and after
003817    ** each recursion.  The boundary between these two regions is determined
003818    ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
003819    ** first field in the recursive region.
003820    ************************************************************************/
003821  
003822    Token sLastToken;       /* The last token parsed */
003823    ynVar nVar;               /* Number of '?' variables seen in the SQL so far */
003824    u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
003825    u8 explain;               /* True if the EXPLAIN flag is found on the query */
003826    u8 eParseMode;            /* PARSE_MODE_XXX constant */
003827  #ifndef SQLITE_OMIT_VIRTUALTABLE
003828    int nVtabLock;            /* Number of virtual tables to lock */
003829  #endif
003830    int nHeight;              /* Expression tree height of current sub-select */
003831  #ifndef SQLITE_OMIT_EXPLAIN
003832    int addrExplain;          /* Address of current OP_Explain opcode */
003833  #endif
003834    VList *pVList;            /* Mapping between variable names and numbers */
003835    Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
003836    const char *zTail;        /* All SQL text past the last semicolon parsed */
003837    Table *pNewTable;         /* A table being constructed by CREATE TABLE */
003838    Index *pNewIndex;         /* An index being constructed by CREATE INDEX.
003839                              ** Also used to hold redundant UNIQUE constraints
003840                              ** during a RENAME COLUMN */
003841    Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
003842    const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
003843  #ifndef SQLITE_OMIT_VIRTUALTABLE
003844    Token sArg;               /* Complete text of a module argument */
003845    Table **apVtabLock;       /* Pointer to virtual tables needing locking */
003846  #endif
003847    With *pWith;              /* Current WITH clause, or NULL */
003848  #ifndef SQLITE_OMIT_ALTERTABLE
003849    RenameToken *pRename;     /* Tokens subject to renaming by ALTER TABLE */
003850  #endif
003851  };
003852  
003853  /* Allowed values for Parse.eParseMode
003854  */
003855  #define PARSE_MODE_NORMAL        0
003856  #define PARSE_MODE_DECLARE_VTAB  1
003857  #define PARSE_MODE_RENAME        2
003858  #define PARSE_MODE_UNMAP         3
003859  
003860  /*
003861  ** Sizes and pointers of various parts of the Parse object.
003862  */
003863  #define PARSE_HDR(X)  (((char*)(X))+offsetof(Parse,zErrMsg))
003864  #define PARSE_HDR_SZ (offsetof(Parse,aTempReg)-offsetof(Parse,zErrMsg)) /* Recursive part w/o aColCache*/
003865  #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken)    /* Recursive part */
003866  #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
003867  #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ)  /* Pointer to tail */
003868  
003869  /*
003870  ** Return true if currently inside an sqlite3_declare_vtab() call.
003871  */
003872  #ifdef SQLITE_OMIT_VIRTUALTABLE
003873    #define IN_DECLARE_VTAB 0
003874  #else
003875    #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
003876  #endif
003877  
003878  #if defined(SQLITE_OMIT_ALTERTABLE)
003879    #define IN_RENAME_OBJECT 0
003880  #else
003881    #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME)
003882  #endif
003883  
003884  #if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
003885    #define IN_SPECIAL_PARSE 0
003886  #else
003887    #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
003888  #endif
003889  
003890  /*
003891  ** An instance of the following structure can be declared on a stack and used
003892  ** to save the Parse.zAuthContext value so that it can be restored later.
003893  */
003894  struct AuthContext {
003895    const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
003896    Parse *pParse;              /* The Parse structure */
003897  };
003898  
003899  /*
003900  ** Bitfield flags for P5 value in various opcodes.
003901  **
003902  ** Value constraints (enforced via assert()):
003903  **    OPFLAG_LENGTHARG    == SQLITE_FUNC_LENGTH
003904  **    OPFLAG_TYPEOFARG    == SQLITE_FUNC_TYPEOF
003905  **    OPFLAG_BULKCSR      == BTREE_BULKLOAD
003906  **    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ
003907  **    OPFLAG_FORDELETE    == BTREE_FORDELETE
003908  **    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
003909  **    OPFLAG_AUXDELETE    == BTREE_AUXDELETE
003910  */
003911  #define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */
003912                                       /* Also used in P2 (not P5) of OP_Delete */
003913  #define OPFLAG_NOCHNG        0x01    /* OP_VColumn nochange for UPDATE */
003914  #define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
003915  #define OPFLAG_LASTROWID     0x20    /* Set to update db->lastRowid */
003916  #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
003917  #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
003918  #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
003919  #define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */
003920  #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
003921  #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
003922  #define OPFLAG_BYTELENARG    0xc0    /* OP_Column only for octet_length() */
003923  #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
003924  #define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
003925  #define OPFLAG_FORDELETE     0x08    /* OP_Open should use BTREE_FORDELETE */
003926  #define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */
003927  #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
003928  #define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete/Insert: save cursor pos */
003929  #define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */
003930  #define OPFLAG_NOCHNG_MAGIC  0x6d    /* OP_MakeRecord: serialtype 10 is ok */
003931  #define OPFLAG_PREFORMAT     0x80    /* OP_Insert uses preformatted cell */
003932  
003933  /*
003934  ** Each trigger present in the database schema is stored as an instance of
003935  ** struct Trigger.
003936  **
003937  ** Pointers to instances of struct Trigger are stored in two ways.
003938  ** 1. In the "trigHash" hash table (part of the sqlite3* that represents the
003939  **    database). This allows Trigger structures to be retrieved by name.
003940  ** 2. All triggers associated with a single table form a linked list, using the
003941  **    pNext member of struct Trigger. A pointer to the first element of the
003942  **    linked list is stored as the "pTrigger" member of the associated
003943  **    struct Table.
003944  **
003945  ** The "step_list" member points to the first element of a linked list
003946  ** containing the SQL statements specified as the trigger program.
003947  */
003948  struct Trigger {
003949    char *zName;            /* The name of the trigger                        */
003950    char *table;            /* The table or view to which the trigger applies */
003951    u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
003952    u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
003953    u8 bReturning;          /* This trigger implements a RETURNING clause */
003954    Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
003955    IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
003956                               the <column-list> is stored here */
003957    Schema *pSchema;        /* Schema containing the trigger */
003958    Schema *pTabSchema;     /* Schema containing the table */
003959    TriggerStep *step_list; /* Link list of trigger program steps             */
003960    Trigger *pNext;         /* Next trigger associated with the table */
003961  };
003962  
003963  /*
003964  ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
003965  ** determine which.
003966  **
003967  ** If there are multiple triggers, you might of some BEFORE and some AFTER.
003968  ** In that cases, the constants below can be ORed together.
003969  */
003970  #define TRIGGER_BEFORE  1
003971  #define TRIGGER_AFTER   2
003972  
003973  /*
003974  ** An instance of struct TriggerStep is used to store a single SQL statement
003975  ** that is a part of a trigger-program.
003976  **
003977  ** Instances of struct TriggerStep are stored in a singly linked list (linked
003978  ** using the "pNext" member) referenced by the "step_list" member of the
003979  ** associated struct Trigger instance. The first element of the linked list is
003980  ** the first step of the trigger-program.
003981  **
003982  ** The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
003983  ** "SELECT" statement. The meanings of the other members is determined by the
003984  ** value of "op" as follows:
003985  **
003986  ** (op == TK_INSERT)
003987  ** orconf    -> stores the ON CONFLICT algorithm
003988  ** pSelect   -> The content to be inserted - either a SELECT statement or
003989  **              a VALUES clause.
003990  ** zTarget   -> Dequoted name of the table to insert into.
003991  ** pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
003992  **              statement, then this stores the column-names to be
003993  **              inserted into.
003994  ** pUpsert   -> The ON CONFLICT clauses for an Upsert
003995  **
003996  ** (op == TK_DELETE)
003997  ** zTarget   -> Dequoted name of the table to delete from.
003998  ** pWhere    -> The WHERE clause of the DELETE statement if one is specified.
003999  **              Otherwise NULL.
004000  **
004001  ** (op == TK_UPDATE)
004002  ** zTarget   -> Dequoted name of the table to update.
004003  ** pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
004004  **              Otherwise NULL.
004005  ** pExprList -> A list of the columns to update and the expressions to update
004006  **              them to. See sqlite3Update() documentation of "pChanges"
004007  **              argument.
004008  **
004009  ** (op == TK_SELECT)
004010  ** pSelect   -> The SELECT statement
004011  **
004012  ** (op == TK_RETURNING)
004013  ** pExprList -> The list of expressions that follow the RETURNING keyword.
004014  **
004015  */
004016  struct TriggerStep {
004017    u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT,
004018                         ** or TK_RETURNING */
004019    u8 orconf;           /* OE_Rollback etc. */
004020    Trigger *pTrig;      /* The trigger that this step is a part of */
004021    Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
004022    char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
004023    SrcList *pFrom;      /* FROM clause for UPDATE statement (if any) */
004024    Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
004025    ExprList *pExprList; /* SET clause for UPDATE, or RETURNING clause */
004026    IdList *pIdList;     /* Column names for INSERT */
004027    Upsert *pUpsert;     /* Upsert clauses on an INSERT */
004028    char *zSpan;         /* Original SQL text of this command */
004029    TriggerStep *pNext;  /* Next in the link-list */
004030    TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
004031  };
004032  
004033  /*
004034  ** Information about a RETURNING clause
004035  */
004036  struct Returning {
004037    Parse *pParse;        /* The parse that includes the RETURNING clause */
004038    ExprList *pReturnEL;  /* List of expressions to return */
004039    Trigger retTrig;      /* The transient trigger that implements RETURNING */
004040    TriggerStep retTStep; /* The trigger step */
004041    int iRetCur;          /* Transient table holding RETURNING results */
004042    int nRetCol;          /* Number of in pReturnEL after expansion */
004043    int iRetReg;          /* Register array for holding a row of RETURNING */
004044  };
004045  
004046  /*
004047  ** An objected used to accumulate the text of a string where we
004048  ** do not necessarily know how big the string will be in the end.
004049  */
004050  struct sqlite3_str {
004051    sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
004052    char *zText;         /* The string collected so far */
004053    u32  nAlloc;         /* Amount of space allocated in zText */
004054    u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
004055    u32  nChar;          /* Length of the string so far */
004056    u8   accError;       /* SQLITE_NOMEM or SQLITE_TOOBIG */
004057    u8   printfFlags;    /* SQLITE_PRINTF flags below */
004058  };
004059  #define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */
004060  #define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */
004061  #define SQLITE_PRINTF_MALLOCED 0x04  /* True if xText is allocated space */
004062  
004063  #define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
004064  
004065  /*
004066  ** The following object is the header for an "RCStr" or "reference-counted
004067  ** string".  An RCStr is passed around and used like any other char*
004068  ** that has been dynamically allocated.  The important interface
004069  ** differences:
004070  **
004071  **   1.  RCStr strings are reference counted.  They are deallocated
004072  **       when the reference count reaches zero.
004073  **
004074  **   2.  Use sqlite3RCStrUnref() to free an RCStr string rather than
004075  **       sqlite3_free()
004076  **
004077  **   3.  Make a (read-only) copy of a read-only RCStr string using
004078  **       sqlite3RCStrRef().
004079  */
004080  struct RCStr {
004081    u64 nRCRef;            /* Number of references */
004082    /* Total structure size should be a multiple of 8 bytes for alignment */
004083  };
004084  
004085  /*
004086  ** A pointer to this structure is used to communicate information
004087  ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
004088  */
004089  typedef struct {
004090    sqlite3 *db;        /* The database being initialized */
004091    char **pzErrMsg;    /* Error message stored here */
004092    int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
004093    int rc;             /* Result code stored here */
004094    u32 mInitFlags;     /* Flags controlling error messages */
004095    u32 nInitRow;       /* Number of rows processed */
004096    Pgno mxPage;        /* Maximum page number.  0 for no limit. */
004097  } InitData;
004098  
004099  /*
004100  ** Allowed values for mInitFlags
004101  */
004102  #define INITFLAG_AlterMask     0x0003  /* Types of ALTER */
004103  #define INITFLAG_AlterRename   0x0001  /* Reparse after a RENAME */
004104  #define INITFLAG_AlterDrop     0x0002  /* Reparse after a DROP COLUMN */
004105  #define INITFLAG_AlterAdd      0x0003  /* Reparse after an ADD COLUMN */
004106  
004107  /* Tuning parameters are set using SQLITE_TESTCTRL_TUNE and are controlled
004108  ** on debug-builds of the CLI using ".testctrl tune ID VALUE".  Tuning
004109  ** parameters are for temporary use during development, to help find
004110  ** optimal values for parameters in the query planner.  The should not
004111  ** be used on trunk check-ins.  They are a temporary mechanism available
004112  ** for transient development builds only.
004113  **
004114  ** Tuning parameters are numbered starting with 1.
004115  */
004116  #define SQLITE_NTUNE  6             /* Should be zero for all trunk check-ins */
004117  #ifdef SQLITE_DEBUG
004118  # define Tuning(X)  (sqlite3Config.aTune[(X)-1])
004119  #else
004120  # define Tuning(X)  0
004121  #endif
004122  
004123  /*
004124  ** Structure containing global configuration data for the SQLite library.
004125  **
004126  ** This structure also contains some state information.
004127  */
004128  struct Sqlite3Config {
004129    int bMemstat;                     /* True to enable memory status */
004130    u8 bCoreMutex;                    /* True to enable core mutexing */
004131    u8 bFullMutex;                    /* True to enable full mutexing */
004132    u8 bOpenUri;                      /* True to interpret filenames as URIs */
004133    u8 bUseCis;                       /* Use covering indices for full-scans */
004134    u8 bSmallMalloc;                  /* Avoid large memory allocations if true */
004135    u8 bExtraSchemaChecks;            /* Verify type,name,tbl_name in schema */
004136    u8 bUseLongDouble;                /* Make use of long double */
004137    int mxStrlen;                     /* Maximum string length */
004138    int neverCorrupt;                 /* Database is always well-formed */
004139    int szLookaside;                  /* Default lookaside buffer size */
004140    int nLookaside;                   /* Default lookaside buffer count */
004141    int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */
004142    sqlite3_mem_methods m;            /* Low-level memory allocation interface */
004143    sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
004144    sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
004145    void *pHeap;                      /* Heap storage space */
004146    int nHeap;                        /* Size of pHeap[] */
004147    int mnReq, mxReq;                 /* Min and max heap requests sizes */
004148    sqlite3_int64 szMmap;             /* mmap() space per open file */
004149    sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
004150    void *pPage;                      /* Page cache memory */
004151    int szPage;                       /* Size of each page in pPage[] */
004152    int nPage;                        /* Number of pages in pPage[] */
004153    int mxParserStack;                /* maximum depth of the parser stack */
004154    int sharedCacheEnabled;           /* true if shared-cache mode enabled */
004155    u32 szPma;                        /* Maximum Sorter PMA size */
004156    /* The above might be initialized to non-zero.  The following need to always
004157    ** initially be zero, however. */
004158    int isInit;                       /* True after initialization has finished */
004159    int inProgress;                   /* True while initialization in progress */
004160    int isMutexInit;                  /* True after mutexes are initialized */
004161    int isMallocInit;                 /* True after malloc is initialized */
004162    int isPCacheInit;                 /* True after malloc is initialized */
004163    int nRefInitMutex;                /* Number of users of pInitMutex */
004164    sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
004165    void (*xLog)(void*,int,const char*); /* Function for logging */
004166    void *pLogArg;                       /* First argument to xLog() */
004167  #ifdef SQLITE_ENABLE_SQLLOG
004168    void(*xSqllog)(void*,sqlite3*,const char*, int);
004169    void *pSqllogArg;
004170  #endif
004171  #ifdef SQLITE_VDBE_COVERAGE
004172    /* The following callback (if not NULL) is invoked on every VDBE branch
004173    ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
004174    */
004175    void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx);  /* Callback */
004176    void *pVdbeBranchArg;                                     /* 1st argument */
004177  #endif
004178  #ifndef SQLITE_OMIT_DESERIALIZE
004179    sqlite3_int64 mxMemdbSize;        /* Default max memdb size */
004180  #endif
004181  #ifndef SQLITE_UNTESTABLE
004182    int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
004183  #endif
004184    int bLocaltimeFault;              /* True to fail localtime() calls */
004185    int (*xAltLocaltime)(const void*,void*); /* Alternative localtime() routine */
004186    int iOnceResetThreshold;          /* When to reset OP_Once counters */
004187    u32 szSorterRef;                  /* Min size in bytes to use sorter-refs */
004188    unsigned int iPrngSeed;           /* Alternative fixed seed for the PRNG */
004189    /* vvvv--- must be last ---vvv */
004190  #ifdef SQLITE_DEBUG
004191    sqlite3_int64 aTune[SQLITE_NTUNE]; /* Tuning parameters */
004192  #endif
004193  };
004194  
004195  /*
004196  ** This macro is used inside of assert() statements to indicate that
004197  ** the assert is only valid on a well-formed database.  Instead of:
004198  **
004199  **     assert( X );
004200  **
004201  ** One writes:
004202  **
004203  **     assert( X || CORRUPT_DB );
004204  **
004205  ** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
004206  ** that the database is definitely corrupt, only that it might be corrupt.
004207  ** For most test cases, CORRUPT_DB is set to false using a special
004208  ** sqlite3_test_control().  This enables assert() statements to prove
004209  ** things that are always true for well-formed databases.
004210  */
004211  #define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
004212  
004213  /*
004214  ** Context pointer passed down through the tree-walk.
004215  */
004216  struct Walker {
004217    Parse *pParse;                            /* Parser context.  */
004218    int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
004219    int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
004220    void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
004221    int walkerDepth;                          /* Number of subqueries */
004222    u16 eCode;                                /* A small processing code */
004223    u16 mWFlags;                              /* Use-dependent flags */
004224    union {                                   /* Extra data for callback */
004225      NameContext *pNC;                         /* Naming context */
004226      int n;                                    /* A counter */
004227      int iCur;                                 /* A cursor number */
004228      SrcList *pSrcList;                        /* FROM clause */
004229      struct CCurHint *pCCurHint;               /* Used by codeCursorHint() */
004230      struct RefSrcList *pRefSrcList;           /* sqlite3ReferencesSrcList() */
004231      int *aiCol;                               /* array of column indexes */
004232      struct IdxCover *pIdxCover;               /* Check for index coverage */
004233      ExprList *pGroupBy;                       /* GROUP BY clause */
004234      Select *pSelect;                          /* HAVING to WHERE clause ctx */
004235      struct WindowRewrite *pRewrite;           /* Window rewrite context */
004236      struct WhereConst *pConst;                /* WHERE clause constants */
004237      struct RenameCtx *pRename;                /* RENAME COLUMN context */
004238      struct Table *pTab;                       /* Table of generated column */
004239      struct CoveringIndexCheck *pCovIdxCk;     /* Check for covering index */
004240      SrcItem *pSrcItem;                        /* A single FROM clause item */
004241      DbFixer *pFix;                            /* See sqlite3FixSelect() */
004242      Mem *aMem;                                /* See sqlite3BtreeCursorHint() */
004243    } u;
004244  };
004245  
004246  /*
004247  ** The following structure contains information used by the sqliteFix...
004248  ** routines as they walk the parse tree to make database references
004249  ** explicit.
004250  */
004251  struct DbFixer {
004252    Parse *pParse;      /* The parsing context.  Error messages written here */
004253    Walker w;           /* Walker object */
004254    Schema *pSchema;    /* Fix items to this schema */
004255    u8 bTemp;           /* True for TEMP schema entries */
004256    const char *zDb;    /* Make sure all objects are contained in this database */
004257    const char *zType;  /* Type of the container - used for error messages */
004258    const Token *pName; /* Name of the container - used for error messages */
004259  };
004260  
004261  /* Forward declarations */
004262  int sqlite3WalkExpr(Walker*, Expr*);
004263  int sqlite3WalkExprNN(Walker*, Expr*);
004264  int sqlite3WalkExprList(Walker*, ExprList*);
004265  int sqlite3WalkSelect(Walker*, Select*);
004266  int sqlite3WalkSelectExpr(Walker*, Select*);
004267  int sqlite3WalkSelectFrom(Walker*, Select*);
004268  int sqlite3ExprWalkNoop(Walker*, Expr*);
004269  int sqlite3SelectWalkNoop(Walker*, Select*);
004270  int sqlite3SelectWalkFail(Walker*, Select*);
004271  int sqlite3WalkerDepthIncrease(Walker*,Select*);
004272  void sqlite3WalkerDepthDecrease(Walker*,Select*);
004273  void sqlite3WalkWinDefnDummyCallback(Walker*,Select*);
004274  
004275  #ifdef SQLITE_DEBUG
004276  void sqlite3SelectWalkAssert2(Walker*, Select*);
004277  #endif
004278  
004279  #ifndef SQLITE_OMIT_CTE
004280  void sqlite3SelectPopWith(Walker*, Select*);
004281  #else
004282  # define sqlite3SelectPopWith 0
004283  #endif
004284  
004285  /*
004286  ** Return code from the parse-tree walking primitives and their
004287  ** callbacks.
004288  */
004289  #define WRC_Continue    0   /* Continue down into children */
004290  #define WRC_Prune       1   /* Omit children but continue walking siblings */
004291  #define WRC_Abort       2   /* Abandon the tree walk */
004292  
004293  /*
004294  ** A single common table expression
004295  */
004296  struct Cte {
004297    char *zName;            /* Name of this CTE */
004298    ExprList *pCols;        /* List of explicit column names, or NULL */
004299    Select *pSelect;        /* The definition of this CTE */
004300    const char *zCteErr;    /* Error message for circular references */
004301    CteUse *pUse;           /* Usage information for this CTE */
004302    u8 eM10d;               /* The MATERIALIZED flag */
004303  };
004304  
004305  /*
004306  ** Allowed values for the materialized flag (eM10d):
004307  */
004308  #define M10d_Yes       0  /* AS MATERIALIZED */
004309  #define M10d_Any       1  /* Not specified.  Query planner's choice */
004310  #define M10d_No        2  /* AS NOT MATERIALIZED */
004311  
004312  /*
004313  ** An instance of the With object represents a WITH clause containing
004314  ** one or more CTEs (common table expressions).
004315  */
004316  struct With {
004317    int nCte;               /* Number of CTEs in the WITH clause */
004318    int bView;              /* Belongs to the outermost Select of a view */
004319    With *pOuter;           /* Containing WITH clause, or NULL */
004320    Cte a[1];               /* For each CTE in the WITH clause.... */
004321  };
004322  
004323  /*
004324  ** The Cte object is not guaranteed to persist for the entire duration
004325  ** of code generation.  (The query flattener or other parser tree
004326  ** edits might delete it.)  The following object records information
004327  ** about each Common Table Expression that must be preserved for the
004328  ** duration of the parse.
004329  **
004330  ** The CteUse objects are freed using sqlite3ParserAddCleanup() rather
004331  ** than sqlite3SelectDelete(), which is what enables them to persist
004332  ** until the end of code generation.
004333  */
004334  struct CteUse {
004335    int nUse;              /* Number of users of this CTE */
004336    int addrM9e;           /* Start of subroutine to compute materialization */
004337    int regRtn;            /* Return address register for addrM9e subroutine */
004338    int iCur;              /* Ephemeral table holding the materialization */
004339    LogEst nRowEst;        /* Estimated number of rows in the table */
004340    u8 eM10d;              /* The MATERIALIZED flag */
004341  };
004342  
004343  
004344  #ifdef SQLITE_DEBUG
004345  /*
004346  ** An instance of the TreeView object is used for printing the content of
004347  ** data structures on sqlite3DebugPrintf() using a tree-like view.
004348  */
004349  struct TreeView {
004350    int iLevel;             /* Which level of the tree we are on */
004351    u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
004352  };
004353  #endif /* SQLITE_DEBUG */
004354  
004355  /*
004356  ** This object is used in various ways, most (but not all) related to window
004357  ** functions.
004358  **
004359  **   (1) A single instance of this structure is attached to the
004360  **       the Expr.y.pWin field for each window function in an expression tree.
004361  **       This object holds the information contained in the OVER clause,
004362  **       plus additional fields used during code generation.
004363  **
004364  **   (2) All window functions in a single SELECT form a linked-list
004365  **       attached to Select.pWin.  The Window.pFunc and Window.pExpr
004366  **       fields point back to the expression that is the window function.
004367  **
004368  **   (3) The terms of the WINDOW clause of a SELECT are instances of this
004369  **       object on a linked list attached to Select.pWinDefn.
004370  **
004371  **   (4) For an aggregate function with a FILTER clause, an instance
004372  **       of this object is stored in Expr.y.pWin with eFrmType set to
004373  **       TK_FILTER. In this case the only field used is Window.pFilter.
004374  **
004375  ** The uses (1) and (2) are really the same Window object that just happens
004376  ** to be accessible in two different ways.  Use case (3) are separate objects.
004377  */
004378  struct Window {
004379    char *zName;            /* Name of window (may be NULL) */
004380    char *zBase;            /* Name of base window for chaining (may be NULL) */
004381    ExprList *pPartition;   /* PARTITION BY clause */
004382    ExprList *pOrderBy;     /* ORDER BY clause */
004383    u8 eFrmType;            /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */
004384    u8 eStart;              /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
004385    u8 eEnd;                /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
004386    u8 bImplicitFrame;      /* True if frame was implicitly specified */
004387    u8 eExclude;            /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */
004388    Expr *pStart;           /* Expression for "<expr> PRECEDING" */
004389    Expr *pEnd;             /* Expression for "<expr> FOLLOWING" */
004390    Window **ppThis;        /* Pointer to this object in Select.pWin list */
004391    Window *pNextWin;       /* Next window function belonging to this SELECT */
004392    Expr *pFilter;          /* The FILTER expression */
004393    FuncDef *pWFunc;        /* The function */
004394    int iEphCsr;            /* Partition buffer or Peer buffer */
004395    int regAccum;           /* Accumulator */
004396    int regResult;          /* Interim result */
004397    int csrApp;             /* Function cursor (used by min/max) */
004398    int regApp;             /* Function register (also used by min/max) */
004399    int regPart;            /* Array of registers for PARTITION BY values */
004400    Expr *pOwner;           /* Expression object this window is attached to */
004401    int nBufferCol;         /* Number of columns in buffer table */
004402    int iArgCol;            /* Offset of first argument for this function */
004403    int regOne;             /* Register containing constant value 1 */
004404    int regStartRowid;
004405    int regEndRowid;
004406    u8 bExprArgs;           /* Defer evaluation of window function arguments
004407                            ** due to the SQLITE_SUBTYPE flag */
004408  };
004409  
004410  #ifndef SQLITE_OMIT_WINDOWFUNC
004411  void sqlite3WindowDelete(sqlite3*, Window*);
004412  void sqlite3WindowUnlinkFromSelect(Window*);
004413  void sqlite3WindowListDelete(sqlite3 *db, Window *p);
004414  Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);
004415  void sqlite3WindowAttach(Parse*, Expr*, Window*);
004416  void sqlite3WindowLink(Select *pSel, Window *pWin);
004417  int sqlite3WindowCompare(const Parse*, const Window*, const Window*, int);
004418  void sqlite3WindowCodeInit(Parse*, Select*);
004419  void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
004420  int sqlite3WindowRewrite(Parse*, Select*);
004421  void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
004422  Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
004423  Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
004424  void sqlite3WindowFunctions(void);
004425  void sqlite3WindowChain(Parse*, Window*, Window*);
004426  Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*);
004427  #else
004428  # define sqlite3WindowDelete(a,b)
004429  # define sqlite3WindowFunctions()
004430  # define sqlite3WindowAttach(a,b,c)
004431  #endif
004432  
004433  /*
004434  ** Assuming zIn points to the first byte of a UTF-8 character,
004435  ** advance zIn to point to the first byte of the next UTF-8 character.
004436  */
004437  #define SQLITE_SKIP_UTF8(zIn) {                        \
004438    if( (*(zIn++))>=0xc0 ){                              \
004439      while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
004440    }                                                    \
004441  }
004442  
004443  /*
004444  ** The SQLITE_*_BKPT macros are substitutes for the error codes with
004445  ** the same name but without the _BKPT suffix.  These macros invoke
004446  ** routines that report the line-number on which the error originated
004447  ** using sqlite3_log().  The routines also provide a convenient place
004448  ** to set a debugger breakpoint.
004449  */
004450  int sqlite3ReportError(int iErr, int lineno, const char *zType);
004451  int sqlite3CorruptError(int);
004452  int sqlite3MisuseError(int);
004453  int sqlite3CantopenError(int);
004454  #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
004455  #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
004456  #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
004457  #ifdef SQLITE_DEBUG
004458    int sqlite3NomemError(int);
004459    int sqlite3IoerrnomemError(int);
004460  # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
004461  # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
004462  #else
004463  # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
004464  # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
004465  #endif
004466  #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
004467    int sqlite3CorruptPgnoError(int,Pgno);
004468  # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
004469  #else
004470  # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
004471  #endif
004472  
004473  /*
004474  ** FTS3 and FTS4 both require virtual table support
004475  */
004476  #if defined(SQLITE_OMIT_VIRTUALTABLE)
004477  # undef SQLITE_ENABLE_FTS3
004478  # undef SQLITE_ENABLE_FTS4
004479  #endif
004480  
004481  /*
004482  ** FTS4 is really an extension for FTS3.  It is enabled using the
004483  ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
004484  ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
004485  */
004486  #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
004487  # define SQLITE_ENABLE_FTS3 1
004488  #endif
004489  
004490  /*
004491  ** The ctype.h header is needed for non-ASCII systems.  It is also
004492  ** needed by FTS3 when FTS3 is included in the amalgamation.
004493  */
004494  #if !defined(SQLITE_ASCII) || \
004495      (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
004496  # include <ctype.h>
004497  #endif
004498  
004499  /*
004500  ** The following macros mimic the standard library functions toupper(),
004501  ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
004502  ** sqlite versions only work for ASCII characters, regardless of locale.
004503  */
004504  #ifdef SQLITE_ASCII
004505  # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
004506  # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
004507  # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
004508  # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
004509  # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
004510  # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
004511  # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
004512  # define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
004513  # define sqlite3JsonId1(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x42)
004514  # define sqlite3JsonId2(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x46)
004515  #else
004516  # define sqlite3Toupper(x)   toupper((unsigned char)(x))
004517  # define sqlite3Isspace(x)   isspace((unsigned char)(x))
004518  # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
004519  # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
004520  # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
004521  # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
004522  # define sqlite3Tolower(x)   tolower((unsigned char)(x))
004523  # define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
004524  # define sqlite3JsonId1(x)   (sqlite3IsIdChar(x)&&(x)<'0')
004525  # define sqlite3JsonId2(x)   sqlite3IsIdChar(x)
004526  #endif
004527  int sqlite3IsIdChar(u8);
004528  
004529  /*
004530  ** Internal function prototypes
004531  */
004532  int sqlite3StrICmp(const char*,const char*);
004533  int sqlite3Strlen30(const char*);
004534  #define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)
004535  char *sqlite3ColumnType(Column*,char*);
004536  #define sqlite3StrNICmp sqlite3_strnicmp
004537  
004538  int sqlite3MallocInit(void);
004539  void sqlite3MallocEnd(void);
004540  void *sqlite3Malloc(u64);
004541  void *sqlite3MallocZero(u64);
004542  void *sqlite3DbMallocZero(sqlite3*, u64);
004543  void *sqlite3DbMallocRaw(sqlite3*, u64);
004544  void *sqlite3DbMallocRawNN(sqlite3*, u64);
004545  char *sqlite3DbStrDup(sqlite3*,const char*);
004546  char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
004547  char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
004548  void *sqlite3Realloc(void*, u64);
004549  void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
004550  void *sqlite3DbRealloc(sqlite3 *, void *, u64);
004551  void sqlite3DbFree(sqlite3*, void*);
004552  void sqlite3DbFreeNN(sqlite3*, void*);
004553  void sqlite3DbNNFreeNN(sqlite3*, void*);
004554  int sqlite3MallocSize(const void*);
004555  int sqlite3DbMallocSize(sqlite3*, const void*);
004556  void *sqlite3PageMalloc(int);
004557  void sqlite3PageFree(void*);
004558  void sqlite3MemSetDefault(void);
004559  #ifndef SQLITE_UNTESTABLE
004560  void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
004561  #endif
004562  int sqlite3HeapNearlyFull(void);
004563  
004564  /*
004565  ** On systems with ample stack space and that support alloca(), make
004566  ** use of alloca() to obtain space for large automatic objects.  By default,
004567  ** obtain space from malloc().
004568  **
004569  ** The alloca() routine never returns NULL.  This will cause code paths
004570  ** that deal with sqlite3StackAlloc() failures to be unreachable.
004571  */
004572  #ifdef SQLITE_USE_ALLOCA
004573  # define sqlite3StackAllocRaw(D,N)   alloca(N)
004574  # define sqlite3StackAllocRawNN(D,N) alloca(N)
004575  # define sqlite3StackFree(D,P)
004576  # define sqlite3StackFreeNN(D,P)
004577  #else
004578  # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
004579  # define sqlite3StackAllocRawNN(D,N) sqlite3DbMallocRawNN(D,N)
004580  # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
004581  # define sqlite3StackFreeNN(D,P)     sqlite3DbFreeNN(D,P)
004582  #endif
004583  
004584  /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together.  If they
004585  ** are, disable MEMSYS3
004586  */
004587  #ifdef SQLITE_ENABLE_MEMSYS5
004588  const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
004589  #undef SQLITE_ENABLE_MEMSYS3
004590  #endif
004591  #ifdef SQLITE_ENABLE_MEMSYS3
004592  const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
004593  #endif
004594  
004595  
004596  #ifndef SQLITE_MUTEX_OMIT
004597    sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
004598    sqlite3_mutex_methods const *sqlite3NoopMutex(void);
004599    sqlite3_mutex *sqlite3MutexAlloc(int);
004600    int sqlite3MutexInit(void);
004601    int sqlite3MutexEnd(void);
004602  #endif
004603  #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
004604    void sqlite3MemoryBarrier(void);
004605  #else
004606  # define sqlite3MemoryBarrier()
004607  #endif
004608  
004609  sqlite3_int64 sqlite3StatusValue(int);
004610  void sqlite3StatusUp(int, int);
004611  void sqlite3StatusDown(int, int);
004612  void sqlite3StatusHighwater(int, int);
004613  int sqlite3LookasideUsed(sqlite3*,int*);
004614  
004615  /* Access to mutexes used by sqlite3_status() */
004616  sqlite3_mutex *sqlite3Pcache1Mutex(void);
004617  sqlite3_mutex *sqlite3MallocMutex(void);
004618  
004619  #if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
004620  void sqlite3MutexWarnOnContention(sqlite3_mutex*);
004621  #else
004622  # define sqlite3MutexWarnOnContention(x)
004623  #endif
004624  
004625  #ifndef SQLITE_OMIT_FLOATING_POINT
004626  # define EXP754 (((u64)0x7ff)<<52)
004627  # define MAN754 ((((u64)1)<<52)-1)
004628  # define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0)
004629    int sqlite3IsNaN(double);
004630  #else
004631  # define IsNaN(X)         0
004632  # define sqlite3IsNaN(X)  0
004633  #endif
004634  
004635  /*
004636  ** An instance of the following structure holds information about SQL
004637  ** functions arguments that are the parameters to the printf() function.
004638  */
004639  struct PrintfArguments {
004640    int nArg;                /* Total number of arguments */
004641    int nUsed;               /* Number of arguments used so far */
004642    sqlite3_value **apArg;   /* The argument values */
004643  };
004644  
004645  /*
004646  ** An instance of this object receives the decoding of a floating point
004647  ** value into an approximate decimal representation.
004648  */
004649  struct FpDecode {
004650    char sign;           /* '+' or '-' */
004651    char isSpecial;      /* 1: Infinity  2: NaN */
004652    int n;               /* Significant digits in the decode */
004653    int iDP;             /* Location of the decimal point */
004654    char *z;             /* Start of significant digits */
004655    char zBuf[24];       /* Storage for significant digits */
004656  };
004657  
004658  void sqlite3FpDecode(FpDecode*,double,int,int);
004659  char *sqlite3MPrintf(sqlite3*,const char*, ...);
004660  char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
004661  #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
004662    void sqlite3DebugPrintf(const char*, ...);
004663  #endif
004664  #if defined(SQLITE_TEST)
004665    void *sqlite3TestTextToPtr(const char*);
004666  #endif
004667  
004668  #if defined(SQLITE_DEBUG)
004669    void sqlite3TreeViewLine(TreeView*, const char *zFormat, ...);
004670    void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
004671    void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
004672    void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
004673    void sqlite3TreeViewBareIdList(TreeView*, const IdList*, const char*);
004674    void sqlite3TreeViewIdList(TreeView*, const IdList*, u8, const char*);
004675    void sqlite3TreeViewColumnList(TreeView*, const Column*, int, u8);
004676    void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
004677    void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
004678    void sqlite3TreeViewWith(TreeView*, const With*, u8);
004679    void sqlite3TreeViewUpsert(TreeView*, const Upsert*, u8);
004680  #if TREETRACE_ENABLED
004681    void sqlite3TreeViewDelete(const With*, const SrcList*, const Expr*,
004682                               const ExprList*,const Expr*, const Trigger*);
004683    void sqlite3TreeViewInsert(const With*, const SrcList*,
004684                               const IdList*, const Select*, const ExprList*,
004685                               int, const Upsert*, const Trigger*);
004686    void sqlite3TreeViewUpdate(const With*, const SrcList*, const ExprList*,
004687                               const Expr*, int, const ExprList*, const Expr*,
004688                               const Upsert*, const Trigger*);
004689  #endif
004690  #ifndef SQLITE_OMIT_TRIGGER
004691    void sqlite3TreeViewTriggerStep(TreeView*, const TriggerStep*, u8, u8);
004692    void sqlite3TreeViewTrigger(TreeView*, const Trigger*, u8, u8);
004693  #endif
004694  #ifndef SQLITE_OMIT_WINDOWFUNC
004695    void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
004696    void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
004697  #endif
004698    void sqlite3ShowExpr(const Expr*);
004699    void sqlite3ShowExprList(const ExprList*);
004700    void sqlite3ShowIdList(const IdList*);
004701    void sqlite3ShowSrcList(const SrcList*);
004702    void sqlite3ShowSelect(const Select*);
004703    void sqlite3ShowWith(const With*);
004704    void sqlite3ShowUpsert(const Upsert*);
004705  #ifndef SQLITE_OMIT_TRIGGER
004706    void sqlite3ShowTriggerStep(const TriggerStep*);
004707    void sqlite3ShowTriggerStepList(const TriggerStep*);
004708    void sqlite3ShowTrigger(const Trigger*);
004709    void sqlite3ShowTriggerList(const Trigger*);
004710  #endif
004711  #ifndef SQLITE_OMIT_WINDOWFUNC
004712    void sqlite3ShowWindow(const Window*);
004713    void sqlite3ShowWinFunc(const Window*);
004714  #endif
004715  #endif
004716  
004717  void sqlite3SetString(char **, sqlite3*, const char*);
004718  void sqlite3ProgressCheck(Parse*);
004719  void sqlite3ErrorMsg(Parse*, const char*, ...);
004720  int sqlite3ErrorToParser(sqlite3*,int);
004721  void sqlite3Dequote(char*);
004722  void sqlite3DequoteExpr(Expr*);
004723  void sqlite3DequoteToken(Token*);
004724  void sqlite3TokenInit(Token*,char*);
004725  int sqlite3KeywordCode(const unsigned char*, int);
004726  int sqlite3RunParser(Parse*, const char*);
004727  void sqlite3FinishCoding(Parse*);
004728  int sqlite3GetTempReg(Parse*);
004729  void sqlite3ReleaseTempReg(Parse*,int);
004730  int sqlite3GetTempRange(Parse*,int);
004731  void sqlite3ReleaseTempRange(Parse*,int,int);
004732  void sqlite3ClearTempRegCache(Parse*);
004733  void sqlite3TouchRegister(Parse*,int);
004734  #if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
004735  int sqlite3FirstAvailableRegister(Parse*,int);
004736  #endif
004737  #ifdef SQLITE_DEBUG
004738  int sqlite3NoTempsInRange(Parse*,int,int);
004739  #endif
004740  Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
004741  Expr *sqlite3Expr(sqlite3*,int,const char*);
004742  void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
004743  Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
004744  void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
004745  Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);
004746  Expr *sqlite3ExprSimplifiedAndOr(Expr*);
004747  Expr *sqlite3ExprFunction(Parse*,ExprList*, const Token*, int);
004748  void sqlite3ExprFunctionUsable(Parse*,const Expr*,const FuncDef*);
004749  void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
004750  void sqlite3ExprDelete(sqlite3*, Expr*);
004751  void sqlite3ExprDeferredDelete(Parse*, Expr*);
004752  void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
004753  ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
004754  ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
004755  Select *sqlite3ExprListToValues(Parse*, int, ExprList*);
004756  void sqlite3ExprListSetSortOrder(ExprList*,int,int);
004757  void sqlite3ExprListSetName(Parse*,ExprList*,const Token*,int);
004758  void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
004759  void sqlite3ExprListDelete(sqlite3*, ExprList*);
004760  u32 sqlite3ExprListFlags(const ExprList*);
004761  int sqlite3IndexHasDuplicateRootPage(Index*);
004762  int sqlite3Init(sqlite3*, char**);
004763  int sqlite3InitCallback(void*, int, char**, char**);
004764  int sqlite3InitOne(sqlite3*, int, char**, u32);
004765  void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
004766  #ifndef SQLITE_OMIT_VIRTUALTABLE
004767  Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
004768  #endif
004769  void sqlite3ResetAllSchemasOfConnection(sqlite3*);
004770  void sqlite3ResetOneSchema(sqlite3*,int);
004771  void sqlite3CollapseDatabaseArray(sqlite3*);
004772  void sqlite3CommitInternalChanges(sqlite3*);
004773  void sqlite3ColumnSetExpr(Parse*,Table*,Column*,Expr*);
004774  Expr *sqlite3ColumnExpr(Table*,Column*);
004775  void sqlite3ColumnSetColl(sqlite3*,Column*,const char*zColl);
004776  const char *sqlite3ColumnColl(Column*);
004777  void sqlite3DeleteColumnNames(sqlite3*,Table*);
004778  void sqlite3GenerateColumnNames(Parse *pParse, Select *pSelect);
004779  int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
004780  void sqlite3SubqueryColumnTypes(Parse*,Table*,Select*,char);
004781  Table *sqlite3ResultSetOfSelect(Parse*,Select*,char);
004782  void sqlite3OpenSchemaTable(Parse *, int);
004783  Index *sqlite3PrimaryKeyIndex(Table*);
004784  i16 sqlite3TableColumnToIndex(Index*, i16);
004785  #ifdef SQLITE_OMIT_GENERATED_COLUMNS
004786  # define sqlite3TableColumnToStorage(T,X) (X)  /* No-op pass-through */
004787  # define sqlite3StorageColumnToTable(T,X) (X)  /* No-op pass-through */
004788  #else
004789    i16 sqlite3TableColumnToStorage(Table*, i16);
004790    i16 sqlite3StorageColumnToTable(Table*, i16);
004791  #endif
004792  void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
004793  #if SQLITE_ENABLE_HIDDEN_COLUMNS
004794    void sqlite3ColumnPropertiesFromName(Table*, Column*);
004795  #else
004796  # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
004797  #endif
004798  void sqlite3AddColumn(Parse*,Token,Token);
004799  void sqlite3AddNotNull(Parse*, int);
004800  void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
004801  void sqlite3AddCheckConstraint(Parse*, Expr*, const char*, const char*);
004802  void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
004803  void sqlite3AddCollateType(Parse*, Token*);
004804  void sqlite3AddGenerated(Parse*,Expr*,Token*);
004805  void sqlite3EndTable(Parse*,Token*,Token*,u32,Select*);
004806  void sqlite3AddReturning(Parse*,ExprList*);
004807  int sqlite3ParseUri(const char*,const char*,unsigned int*,
004808                      sqlite3_vfs**,char**,char **);
004809  #define sqlite3CodecQueryParameters(A,B,C) 0
004810  Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
004811  
004812  #ifdef SQLITE_UNTESTABLE
004813  # define sqlite3FaultSim(X) SQLITE_OK
004814  #else
004815    int sqlite3FaultSim(int);
004816  #endif
004817  
004818  Bitvec *sqlite3BitvecCreate(u32);
004819  int sqlite3BitvecTest(Bitvec*, u32);
004820  int sqlite3BitvecTestNotNull(Bitvec*, u32);
004821  int sqlite3BitvecSet(Bitvec*, u32);
004822  void sqlite3BitvecClear(Bitvec*, u32, void*);
004823  void sqlite3BitvecDestroy(Bitvec*);
004824  u32 sqlite3BitvecSize(Bitvec*);
004825  #ifndef SQLITE_UNTESTABLE
004826  int sqlite3BitvecBuiltinTest(int,int*);
004827  #endif
004828  
004829  RowSet *sqlite3RowSetInit(sqlite3*);
004830  void sqlite3RowSetDelete(void*);
004831  void sqlite3RowSetClear(void*);
004832  void sqlite3RowSetInsert(RowSet*, i64);
004833  int sqlite3RowSetTest(RowSet*, int iBatch, i64);
004834  int sqlite3RowSetNext(RowSet*, i64*);
004835  
004836  void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
004837  
004838  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
004839    int sqlite3ViewGetColumnNames(Parse*,Table*);
004840  #else
004841  # define sqlite3ViewGetColumnNames(A,B) 0
004842  #endif
004843  
004844  #if SQLITE_MAX_ATTACHED>30
004845    int sqlite3DbMaskAllZero(yDbMask);
004846  #endif
004847  void sqlite3DropTable(Parse*, SrcList*, int, int);
004848  void sqlite3CodeDropTable(Parse*, Table*, int, int);
004849  void sqlite3DeleteTable(sqlite3*, Table*);
004850  void sqlite3FreeIndex(sqlite3*, Index*);
004851  #ifndef SQLITE_OMIT_AUTOINCREMENT
004852    void sqlite3AutoincrementBegin(Parse *pParse);
004853    void sqlite3AutoincrementEnd(Parse *pParse);
004854  #else
004855  # define sqlite3AutoincrementBegin(X)
004856  # define sqlite3AutoincrementEnd(X)
004857  #endif
004858  void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
004859  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
004860    void sqlite3ComputeGeneratedColumns(Parse*, int, Table*);
004861  #endif
004862  void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
004863  IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
004864  int sqlite3IdListIndex(IdList*,const char*);
004865  SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);
004866  SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2);
004867  SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);
004868  SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
004869                                        Token*, Select*, OnOrUsing*);
004870  void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
004871  void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
004872  int sqlite3IndexedByLookup(Parse *, SrcItem *);
004873  void sqlite3SrcListShiftJoinType(Parse*,SrcList*);
004874  void sqlite3SrcListAssignCursors(Parse*, SrcList*);
004875  void sqlite3IdListDelete(sqlite3*, IdList*);
004876  void sqlite3ClearOnOrUsing(sqlite3*, OnOrUsing*);
004877  void sqlite3SrcListDelete(sqlite3*, SrcList*);
004878  Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
004879  void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
004880                            Expr*, int, int, u8);
004881  void sqlite3DropIndex(Parse*, SrcList*, int);
004882  int sqlite3Select(Parse*, Select*, SelectDest*);
004883  Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
004884                           Expr*,ExprList*,u32,Expr*);
004885  void sqlite3SelectDelete(sqlite3*, Select*);
004886  Table *sqlite3SrcListLookup(Parse*, SrcList*);
004887  int sqlite3IsReadOnly(Parse*, Table*, Trigger*);
004888  void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
004889  #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
004890  Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
004891  #endif
004892  void sqlite3CodeChangeCount(Vdbe*,int,const char*);
004893  void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
004894  void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
004895                     Upsert*);
004896  WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,
004897                               ExprList*,Select*,u16,int);
004898  void sqlite3WhereEnd(WhereInfo*);
004899  LogEst sqlite3WhereOutputRowCount(WhereInfo*);
004900  int sqlite3WhereIsDistinct(WhereInfo*);
004901  int sqlite3WhereIsOrdered(WhereInfo*);
004902  int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
004903  void sqlite3WhereMinMaxOptEarlyOut(Vdbe*,WhereInfo*);
004904  int sqlite3WhereIsSorted(WhereInfo*);
004905  int sqlite3WhereContinueLabel(WhereInfo*);
004906  int sqlite3WhereBreakLabel(WhereInfo*);
004907  int sqlite3WhereOkOnePass(WhereInfo*, int*);
004908  #define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
004909  #define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
004910  #define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
004911  int sqlite3WhereUsesDeferredSeek(WhereInfo*);
004912  void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
004913  int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
004914  void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
004915  void sqlite3ExprCodeMove(Parse*, int, int, int);
004916  void sqlite3ExprCode(Parse*, Expr*, int);
004917  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
004918  void sqlite3ExprCodeGeneratedColumn(Parse*, Table*, Column*, int);
004919  #endif
004920  void sqlite3ExprCodeCopy(Parse*, Expr*, int);
004921  void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
004922  int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);
004923  int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
004924  int sqlite3ExprCodeTarget(Parse*, Expr*, int);
004925  int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
004926  #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
004927  #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
004928  #define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */
004929  #define SQLITE_ECEL_OMITREF  0x08  /* Omit if ExprList.u.x.iOrderByCol */
004930  void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
004931  void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
004932  void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
004933  Table *sqlite3FindTable(sqlite3*,const char*, const char*);
004934  #define LOCATE_VIEW    0x01
004935  #define LOCATE_NOERR   0x02
004936  Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
004937  const char *sqlite3PreferredTableName(const char*);
004938  Table *sqlite3LocateTableItem(Parse*,u32 flags,SrcItem *);
004939  Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
004940  void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
004941  void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
004942  void sqlite3Vacuum(Parse*,Token*,Expr*);
004943  int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);
004944  char *sqlite3NameFromToken(sqlite3*, const Token*);
004945  int sqlite3ExprCompare(const Parse*,const Expr*,const Expr*, int);
004946  int sqlite3ExprCompareSkip(Expr*,Expr*,int);
004947  int sqlite3ExprListCompare(const ExprList*,const ExprList*, int);
004948  int sqlite3ExprImpliesExpr(const Parse*,const Expr*,const Expr*, int);
004949  int sqlite3ExprImpliesNonNullRow(Expr*,int,int);
004950  void sqlite3AggInfoPersistWalkerInit(Walker*,Parse*);
004951  void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
004952  void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
004953  int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
004954  int sqlite3ReferencesSrcList(Parse*, Expr*, SrcList*);
004955  Vdbe *sqlite3GetVdbe(Parse*);
004956  #ifndef SQLITE_UNTESTABLE
004957  void sqlite3PrngSaveState(void);
004958  void sqlite3PrngRestoreState(void);
004959  #endif
004960  void sqlite3RollbackAll(sqlite3*,int);
004961  void sqlite3CodeVerifySchema(Parse*, int);
004962  void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
004963  void sqlite3BeginTransaction(Parse*, int);
004964  void sqlite3EndTransaction(Parse*,int);
004965  void sqlite3Savepoint(Parse*, int, Token*);
004966  void sqlite3CloseSavepoints(sqlite3 *);
004967  void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
004968  u32 sqlite3IsTrueOrFalse(const char*);
004969  int sqlite3ExprIdToTrueFalse(Expr*);
004970  int sqlite3ExprTruthValue(const Expr*);
004971  int sqlite3ExprIsConstant(Expr*);
004972  int sqlite3ExprIsConstantNotJoin(Expr*);
004973  int sqlite3ExprIsConstantOrFunction(Expr*, u8);
004974  int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
004975  int sqlite3ExprIsTableConstant(Expr*,int);
004976  int sqlite3ExprIsSingleTableConstraint(Expr*,const SrcList*,int);
004977  #ifdef SQLITE_ENABLE_CURSOR_HINTS
004978  int sqlite3ExprContainsSubquery(Expr*);
004979  #endif
004980  int sqlite3ExprIsInteger(const Expr*, int*);
004981  int sqlite3ExprCanBeNull(const Expr*);
004982  int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
004983  int sqlite3IsRowid(const char*);
004984  void sqlite3GenerateRowDelete(
004985      Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
004986  void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
004987  int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
004988  void sqlite3ResolvePartIdxLabel(Parse*,int);
004989  int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
004990  void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
004991                                       u8,u8,int,int*,int*,Upsert*);
004992  #ifdef SQLITE_ENABLE_NULL_TRIM
004993    void sqlite3SetMakeRecordP5(Vdbe*,Table*);
004994  #else
004995  # define sqlite3SetMakeRecordP5(A,B)
004996  #endif
004997  void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
004998  int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
004999  void sqlite3BeginWriteOperation(Parse*, int, int);
005000  void sqlite3MultiWrite(Parse*);
005001  void sqlite3MayAbort(Parse*);
005002  void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
005003  void sqlite3UniqueConstraint(Parse*, int, Index*);
005004  void sqlite3RowidConstraint(Parse*, int, Table*);
005005  Expr *sqlite3ExprDup(sqlite3*,const Expr*,int);
005006  ExprList *sqlite3ExprListDup(sqlite3*,const ExprList*,int);
005007  SrcList *sqlite3SrcListDup(sqlite3*,const SrcList*,int);
005008  IdList *sqlite3IdListDup(sqlite3*,const IdList*);
005009  Select *sqlite3SelectDup(sqlite3*,const Select*,int);
005010  FuncDef *sqlite3FunctionSearch(int,const char*);
005011  void sqlite3InsertBuiltinFuncs(FuncDef*,int);
005012  FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
005013  void sqlite3QuoteValue(StrAccum*,sqlite3_value*);
005014  void sqlite3RegisterBuiltinFunctions(void);
005015  void sqlite3RegisterDateTimeFunctions(void);
005016  void sqlite3RegisterJsonFunctions(void);
005017  void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
005018  #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
005019    int sqlite3JsonTableFunctions(sqlite3*);
005020  #endif
005021  int sqlite3SafetyCheckOk(sqlite3*);
005022  int sqlite3SafetyCheckSickOrOk(sqlite3*);
005023  void sqlite3ChangeCookie(Parse*, int);
005024  With *sqlite3WithDup(sqlite3 *db, With *p);
005025  
005026  #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
005027  void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
005028  #endif
005029  
005030  #ifndef SQLITE_OMIT_TRIGGER
005031    void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
005032                             Expr*,int, int);
005033    void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
005034    void sqlite3DropTrigger(Parse*, SrcList*, int);
005035    void sqlite3DropTriggerPtr(Parse*, Trigger*);
005036    Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
005037    Trigger *sqlite3TriggerList(Parse *, Table *);
005038    void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
005039                              int, int, int);
005040    void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
005041    void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
005042    void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
005043    TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
005044                                          const char*,const char*);
005045    TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
005046                                          Select*,u8,Upsert*,
005047                                          const char*,const char*);
005048    TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,SrcList*,ExprList*,
005049                                          Expr*, u8, const char*,const char*);
005050    TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
005051                                          const char*,const char*);
005052    void sqlite3DeleteTrigger(sqlite3*, Trigger*);
005053    void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
005054    u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
005055    SrcList *sqlite3TriggerStepSrc(Parse*, TriggerStep*);
005056  # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
005057  # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
005058  #else
005059  # define sqlite3TriggersExist(B,C,D,E,F) 0
005060  # define sqlite3DeleteTrigger(A,B)
005061  # define sqlite3DropTriggerPtr(A,B)
005062  # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
005063  # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
005064  # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
005065  # define sqlite3TriggerList(X, Y) 0
005066  # define sqlite3ParseToplevel(p) p
005067  # define sqlite3IsToplevel(p) 1
005068  # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
005069  # define sqlite3TriggerStepSrc(A,B) 0
005070  #endif
005071  
005072  int sqlite3JoinType(Parse*, Token*, Token*, Token*);
005073  int sqlite3ColumnIndex(Table *pTab, const char *zCol);
005074  void sqlite3SrcItemColumnUsed(SrcItem*,int);
005075  void sqlite3SetJoinExpr(Expr*,int,u32);
005076  void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
005077  void sqlite3DeferForeignKey(Parse*, int);
005078  #ifndef SQLITE_OMIT_AUTHORIZATION
005079    void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
005080    int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
005081    void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
005082    void sqlite3AuthContextPop(AuthContext*);
005083    int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
005084  #else
005085  # define sqlite3AuthRead(a,b,c,d)
005086  # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
005087  # define sqlite3AuthContextPush(a,b,c)
005088  # define sqlite3AuthContextPop(a)  ((void)(a))
005089  #endif
005090  int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName);
005091  void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
005092  void sqlite3Detach(Parse*, Expr*);
005093  void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
005094  int sqlite3FixSrcList(DbFixer*, SrcList*);
005095  int sqlite3FixSelect(DbFixer*, Select*);
005096  int sqlite3FixExpr(DbFixer*, Expr*);
005097  int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
005098  
005099  int sqlite3RealSameAsInt(double,sqlite3_int64);
005100  i64 sqlite3RealToI64(double);
005101  int sqlite3Int64ToText(i64,char*);
005102  int sqlite3AtoF(const char *z, double*, int, u8);
005103  int sqlite3GetInt32(const char *, int*);
005104  int sqlite3GetUInt32(const char*, u32*);
005105  int sqlite3Atoi(const char*);
005106  #ifndef SQLITE_OMIT_UTF16
005107  int sqlite3Utf16ByteLen(const void *pData, int nChar);
005108  #endif
005109  int sqlite3Utf8CharLen(const char *pData, int nByte);
005110  u32 sqlite3Utf8Read(const u8**);
005111  LogEst sqlite3LogEst(u64);
005112  LogEst sqlite3LogEstAdd(LogEst,LogEst);
005113  LogEst sqlite3LogEstFromDouble(double);
005114  u64 sqlite3LogEstToInt(LogEst);
005115  VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
005116  const char *sqlite3VListNumToName(VList*,int);
005117  int sqlite3VListNameToNum(VList*,const char*,int);
005118  
005119  /*
005120  ** Routines to read and write variable-length integers.  These used to
005121  ** be defined locally, but now we use the varint routines in the util.c
005122  ** file.
005123  */
005124  int sqlite3PutVarint(unsigned char*, u64);
005125  u8 sqlite3GetVarint(const unsigned char *, u64 *);
005126  u8 sqlite3GetVarint32(const unsigned char *, u32 *);
005127  int sqlite3VarintLen(u64 v);
005128  
005129  /*
005130  ** The common case is for a varint to be a single byte.  They following
005131  ** macros handle the common case without a procedure call, but then call
005132  ** the procedure for larger varints.
005133  */
005134  #define getVarint32(A,B)  \
005135    (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
005136  #define getVarint32NR(A,B) \
005137    B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&(B))
005138  #define putVarint32(A,B)  \
005139    (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
005140    sqlite3PutVarint((A),(B)))
005141  #define getVarint    sqlite3GetVarint
005142  #define putVarint    sqlite3PutVarint
005143  
005144  
005145  const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
005146  char *sqlite3TableAffinityStr(sqlite3*,const Table*);
005147  void sqlite3TableAffinity(Vdbe*, Table*, int);
005148  char sqlite3CompareAffinity(const Expr *pExpr, char aff2);
005149  int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity);
005150  char sqlite3TableColumnAffinity(const Table*,int);
005151  char sqlite3ExprAffinity(const Expr *pExpr);
005152  int sqlite3ExprDataType(const Expr *pExpr);
005153  int sqlite3Atoi64(const char*, i64*, int, u8);
005154  int sqlite3DecOrHexToI64(const char*, i64*);
005155  void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
005156  void sqlite3Error(sqlite3*,int);
005157  void sqlite3ErrorClear(sqlite3*);
005158  void sqlite3SystemError(sqlite3*,int);
005159  void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
005160  u8 sqlite3HexToInt(int h);
005161  int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
005162  
005163  #if defined(SQLITE_NEED_ERR_NAME)
005164  const char *sqlite3ErrName(int);
005165  #endif
005166  
005167  #ifndef SQLITE_OMIT_DESERIALIZE
005168  int sqlite3MemdbInit(void);
005169  int sqlite3IsMemdb(const sqlite3_vfs*);
005170  #else
005171  # define sqlite3IsMemdb(X) 0
005172  #endif
005173  
005174  const char *sqlite3ErrStr(int);
005175  int sqlite3ReadSchema(Parse *pParse);
005176  CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
005177  int sqlite3IsBinary(const CollSeq*);
005178  CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
005179  void sqlite3SetTextEncoding(sqlite3 *db, u8);
005180  CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr);
005181  CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr);
005182  int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*);
005183  Expr *sqlite3ExprAddCollateToken(const Parse *pParse, Expr*, const Token*, int);
005184  Expr *sqlite3ExprAddCollateString(const Parse*,Expr*,const char*);
005185  Expr *sqlite3ExprSkipCollate(Expr*);
005186  Expr *sqlite3ExprSkipCollateAndLikely(Expr*);
005187  int sqlite3CheckCollSeq(Parse *, CollSeq *);
005188  int sqlite3WritableSchema(sqlite3*);
005189  int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*);
005190  void sqlite3VdbeSetChanges(sqlite3 *, i64);
005191  int sqlite3AddInt64(i64*,i64);
005192  int sqlite3SubInt64(i64*,i64);
005193  int sqlite3MulInt64(i64*,i64);
005194  int sqlite3AbsInt32(int);
005195  #ifdef SQLITE_ENABLE_8_3_NAMES
005196  void sqlite3FileSuffix3(const char*, char*);
005197  #else
005198  # define sqlite3FileSuffix3(X,Y)
005199  #endif
005200  u8 sqlite3GetBoolean(const char *z,u8);
005201  
005202  const void *sqlite3ValueText(sqlite3_value*, u8);
005203  int sqlite3ValueIsOfClass(const sqlite3_value*, void(*)(void*));
005204  int sqlite3ValueBytes(sqlite3_value*, u8);
005205  void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
005206                          void(*)(void*));
005207  void sqlite3ValueSetNull(sqlite3_value*);
005208  void sqlite3ValueFree(sqlite3_value*);
005209  #ifndef SQLITE_UNTESTABLE
005210  void sqlite3ResultIntReal(sqlite3_context*);
005211  #endif
005212  sqlite3_value *sqlite3ValueNew(sqlite3 *);
005213  #ifndef SQLITE_OMIT_UTF16
005214  char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
005215  #endif
005216  int sqlite3ValueFromExpr(sqlite3 *, const Expr *, u8, u8, sqlite3_value **);
005217  void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
005218  #ifndef SQLITE_AMALGAMATION
005219  extern const unsigned char sqlite3OpcodeProperty[];
005220  extern const char sqlite3StrBINARY[];
005221  extern const unsigned char sqlite3StdTypeLen[];
005222  extern const char sqlite3StdTypeAffinity[];
005223  extern const char *sqlite3StdType[];
005224  extern const unsigned char sqlite3UpperToLower[];
005225  extern const unsigned char *sqlite3aLTb;
005226  extern const unsigned char *sqlite3aEQb;
005227  extern const unsigned char *sqlite3aGTb;
005228  extern const unsigned char sqlite3CtypeMap[];
005229  extern SQLITE_WSD struct Sqlite3Config sqlite3Config;
005230  extern FuncDefHash sqlite3BuiltinFunctions;
005231  #ifndef SQLITE_OMIT_WSD
005232  extern int sqlite3PendingByte;
005233  #endif
005234  #endif /* SQLITE_AMALGAMATION */
005235  #ifdef VDBE_PROFILE
005236  extern sqlite3_uint64 sqlite3NProfileCnt;
005237  #endif
005238  void sqlite3RootPageMoved(sqlite3*, int, Pgno, Pgno);
005239  void sqlite3Reindex(Parse*, Token*, Token*);
005240  void sqlite3AlterFunctions(void);
005241  void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
005242  void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
005243  int sqlite3GetToken(const unsigned char *, int *);
005244  void sqlite3NestedParse(Parse*, const char*, ...);
005245  void sqlite3ExpirePreparedStatements(sqlite3*, int);
005246  void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
005247  int sqlite3CodeSubselect(Parse*, Expr*);
005248  void sqlite3SelectPrep(Parse*, Select*, NameContext*);
005249  int sqlite3ExpandSubquery(Parse*, SrcItem*);
005250  void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
005251  int sqlite3MatchEName(
005252    const struct ExprList_item*,
005253    const char*,
005254    const char*,
005255    const char*
005256  );
005257  Bitmask sqlite3ExprColUsed(Expr*);
005258  u8 sqlite3StrIHash(const char*);
005259  int sqlite3ResolveExprNames(NameContext*, Expr*);
005260  int sqlite3ResolveExprListNames(NameContext*, ExprList*);
005261  void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
005262  int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
005263  int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
005264  void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
005265  void sqlite3AlterFinishAddColumn(Parse *, Token *);
005266  void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
005267  void sqlite3AlterDropColumn(Parse*, SrcList*, const Token*);
005268  const void *sqlite3RenameTokenMap(Parse*, const void*, const Token*);
005269  void sqlite3RenameTokenRemap(Parse*, const void *pTo, const void *pFrom);
005270  void sqlite3RenameExprUnmap(Parse*, Expr*);
005271  void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
005272  CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
005273  char sqlite3AffinityType(const char*, Column*);
005274  void sqlite3Analyze(Parse*, Token*, Token*);
005275  int sqlite3InvokeBusyHandler(BusyHandler*);
005276  int sqlite3FindDb(sqlite3*, Token*);
005277  int sqlite3FindDbName(sqlite3 *, const char *);
005278  int sqlite3AnalysisLoad(sqlite3*,int iDB);
005279  void sqlite3DeleteIndexSamples(sqlite3*,Index*);
005280  void sqlite3DefaultRowEst(Index*);
005281  void sqlite3RegisterLikeFunctions(sqlite3*, int);
005282  int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
005283  void sqlite3SchemaClear(void *);
005284  Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
005285  int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
005286  KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
005287  void sqlite3KeyInfoUnref(KeyInfo*);
005288  KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
005289  KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
005290  KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
005291  const char *sqlite3SelectOpName(int);
005292  int sqlite3HasExplicitNulls(Parse*, ExprList*);
005293  
005294  #ifdef SQLITE_DEBUG
005295  int sqlite3KeyInfoIsWriteable(KeyInfo*);
005296  #endif
005297  int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
005298    void (*)(sqlite3_context*,int,sqlite3_value **),
005299    void (*)(sqlite3_context*,int,sqlite3_value **),
005300    void (*)(sqlite3_context*),
005301    void (*)(sqlite3_context*),
005302    void (*)(sqlite3_context*,int,sqlite3_value **),
005303    FuncDestructor *pDestructor
005304  );
005305  void sqlite3NoopDestructor(void*);
005306  void *sqlite3OomFault(sqlite3*);
005307  void sqlite3OomClear(sqlite3*);
005308  int sqlite3ApiExit(sqlite3 *db, int);
005309  int sqlite3OpenTempDatabase(Parse *);
005310  
005311  char *sqlite3RCStrRef(char*);
005312  void sqlite3RCStrUnref(char*);
005313  char *sqlite3RCStrNew(u64);
005314  char *sqlite3RCStrResize(char*,u64);
005315  
005316  void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
005317  int sqlite3StrAccumEnlarge(StrAccum*, i64);
005318  char *sqlite3StrAccumFinish(StrAccum*);
005319  void sqlite3StrAccumSetError(StrAccum*, u8);
005320  void sqlite3ResultStrAccum(sqlite3_context*,StrAccum*);
005321  void sqlite3SelectDestInit(SelectDest*,int,int);
005322  Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
005323  void sqlite3RecordErrorByteOffset(sqlite3*,const char*);
005324  void sqlite3RecordErrorOffsetOfExpr(sqlite3*,const Expr*);
005325  
005326  void sqlite3BackupRestart(sqlite3_backup *);
005327  void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
005328  
005329  #ifndef SQLITE_OMIT_SUBQUERY
005330  int sqlite3ExprCheckIN(Parse*, Expr*);
005331  #else
005332  # define sqlite3ExprCheckIN(x,y) SQLITE_OK
005333  #endif
005334  
005335  #ifdef SQLITE_ENABLE_STAT4
005336  int sqlite3Stat4ProbeSetValue(
005337      Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
005338  int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
005339  void sqlite3Stat4ProbeFree(UnpackedRecord*);
005340  int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
005341  char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
005342  #endif
005343  
005344  /*
005345  ** The interface to the LEMON-generated parser
005346  */
005347  #ifndef SQLITE_AMALGAMATION
005348    void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
005349    void sqlite3ParserFree(void*, void(*)(void*));
005350  #endif
005351  void sqlite3Parser(void*, int, Token);
005352  int sqlite3ParserFallback(int);
005353  #ifdef YYTRACKMAXSTACKDEPTH
005354    int sqlite3ParserStackPeak(void*);
005355  #endif
005356  
005357  void sqlite3AutoLoadExtensions(sqlite3*);
005358  #ifndef SQLITE_OMIT_LOAD_EXTENSION
005359    void sqlite3CloseExtensions(sqlite3*);
005360  #else
005361  # define sqlite3CloseExtensions(X)
005362  #endif
005363  
005364  #ifndef SQLITE_OMIT_SHARED_CACHE
005365    void sqlite3TableLock(Parse *, int, Pgno, u8, const char *);
005366  #else
005367    #define sqlite3TableLock(v,w,x,y,z)
005368  #endif
005369  
005370  #ifdef SQLITE_TEST
005371    int sqlite3Utf8To8(unsigned char*);
005372  #endif
005373  
005374  #ifdef SQLITE_OMIT_VIRTUALTABLE
005375  #  define sqlite3VtabClear(D,T)
005376  #  define sqlite3VtabSync(X,Y) SQLITE_OK
005377  #  define sqlite3VtabRollback(X)
005378  #  define sqlite3VtabCommit(X)
005379  #  define sqlite3VtabInSync(db) 0
005380  #  define sqlite3VtabLock(X)
005381  #  define sqlite3VtabUnlock(X)
005382  #  define sqlite3VtabModuleUnref(D,X)
005383  #  define sqlite3VtabUnlockList(X)
005384  #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
005385  #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
005386  #else
005387     void sqlite3VtabClear(sqlite3 *db, Table*);
005388     void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
005389     int sqlite3VtabSync(sqlite3 *db, Vdbe*);
005390     int sqlite3VtabRollback(sqlite3 *db);
005391     int sqlite3VtabCommit(sqlite3 *db);
005392     void sqlite3VtabLock(VTable *);
005393     void sqlite3VtabUnlock(VTable *);
005394     void sqlite3VtabModuleUnref(sqlite3*,Module*);
005395     void sqlite3VtabUnlockList(sqlite3*);
005396     int sqlite3VtabSavepoint(sqlite3 *, int, int);
005397     void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
005398     VTable *sqlite3GetVTable(sqlite3*, Table*);
005399     Module *sqlite3VtabCreateModule(
005400       sqlite3*,
005401       const char*,
005402       const sqlite3_module*,
005403       void*,
005404       void(*)(void*)
005405     );
005406  #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
005407  #endif
005408  int sqlite3ReadOnlyShadowTables(sqlite3 *db);
005409  #ifndef SQLITE_OMIT_VIRTUALTABLE
005410    int sqlite3ShadowTableName(sqlite3 *db, const char *zName);
005411    int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);
005412    void sqlite3MarkAllShadowTablesOf(sqlite3*, Table*);
005413  #else
005414  # define sqlite3ShadowTableName(A,B) 0
005415  # define sqlite3IsShadowTableOf(A,B,C) 0
005416  # define sqlite3MarkAllShadowTablesOf(A,B)
005417  #endif
005418  int sqlite3VtabEponymousTableInit(Parse*,Module*);
005419  void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
005420  void sqlite3VtabMakeWritable(Parse*,Table*);
005421  void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
005422  void sqlite3VtabFinishParse(Parse*, Token*);
005423  void sqlite3VtabArgInit(Parse*);
005424  void sqlite3VtabArgExtend(Parse*, Token*);
005425  int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
005426  int sqlite3VtabCallConnect(Parse*, Table*);
005427  int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
005428  int sqlite3VtabBegin(sqlite3 *, VTable *);
005429  
005430  FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
005431  void sqlite3VtabUsesAllSchemas(Parse*);
005432  sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
005433  int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
005434  int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
005435  void sqlite3ParseObjectInit(Parse*,sqlite3*);
005436  void sqlite3ParseObjectReset(Parse*);
005437  void *sqlite3ParserAddCleanup(Parse*,void(*)(sqlite3*,void*),void*);
005438  #ifdef SQLITE_ENABLE_NORMALIZE
005439  char *sqlite3Normalize(Vdbe*, const char*);
005440  #endif
005441  int sqlite3Reprepare(Vdbe*);
005442  void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
005443  CollSeq *sqlite3ExprCompareCollSeq(Parse*,const Expr*);
005444  CollSeq *sqlite3BinaryCompareCollSeq(Parse *, const Expr*, const Expr*);
005445  int sqlite3TempInMemory(const sqlite3*);
005446  const char *sqlite3JournalModename(int);
005447  #ifndef SQLITE_OMIT_WAL
005448    int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
005449    int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
005450  #endif
005451  #ifndef SQLITE_OMIT_CTE
005452    Cte *sqlite3CteNew(Parse*,Token*,ExprList*,Select*,u8);
005453    void sqlite3CteDelete(sqlite3*,Cte*);
005454    With *sqlite3WithAdd(Parse*,With*,Cte*);
005455    void sqlite3WithDelete(sqlite3*,With*);
005456    With *sqlite3WithPush(Parse*, With*, u8);
005457  #else
005458  # define sqlite3CteNew(P,T,E,S)   ((void*)0)
005459  # define sqlite3CteDelete(D,C)
005460  # define sqlite3CteWithAdd(P,W,C) ((void*)0)
005461  # define sqlite3WithDelete(x,y)
005462  # define sqlite3WithPush(x,y,z) ((void*)0)
005463  #endif
005464  #ifndef SQLITE_OMIT_UPSERT
005465    Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*,Upsert*);
005466    void sqlite3UpsertDelete(sqlite3*,Upsert*);
005467    Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
005468    int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);
005469    void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
005470    Upsert *sqlite3UpsertOfIndex(Upsert*,Index*);
005471    int sqlite3UpsertNextIsIPK(Upsert*);
005472  #else
005473  #define sqlite3UpsertNew(u,v,w,x,y,z) ((Upsert*)0)
005474  #define sqlite3UpsertDelete(x,y)
005475  #define sqlite3UpsertDup(x,y)         ((Upsert*)0)
005476  #define sqlite3UpsertOfIndex(x,y)     ((Upsert*)0)
005477  #define sqlite3UpsertNextIsIPK(x)     0
005478  #endif
005479  
005480  
005481  /* Declarations for functions in fkey.c. All of these are replaced by
005482  ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
005483  ** key functionality is available. If OMIT_TRIGGER is defined but
005484  ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
005485  ** this case foreign keys are parsed, but no other functionality is
005486  ** provided (enforcement of FK constraints requires the triggers sub-system).
005487  */
005488  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
005489    void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
005490    void sqlite3FkDropTable(Parse*, SrcList *, Table*);
005491    void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
005492    int sqlite3FkRequired(Parse*, Table*, int*, int);
005493    u32 sqlite3FkOldmask(Parse*, Table*);
005494    FKey *sqlite3FkReferences(Table *);
005495    void sqlite3FkClearTriggerCache(sqlite3*,int);
005496  #else
005497    #define sqlite3FkActions(a,b,c,d,e,f)
005498    #define sqlite3FkCheck(a,b,c,d,e,f)
005499    #define sqlite3FkDropTable(a,b,c)
005500    #define sqlite3FkOldmask(a,b)         0
005501    #define sqlite3FkRequired(a,b,c,d)    0
005502    #define sqlite3FkReferences(a)        0
005503    #define sqlite3FkClearTriggerCache(a,b)
005504  #endif
005505  #ifndef SQLITE_OMIT_FOREIGN_KEY
005506    void sqlite3FkDelete(sqlite3 *, Table*);
005507    int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
005508  #else
005509    #define sqlite3FkDelete(a,b)
005510    #define sqlite3FkLocateIndex(a,b,c,d,e)
005511  #endif
005512  
005513  
005514  /*
005515  ** Available fault injectors.  Should be numbered beginning with 0.
005516  */
005517  #define SQLITE_FAULTINJECTOR_MALLOC     0
005518  #define SQLITE_FAULTINJECTOR_COUNT      1
005519  
005520  /*
005521  ** The interface to the code in fault.c used for identifying "benign"
005522  ** malloc failures. This is only present if SQLITE_UNTESTABLE
005523  ** is not defined.
005524  */
005525  #ifndef SQLITE_UNTESTABLE
005526    void sqlite3BeginBenignMalloc(void);
005527    void sqlite3EndBenignMalloc(void);
005528  #else
005529    #define sqlite3BeginBenignMalloc()
005530    #define sqlite3EndBenignMalloc()
005531  #endif
005532  
005533  /*
005534  ** Allowed return values from sqlite3FindInIndex()
005535  */
005536  #define IN_INDEX_ROWID        1   /* Search the rowid of the table */
005537  #define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
005538  #define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
005539  #define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
005540  #define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
005541  /*
005542  ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
005543  */
005544  #define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
005545  #define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
005546  #define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
005547  int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);
005548  
005549  int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
005550  int sqlite3JournalSize(sqlite3_vfs *);
005551  #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
005552   || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
005553    int sqlite3JournalCreate(sqlite3_file *);
005554  #endif
005555  
005556  int sqlite3JournalIsInMemory(sqlite3_file *p);
005557  void sqlite3MemJournalOpen(sqlite3_file *);
005558  
005559  void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
005560  #if SQLITE_MAX_EXPR_DEPTH>0
005561    int sqlite3SelectExprHeight(const Select *);
005562    int sqlite3ExprCheckHeight(Parse*, int);
005563  #else
005564    #define sqlite3SelectExprHeight(x) 0
005565    #define sqlite3ExprCheckHeight(x,y)
005566  #endif
005567  void sqlite3ExprSetErrorOffset(Expr*,int);
005568  
005569  u32 sqlite3Get4byte(const u8*);
005570  void sqlite3Put4byte(u8*, u32);
005571  
005572  #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
005573    void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
005574    void sqlite3ConnectionUnlocked(sqlite3 *db);
005575    void sqlite3ConnectionClosed(sqlite3 *db);
005576  #else
005577    #define sqlite3ConnectionBlocked(x,y)
005578    #define sqlite3ConnectionUnlocked(x)
005579    #define sqlite3ConnectionClosed(x)
005580  #endif
005581  
005582  #ifdef SQLITE_DEBUG
005583    void sqlite3ParserTrace(FILE*, char *);
005584  #endif
005585  #if defined(YYCOVERAGE)
005586    int sqlite3ParserCoverage(FILE*);
005587  #endif
005588  
005589  /*
005590  ** If the SQLITE_ENABLE IOTRACE exists then the global variable
005591  ** sqlite3IoTrace is a pointer to a printf-like routine used to
005592  ** print I/O tracing messages.
005593  */
005594  #ifdef SQLITE_ENABLE_IOTRACE
005595  # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
005596    void sqlite3VdbeIOTraceSql(Vdbe*);
005597  SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
005598  #else
005599  # define IOTRACE(A)
005600  # define sqlite3VdbeIOTraceSql(X)
005601  #endif
005602  
005603  /*
005604  ** These routines are available for the mem2.c debugging memory allocator
005605  ** only.  They are used to verify that different "types" of memory
005606  ** allocations are properly tracked by the system.
005607  **
005608  ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
005609  ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
005610  ** a single bit set.
005611  **
005612  ** sqlite3MemdebugHasType() returns true if any of the bits in its second
005613  ** argument match the type set by the previous sqlite3MemdebugSetType().
005614  ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
005615  **
005616  ** sqlite3MemdebugNoType() returns true if none of the bits in its second
005617  ** argument match the type set by the previous sqlite3MemdebugSetType().
005618  **
005619  ** Perhaps the most important point is the difference between MEMTYPE_HEAP
005620  ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
005621  ** it might have been allocated by lookaside, except the allocation was
005622  ** too large or lookaside was already full.  It is important to verify
005623  ** that allocations that might have been satisfied by lookaside are not
005624  ** passed back to non-lookaside free() routines.  Asserts such as the
005625  ** example above are placed on the non-lookaside free() routines to verify
005626  ** this constraint.
005627  **
005628  ** All of this is no-op for a production build.  It only comes into
005629  ** play when the SQLITE_MEMDEBUG compile-time option is used.
005630  */
005631  #ifdef SQLITE_MEMDEBUG
005632    void sqlite3MemdebugSetType(void*,u8);
005633    int sqlite3MemdebugHasType(const void*,u8);
005634    int sqlite3MemdebugNoType(const void*,u8);
005635  #else
005636  # define sqlite3MemdebugSetType(X,Y)  /* no-op */
005637  # define sqlite3MemdebugHasType(X,Y)  1
005638  # define sqlite3MemdebugNoType(X,Y)   1
005639  #endif
005640  #define MEMTYPE_HEAP       0x01  /* General heap allocations */
005641  #define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
005642  #define MEMTYPE_PCACHE     0x04  /* Page cache allocations */
005643  
005644  /*
005645  ** Threading interface
005646  */
005647  #if SQLITE_MAX_WORKER_THREADS>0
005648  int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
005649  int sqlite3ThreadJoin(SQLiteThread*, void**);
005650  #endif
005651  
005652  #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
005653  int sqlite3DbpageRegister(sqlite3*);
005654  #endif
005655  #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
005656  int sqlite3DbstatRegister(sqlite3*);
005657  #endif
005658  
005659  int sqlite3ExprVectorSize(const Expr *pExpr);
005660  int sqlite3ExprIsVector(const Expr *pExpr);
005661  Expr *sqlite3VectorFieldSubexpr(Expr*, int);
005662  Expr *sqlite3ExprForVectorField(Parse*,Expr*,int,int);
005663  void sqlite3VectorErrorMsg(Parse*, Expr*);
005664  
005665  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
005666  const char **sqlite3CompileOptions(int *pnOpt);
005667  #endif
005668  
005669  #if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
005670  int sqlite3KvvfsInit(void);
005671  #endif
005672  
005673  #if defined(VDBE_PROFILE) \
005674   || defined(SQLITE_PERFORMANCE_TRACE) \
005675   || defined(SQLITE_ENABLE_STMT_SCANSTATUS)
005676  sqlite3_uint64 sqlite3Hwtime(void);
005677  #endif
005678  
005679  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
005680  # define IS_STMT_SCANSTATUS(db) (db->flags & SQLITE_StmtScanStatus)
005681  #else
005682  # define IS_STMT_SCANSTATUS(db) 0
005683  #endif
005684  
005685  #endif /* SQLITEINT_H */