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