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