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