Merge sqlite-release(3.41.1) into prerelease-integration
[sqlcipher.git] / src / sqliteInt.h
blob8899cdad5e38f638f0454bd95ff8507e8909a3f3
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** Internal interface definitions for SQLite.
15 #ifndef SQLITEINT_H
16 #define SQLITEINT_H
18 /* Special Comments:
20 ** Some comments have special meaning to the tools that measure test
21 ** coverage:
23 ** NO_TEST - The branches on this line are not
24 ** measured by branch coverage. This is
25 ** used on lines of code that actually
26 ** implement parts of coverage testing.
28 ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
29 ** and the correct answer is still obtained,
30 ** though perhaps more slowly.
32 ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
33 ** and the correct answer is still obtained,
34 ** though perhaps more slowly.
36 ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
37 ** that would be harmless and undetectable
38 ** if it did occur.
40 ** In all cases, the special comment must be enclosed in the usual
41 ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
42 ** asterisks and the comment text.
46 ** Make sure the Tcl calling convention macro is defined. This macro is
47 ** only used by test code and Tcl integration code.
49 #ifndef SQLITE_TCLAPI
50 # define SQLITE_TCLAPI
51 #endif
54 ** Include the header file used to customize the compiler options for MSVC.
55 ** This should be done first so that it can successfully prevent spurious
56 ** compiler warnings due to subsequent content in this file and other files
57 ** that are included by this file.
59 #include "msvc.h"
62 ** Special setup for VxWorks
64 #include "vxworks.h"
67 ** These #defines should enable >2GB file support on POSIX if the
68 ** underlying operating system supports it. If the OS lacks
69 ** large file support, or if the OS is windows, these should be no-ops.
71 ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
72 ** system #includes. Hence, this block of code must be the very first
73 ** code in all source files.
75 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
76 ** on the compiler command line. This is necessary if you are compiling
77 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
78 ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
79 ** without this option, LFS is enable. But LFS does not exist in the kernel
80 ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
81 ** portability you should omit LFS.
83 ** The previous paragraph was written in 2005. (This paragraph is written
84 ** on 2008-11-28.) These days, all Linux kernels support large files, so
85 ** you should probably leave LFS enabled. But some embedded platforms might
86 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
88 ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
90 #ifndef SQLITE_DISABLE_LFS
91 # define _LARGE_FILE 1
92 # ifndef _FILE_OFFSET_BITS
93 # define _FILE_OFFSET_BITS 64
94 # endif
95 # define _LARGEFILE_SOURCE 1
96 #endif
98 /* The GCC_VERSION and MSVC_VERSION macros are used to
99 ** conditionally include optimizations for each of these compilers. A
100 ** value of 0 means that compiler is not being used. The
101 ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
102 ** optimizations, and hence set all compiler macros to 0
104 ** There was once also a CLANG_VERSION macro. However, we learn that the
105 ** version numbers in clang are for "marketing" only and are inconsistent
106 ** and unreliable. Fortunately, all versions of clang also recognize the
107 ** gcc version numbers and have reasonable settings for gcc version numbers,
108 ** so the GCC_VERSION macro will be set to a correct non-zero value even
109 ** when compiling with clang.
111 #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
112 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
113 #else
114 # define GCC_VERSION 0
115 #endif
116 #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
117 # define MSVC_VERSION _MSC_VER
118 #else
119 # define MSVC_VERSION 0
120 #endif
123 ** Some C99 functions in "math.h" are only present for MSVC when its version
124 ** is associated with Visual Studio 2013 or higher.
126 #ifndef SQLITE_HAVE_C99_MATH_FUNCS
127 # if MSVC_VERSION==0 || MSVC_VERSION>=1800
128 # define SQLITE_HAVE_C99_MATH_FUNCS (1)
129 # else
130 # define SQLITE_HAVE_C99_MATH_FUNCS (0)
131 # endif
132 #endif
134 /* Needed for various definitions... */
135 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
136 # define _GNU_SOURCE
137 #endif
139 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
140 # define _BSD_SOURCE
141 #endif
144 ** Macro to disable warnings about missing "break" at the end of a "case".
146 #if GCC_VERSION>=7000000
147 # define deliberate_fall_through __attribute__((fallthrough));
148 #else
149 # define deliberate_fall_through
150 #endif
153 ** For MinGW, check to see if we can include the header file containing its
154 ** version information, among other things. Normally, this internal MinGW
155 ** header file would [only] be included automatically by other MinGW header
156 ** files; however, the contained version information is now required by this
157 ** header file to work around binary compatibility issues (see below) and
158 ** this is the only known way to reliably obtain it. This entire #if block
159 ** would be completely unnecessary if there was any other way of detecting
160 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
161 ** some MinGW-specific macros). When compiling for MinGW, either the
162 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
163 ** defined; otherwise, detection of conditions specific to MinGW will be
164 ** disabled.
166 #if defined(_HAVE_MINGW_H)
167 # include "mingw.h"
168 #elif defined(_HAVE__MINGW_H)
169 # include "_mingw.h"
170 #endif
173 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
174 ** define is required to maintain binary compatibility with the MSVC runtime
175 ** library in use (e.g. for Windows XP).
177 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
178 defined(_WIN32) && !defined(_WIN64) && \
179 defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
180 defined(__MSVCRT__)
181 # define _USE_32BIT_TIME_T
182 #endif
184 /* Optionally #include a user-defined header, whereby compilation options
185 ** may be set prior to where they take effect, but after platform setup.
186 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
187 ** file.
189 #ifdef SQLITE_CUSTOM_INCLUDE
190 # define INC_STRINGIFY_(f) #f
191 # define INC_STRINGIFY(f) INC_STRINGIFY_(f)
192 # include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
193 #endif
195 /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
196 ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
197 ** MinGW.
199 #include "sqlite3.h"
202 ** Reuse the STATIC_LRU for mutex access to sqlite3_temp_directory.
204 #define SQLITE_MUTEX_STATIC_TEMPDIR SQLITE_MUTEX_STATIC_VFS1
207 ** Include the configuration header output by 'configure' if we're using the
208 ** autoconf-based build
210 #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
211 #include "sqlite_cfg.h"
212 #define SQLITECONFIG_H 1
213 #endif
215 #include "sqliteLimit.h"
217 /* Disable nuisance warnings on Borland compilers */
218 #if defined(__BORLANDC__)
219 #pragma warn -rch /* unreachable code */
220 #pragma warn -ccc /* Condition is always true or false */
221 #pragma warn -aus /* Assigned value is never used */
222 #pragma warn -csu /* Comparing signed and unsigned */
223 #pragma warn -spa /* Suspicious pointer arithmetic */
224 #endif
227 ** WAL mode depends on atomic aligned 32-bit loads and stores in a few
228 ** places. The following macros try to make this explicit.
230 #ifndef __has_extension
231 # define __has_extension(x) 0 /* compatibility with non-clang compilers */
232 #endif
233 #if GCC_VERSION>=4007000 || __has_extension(c_atomic)
234 # define SQLITE_ATOMIC_INTRINSICS 1
235 # define AtomicLoad(PTR) __atomic_load_n((PTR),__ATOMIC_RELAXED)
236 # define AtomicStore(PTR,VAL) __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
237 #else
238 # define SQLITE_ATOMIC_INTRINSICS 0
239 # define AtomicLoad(PTR) (*(PTR))
240 # define AtomicStore(PTR,VAL) (*(PTR) = (VAL))
241 #endif
244 ** Include standard header files as necessary
246 #ifdef HAVE_STDINT_H
247 #include <stdint.h>
248 #endif
249 #ifdef HAVE_INTTYPES_H
250 #include <inttypes.h>
251 #endif
254 ** The following macros are used to cast pointers to integers and
255 ** integers to pointers. The way you do this varies from one compiler
256 ** to the next, so we have developed the following set of #if statements
257 ** to generate appropriate macros for a wide range of compilers.
259 ** The correct "ANSI" way to do this is to use the intptr_t type.
260 ** Unfortunately, that typedef is not available on all compilers, or
261 ** if it is available, it requires an #include of specific headers
262 ** that vary from one machine to the next.
264 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
265 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
266 ** So we have to define the macros in different ways depending on the
267 ** compiler.
269 #if defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
270 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
271 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
272 #elif defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
273 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
274 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
275 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
276 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
277 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
278 #else /* Generates a warning - but it always works */
279 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
280 # define SQLITE_PTR_TO_INT(X) ((int)(X))
281 #endif
284 ** A macro to hint to the compiler that a function should not be
285 ** inlined.
287 #if defined(__GNUC__)
288 # define SQLITE_NOINLINE __attribute__((noinline))
289 #elif defined(_MSC_VER) && _MSC_VER>=1310
290 # define SQLITE_NOINLINE __declspec(noinline)
291 #else
292 # define SQLITE_NOINLINE
293 #endif
296 ** Make sure that the compiler intrinsics we desire are enabled when
297 ** compiling with an appropriate version of MSVC unless prevented by
298 ** the SQLITE_DISABLE_INTRINSIC define.
300 #if !defined(SQLITE_DISABLE_INTRINSIC)
301 # if defined(_MSC_VER) && _MSC_VER>=1400
302 # if !defined(_WIN32_WCE)
303 # include <intrin.h>
304 # pragma intrinsic(_byteswap_ushort)
305 # pragma intrinsic(_byteswap_ulong)
306 # pragma intrinsic(_byteswap_uint64)
307 # pragma intrinsic(_ReadWriteBarrier)
308 # else
309 # include <cmnintrin.h>
310 # endif
311 # endif
312 #endif
315 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
316 ** 0 means mutexes are permanently disable and the library is never
317 ** threadsafe. 1 means the library is serialized which is the highest
318 ** level of threadsafety. 2 means the library is multithreaded - multiple
319 ** threads can use SQLite as long as no two threads try to use the same
320 ** database connection at the same time.
322 ** Older versions of SQLite used an optional THREADSAFE macro.
323 ** We support that for legacy.
325 ** To ensure that the correct value of "THREADSAFE" is reported when querying
326 ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
327 ** logic is partially replicated in ctime.c. If it is updated here, it should
328 ** also be updated there.
330 #if !defined(SQLITE_THREADSAFE)
331 # if defined(THREADSAFE)
332 # define SQLITE_THREADSAFE THREADSAFE
333 # else
334 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
335 # endif
336 #endif
339 ** Powersafe overwrite is on by default. But can be turned off using
340 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
342 #ifndef SQLITE_POWERSAFE_OVERWRITE
343 # define SQLITE_POWERSAFE_OVERWRITE 1
344 #endif
347 ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
348 ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
349 ** which case memory allocation statistics are disabled by default.
351 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
352 # define SQLITE_DEFAULT_MEMSTATUS 1
353 #endif
356 ** Exactly one of the following macros must be defined in order to
357 ** specify which memory allocation subsystem to use.
359 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
360 ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
361 ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
362 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
364 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
365 ** assert() macro is enabled, each call into the Win32 native heap subsystem
366 ** will cause HeapValidate to be called. If heap validation should fail, an
367 ** assertion will be triggered.
369 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
370 ** the default.
372 #if defined(SQLITE_SYSTEM_MALLOC) \
373 + defined(SQLITE_WIN32_MALLOC) \
374 + defined(SQLITE_ZERO_MALLOC) \
375 + defined(SQLITE_MEMDEBUG)>1
376 # error "Two or more of the following compile-time configuration options\
377 are defined but at most one is allowed:\
378 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
379 SQLITE_ZERO_MALLOC"
380 #endif
381 #if defined(SQLITE_SYSTEM_MALLOC) \
382 + defined(SQLITE_WIN32_MALLOC) \
383 + defined(SQLITE_ZERO_MALLOC) \
384 + defined(SQLITE_MEMDEBUG)==0
385 # define SQLITE_SYSTEM_MALLOC 1
386 #endif
389 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
390 ** sizes of memory allocations below this value where possible.
392 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
393 # define SQLITE_MALLOC_SOFT_LIMIT 1024
394 #endif
397 ** We need to define _XOPEN_SOURCE as follows in order to enable
398 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
399 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
400 ** it.
402 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
403 # define _XOPEN_SOURCE 600
404 #endif
407 ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
408 ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
409 ** make it true by defining or undefining NDEBUG.
411 ** Setting NDEBUG makes the code smaller and faster by disabling the
412 ** assert() statements in the code. So we want the default action
413 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
414 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
415 ** feature.
417 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
418 # define NDEBUG 1
419 #endif
420 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
421 # undef NDEBUG
422 #endif
425 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
427 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
428 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
429 #endif
432 ** The testcase() macro is used to aid in coverage testing. When
433 ** doing coverage testing, the condition inside the argument to
434 ** testcase() must be evaluated both true and false in order to
435 ** get full branch coverage. The testcase() macro is inserted
436 ** to help ensure adequate test coverage in places where simple
437 ** condition/decision coverage is inadequate. For example, testcase()
438 ** can be used to make sure boundary values are tested. For
439 ** bitmask tests, testcase() can be used to make sure each bit
440 ** is significant and used at least once. On switch statements
441 ** where multiple cases go to the same block of code, testcase()
442 ** can insure that all cases are evaluated.
444 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
445 # ifndef SQLITE_AMALGAMATION
446 extern unsigned int sqlite3CoverageCounter;
447 # endif
448 # define testcase(X) if( X ){ sqlite3CoverageCounter += (unsigned)__LINE__; }
449 #else
450 # define testcase(X)
451 #endif
454 ** The TESTONLY macro is used to enclose variable declarations or
455 ** other bits of code that are needed to support the arguments
456 ** within testcase() and assert() macros.
458 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
459 # define TESTONLY(X) X
460 #else
461 # define TESTONLY(X)
462 #endif
465 ** Sometimes we need a small amount of code such as a variable initialization
466 ** to setup for a later assert() statement. We do not want this code to
467 ** appear when assert() is disabled. The following macro is therefore
468 ** used to contain that setup code. The "VVA" acronym stands for
469 ** "Verification, Validation, and Accreditation". In other words, the
470 ** code within VVA_ONLY() will only run during verification processes.
472 #ifndef NDEBUG
473 # define VVA_ONLY(X) X
474 #else
475 # define VVA_ONLY(X)
476 #endif
479 ** Disable ALWAYS() and NEVER() (make them pass-throughs) for coverage
480 ** and mutation testing
482 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
483 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
484 #endif
487 ** The ALWAYS and NEVER macros surround boolean expressions which
488 ** are intended to always be true or false, respectively. Such
489 ** expressions could be omitted from the code completely. But they
490 ** are included in a few cases in order to enhance the resilience
491 ** of SQLite to unexpected behavior - to make the code "self-healing"
492 ** or "ductile" rather than being "brittle" and crashing at the first
493 ** hint of unplanned behavior.
495 ** In other words, ALWAYS and NEVER are added for defensive code.
497 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
498 ** be true and false so that the unreachable code they specify will
499 ** not be counted as untested code.
501 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
502 # define ALWAYS(X) (1)
503 # define NEVER(X) (0)
504 #elif !defined(NDEBUG)
505 # define ALWAYS(X) ((X)?1:(assert(0),0))
506 # define NEVER(X) ((X)?(assert(0),1):0)
507 #else
508 # define ALWAYS(X) (X)
509 # define NEVER(X) (X)
510 #endif
513 ** Some conditionals are optimizations only. In other words, if the
514 ** conditionals are replaced with a constant 1 (true) or 0 (false) then
515 ** the correct answer is still obtained, though perhaps not as quickly.
517 ** The following macros mark these optimizations conditionals.
519 #if defined(SQLITE_MUTATION_TEST)
520 # define OK_IF_ALWAYS_TRUE(X) (1)
521 # define OK_IF_ALWAYS_FALSE(X) (0)
522 #else
523 # define OK_IF_ALWAYS_TRUE(X) (X)
524 # define OK_IF_ALWAYS_FALSE(X) (X)
525 #endif
528 ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
529 ** defined. We need to defend against those failures when testing with
530 ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
531 ** during a normal build. The following macro can be used to disable tests
532 ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
534 #if defined(SQLITE_TEST_REALLOC_STRESS)
535 # define ONLY_IF_REALLOC_STRESS(X) (X)
536 #elif !defined(NDEBUG)
537 # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
538 #else
539 # define ONLY_IF_REALLOC_STRESS(X) (0)
540 #endif
543 ** Declarations used for tracing the operating system interfaces.
545 #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
546 (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
547 extern int sqlite3OSTrace;
548 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
549 # define SQLITE_HAVE_OS_TRACE
550 #else
551 # define OSTRACE(X)
552 # undef SQLITE_HAVE_OS_TRACE
553 #endif
556 ** Is the sqlite3ErrName() function needed in the build? Currently,
557 ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
558 ** OSTRACE is enabled), and by several "test*.c" files (which are
559 ** compiled using SQLITE_TEST).
561 #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
562 (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
563 # define SQLITE_NEED_ERR_NAME
564 #else
565 # undef SQLITE_NEED_ERR_NAME
566 #endif
569 ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
571 #ifdef SQLITE_OMIT_EXPLAIN
572 # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
573 #endif
576 ** SQLITE_OMIT_VIRTUALTABLE implies SQLITE_OMIT_ALTERTABLE
578 #if defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_ALTERTABLE)
579 # define SQLITE_OMIT_ALTERTABLE
580 #endif
583 ** Return true (non-zero) if the input is an integer that is too large
584 ** to fit in 32-bits. This macro is used inside of various testcase()
585 ** macros to verify that we have tested SQLite for large-file support.
587 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
590 ** The macro unlikely() is a hint that surrounds a boolean
591 ** expression that is usually false. Macro likely() surrounds
592 ** a boolean expression that is usually true. These hints could,
593 ** in theory, be used by the compiler to generate better code, but
594 ** currently they are just comments for human readers.
596 #define likely(X) (X)
597 #define unlikely(X) (X)
599 #include "hash.h"
600 #include "parse.h"
601 #include <stdio.h>
602 #include <stdlib.h>
603 #include <string.h>
604 #include <assert.h>
605 #include <stddef.h>
608 ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
609 ** This allows better measurements of where memcpy() is used when running
610 ** cachegrind. But this macro version of memcpy() is very slow so it
611 ** should not be used in production. This is a performance measurement
612 ** hack only.
614 #ifdef SQLITE_INLINE_MEMCPY
615 # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
616 int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
617 #endif
620 ** If compiling for a processor that lacks floating point support,
621 ** substitute integer for floating-point
623 #ifdef SQLITE_OMIT_FLOATING_POINT
624 # define double sqlite_int64
625 # define float sqlite_int64
626 # define LONGDOUBLE_TYPE sqlite_int64
627 # ifndef SQLITE_BIG_DBL
628 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
629 # endif
630 # define SQLITE_OMIT_DATETIME_FUNCS 1
631 # define SQLITE_OMIT_TRACE 1
632 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
633 # undef SQLITE_HAVE_ISNAN
634 #endif
635 #ifndef SQLITE_BIG_DBL
636 # define SQLITE_BIG_DBL (1e99)
637 #endif
640 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
641 ** afterward. Having this macro allows us to cause the C compiler
642 ** to omit code used by TEMP tables without messy #ifndef statements.
644 #ifdef SQLITE_OMIT_TEMPDB
645 #define OMIT_TEMPDB 1
646 #else
647 #define OMIT_TEMPDB 0
648 #endif
651 ** The "file format" number is an integer that is incremented whenever
652 ** the VDBE-level file format changes. The following macros define the
653 ** the default file format for new databases and the maximum file format
654 ** that the library can read.
656 #define SQLITE_MAX_FILE_FORMAT 4
657 #ifndef SQLITE_DEFAULT_FILE_FORMAT
658 # define SQLITE_DEFAULT_FILE_FORMAT 4
659 #endif
662 ** Determine whether triggers are recursive by default. This can be
663 ** changed at run-time using a pragma.
665 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
666 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
667 #endif
670 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
671 ** on the command-line
673 #ifndef SQLITE_TEMP_STORE
674 # define SQLITE_TEMP_STORE 1
675 #endif
678 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
679 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
680 ** to zero.
682 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
683 # undef SQLITE_MAX_WORKER_THREADS
684 # define SQLITE_MAX_WORKER_THREADS 0
685 #endif
686 #ifndef SQLITE_MAX_WORKER_THREADS
687 # define SQLITE_MAX_WORKER_THREADS 8
688 #endif
689 #ifndef SQLITE_DEFAULT_WORKER_THREADS
690 # define SQLITE_DEFAULT_WORKER_THREADS 0
691 #endif
692 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
693 # undef SQLITE_MAX_WORKER_THREADS
694 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
695 #endif
698 ** The default initial allocation for the pagecache when using separate
699 ** pagecaches for each database connection. A positive number is the
700 ** number of pages. A negative number N translations means that a buffer
701 ** of -1024*N bytes is allocated and used for as many pages as it will hold.
703 ** The default value of "20" was chosen to minimize the run-time of the
704 ** speedtest1 test program with options: --shrink-memory --reprepare
706 #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
707 # define SQLITE_DEFAULT_PCACHE_INITSZ 20
708 #endif
711 ** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
713 #ifndef SQLITE_DEFAULT_SORTERREF_SIZE
714 # define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff
715 #endif
718 ** The compile-time options SQLITE_MMAP_READWRITE and
719 ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
720 ** You must choose one or the other (or neither) but not both.
722 #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
723 #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
724 #endif
727 ** GCC does not define the offsetof() macro so we'll have to do it
728 ** ourselves.
730 #ifndef offsetof
731 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
732 #endif
735 ** Macros to compute minimum and maximum of two numbers.
737 #ifndef MIN
738 # define MIN(A,B) ((A)<(B)?(A):(B))
739 #endif
740 #ifndef MAX
741 # define MAX(A,B) ((A)>(B)?(A):(B))
742 #endif
745 ** Swap two objects of type TYPE.
747 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
750 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
751 ** not, there are still machines out there that use EBCDIC.)
753 #if 'A' == '\301'
754 # define SQLITE_EBCDIC 1
755 #else
756 # define SQLITE_ASCII 1
757 #endif
760 ** Integers of known sizes. These typedefs might change for architectures
761 ** where the sizes very. Preprocessor macros are available so that the
762 ** types can be conveniently redefined at compile-type. Like this:
764 ** cc '-DUINTPTR_TYPE=long long int' ...
766 #ifndef UINT32_TYPE
767 # ifdef HAVE_UINT32_T
768 # define UINT32_TYPE uint32_t
769 # else
770 # define UINT32_TYPE unsigned int
771 # endif
772 #endif
773 #ifndef UINT16_TYPE
774 # ifdef HAVE_UINT16_T
775 # define UINT16_TYPE uint16_t
776 # else
777 # define UINT16_TYPE unsigned short int
778 # endif
779 #endif
780 #ifndef INT16_TYPE
781 # ifdef HAVE_INT16_T
782 # define INT16_TYPE int16_t
783 # else
784 # define INT16_TYPE short int
785 # endif
786 #endif
787 #ifndef UINT8_TYPE
788 # ifdef HAVE_UINT8_T
789 # define UINT8_TYPE uint8_t
790 # else
791 # define UINT8_TYPE unsigned char
792 # endif
793 #endif
794 #ifndef INT8_TYPE
795 # ifdef HAVE_INT8_T
796 # define INT8_TYPE int8_t
797 # else
798 # define INT8_TYPE signed char
799 # endif
800 #endif
801 #ifndef LONGDOUBLE_TYPE
802 # define LONGDOUBLE_TYPE long double
803 #endif
804 typedef sqlite_int64 i64; /* 8-byte signed integer */
805 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
806 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
807 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
808 typedef INT16_TYPE i16; /* 2-byte signed integer */
809 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
810 typedef INT8_TYPE i8; /* 1-byte signed integer */
813 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
814 ** that can be stored in a u32 without loss of data. The value
815 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
816 ** have to specify the value in the less intuitive manner shown:
818 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
821 ** The datatype used to store estimates of the number of rows in a
822 ** table or index.
824 typedef u64 tRowcnt;
827 ** Estimated quantities used for query planning are stored as 16-bit
828 ** logarithms. For quantity X, the value stored is 10*log2(X). This
829 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
830 ** But the allowed values are "grainy". Not every value is representable.
831 ** For example, quantities 16 and 17 are both represented by a LogEst
832 ** of 40. However, since LogEst quantities are suppose to be estimates,
833 ** not exact values, this imprecision is not a problem.
835 ** "LogEst" is short for "Logarithmic Estimate".
837 ** Examples:
838 ** 1 -> 0 20 -> 43 10000 -> 132
839 ** 2 -> 10 25 -> 46 25000 -> 146
840 ** 3 -> 16 100 -> 66 1000000 -> 199
841 ** 4 -> 20 1000 -> 99 1048576 -> 200
842 ** 10 -> 33 1024 -> 100 4294967296 -> 320
844 ** The LogEst can be negative to indicate fractional values.
845 ** Examples:
847 ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
849 typedef INT16_TYPE LogEst;
852 ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
854 #ifndef SQLITE_PTRSIZE
855 # if defined(__SIZEOF_POINTER__)
856 # define SQLITE_PTRSIZE __SIZEOF_POINTER__
857 # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
858 defined(_M_ARM) || defined(__arm__) || defined(__x86) || \
859 (defined(__APPLE__) && defined(__POWERPC__)) || \
860 (defined(__TOS_AIX__) && !defined(__64BIT__))
861 # define SQLITE_PTRSIZE 4
862 # else
863 # define SQLITE_PTRSIZE 8
864 # endif
865 #endif
867 /* The uptr type is an unsigned integer large enough to hold a pointer
869 #if defined(HAVE_STDINT_H)
870 typedef uintptr_t uptr;
871 #elif SQLITE_PTRSIZE==4
872 typedef u32 uptr;
873 #else
874 typedef u64 uptr;
875 #endif
878 ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
879 ** something between S (inclusive) and E (exclusive).
881 ** In other words, S is a buffer and E is a pointer to the first byte after
882 ** the end of buffer S. This macro returns true if P points to something
883 ** contained within the buffer S.
885 #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
889 ** Macros to determine whether the machine is big or little endian,
890 ** and whether or not that determination is run-time or compile-time.
892 ** For best performance, an attempt is made to guess at the byte-order
893 ** using C-preprocessor macros. If that is unsuccessful, or if
894 ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
895 ** at run-time.
897 #ifndef SQLITE_BYTEORDER
898 # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
899 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
900 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
901 defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
902 # define SQLITE_BYTEORDER 1234
903 # elif defined(sparc) || defined(__ppc__) || \
904 defined(__ARMEB__) || defined(__AARCH64EB__)
905 # define SQLITE_BYTEORDER 4321
906 # else
907 # define SQLITE_BYTEORDER 0
908 # endif
909 #endif
910 #if SQLITE_BYTEORDER==4321
911 # define SQLITE_BIGENDIAN 1
912 # define SQLITE_LITTLEENDIAN 0
913 # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
914 #elif SQLITE_BYTEORDER==1234
915 # define SQLITE_BIGENDIAN 0
916 # define SQLITE_LITTLEENDIAN 1
917 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
918 #else
919 # ifdef SQLITE_AMALGAMATION
920 const int sqlite3one = 1;
921 # else
922 extern const int sqlite3one;
923 # endif
924 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
925 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
926 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
927 #endif
930 ** Constants for the largest and smallest possible 64-bit signed integers.
931 ** These macros are designed to work correctly on both 32-bit and 64-bit
932 ** compilers.
934 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
935 #define LARGEST_UINT64 (0xffffffff|(((u64)0xffffffff)<<32))
936 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
939 ** Round up a number to the next larger multiple of 8. This is used
940 ** to force 8-byte alignment on 64-bit architectures.
942 ** ROUND8() always does the rounding, for any argument.
944 ** ROUND8P() assumes that the argument is already an integer number of
945 ** pointers in size, and so it is a no-op on systems where the pointer
946 ** size is 8.
948 #define ROUND8(x) (((x)+7)&~7)
949 #if SQLITE_PTRSIZE==8
950 # define ROUND8P(x) (x)
951 #else
952 # define ROUND8P(x) (((x)+7)&~7)
953 #endif
956 ** Round down to the nearest multiple of 8
958 #define ROUNDDOWN8(x) ((x)&~7)
961 ** Assert that the pointer X is aligned to an 8-byte boundary. This
962 ** macro is used only within assert() to verify that the code gets
963 ** all alignment restrictions correct.
965 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
966 ** underlying malloc() implementation might return us 4-byte aligned
967 ** pointers. In that case, only verify 4-byte alignment.
969 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
970 # define EIGHT_BYTE_ALIGNMENT(X) ((((uptr)(X) - (uptr)0)&3)==0)
971 #else
972 # define EIGHT_BYTE_ALIGNMENT(X) ((((uptr)(X) - (uptr)0)&7)==0)
973 #endif
976 ** Disable MMAP on platforms where it is known to not work
978 #if defined(__OpenBSD__) || defined(__QNXNTO__)
979 # undef SQLITE_MAX_MMAP_SIZE
980 # define SQLITE_MAX_MMAP_SIZE 0
981 #endif
984 ** Default maximum size of memory used by memory-mapped I/O in the VFS
986 #ifdef __APPLE__
987 # include <TargetConditionals.h>
988 #endif
989 #ifndef SQLITE_MAX_MMAP_SIZE
990 # if defined(__linux__) \
991 || defined(_WIN32) \
992 || (defined(__APPLE__) && defined(__MACH__)) \
993 || defined(__sun) \
994 || defined(__FreeBSD__) \
995 || defined(__DragonFly__)
996 # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
997 # else
998 # define SQLITE_MAX_MMAP_SIZE 0
999 # endif
1000 #endif
1003 ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
1004 ** default MMAP_SIZE is specified at compile-time, make sure that it does
1005 ** not exceed the maximum mmap size.
1007 #ifndef SQLITE_DEFAULT_MMAP_SIZE
1008 # define SQLITE_DEFAULT_MMAP_SIZE 0
1009 #endif
1010 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
1011 # undef SQLITE_DEFAULT_MMAP_SIZE
1012 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
1013 #endif
1016 ** TREETRACE_ENABLED will be either 1 or 0 depending on whether or not
1017 ** the Abstract Syntax Tree tracing logic is turned on.
1019 #if !defined(SQLITE_AMALGAMATION)
1020 extern u32 sqlite3TreeTrace;
1021 #endif
1022 #if defined(SQLITE_DEBUG) \
1023 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_SELECTTRACE) \
1024 || defined(SQLITE_ENABLE_TREETRACE))
1025 # define TREETRACE_ENABLED 1
1026 # define TREETRACE(K,P,S,X) \
1027 if(sqlite3TreeTrace&(K)) \
1028 sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
1029 sqlite3DebugPrintf X
1030 #else
1031 # define TREETRACE(K,P,S,X)
1032 # define TREETRACE_ENABLED 0
1033 #endif
1035 /* TREETRACE flag meanings:
1037 ** 0x00000001 Beginning and end of SELECT processing
1038 ** 0x00000002 WHERE clause processing
1039 ** 0x00000004 Query flattener
1040 ** 0x00000008 Result-set wildcard expansion
1041 ** 0x00000010 Query name resolution
1042 ** 0x00000020 Aggregate analysis
1043 ** 0x00000040 Window functions
1044 ** 0x00000080 Generated column names
1045 ** 0x00000100 Move HAVING terms into WHERE
1046 ** 0x00000200 Count-of-view optimization
1047 ** 0x00000400 Compound SELECT processing
1048 ** 0x00000800 Drop superfluous ORDER BY
1049 ** 0x00001000 LEFT JOIN simplifies to JOIN
1050 ** 0x00002000 Constant propagation
1051 ** 0x00004000 Push-down optimization
1052 ** 0x00008000 After all FROM-clause analysis
1053 ** 0x00010000 Beginning of DELETE/INSERT/UPDATE processing
1054 ** 0x00020000 Transform DISTINCT into GROUP BY
1055 ** 0x00040000 SELECT tree dump after all code has been generated
1059 ** Macros for "wheretrace"
1061 extern u32 sqlite3WhereTrace;
1062 #if defined(SQLITE_DEBUG) \
1063 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
1064 # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
1065 # define WHERETRACE_ENABLED 1
1066 #else
1067 # define WHERETRACE(K,X)
1068 #endif
1071 ** Bits for the sqlite3WhereTrace mask:
1073 ** (---any--) Top-level block structure
1074 ** 0x-------F High-level debug messages
1075 ** 0x----FFF- More detail
1076 ** 0xFFFF---- Low-level debug messages
1078 ** 0x00000001 Code generation
1079 ** 0x00000002 Solver
1080 ** 0x00000004 Solver costs
1081 ** 0x00000008 WhereLoop inserts
1083 ** 0x00000010 Display sqlite3_index_info xBestIndex calls
1084 ** 0x00000020 Range an equality scan metrics
1085 ** 0x00000040 IN operator decisions
1086 ** 0x00000080 WhereLoop cost adjustements
1087 ** 0x00000100
1088 ** 0x00000200 Covering index decisions
1089 ** 0x00000400 OR optimization
1090 ** 0x00000800 Index scanner
1091 ** 0x00001000 More details associated with code generation
1092 ** 0x00002000
1093 ** 0x00004000 Show all WHERE terms at key points
1094 ** 0x00008000 Show the full SELECT statement at key places
1096 ** 0x00010000 Show more detail when printing WHERE terms
1097 ** 0x00020000 Show WHERE terms returned from whereScanNext()
1102 ** An instance of the following structure is used to store the busy-handler
1103 ** callback for a given sqlite handle.
1105 ** The sqlite.busyHandler member of the sqlite struct contains the busy
1106 ** callback for the database handle. Each pager opened via the sqlite
1107 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
1108 ** callback is currently invoked only from within pager.c.
1110 typedef struct BusyHandler BusyHandler;
1111 struct BusyHandler {
1112 int (*xBusyHandler)(void *,int); /* The busy callback */
1113 void *pBusyArg; /* First arg to busy callback */
1114 int nBusy; /* Incremented with each busy call */
1118 ** Name of table that holds the database schema.
1120 ** The PREFERRED names are used whereever possible. But LEGACY is also
1121 ** used for backwards compatibility.
1123 ** 1. Queries can use either the PREFERRED or the LEGACY names
1124 ** 2. The sqlite3_set_authorizer() callback uses the LEGACY name
1125 ** 3. The PRAGMA table_list statement uses the PREFERRED name
1127 ** The LEGACY names are stored in the internal symbol hash table
1128 ** in support of (2). Names are translated using sqlite3PreferredTableName()
1129 ** for (3). The sqlite3FindTable() function takes care of translating
1130 ** names for (1).
1132 ** Note that "sqlite_temp_schema" can also be called "temp.sqlite_schema".
1134 #define LEGACY_SCHEMA_TABLE "sqlite_master"
1135 #define LEGACY_TEMP_SCHEMA_TABLE "sqlite_temp_master"
1136 #define PREFERRED_SCHEMA_TABLE "sqlite_schema"
1137 #define PREFERRED_TEMP_SCHEMA_TABLE "sqlite_temp_schema"
1141 ** The root-page of the schema table.
1143 #define SCHEMA_ROOT 1
1146 ** The name of the schema table. The name is different for TEMP.
1148 #define SCHEMA_TABLE(x) \
1149 ((!OMIT_TEMPDB)&&(x==1)?LEGACY_TEMP_SCHEMA_TABLE:LEGACY_SCHEMA_TABLE)
1152 ** A convenience macro that returns the number of elements in
1153 ** an array.
1155 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
1158 ** Determine if the argument is a power of two
1160 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
1163 ** The following value as a destructor means to use sqlite3DbFree().
1164 ** The sqlite3DbFree() routine requires two parameters instead of the
1165 ** one parameter that destructors normally want. So we have to introduce
1166 ** this magic value that the code knows to handle differently. Any
1167 ** pointer will work here as long as it is distinct from SQLITE_STATIC
1168 ** and SQLITE_TRANSIENT.
1170 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3OomClear)
1173 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
1174 ** not support Writable Static Data (WSD) such as global and static variables.
1175 ** All variables must either be on the stack or dynamically allocated from
1176 ** the heap. When WSD is unsupported, the variable declarations scattered
1177 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
1178 ** macro is used for this purpose. And instead of referencing the variable
1179 ** directly, we use its constant as a key to lookup the run-time allocated
1180 ** buffer that holds real variable. The constant is also the initializer
1181 ** for the run-time allocated buffer.
1183 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
1184 ** macros become no-ops and have zero performance impact.
1186 #ifdef SQLITE_OMIT_WSD
1187 #define SQLITE_WSD const
1188 #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
1189 #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
1190 int sqlite3_wsd_init(int N, int J);
1191 void *sqlite3_wsd_find(void *K, int L);
1192 #else
1193 #define SQLITE_WSD
1194 #define GLOBAL(t,v) v
1195 #define sqlite3GlobalConfig sqlite3Config
1196 #endif
1199 ** The following macros are used to suppress compiler warnings and to
1200 ** make it clear to human readers when a function parameter is deliberately
1201 ** left unused within the body of a function. This usually happens when
1202 ** a function is called via a function pointer. For example the
1203 ** implementation of an SQL aggregate step callback may not use the
1204 ** parameter indicating the number of arguments passed to the aggregate,
1205 ** if it knows that this is enforced elsewhere.
1207 ** When a function parameter is not used at all within the body of a function,
1208 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
1209 ** However, these macros may also be used to suppress warnings related to
1210 ** parameters that may or may not be used depending on compilation options.
1211 ** For example those parameters only used in assert() statements. In these
1212 ** cases the parameters are named as per the usual conventions.
1214 #define UNUSED_PARAMETER(x) (void)(x)
1215 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
1218 ** Forward references to structures
1220 typedef struct AggInfo AggInfo;
1221 typedef struct AuthContext AuthContext;
1222 typedef struct AutoincInfo AutoincInfo;
1223 typedef struct Bitvec Bitvec;
1224 typedef struct CollSeq CollSeq;
1225 typedef struct Column Column;
1226 typedef struct Cte Cte;
1227 typedef struct CteUse CteUse;
1228 typedef struct Db Db;
1229 typedef struct DbFixer DbFixer;
1230 typedef struct Schema Schema;
1231 typedef struct Expr Expr;
1232 typedef struct ExprList ExprList;
1233 typedef struct FKey FKey;
1234 typedef struct FuncDestructor FuncDestructor;
1235 typedef struct FuncDef FuncDef;
1236 typedef struct FuncDefHash FuncDefHash;
1237 typedef struct IdList IdList;
1238 typedef struct Index Index;
1239 typedef struct IndexedExpr IndexedExpr;
1240 typedef struct IndexSample IndexSample;
1241 typedef struct KeyClass KeyClass;
1242 typedef struct KeyInfo KeyInfo;
1243 typedef struct Lookaside Lookaside;
1244 typedef struct LookasideSlot LookasideSlot;
1245 typedef struct Module Module;
1246 typedef struct NameContext NameContext;
1247 typedef struct OnOrUsing OnOrUsing;
1248 typedef struct Parse Parse;
1249 typedef struct ParseCleanup ParseCleanup;
1250 typedef struct PreUpdate PreUpdate;
1251 typedef struct PrintfArguments PrintfArguments;
1252 typedef struct RenameToken RenameToken;
1253 typedef struct Returning Returning;
1254 typedef struct RowSet RowSet;
1255 typedef struct Savepoint Savepoint;
1256 typedef struct Select Select;
1257 typedef struct SQLiteThread SQLiteThread;
1258 typedef struct SelectDest SelectDest;
1259 typedef struct SrcItem SrcItem;
1260 typedef struct SrcList SrcList;
1261 typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
1262 typedef struct Table Table;
1263 typedef struct TableLock TableLock;
1264 typedef struct Token Token;
1265 typedef struct TreeView TreeView;
1266 typedef struct Trigger Trigger;
1267 typedef struct TriggerPrg TriggerPrg;
1268 typedef struct TriggerStep TriggerStep;
1269 typedef struct UnpackedRecord UnpackedRecord;
1270 typedef struct Upsert Upsert;
1271 typedef struct VTable VTable;
1272 typedef struct VtabCtx VtabCtx;
1273 typedef struct Walker Walker;
1274 typedef struct WhereInfo WhereInfo;
1275 typedef struct Window Window;
1276 typedef struct With With;
1280 ** The bitmask datatype defined below is used for various optimizations.
1282 ** Changing this from a 64-bit to a 32-bit type limits the number of
1283 ** tables in a join to 32 instead of 64. But it also reduces the size
1284 ** of the library by 738 bytes on ix86.
1286 #ifdef SQLITE_BITMASK_TYPE
1287 typedef SQLITE_BITMASK_TYPE Bitmask;
1288 #else
1289 typedef u64 Bitmask;
1290 #endif
1293 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
1295 #define BMS ((int)(sizeof(Bitmask)*8))
1298 ** A bit in a Bitmask
1300 #define MASKBIT(n) (((Bitmask)1)<<(n))
1301 #define MASKBIT64(n) (((u64)1)<<(n))
1302 #define MASKBIT32(n) (((unsigned int)1)<<(n))
1303 #define SMASKBIT32(n) ((n)<=31?((unsigned int)1)<<(n):0)
1304 #define ALLBITS ((Bitmask)-1)
1305 #define TOPBIT (((Bitmask)1)<<(BMS-1))
1307 /* A VList object records a mapping between parameters/variables/wildcards
1308 ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
1309 ** variable number associated with that parameter. See the format description
1310 ** on the sqlite3VListAdd() routine for more information. A VList is really
1311 ** just an array of integers.
1313 typedef int VList;
1316 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
1317 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
1318 ** pointer types (i.e. FuncDef) defined above.
1320 #include "os.h"
1321 #include "pager.h"
1322 #include "btree.h"
1323 #include "vdbe.h"
1324 #include "pcache.h"
1325 #include "mutex.h"
1327 /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
1328 ** synchronous setting to EXTRA. It is no longer supported.
1330 #ifdef SQLITE_EXTRA_DURABLE
1331 # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
1332 # define SQLITE_DEFAULT_SYNCHRONOUS 3
1333 #endif
1336 ** Default synchronous levels.
1338 ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
1339 ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
1341 ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
1342 ** OFF 1 0
1343 ** NORMAL 2 1
1344 ** FULL 3 2
1345 ** EXTRA 4 3
1347 ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
1348 ** In other words, the zero-based numbers are used for all external interfaces
1349 ** and the one-based values are used internally.
1351 #ifndef SQLITE_DEFAULT_SYNCHRONOUS
1352 # define SQLITE_DEFAULT_SYNCHRONOUS 2
1353 #endif
1354 #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
1355 # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
1356 #endif
1359 ** Each database file to be accessed by the system is an instance
1360 ** of the following structure. There are normally two of these structures
1361 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
1362 ** aDb[1] is the database file used to hold temporary tables. Additional
1363 ** databases may be attached.
1365 struct Db {
1366 char *zDbSName; /* Name of this database. (schema name, not filename) */
1367 Btree *pBt; /* The B*Tree structure for this database file */
1368 u8 safety_level; /* How aggressive at syncing data to disk */
1369 u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
1370 Schema *pSchema; /* Pointer to database schema (possibly shared) */
1374 ** An instance of the following structure stores a database schema.
1376 ** Most Schema objects are associated with a Btree. The exception is
1377 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
1378 ** In shared cache mode, a single Schema object can be shared by multiple
1379 ** Btrees that refer to the same underlying BtShared object.
1381 ** Schema objects are automatically deallocated when the last Btree that
1382 ** references them is destroyed. The TEMP Schema is manually freed by
1383 ** sqlite3_close().
1385 ** A thread must be holding a mutex on the corresponding Btree in order
1386 ** to access Schema content. This implies that the thread must also be
1387 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
1388 ** For a TEMP Schema, only the connection mutex is required.
1390 struct Schema {
1391 int schema_cookie; /* Database schema version number for this file */
1392 int iGeneration; /* Generation counter. Incremented with each change */
1393 Hash tblHash; /* All tables indexed by name */
1394 Hash idxHash; /* All (named) indices indexed by name */
1395 Hash trigHash; /* All triggers indexed by name */
1396 Hash fkeyHash; /* All foreign keys by referenced table name */
1397 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
1398 u8 file_format; /* Schema format version for this file */
1399 u8 enc; /* Text encoding used by this database */
1400 u16 schemaFlags; /* Flags associated with this schema */
1401 int cache_size; /* Number of pages to use in the cache */
1405 ** These macros can be used to test, set, or clear bits in the
1406 ** Db.pSchema->flags field.
1408 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
1409 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
1410 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
1411 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
1414 ** Allowed values for the DB.pSchema->flags field.
1416 ** The DB_SchemaLoaded flag is set after the database schema has been
1417 ** read into internal hash tables.
1419 ** DB_UnresetViews means that one or more views have column names that
1420 ** have been filled out. If the schema changes, these column names might
1421 ** changes and so the view will need to be reset.
1423 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
1424 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
1425 #define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */
1428 ** The number of different kinds of things that can be limited
1429 ** using the sqlite3_limit() interface.
1431 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
1434 ** Lookaside malloc is a set of fixed-size buffers that can be used
1435 ** to satisfy small transient memory allocation requests for objects
1436 ** associated with a particular database connection. The use of
1437 ** lookaside malloc provides a significant performance enhancement
1438 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
1439 ** SQL statements.
1441 ** The Lookaside structure holds configuration information about the
1442 ** lookaside malloc subsystem. Each available memory allocation in
1443 ** the lookaside subsystem is stored on a linked list of LookasideSlot
1444 ** objects.
1446 ** Lookaside allocations are only allowed for objects that are associated
1447 ** with a particular database connection. Hence, schema information cannot
1448 ** be stored in lookaside because in shared cache mode the schema information
1449 ** is shared by multiple database connections. Therefore, while parsing
1450 ** schema information, the Lookaside.bEnabled flag is cleared so that
1451 ** lookaside allocations are not used to construct the schema objects.
1453 ** New lookaside allocations are only allowed if bDisable==0. When
1454 ** bDisable is greater than zero, sz is set to zero which effectively
1455 ** disables lookaside without adding a new test for the bDisable flag
1456 ** in a performance-critical path. sz should be set by to szTrue whenever
1457 ** bDisable changes back to zero.
1459 ** Lookaside buffers are initially held on the pInit list. As they are
1460 ** used and freed, they are added back to the pFree list. New allocations
1461 ** come off of pFree first, then pInit as a fallback. This dual-list
1462 ** allows use to compute a high-water mark - the maximum number of allocations
1463 ** outstanding at any point in the past - by subtracting the number of
1464 ** allocations on the pInit list from the total number of allocations.
1466 ** Enhancement on 2019-12-12: Two-size-lookaside
1467 ** The default lookaside configuration is 100 slots of 1200 bytes each.
1468 ** The larger slot sizes are important for performance, but they waste
1469 ** a lot of space, as most lookaside allocations are less than 128 bytes.
1470 ** The two-size-lookaside enhancement breaks up the lookaside allocation
1471 ** into two pools: One of 128-byte slots and the other of the default size
1472 ** (1200-byte) slots. Allocations are filled from the small-pool first,
1473 ** failing over to the full-size pool if that does not work. Thus more
1474 ** lookaside slots are available while also using less memory.
1475 ** This enhancement can be omitted by compiling with
1476 ** SQLITE_OMIT_TWOSIZE_LOOKASIDE.
1478 struct Lookaside {
1479 u32 bDisable; /* Only operate the lookaside when zero */
1480 u16 sz; /* Size of each buffer in bytes */
1481 u16 szTrue; /* True value of sz, even if disabled */
1482 u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
1483 u32 nSlot; /* Number of lookaside slots allocated */
1484 u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
1485 LookasideSlot *pInit; /* List of buffers not previously used */
1486 LookasideSlot *pFree; /* List of available buffers */
1487 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
1488 LookasideSlot *pSmallInit; /* List of small buffers not prediously used */
1489 LookasideSlot *pSmallFree; /* List of available small buffers */
1490 void *pMiddle; /* First byte past end of full-size buffers and
1491 ** the first byte of LOOKASIDE_SMALL buffers */
1492 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
1493 void *pStart; /* First byte of available memory space */
1494 void *pEnd; /* First byte past end of available space */
1495 void *pTrueEnd; /* True value of pEnd, when db->pnBytesFreed!=0 */
1497 struct LookasideSlot {
1498 LookasideSlot *pNext; /* Next buffer in the list of free buffers */
1501 #define DisableLookaside db->lookaside.bDisable++;db->lookaside.sz=0
1502 #define EnableLookaside db->lookaside.bDisable--;\
1503 db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue
1505 /* Size of the smaller allocations in two-size lookside */
1506 #ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
1507 # define LOOKASIDE_SMALL 0
1508 #else
1509 # define LOOKASIDE_SMALL 128
1510 #endif
1513 ** A hash table for built-in function definitions. (Application-defined
1514 ** functions use a regular table table from hash.h.)
1516 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
1517 ** Collisions are on the FuncDef.u.pHash chain. Use the SQLITE_FUNC_HASH()
1518 ** macro to compute a hash on the function name.
1520 #define SQLITE_FUNC_HASH_SZ 23
1521 struct FuncDefHash {
1522 FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
1524 #define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)
1526 #ifdef SQLITE_USER_AUTHENTICATION
1528 ** Information held in the "sqlite3" database connection object and used
1529 ** to manage user authentication.
1531 typedef struct sqlite3_userauth sqlite3_userauth;
1532 struct sqlite3_userauth {
1533 u8 authLevel; /* Current authentication level */
1534 int nAuthPW; /* Size of the zAuthPW in bytes */
1535 char *zAuthPW; /* Password used to authenticate */
1536 char *zAuthUser; /* User name used to authenticate */
1539 /* Allowed values for sqlite3_userauth.authLevel */
1540 #define UAUTH_Unknown 0 /* Authentication not yet checked */
1541 #define UAUTH_Fail 1 /* User authentication failed */
1542 #define UAUTH_User 2 /* Authenticated as a normal user */
1543 #define UAUTH_Admin 3 /* Authenticated as an administrator */
1545 /* Functions used only by user authorization logic */
1546 int sqlite3UserAuthTable(const char*);
1547 int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
1548 void sqlite3UserAuthInit(sqlite3*);
1549 void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
1551 #endif /* SQLITE_USER_AUTHENTICATION */
1554 ** typedef for the authorization callback function.
1556 #ifdef SQLITE_USER_AUTHENTICATION
1557 typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
1558 const char*, const char*);
1559 #else
1560 typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
1561 const char*);
1562 #endif
1564 #ifndef SQLITE_OMIT_DEPRECATED
1565 /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
1566 ** in the style of sqlite3_trace()
1568 #define SQLITE_TRACE_LEGACY 0x40 /* Use the legacy xTrace */
1569 #define SQLITE_TRACE_XPROFILE 0x80 /* Use the legacy xProfile */
1570 #else
1571 #define SQLITE_TRACE_LEGACY 0
1572 #define SQLITE_TRACE_XPROFILE 0
1573 #endif /* SQLITE_OMIT_DEPRECATED */
1574 #define SQLITE_TRACE_NONLEGACY_MASK 0x0f /* Normal flags */
1577 ** Maximum number of sqlite3.aDb[] entries. This is the number of attached
1578 ** databases plus 2 for "main" and "temp".
1580 #define SQLITE_MAX_DB (SQLITE_MAX_ATTACHED+2)
1583 ** Each database connection is an instance of the following structure.
1585 struct sqlite3 {
1586 sqlite3_vfs *pVfs; /* OS Interface */
1587 struct Vdbe *pVdbe; /* List of active virtual machines */
1588 CollSeq *pDfltColl; /* BINARY collseq for the database encoding */
1589 sqlite3_mutex *mutex; /* Connection mutex */
1590 Db *aDb; /* All backends */
1591 int nDb; /* Number of backends currently in use */
1592 u32 mDbFlags; /* flags recording internal state */
1593 u64 flags; /* flags settable by pragmas. See below */
1594 i64 lastRowid; /* ROWID of most recent insert (see above) */
1595 i64 szMmap; /* Default mmap_size setting */
1596 u32 nSchemaLock; /* Do not reset the schema when non-zero */
1597 unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
1598 int errCode; /* Most recent error code (SQLITE_*) */
1599 int errByteOffset; /* Byte offset of error in SQL statement */
1600 int errMask; /* & result codes with this before returning */
1601 int iSysErrno; /* Errno value from last system error */
1602 u32 dbOptFlags; /* Flags to enable/disable optimizations */
1603 u8 enc; /* Text encoding */
1604 u8 autoCommit; /* The auto-commit flag. */
1605 u8 temp_store; /* 1: file 2: memory 0: default */
1606 u8 mallocFailed; /* True if we have seen a malloc failure */
1607 u8 bBenignMalloc; /* Do not require OOMs if true */
1608 u8 dfltLockMode; /* Default locking-mode for attached dbs */
1609 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
1610 u8 suppressErr; /* Do not issue error messages if true */
1611 u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
1612 u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
1613 u8 mTrace; /* zero or more SQLITE_TRACE flags */
1614 u8 noSharedCache; /* True if no shared-cache backends */
1615 u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
1616 u8 eOpenState; /* Current condition of the connection */
1617 int nextPagesize; /* Pagesize after VACUUM if >0 */
1618 i64 nChange; /* Value returned by sqlite3_changes() */
1619 i64 nTotalChange; /* Value returned by sqlite3_total_changes() */
1620 int aLimit[SQLITE_N_LIMIT]; /* Limits */
1621 int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
1622 struct sqlite3InitInfo { /* Information used during initialization */
1623 Pgno newTnum; /* Rootpage of table being initialized */
1624 u8 iDb; /* Which db file is being initialized */
1625 u8 busy; /* TRUE if currently initializing */
1626 unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
1627 unsigned imposterTable : 1; /* Building an imposter table */
1628 unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */
1629 const char **azInit; /* "type", "name", and "tbl_name" columns */
1630 } init;
1631 int nVdbeActive; /* Number of VDBEs currently running */
1632 int nVdbeRead; /* Number of active VDBEs that read or write */
1633 int nVdbeWrite; /* Number of active VDBEs that read and write */
1634 int nVdbeExec; /* Number of nested calls to VdbeExec() */
1635 int nVDestroy; /* Number of active OP_VDestroy operations */
1636 int nExtension; /* Number of loaded extensions */
1637 void **aExtension; /* Array of shared library handles */
1638 union {
1639 void (*xLegacy)(void*,const char*); /* mTrace==SQLITE_TRACE_LEGACY */
1640 int (*xV2)(u32,void*,void*,void*); /* All other mTrace values */
1641 } trace;
1642 void *pTraceArg; /* Argument to the trace function */
1643 #ifndef SQLITE_OMIT_DEPRECATED
1644 void (*xProfile)(void*,const char*,u64); /* Profiling function */
1645 void *pProfileArg; /* Argument to profile function */
1646 #endif
1647 void *pCommitArg; /* Argument to xCommitCallback() */
1648 int (*xCommitCallback)(void*); /* Invoked at every commit. */
1649 void *pRollbackArg; /* Argument to xRollbackCallback() */
1650 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
1651 void *pUpdateArg;
1652 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
1653 void *pAutovacPagesArg; /* Client argument to autovac_pages */
1654 void (*xAutovacDestr)(void*); /* Destructor for pAutovacPAgesArg */
1655 unsigned int (*xAutovacPages)(void*,const char*,u32,u32,u32);
1656 Parse *pParse; /* Current parse */
1657 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1658 void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
1659 void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
1660 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
1662 PreUpdate *pPreUpdate; /* Context for active pre-update callback */
1663 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
1664 #ifndef SQLITE_OMIT_WAL
1665 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
1666 void *pWalArg;
1667 #endif
1668 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
1669 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
1670 void *pCollNeededArg;
1671 sqlite3_value *pErr; /* Most recent error message */
1672 union {
1673 volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
1674 double notUsed1; /* Spacer */
1675 } u1;
1676 Lookaside lookaside; /* Lookaside malloc configuration */
1677 #ifndef SQLITE_OMIT_AUTHORIZATION
1678 sqlite3_xauth xAuth; /* Access authorization function */
1679 void *pAuthArg; /* 1st argument to the access auth function */
1680 #endif
1681 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1682 int (*xProgress)(void *); /* The progress callback */
1683 void *pProgressArg; /* Argument to the progress callback */
1684 unsigned nProgressOps; /* Number of opcodes for progress callback */
1685 #endif
1686 #ifndef SQLITE_OMIT_VIRTUALTABLE
1687 int nVTrans; /* Allocated size of aVTrans */
1688 Hash aModule; /* populated by sqlite3_create_module() */
1689 VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
1690 VTable **aVTrans; /* Virtual tables with open transactions */
1691 VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
1692 #endif
1693 Hash aFunc; /* Hash table of connection functions */
1694 Hash aCollSeq; /* All collating sequences */
1695 BusyHandler busyHandler; /* Busy callback */
1696 Db aDbStatic[2]; /* Static space for the 2 default backends */
1697 Savepoint *pSavepoint; /* List of active savepoints */
1698 int nAnalysisLimit; /* Number of index rows to ANALYZE */
1699 int busyTimeout; /* Busy handler timeout, in msec */
1700 int nSavepoint; /* Number of non-transaction savepoints */
1701 int nStatement; /* Number of nested statement-transactions */
1702 i64 nDeferredCons; /* Net deferred constraints this transaction. */
1703 i64 nDeferredImmCons; /* Net deferred immediate constraints */
1704 int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
1705 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
1706 /* The following variables are all protected by the STATIC_MAIN
1707 ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
1709 ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
1710 ** unlock so that it can proceed.
1712 ** When X.pBlockingConnection==Y, that means that something that X tried
1713 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
1714 ** held by Y.
1716 sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
1717 sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
1718 void *pUnlockArg; /* Argument to xUnlockNotify */
1719 void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
1720 sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
1721 #endif
1722 #ifdef SQLITE_USER_AUTHENTICATION
1723 sqlite3_userauth auth; /* User authentication information */
1724 #endif
1728 ** A macro to discover the encoding of a database.
1730 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
1731 #define ENC(db) ((db)->enc)
1734 ** A u64 constant where the lower 32 bits are all zeros. Only the
1735 ** upper 32 bits are included in the argument. Necessary because some
1736 ** C-compilers still do not accept LL integer literals.
1738 #define HI(X) ((u64)(X)<<32)
1741 ** Possible values for the sqlite3.flags.
1743 ** Value constraints (enforced via assert()):
1744 ** SQLITE_FullFSync == PAGER_FULLFSYNC
1745 ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
1746 ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
1748 #define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_SCHEMA */
1749 #define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */
1750 #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
1751 #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
1752 #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
1753 #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
1754 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
1755 #define SQLITE_TrustedSchema 0x00000080 /* Allow unsafe functions and
1756 ** vtabs in the schema definition */
1757 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
1758 /* result set is empty */
1759 #define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */
1760 #define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
1761 #define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */
1762 #define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */
1763 #define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */
1764 #define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */
1765 #define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */
1766 #define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */
1767 #define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */
1768 #define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */
1769 #define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */
1770 #define SQLITE_QueryOnly 0x00100000 /* Disable database changes */
1771 #define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */
1772 #define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */
1773 #define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee*/
1774 #define SQLITE_TriggerEQP 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */
1775 #define SQLITE_ResetDatabase 0x02000000 /* Reset the database */
1776 #define SQLITE_LegacyAlter 0x04000000 /* Legacy ALTER TABLE behaviour */
1777 #define SQLITE_NoSchemaError 0x08000000 /* Do not report schema parse errors*/
1778 #define SQLITE_Defensive 0x10000000 /* Input SQL is likely hostile */
1779 #define SQLITE_DqsDDL 0x20000000 /* dbl-quoted strings allowed in DDL*/
1780 #define SQLITE_DqsDML 0x40000000 /* dbl-quoted strings allowed in DML*/
1781 #define SQLITE_EnableView 0x80000000 /* Enable the use of views */
1782 #define SQLITE_CountRows HI(0x00001) /* Count rows changed by INSERT, */
1783 /* DELETE, or UPDATE and return */
1784 /* the count using a callback. */
1785 #define SQLITE_CorruptRdOnly HI(0x00002) /* Prohibit writes due to error */
1787 /* Flags used only if debugging */
1788 #ifdef SQLITE_DEBUG
1789 #define SQLITE_SqlTrace HI(0x0100000) /* Debug print SQL as it executes */
1790 #define SQLITE_VdbeListing HI(0x0200000) /* Debug listings of VDBE progs */
1791 #define SQLITE_VdbeTrace HI(0x0400000) /* True to trace VDBE execution */
1792 #define SQLITE_VdbeAddopTrace HI(0x0800000) /* Trace sqlite3VdbeAddOp() calls */
1793 #define SQLITE_VdbeEQP HI(0x1000000) /* Debug EXPLAIN QUERY PLAN */
1794 #define SQLITE_ParserTrace HI(0x2000000) /* PRAGMA parser_trace=ON */
1795 #endif
1798 ** Allowed values for sqlite3.mDbFlags
1800 #define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */
1801 #define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
1802 #define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */
1803 #define DBFLAG_VacuumInto 0x0008 /* Currently running VACUUM INTO */
1804 #define DBFLAG_SchemaKnownOk 0x0010 /* Schema is known to be valid */
1805 #define DBFLAG_InternalFunc 0x0020 /* Allow use of internal functions */
1806 #define DBFLAG_EncodingFixed 0x0040 /* No longer possible to change enc. */
1809 ** Bits of the sqlite3.dbOptFlags field that are used by the
1810 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
1811 ** selectively disable various optimizations.
1813 #define SQLITE_QueryFlattener 0x00000001 /* Query flattening */
1814 #define SQLITE_WindowFunc 0x00000002 /* Use xInverse for window functions */
1815 #define SQLITE_GroupByOrder 0x00000004 /* GROUPBY cover of ORDERBY */
1816 #define SQLITE_FactorOutConst 0x00000008 /* Constant factoring */
1817 #define SQLITE_DistinctOpt 0x00000010 /* DISTINCT using indexes */
1818 #define SQLITE_CoverIdxScan 0x00000020 /* Covering index scans */
1819 #define SQLITE_OrderByIdxJoin 0x00000040 /* ORDER BY of joins via index */
1820 #define SQLITE_Transitive 0x00000080 /* Transitive constraints */
1821 #define SQLITE_OmitNoopJoin 0x00000100 /* Omit unused tables in joins */
1822 #define SQLITE_CountOfView 0x00000200 /* The count-of-view optimization */
1823 #define SQLITE_CursorHints 0x00000400 /* Add OP_CursorHint opcodes */
1824 #define SQLITE_Stat4 0x00000800 /* Use STAT4 data */
1825 /* TH3 expects this value ^^^^^^^^^^ to be 0x0000800. Don't change it */
1826 #define SQLITE_PushDown 0x00001000 /* The push-down optimization */
1827 #define SQLITE_SimplifyJoin 0x00002000 /* Convert LEFT JOIN to JOIN */
1828 #define SQLITE_SkipScan 0x00004000 /* Skip-scans */
1829 #define SQLITE_PropagateConst 0x00008000 /* The constant propagation opt */
1830 #define SQLITE_MinMaxOpt 0x00010000 /* The min/max optimization */
1831 #define SQLITE_SeekScan 0x00020000 /* The OP_SeekScan optimization */
1832 #define SQLITE_OmitOrderBy 0x00040000 /* Omit pointless ORDER BY */
1833 /* TH3 expects this value ^^^^^^^^^^ to be 0x40000. Coordinate any change */
1834 #define SQLITE_BloomFilter 0x00080000 /* Use a Bloom filter on searches */
1835 #define SQLITE_BloomPulldown 0x00100000 /* Run Bloom filters early */
1836 #define SQLITE_BalancedMerge 0x00200000 /* Balance multi-way merges */
1837 #define SQLITE_ReleaseReg 0x00400000 /* Use OP_ReleaseReg for testing */
1838 #define SQLITE_FlttnUnionAll 0x00800000 /* Disable the UNION ALL flattener */
1839 /* TH3 expects this value ^^^^^^^^^^ See flatten04.test */
1840 #define SQLITE_IndexedExpr 0x01000000 /* Pull exprs from index when able */
1841 #define SQLITE_Coroutines 0x02000000 /* Co-routines for subqueries */
1842 #define SQLITE_AllOpts 0xffffffff /* All optimizations */
1845 ** Macros for testing whether or not optimizations are enabled or disabled.
1847 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
1848 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
1851 ** Return true if it OK to factor constant expressions into the initialization
1852 ** code. The argument is a Parse object for the code generator.
1854 #define ConstFactorOk(P) ((P)->okConstFactor)
1856 /* Possible values for the sqlite3.eOpenState field.
1857 ** The numbers are randomly selected such that a minimum of three bits must
1858 ** change to convert any number to another or to zero
1860 #define SQLITE_STATE_OPEN 0x76 /* Database is open */
1861 #define SQLITE_STATE_CLOSED 0xce /* Database is closed */
1862 #define SQLITE_STATE_SICK 0xba /* Error and awaiting close */
1863 #define SQLITE_STATE_BUSY 0x6d /* Database currently in use */
1864 #define SQLITE_STATE_ERROR 0xd5 /* An SQLITE_MISUSE error occurred */
1865 #define SQLITE_STATE_ZOMBIE 0xa7 /* Close with last statement close */
1868 ** Each SQL function is defined by an instance of the following
1869 ** structure. For global built-in functions (ex: substr(), max(), count())
1870 ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
1871 ** For per-connection application-defined functions, a pointer to this
1872 ** structure is held in the db->aHash hash table.
1874 ** The u.pHash field is used by the global built-ins. The u.pDestructor
1875 ** field is used by per-connection app-def functions.
1877 struct FuncDef {
1878 i8 nArg; /* Number of arguments. -1 means unlimited */
1879 u32 funcFlags; /* Some combination of SQLITE_FUNC_* */
1880 void *pUserData; /* User data parameter */
1881 FuncDef *pNext; /* Next function with same name */
1882 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
1883 void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
1884 void (*xValue)(sqlite3_context*); /* Current agg value */
1885 void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
1886 const char *zName; /* SQL name of the function. */
1887 union {
1888 FuncDef *pHash; /* Next with a different name but the same hash */
1889 FuncDestructor *pDestructor; /* Reference counted destructor function */
1890 } u; /* pHash if SQLITE_FUNC_BUILTIN, pDestructor otherwise */
1894 ** This structure encapsulates a user-function destructor callback (as
1895 ** configured using create_function_v2()) and a reference counter. When
1896 ** create_function_v2() is called to create a function with a destructor,
1897 ** a single object of this type is allocated. FuncDestructor.nRef is set to
1898 ** the number of FuncDef objects created (either 1 or 3, depending on whether
1899 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
1900 ** member of each of the new FuncDef objects is set to point to the allocated
1901 ** FuncDestructor.
1903 ** Thereafter, when one of the FuncDef objects is deleted, the reference
1904 ** count on this object is decremented. When it reaches 0, the destructor
1905 ** is invoked and the FuncDestructor structure freed.
1907 struct FuncDestructor {
1908 int nRef;
1909 void (*xDestroy)(void *);
1910 void *pUserData;
1914 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
1915 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
1916 ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
1917 ** are assert() statements in the code to verify this.
1919 ** Value constraints (enforced via assert()):
1920 ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
1921 ** SQLITE_FUNC_ANYORDER == NC_OrderAgg == SF_OrderByReqd
1922 ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
1923 ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
1924 ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
1925 ** SQLITE_FUNC_DIRECT == SQLITE_DIRECTONLY from the API
1926 ** SQLITE_FUNC_UNSAFE == SQLITE_INNOCUOUS -- opposite meanings!!!
1927 ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
1929 ** Note that even though SQLITE_FUNC_UNSAFE and SQLITE_INNOCUOUS have the
1930 ** same bit value, their meanings are inverted. SQLITE_FUNC_UNSAFE is
1931 ** used internally and if set means tha the function has side effects.
1932 ** SQLITE_INNOCUOUS is used by application code and means "not unsafe".
1933 ** See multiple instances of tag-20230109-1.
1935 #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
1936 #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
1937 #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
1938 #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
1939 #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
1940 #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
1941 #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
1942 #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
1943 /* 0x0200 -- available for reuse */
1944 #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
1945 #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
1946 #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
1947 #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
1948 ** single query - might change over time */
1949 #define SQLITE_FUNC_TEST 0x4000 /* Built-in testing functions */
1950 /* 0x8000 -- available for reuse */
1951 #define SQLITE_FUNC_WINDOW 0x00010000 /* Built-in window-only function */
1952 #define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
1953 #define SQLITE_FUNC_DIRECT 0x00080000 /* Not for use in TRIGGERs or VIEWs */
1954 #define SQLITE_FUNC_SUBTYPE 0x00100000 /* Result likely to have sub-type */
1955 #define SQLITE_FUNC_UNSAFE 0x00200000 /* Function has side effects */
1956 #define SQLITE_FUNC_INLINE 0x00400000 /* Functions implemented in-line */
1957 #define SQLITE_FUNC_BUILTIN 0x00800000 /* This is a built-in function */
1958 #define SQLITE_FUNC_ANYORDER 0x08000000 /* count/min/max aggregate */
1960 /* Identifier numbers for each in-line function */
1961 #define INLINEFUNC_coalesce 0
1962 #define INLINEFUNC_implies_nonnull_row 1
1963 #define INLINEFUNC_expr_implies_expr 2
1964 #define INLINEFUNC_expr_compare 3
1965 #define INLINEFUNC_affinity 4
1966 #define INLINEFUNC_iif 5
1967 #define INLINEFUNC_sqlite_offset 6
1968 #define INLINEFUNC_unlikely 99 /* Default case */
1971 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
1972 ** used to create the initializers for the FuncDef structures.
1974 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
1975 ** Used to create a scalar function definition of a function zName
1976 ** implemented by C function xFunc that accepts nArg arguments. The
1977 ** value passed as iArg is cast to a (void*) and made available
1978 ** as the user-data (sqlite3_user_data()) for the function. If
1979 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
1981 ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
1982 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
1984 ** SFUNCTION(zName, nArg, iArg, bNC, xFunc)
1985 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
1986 ** adds the SQLITE_DIRECTONLY flag.
1988 ** INLINE_FUNC(zName, nArg, iFuncId, mFlags)
1989 ** zName is the name of a function that is implemented by in-line
1990 ** byte code rather than by the usual callbacks. The iFuncId
1991 ** parameter determines the function id. The mFlags parameter is
1992 ** optional SQLITE_FUNC_ flags for this function.
1994 ** TEST_FUNC(zName, nArg, iFuncId, mFlags)
1995 ** zName is the name of a test-only function implemented by in-line
1996 ** byte code rather than by the usual callbacks. The iFuncId
1997 ** parameter determines the function id. The mFlags parameter is
1998 ** optional SQLITE_FUNC_ flags for this function.
2000 ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
2001 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
2002 ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
2003 ** and functions like sqlite_version() that can change, but not during
2004 ** a single query. The iArg is ignored. The user-data is always set
2005 ** to a NULL pointer. The bNC parameter is not used.
2007 ** MFUNCTION(zName, nArg, xPtr, xFunc)
2008 ** For math-library functions. xPtr is an arbitrary pointer.
2010 ** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
2011 ** Used for "pure" date/time functions, this macro is like DFUNCTION
2012 ** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
2013 ** ignored and the user-data for these functions is set to an
2014 ** arbitrary non-NULL pointer. The bNC parameter is not used.
2016 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
2017 ** Used to create an aggregate function definition implemented by
2018 ** the C functions xStep and xFinal. The first four parameters
2019 ** are interpreted in the same way as the first 4 parameters to
2020 ** FUNCTION().
2022 ** WAGGREGATE(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
2023 ** Used to create an aggregate function definition implemented by
2024 ** the C functions xStep and xFinal. The first four parameters
2025 ** are interpreted in the same way as the first 4 parameters to
2026 ** FUNCTION().
2028 ** LIKEFUNC(zName, nArg, pArg, flags)
2029 ** Used to create a scalar function definition of a function zName
2030 ** that accepts nArg arguments and is implemented by a call to C
2031 ** function likeFunc. Argument pArg is cast to a (void *) and made
2032 ** available as the function user-data (sqlite3_user_data()). The
2033 ** FuncDef.flags variable is set to the value passed as the flags
2034 ** parameter.
2036 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
2037 {nArg, SQLITE_FUNC_BUILTIN|\
2038 SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
2039 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
2040 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
2041 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
2042 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
2043 #define SFUNCTION(zName, nArg, iArg, bNC, xFunc) \
2044 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \
2045 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
2046 #define MFUNCTION(zName, nArg, xPtr, xFunc) \
2047 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8, \
2048 xPtr, 0, xFunc, 0, 0, 0, #zName, {0} }
2049 #define JFUNCTION(zName, nArg, iArg, xFunc) \
2050 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_DETERMINISTIC|\
2051 SQLITE_FUNC_CONSTANT|SQLITE_UTF8, \
2052 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
2053 #define INLINE_FUNC(zName, nArg, iArg, mFlags) \
2054 {nArg, SQLITE_FUNC_BUILTIN|\
2055 SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
2056 SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
2057 #define TEST_FUNC(zName, nArg, iArg, mFlags) \
2058 {nArg, SQLITE_FUNC_BUILTIN|\
2059 SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \
2060 SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
2061 SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
2062 #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
2063 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
2064 0, 0, xFunc, 0, 0, 0, #zName, {0} }
2065 #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
2066 {nArg, SQLITE_FUNC_BUILTIN|\
2067 SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
2068 (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
2069 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
2070 {nArg, SQLITE_FUNC_BUILTIN|\
2071 SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
2072 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
2073 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
2074 {nArg, SQLITE_FUNC_BUILTIN|\
2075 SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
2076 pArg, 0, xFunc, 0, 0, 0, #zName, }
2077 #define LIKEFUNC(zName, nArg, arg, flags) \
2078 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
2079 (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
2080 #define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
2081 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
2082 SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
2083 #define INTERNAL_FUNCTION(zName, nArg, xFunc) \
2084 {nArg, SQLITE_FUNC_BUILTIN|\
2085 SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
2086 0, 0, xFunc, 0, 0, 0, #zName, {0} }
2090 ** All current savepoints are stored in a linked list starting at
2091 ** sqlite3.pSavepoint. The first element in the list is the most recently
2092 ** opened savepoint. Savepoints are added to the list by the vdbe
2093 ** OP_Savepoint instruction.
2095 struct Savepoint {
2096 char *zName; /* Savepoint name (nul-terminated) */
2097 i64 nDeferredCons; /* Number of deferred fk violations */
2098 i64 nDeferredImmCons; /* Number of deferred imm fk. */
2099 Savepoint *pNext; /* Parent savepoint (if any) */
2103 ** The following are used as the second parameter to sqlite3Savepoint(),
2104 ** and as the P1 argument to the OP_Savepoint instruction.
2106 #define SAVEPOINT_BEGIN 0
2107 #define SAVEPOINT_RELEASE 1
2108 #define SAVEPOINT_ROLLBACK 2
2112 ** Each SQLite module (virtual table definition) is defined by an
2113 ** instance of the following structure, stored in the sqlite3.aModule
2114 ** hash table.
2116 struct Module {
2117 const sqlite3_module *pModule; /* Callback pointers */
2118 const char *zName; /* Name passed to create_module() */
2119 int nRefModule; /* Number of pointers to this object */
2120 void *pAux; /* pAux passed to create_module() */
2121 void (*xDestroy)(void *); /* Module destructor function */
2122 Table *pEpoTab; /* Eponymous table for this module */
2126 ** Information about each column of an SQL table is held in an instance
2127 ** of the Column structure, in the Table.aCol[] array.
2129 ** Definitions:
2131 ** "table column index" This is the index of the column in the
2132 ** Table.aCol[] array, and also the index of
2133 ** the column in the original CREATE TABLE stmt.
2135 ** "storage column index" This is the index of the column in the
2136 ** record BLOB generated by the OP_MakeRecord
2137 ** opcode. The storage column index is less than
2138 ** or equal to the table column index. It is
2139 ** equal if and only if there are no VIRTUAL
2140 ** columns to the left.
2142 ** Notes on zCnName:
2143 ** The zCnName field stores the name of the column, the datatype of the
2144 ** column, and the collating sequence for the column, in that order, all in
2145 ** a single allocation. Each string is 0x00 terminated. The datatype
2146 ** is only included if the COLFLAG_HASTYPE bit of colFlags is set and the
2147 ** collating sequence name is only included if the COLFLAG_HASCOLL bit is
2148 ** set.
2150 struct Column {
2151 char *zCnName; /* Name of this column */
2152 unsigned notNull :4; /* An OE_ code for handling a NOT NULL constraint */
2153 unsigned eCType :4; /* One of the standard types */
2154 char affinity; /* One of the SQLITE_AFF_... values */
2155 u8 szEst; /* Est size of value in this column. sizeof(INT)==1 */
2156 u8 hName; /* Column name hash for faster lookup */
2157 u16 iDflt; /* 1-based index of DEFAULT. 0 means "none" */
2158 u16 colFlags; /* Boolean properties. See COLFLAG_ defines below */
2161 /* Allowed values for Column.eCType.
2163 ** Values must match entries in the global constant arrays
2164 ** sqlite3StdTypeLen[] and sqlite3StdType[]. Each value is one more
2165 ** than the offset into these arrays for the corresponding name.
2166 ** Adjust the SQLITE_N_STDTYPE value if adding or removing entries.
2168 #define COLTYPE_CUSTOM 0 /* Type appended to zName */
2169 #define COLTYPE_ANY 1
2170 #define COLTYPE_BLOB 2
2171 #define COLTYPE_INT 3
2172 #define COLTYPE_INTEGER 4
2173 #define COLTYPE_REAL 5
2174 #define COLTYPE_TEXT 6
2175 #define SQLITE_N_STDTYPE 6 /* Number of standard types */
2177 /* Allowed values for Column.colFlags.
2179 ** Constraints:
2180 ** TF_HasVirtual == COLFLAG_VIRTUAL
2181 ** TF_HasStored == COLFLAG_STORED
2182 ** TF_HasHidden == COLFLAG_HIDDEN
2184 #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
2185 #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
2186 #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
2187 #define COLFLAG_UNIQUE 0x0008 /* Column def contains "UNIQUE" or "PK" */
2188 #define COLFLAG_SORTERREF 0x0010 /* Use sorter-refs with this column */
2189 #define COLFLAG_VIRTUAL 0x0020 /* GENERATED ALWAYS AS ... VIRTUAL */
2190 #define COLFLAG_STORED 0x0040 /* GENERATED ALWAYS AS ... STORED */
2191 #define COLFLAG_NOTAVAIL 0x0080 /* STORED column not yet calculated */
2192 #define COLFLAG_BUSY 0x0100 /* Blocks recursion on GENERATED columns */
2193 #define COLFLAG_HASCOLL 0x0200 /* Has collating sequence name in zCnName */
2194 #define COLFLAG_NOEXPAND 0x0400 /* Omit this column when expanding "*" */
2195 #define COLFLAG_GENERATED 0x0060 /* Combo: _STORED, _VIRTUAL */
2196 #define COLFLAG_NOINSERT 0x0062 /* Combo: _HIDDEN, _STORED, _VIRTUAL */
2199 ** A "Collating Sequence" is defined by an instance of the following
2200 ** structure. Conceptually, a collating sequence consists of a name and
2201 ** a comparison routine that defines the order of that sequence.
2203 ** If CollSeq.xCmp is NULL, it means that the
2204 ** collating sequence is undefined. Indices built on an undefined
2205 ** collating sequence may not be read or written.
2207 struct CollSeq {
2208 char *zName; /* Name of the collating sequence, UTF-8 encoded */
2209 u8 enc; /* Text encoding handled by xCmp() */
2210 void *pUser; /* First argument to xCmp() */
2211 int (*xCmp)(void*,int, const void*, int, const void*);
2212 void (*xDel)(void*); /* Destructor for pUser */
2216 ** A sort order can be either ASC or DESC.
2218 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
2219 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
2220 #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
2223 ** Column affinity types.
2225 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
2226 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
2227 ** the speed a little by numbering the values consecutively.
2229 ** But rather than start with 0 or 1, we begin with 'A'. That way,
2230 ** when multiple affinity types are concatenated into a string and
2231 ** used as the P4 operand, they will be more readable.
2233 ** Note also that the numeric types are grouped together so that testing
2234 ** for a numeric type is a single comparison. And the BLOB type is first.
2236 #define SQLITE_AFF_NONE 0x40 /* '@' */
2237 #define SQLITE_AFF_BLOB 0x41 /* 'A' */
2238 #define SQLITE_AFF_TEXT 0x42 /* 'B' */
2239 #define SQLITE_AFF_NUMERIC 0x43 /* 'C' */
2240 #define SQLITE_AFF_INTEGER 0x44 /* 'D' */
2241 #define SQLITE_AFF_REAL 0x45 /* 'E' */
2242 #define SQLITE_AFF_FLEXNUM 0x46 /* 'F' */
2244 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
2247 ** The SQLITE_AFF_MASK values masks off the significant bits of an
2248 ** affinity value.
2250 #define SQLITE_AFF_MASK 0x47
2253 ** Additional bit values that can be ORed with an affinity without
2254 ** changing the affinity.
2256 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
2257 ** It causes an assert() to fire if either operand to a comparison
2258 ** operator is NULL. It is added to certain comparison operators to
2259 ** prove that the operands are always NOT NULL.
2261 #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
2262 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
2263 #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
2266 ** An object of this type is created for each virtual table present in
2267 ** the database schema.
2269 ** If the database schema is shared, then there is one instance of this
2270 ** structure for each database connection (sqlite3*) that uses the shared
2271 ** schema. This is because each database connection requires its own unique
2272 ** instance of the sqlite3_vtab* handle used to access the virtual table
2273 ** implementation. sqlite3_vtab* handles can not be shared between
2274 ** database connections, even when the rest of the in-memory database
2275 ** schema is shared, as the implementation often stores the database
2276 ** connection handle passed to it via the xConnect() or xCreate() method
2277 ** during initialization internally. This database connection handle may
2278 ** then be used by the virtual table implementation to access real tables
2279 ** within the database. So that they appear as part of the callers
2280 ** transaction, these accesses need to be made via the same database
2281 ** connection as that used to execute SQL operations on the virtual table.
2283 ** All VTable objects that correspond to a single table in a shared
2284 ** database schema are initially stored in a linked-list pointed to by
2285 ** the Table.pVTable member variable of the corresponding Table object.
2286 ** When an sqlite3_prepare() operation is required to access the virtual
2287 ** table, it searches the list for the VTable that corresponds to the
2288 ** database connection doing the preparing so as to use the correct
2289 ** sqlite3_vtab* handle in the compiled query.
2291 ** When an in-memory Table object is deleted (for example when the
2292 ** schema is being reloaded for some reason), the VTable objects are not
2293 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
2294 ** immediately. Instead, they are moved from the Table.pVTable list to
2295 ** another linked list headed by the sqlite3.pDisconnect member of the
2296 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
2297 ** next time a statement is prepared using said sqlite3*. This is done
2298 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
2299 ** Refer to comments above function sqlite3VtabUnlockList() for an
2300 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
2301 ** list without holding the corresponding sqlite3.mutex mutex.
2303 ** The memory for objects of this type is always allocated by
2304 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
2305 ** the first argument.
2307 struct VTable {
2308 sqlite3 *db; /* Database connection associated with this table */
2309 Module *pMod; /* Pointer to module implementation */
2310 sqlite3_vtab *pVtab; /* Pointer to vtab instance */
2311 int nRef; /* Number of pointers to this structure */
2312 u8 bConstraint; /* True if constraints are supported */
2313 u8 eVtabRisk; /* Riskiness of allowing hacker access */
2314 int iSavepoint; /* Depth of the SAVEPOINT stack */
2315 VTable *pNext; /* Next in linked list (see above) */
2318 /* Allowed values for VTable.eVtabRisk
2320 #define SQLITE_VTABRISK_Low 0
2321 #define SQLITE_VTABRISK_Normal 1
2322 #define SQLITE_VTABRISK_High 2
2325 ** The schema for each SQL table, virtual table, and view is represented
2326 ** in memory by an instance of the following structure.
2328 struct Table {
2329 char *zName; /* Name of the table or view */
2330 Column *aCol; /* Information about each column */
2331 Index *pIndex; /* List of SQL indexes on this table. */
2332 char *zColAff; /* String defining the affinity of each column */
2333 ExprList *pCheck; /* All CHECK constraints */
2334 /* ... also used as column name list in a VIEW */
2335 Pgno tnum; /* Root BTree page for this table */
2336 u32 nTabRef; /* Number of pointers to this Table */
2337 u32 tabFlags; /* Mask of TF_* values */
2338 i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
2339 i16 nCol; /* Number of columns in this table */
2340 i16 nNVCol; /* Number of columns that are not VIRTUAL */
2341 LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
2342 LogEst szTabRow; /* Estimated size of each table row in bytes */
2343 #ifdef SQLITE_ENABLE_COSTMULT
2344 LogEst costMult; /* Cost multiplier for using this table */
2345 #endif
2346 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
2347 u8 eTabType; /* 0: normal, 1: virtual, 2: view */
2348 union {
2349 struct { /* Used by ordinary tables: */
2350 int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
2351 FKey *pFKey; /* Linked list of all foreign keys in this table */
2352 ExprList *pDfltList; /* DEFAULT clauses on various columns.
2353 ** Or the AS clause for generated columns. */
2354 } tab;
2355 struct { /* Used by views: */
2356 Select *pSelect; /* View definition */
2357 } view;
2358 struct { /* Used by virtual tables only: */
2359 int nArg; /* Number of arguments to the module */
2360 char **azArg; /* 0: module 1: schema 2: vtab name 3...: args */
2361 VTable *p; /* List of VTable objects. */
2362 } vtab;
2363 } u;
2364 Trigger *pTrigger; /* List of triggers on this object */
2365 Schema *pSchema; /* Schema that contains this table */
2369 ** Allowed values for Table.tabFlags.
2371 ** TF_OOOHidden applies to tables or view that have hidden columns that are
2372 ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
2373 ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
2374 ** the TF_OOOHidden attribute would apply in this case. Such tables require
2375 ** special handling during INSERT processing. The "OOO" means "Out Of Order".
2377 ** Constraints:
2379 ** TF_HasVirtual == COLFLAG_VIRTUAL
2380 ** TF_HasStored == COLFLAG_STORED
2381 ** TF_HasHidden == COLFLAG_HIDDEN
2383 #define TF_Readonly 0x00000001 /* Read-only system table */
2384 #define TF_HasHidden 0x00000002 /* Has one or more hidden columns */
2385 #define TF_HasPrimaryKey 0x00000004 /* Table has a primary key */
2386 #define TF_Autoincrement 0x00000008 /* Integer primary key is autoincrement */
2387 #define TF_HasStat1 0x00000010 /* nRowLogEst set from sqlite_stat1 */
2388 #define TF_HasVirtual 0x00000020 /* Has one or more VIRTUAL columns */
2389 #define TF_HasStored 0x00000040 /* Has one or more STORED columns */
2390 #define TF_HasGenerated 0x00000060 /* Combo: HasVirtual + HasStored */
2391 #define TF_WithoutRowid 0x00000080 /* No rowid. PRIMARY KEY is the key */
2392 #define TF_StatsUsed 0x00000100 /* Query planner decisions affected by
2393 ** Index.aiRowLogEst[] values */
2394 #define TF_NoVisibleRowid 0x00000200 /* No user-visible "rowid" column */
2395 #define TF_OOOHidden 0x00000400 /* Out-of-Order hidden columns */
2396 #define TF_HasNotNull 0x00000800 /* Contains NOT NULL constraints */
2397 #define TF_Shadow 0x00001000 /* True for a shadow table */
2398 #define TF_HasStat4 0x00002000 /* STAT4 info available for this table */
2399 #define TF_Ephemeral 0x00004000 /* An ephemeral table */
2400 #define TF_Eponymous 0x00008000 /* An eponymous virtual table */
2401 #define TF_Strict 0x00010000 /* STRICT mode */
2404 ** Allowed values for Table.eTabType
2406 #define TABTYP_NORM 0 /* Ordinary table */
2407 #define TABTYP_VTAB 1 /* Virtual table */
2408 #define TABTYP_VIEW 2 /* A view */
2410 #define IsView(X) ((X)->eTabType==TABTYP_VIEW)
2411 #define IsOrdinaryTable(X) ((X)->eTabType==TABTYP_NORM)
2414 ** Test to see whether or not a table is a virtual table. This is
2415 ** done as a macro so that it will be optimized out when virtual
2416 ** table support is omitted from the build.
2418 #ifndef SQLITE_OMIT_VIRTUALTABLE
2419 # define IsVirtual(X) ((X)->eTabType==TABTYP_VTAB)
2420 # define ExprIsVtab(X) \
2421 ((X)->op==TK_COLUMN && (X)->y.pTab->eTabType==TABTYP_VTAB)
2422 #else
2423 # define IsVirtual(X) 0
2424 # define ExprIsVtab(X) 0
2425 #endif
2428 ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
2429 ** only works for non-virtual tables (ordinary tables and views) and is
2430 ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
2431 ** IsHiddenColumn() macro is general purpose.
2433 #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
2434 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
2435 # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
2436 #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
2437 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
2438 # define IsOrdinaryHiddenColumn(X) 0
2439 #else
2440 # define IsHiddenColumn(X) 0
2441 # define IsOrdinaryHiddenColumn(X) 0
2442 #endif
2445 /* Does the table have a rowid */
2446 #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
2447 #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
2450 ** Each foreign key constraint is an instance of the following structure.
2452 ** A foreign key is associated with two tables. The "from" table is
2453 ** the table that contains the REFERENCES clause that creates the foreign
2454 ** key. The "to" table is the table that is named in the REFERENCES clause.
2455 ** Consider this example:
2457 ** CREATE TABLE ex1(
2458 ** a INTEGER PRIMARY KEY,
2459 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
2460 ** );
2462 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
2463 ** Equivalent names:
2465 ** from-table == child-table
2466 ** to-table == parent-table
2468 ** Each REFERENCES clause generates an instance of the following structure
2469 ** which is attached to the from-table. The to-table need not exist when
2470 ** the from-table is created. The existence of the to-table is not checked.
2472 ** The list of all parents for child Table X is held at X.pFKey.
2474 ** A list of all children for a table named Z (which might not even exist)
2475 ** is held in Schema.fkeyHash with a hash key of Z.
2477 struct FKey {
2478 Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
2479 FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
2480 char *zTo; /* Name of table that the key points to (aka: Parent) */
2481 FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
2482 FKey *pPrevTo; /* Previous with the same zTo */
2483 int nCol; /* Number of columns in this key */
2484 /* EV: R-30323-21917 */
2485 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
2486 u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
2487 Trigger *apTrigger[2];/* Triggers for aAction[] actions */
2488 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
2489 int iFrom; /* Index of column in pFrom */
2490 char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
2491 } aCol[1]; /* One entry for each of nCol columns */
2495 ** SQLite supports many different ways to resolve a constraint
2496 ** error. ROLLBACK processing means that a constraint violation
2497 ** causes the operation in process to fail and for the current transaction
2498 ** to be rolled back. ABORT processing means the operation in process
2499 ** fails and any prior changes from that one operation are backed out,
2500 ** but the transaction is not rolled back. FAIL processing means that
2501 ** the operation in progress stops and returns an error code. But prior
2502 ** changes due to the same operation are not backed out and no rollback
2503 ** occurs. IGNORE means that the particular row that caused the constraint
2504 ** error is not inserted or updated. Processing continues and no error
2505 ** is returned. REPLACE means that preexisting database rows that caused
2506 ** a UNIQUE constraint violation are removed so that the new insert or
2507 ** update can proceed. Processing continues and no error is reported.
2508 ** UPDATE applies to insert operations only and means that the insert
2509 ** is omitted and the DO UPDATE clause of an upsert is run instead.
2511 ** RESTRICT, SETNULL, SETDFLT, and CASCADE actions apply only to foreign keys.
2512 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
2513 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
2514 ** key is set to NULL. SETDFLT means that the foreign key is set
2515 ** to its default value. CASCADE means that a DELETE or UPDATE of the
2516 ** referenced table row is propagated into the row that holds the
2517 ** foreign key.
2519 ** The OE_Default value is a place holder that means to use whatever
2520 ** conflict resolution algorthm is required from context.
2522 ** The following symbolic values are used to record which type
2523 ** of conflict resolution action to take.
2525 #define OE_None 0 /* There is no constraint to check */
2526 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
2527 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
2528 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
2529 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
2530 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
2531 #define OE_Update 6 /* Process as a DO UPDATE in an upsert */
2532 #define OE_Restrict 7 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
2533 #define OE_SetNull 8 /* Set the foreign key value to NULL */
2534 #define OE_SetDflt 9 /* Set the foreign key value to its default */
2535 #define OE_Cascade 10 /* Cascade the changes */
2536 #define OE_Default 11 /* Do whatever the default action is */
2540 ** An instance of the following structure is passed as the first
2541 ** argument to sqlite3VdbeKeyCompare and is used to control the
2542 ** comparison of the two index keys.
2544 ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
2545 ** are nField slots for the columns of an index then one extra slot
2546 ** for the rowid at the end.
2548 struct KeyInfo {
2549 u32 nRef; /* Number of references to this KeyInfo object */
2550 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
2551 u16 nKeyField; /* Number of key columns in the index */
2552 u16 nAllField; /* Total columns, including key plus others */
2553 sqlite3 *db; /* The database connection */
2554 u8 *aSortFlags; /* Sort order for each column. */
2555 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
2559 ** Allowed bit values for entries in the KeyInfo.aSortFlags[] array.
2561 #define KEYINFO_ORDER_DESC 0x01 /* DESC sort order */
2562 #define KEYINFO_ORDER_BIGNULL 0x02 /* NULL is larger than any other value */
2565 ** This object holds a record which has been parsed out into individual
2566 ** fields, for the purposes of doing a comparison.
2568 ** A record is an object that contains one or more fields of data.
2569 ** Records are used to store the content of a table row and to store
2570 ** the key of an index. A blob encoding of a record is created by
2571 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
2572 ** OP_Column opcode.
2574 ** An instance of this object serves as a "key" for doing a search on
2575 ** an index b+tree. The goal of the search is to find the entry that
2576 ** is closed to the key described by this object. This object might hold
2577 ** just a prefix of the key. The number of fields is given by
2578 ** pKeyInfo->nField.
2580 ** The r1 and r2 fields are the values to return if this key is less than
2581 ** or greater than a key in the btree, respectively. These are normally
2582 ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
2583 ** is in DESC order.
2585 ** The key comparison functions actually return default_rc when they find
2586 ** an equals comparison. default_rc can be -1, 0, or +1. If there are
2587 ** multiple entries in the b-tree with the same key (when only looking
2588 ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
2589 ** cause the search to find the last match, or +1 to cause the search to
2590 ** find the first match.
2592 ** The key comparison functions will set eqSeen to true if they ever
2593 ** get and equal results when comparing this structure to a b-tree record.
2594 ** When default_rc!=0, the search might end up on the record immediately
2595 ** before the first match or immediately after the last match. The
2596 ** eqSeen field will indicate whether or not an exact match exists in the
2597 ** b-tree.
2599 struct UnpackedRecord {
2600 KeyInfo *pKeyInfo; /* Collation and sort-order information */
2601 Mem *aMem; /* Values */
2602 union {
2603 char *z; /* Cache of aMem[0].z for vdbeRecordCompareString() */
2604 i64 i; /* Cache of aMem[0].u.i for vdbeRecordCompareInt() */
2605 } u;
2606 int n; /* Cache of aMem[0].n used by vdbeRecordCompareString() */
2607 u16 nField; /* Number of entries in apMem[] */
2608 i8 default_rc; /* Comparison result if keys are equal */
2609 u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
2610 i8 r1; /* Value to return if (lhs < rhs) */
2611 i8 r2; /* Value to return if (lhs > rhs) */
2612 u8 eqSeen; /* True if an equality comparison has been seen */
2617 ** Each SQL index is represented in memory by an
2618 ** instance of the following structure.
2620 ** The columns of the table that are to be indexed are described
2621 ** by the aiColumn[] field of this structure. For example, suppose
2622 ** we have the following table and index:
2624 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
2625 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
2627 ** In the Table structure describing Ex1, nCol==3 because there are
2628 ** three columns in the table. In the Index structure describing
2629 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
2630 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
2631 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
2632 ** The second column to be indexed (c1) has an index of 0 in
2633 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
2635 ** The Index.onError field determines whether or not the indexed columns
2636 ** must be unique and what to do if they are not. When Index.onError=OE_None,
2637 ** it means this is not a unique index. Otherwise it is a unique index
2638 ** and the value of Index.onError indicates which conflict resolution
2639 ** algorithm to employ when an attempt is made to insert a non-unique
2640 ** element.
2642 ** The colNotIdxed bitmask is used in combination with SrcItem.colUsed
2643 ** for a fast test to see if an index can serve as a covering index.
2644 ** colNotIdxed has a 1 bit for every column of the original table that
2645 ** is *not* available in the index. Thus the expression
2646 ** "colUsed & colNotIdxed" will be non-zero if the index is not a
2647 ** covering index. The most significant bit of of colNotIdxed will always
2648 ** be true (note-20221022-a). If a column beyond the 63rd column of the
2649 ** table is used, the "colUsed & colNotIdxed" test will always be non-zero
2650 ** and we have to assume either that the index is not covering, or use
2651 ** an alternative (slower) algorithm to determine whether or not
2652 ** the index is covering.
2654 ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
2655 ** generate VDBE code (as opposed to parsing one read from an sqlite_schema
2656 ** table as part of parsing an existing database schema), transient instances
2657 ** of this structure may be created. In this case the Index.tnum variable is
2658 ** used to store the address of a VDBE instruction, not a database page
2659 ** number (it cannot - the database page is not allocated until the VDBE
2660 ** program is executed). See convertToWithoutRowidTable() for details.
2662 struct Index {
2663 char *zName; /* Name of this index */
2664 i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
2665 LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
2666 Table *pTable; /* The SQL table being indexed */
2667 char *zColAff; /* String defining the affinity of each column */
2668 Index *pNext; /* The next index associated with the same table */
2669 Schema *pSchema; /* Schema containing this index */
2670 u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
2671 const char **azColl; /* Array of collation sequence names for index */
2672 Expr *pPartIdxWhere; /* WHERE clause for partial indices */
2673 ExprList *aColExpr; /* Column expressions */
2674 Pgno tnum; /* DB Page containing root of this index */
2675 LogEst szIdxRow; /* Estimated average row size in bytes */
2676 u16 nKeyCol; /* Number of columns forming the key */
2677 u16 nColumn; /* Number of columns stored in the index */
2678 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2679 unsigned idxType:2; /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */
2680 unsigned bUnordered:1; /* Use this index for == or IN queries only */
2681 unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
2682 unsigned isResized:1; /* True if resizeIndexObject() has been called */
2683 unsigned isCovering:1; /* True if this is a covering index */
2684 unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
2685 unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
2686 unsigned bNoQuery:1; /* Do not use this index to optimize queries */
2687 unsigned bAscKeyBug:1; /* True if the bba7b69f9849b5bf bug applies */
2688 unsigned bHasVCol:1; /* Index references one or more VIRTUAL columns */
2689 unsigned bHasExpr:1; /* Index contains an expression, either a literal
2690 ** expression, or a reference to a VIRTUAL column */
2691 #ifdef SQLITE_ENABLE_STAT4
2692 int nSample; /* Number of elements in aSample[] */
2693 int nSampleCol; /* Size of IndexSample.anEq[] and so on */
2694 tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
2695 IndexSample *aSample; /* Samples of the left-most key */
2696 tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
2697 tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
2698 #endif
2699 Bitmask colNotIdxed; /* Unindexed columns in pTab */
2703 ** Allowed values for Index.idxType
2705 #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
2706 #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
2707 #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
2708 #define SQLITE_IDXTYPE_IPK 3 /* INTEGER PRIMARY KEY index */
2710 /* Return true if index X is a PRIMARY KEY index */
2711 #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
2713 /* Return true if index X is a UNIQUE index */
2714 #define IsUniqueIndex(X) ((X)->onError!=OE_None)
2716 /* The Index.aiColumn[] values are normally positive integer. But
2717 ** there are some negative values that have special meaning:
2719 #define XN_ROWID (-1) /* Indexed column is the rowid */
2720 #define XN_EXPR (-2) /* Indexed column is an expression */
2723 ** Each sample stored in the sqlite_stat4 table is represented in memory
2724 ** using a structure of this type. See documentation at the top of the
2725 ** analyze.c source file for additional information.
2727 struct IndexSample {
2728 void *p; /* Pointer to sampled record */
2729 int n; /* Size of record in bytes */
2730 tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
2731 tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
2732 tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
2736 ** Possible values to use within the flags argument to sqlite3GetToken().
2738 #define SQLITE_TOKEN_QUOTED 0x1 /* Token is a quoted identifier. */
2739 #define SQLITE_TOKEN_KEYWORD 0x2 /* Token is a keyword. */
2742 ** Each token coming out of the lexer is an instance of
2743 ** this structure. Tokens are also used as part of an expression.
2745 ** The memory that "z" points to is owned by other objects. Take care
2746 ** that the owner of the "z" string does not deallocate the string before
2747 ** the Token goes out of scope! Very often, the "z" points to some place
2748 ** in the middle of the Parse.zSql text. But it might also point to a
2749 ** static string.
2751 struct Token {
2752 const char *z; /* Text of the token. Not NULL-terminated! */
2753 unsigned int n; /* Number of characters in this token */
2757 ** An instance of this structure contains information needed to generate
2758 ** code for a SELECT that contains aggregate functions.
2760 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
2761 ** pointer to this structure. The Expr.iAgg field is the index in
2762 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
2763 ** code for that node.
2765 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
2766 ** original Select structure that describes the SELECT statement. These
2767 ** fields do not need to be freed when deallocating the AggInfo structure.
2769 struct AggInfo {
2770 u8 directMode; /* Direct rendering mode means take data directly
2771 ** from source tables rather than from accumulators */
2772 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
2773 ** than the source table */
2774 u16 nSortingColumn; /* Number of columns in the sorting index */
2775 int sortingIdx; /* Cursor number of the sorting index */
2776 int sortingIdxPTab; /* Cursor number of pseudo-table */
2777 int iFirstReg; /* First register in range for aCol[] and aFunc[] */
2778 ExprList *pGroupBy; /* The group by clause */
2779 struct AggInfo_col { /* For each column used in source tables */
2780 Table *pTab; /* Source table */
2781 Expr *pCExpr; /* The original expression */
2782 int iTable; /* Cursor number of the source table */
2783 i16 iColumn; /* Column number within the source table */
2784 i16 iSorterColumn; /* Column number in the sorting index */
2785 } *aCol;
2786 int nColumn; /* Number of used entries in aCol[] */
2787 int nAccumulator; /* Number of columns that show through to the output.
2788 ** Additional columns are used only as parameters to
2789 ** aggregate functions */
2790 struct AggInfo_func { /* For each aggregate function */
2791 Expr *pFExpr; /* Expression encoding the function */
2792 FuncDef *pFunc; /* The aggregate function implementation */
2793 int iDistinct; /* Ephemeral table used to enforce DISTINCT */
2794 int iDistAddr; /* Address of OP_OpenEphemeral */
2795 } *aFunc;
2796 int nFunc; /* Number of entries in aFunc[] */
2797 u32 selId; /* Select to which this AggInfo belongs */
2798 #ifdef SQLITE_DEBUG
2799 Select *pSelect; /* SELECT statement that this AggInfo supports */
2800 #endif
2804 ** Macros to compute aCol[] and aFunc[] register numbers.
2806 ** These macros should not be used prior to the call to
2807 ** assignAggregateRegisters() that computes the value of pAggInfo->iFirstReg.
2808 ** The assert()s that are part of this macro verify that constraint.
2810 #define AggInfoColumnReg(A,I) (assert((A)->iFirstReg),(A)->iFirstReg+(I))
2811 #define AggInfoFuncReg(A,I) \
2812 (assert((A)->iFirstReg),(A)->iFirstReg+(A)->nColumn+(I))
2815 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
2816 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
2817 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
2818 ** it uses less memory in the Expr object, which is a big memory user
2819 ** in systems with lots of prepared statements. And few applications
2820 ** need more than about 10 or 20 variables. But some extreme users want
2821 ** to have prepared statements with over 32766 variables, and for them
2822 ** the option is available (at compile-time).
2824 #if SQLITE_MAX_VARIABLE_NUMBER<32767
2825 typedef i16 ynVar;
2826 #else
2827 typedef int ynVar;
2828 #endif
2831 ** Each node of an expression in the parse tree is an instance
2832 ** of this structure.
2834 ** Expr.op is the opcode. The integer parser token codes are reused
2835 ** as opcodes here. For example, the parser defines TK_GE to be an integer
2836 ** code representing the ">=" operator. This same integer code is reused
2837 ** to represent the greater-than-or-equal-to operator in the expression
2838 ** tree.
2840 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
2841 ** or TK_STRING), then Expr.u.zToken contains the text of the SQL literal. If
2842 ** the expression is a variable (TK_VARIABLE), then Expr.u.zToken contains the
2843 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
2844 ** then Expr.u.zToken contains the name of the function.
2846 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
2847 ** binary operator. Either or both may be NULL.
2849 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
2850 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
2851 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
2852 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
2853 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
2854 ** valid.
2856 ** An expression of the form ID or ID.ID refers to a column in a table.
2857 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
2858 ** the integer cursor number of a VDBE cursor pointing to that table and
2859 ** Expr.iColumn is the column number for the specific column. If the
2860 ** expression is used as a result in an aggregate SELECT, then the
2861 ** value is also stored in the Expr.iAgg column in the aggregate so that
2862 ** it can be accessed after all aggregates are computed.
2864 ** If the expression is an unbound variable marker (a question mark
2865 ** character '?' in the original SQL) then the Expr.iTable holds the index
2866 ** number for that variable.
2868 ** If the expression is a subquery then Expr.iColumn holds an integer
2869 ** register number containing the result of the subquery. If the
2870 ** subquery gives a constant result, then iTable is -1. If the subquery
2871 ** gives a different answer at different times during statement processing
2872 ** then iTable is the address of a subroutine that computes the subquery.
2874 ** If the Expr is of type OP_Column, and the table it is selecting from
2875 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
2876 ** corresponding table definition.
2878 ** ALLOCATION NOTES:
2880 ** Expr objects can use a lot of memory space in database schema. To
2881 ** help reduce memory requirements, sometimes an Expr object will be
2882 ** truncated. And to reduce the number of memory allocations, sometimes
2883 ** two or more Expr objects will be stored in a single memory allocation,
2884 ** together with Expr.u.zToken strings.
2886 ** If the EP_Reduced and EP_TokenOnly flags are set when
2887 ** an Expr object is truncated. When EP_Reduced is set, then all
2888 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
2889 ** are contained within the same memory allocation. Note, however, that
2890 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
2891 ** allocated, regardless of whether or not EP_Reduced is set.
2893 struct Expr {
2894 u8 op; /* Operation performed by this node */
2895 char affExpr; /* affinity, or RAISE type */
2896 u8 op2; /* TK_REGISTER/TK_TRUTH: original value of Expr.op
2897 ** TK_COLUMN: the value of p5 for OP_Column
2898 ** TK_AGG_FUNCTION: nesting depth
2899 ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */
2900 #ifdef SQLITE_DEBUG
2901 u8 vvaFlags; /* Verification flags. */
2902 #endif
2903 u32 flags; /* Various flags. EP_* See below */
2904 union {
2905 char *zToken; /* Token value. Zero terminated and dequoted */
2906 int iValue; /* Non-negative integer value if EP_IntValue */
2907 } u;
2909 /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
2910 ** space is allocated for the fields below this point. An attempt to
2911 ** access them will result in a segfault or malfunction.
2912 *********************************************************************/
2914 Expr *pLeft; /* Left subnode */
2915 Expr *pRight; /* Right subnode */
2916 union {
2917 ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
2918 Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
2919 } x;
2921 /* If the EP_Reduced flag is set in the Expr.flags mask, then no
2922 ** space is allocated for the fields below this point. An attempt to
2923 ** access them will result in a segfault or malfunction.
2924 *********************************************************************/
2926 #if SQLITE_MAX_EXPR_DEPTH>0
2927 int nHeight; /* Height of the tree headed by this node */
2928 #endif
2929 int iTable; /* TK_COLUMN: cursor number of table holding column
2930 ** TK_REGISTER: register number
2931 ** TK_TRIGGER: 1 -> new, 0 -> old
2932 ** EP_Unlikely: 134217728 times likelihood
2933 ** TK_IN: ephemerial table holding RHS
2934 ** TK_SELECT_COLUMN: Number of columns on the LHS
2935 ** TK_SELECT: 1st register of result vector */
2936 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
2937 ** TK_VARIABLE: variable number (always >= 1).
2938 ** TK_SELECT_COLUMN: column of the result vector */
2939 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
2940 union {
2941 int iJoin; /* If EP_OuterON or EP_InnerON, the right table */
2942 int iOfst; /* else: start of token from start of statement */
2943 } w;
2944 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
2945 union {
2946 Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL
2947 ** for a column of an index on an expression */
2948 Window *pWin; /* EP_WinFunc: Window/Filter defn for a function */
2949 struct { /* TK_IN, TK_SELECT, and TK_EXISTS */
2950 int iAddr; /* Subroutine entry address */
2951 int regReturn; /* Register used to hold return address */
2952 } sub;
2953 } y;
2956 /* The following are the meanings of bits in the Expr.flags field.
2957 ** Value restrictions:
2959 ** EP_Agg == NC_HasAgg == SF_HasAgg
2960 ** EP_Win == NC_HasWin
2962 #define EP_OuterON 0x000001 /* Originates in ON/USING clause of outer join */
2963 #define EP_InnerON 0x000002 /* Originates in ON/USING of an inner join */
2964 #define EP_Distinct 0x000004 /* Aggregate function with DISTINCT keyword */
2965 #define EP_HasFunc 0x000008 /* Contains one or more functions of any kind */
2966 #define EP_Agg 0x000010 /* Contains one or more aggregate functions */
2967 #define EP_FixedCol 0x000020 /* TK_Column with a known fixed value */
2968 #define EP_VarSelect 0x000040 /* pSelect is correlated, not constant */
2969 #define EP_DblQuoted 0x000080 /* token.z was originally in "..." */
2970 #define EP_InfixFunc 0x000100 /* True for an infix function: LIKE, GLOB, etc */
2971 #define EP_Collate 0x000200 /* Tree contains a TK_COLLATE operator */
2972 #define EP_Commuted 0x000400 /* Comparison operator has been commuted */
2973 #define EP_IntValue 0x000800 /* Integer value contained in u.iValue */
2974 #define EP_xIsSelect 0x001000 /* x.pSelect is valid (otherwise x.pList is) */
2975 #define EP_Skip 0x002000 /* Operator does not contribute to affinity */
2976 #define EP_Reduced 0x004000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
2977 #define EP_Win 0x008000 /* Contains window functions */
2978 #define EP_TokenOnly 0x010000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
2979 /* 0x020000 // Available for reuse */
2980 #define EP_IfNullRow 0x040000 /* The TK_IF_NULL_ROW opcode */
2981 #define EP_Unlikely 0x080000 /* unlikely() or likelihood() function */
2982 #define EP_ConstFunc 0x100000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
2983 #define EP_CanBeNull 0x200000 /* Can be null despite NOT NULL constraint */
2984 #define EP_Subquery 0x400000 /* Tree contains a TK_SELECT operator */
2985 #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
2986 #define EP_WinFunc 0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
2987 #define EP_Subrtn 0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
2988 #define EP_Quoted 0x4000000 /* TK_ID was originally quoted */
2989 #define EP_Static 0x8000000 /* Held in memory not obtained from malloc() */
2990 #define EP_IsTrue 0x10000000 /* Always has boolean value of TRUE */
2991 #define EP_IsFalse 0x20000000 /* Always has boolean value of FALSE */
2992 #define EP_FromDDL 0x40000000 /* Originates from sqlite_schema */
2993 /* 0x80000000 // Available */
2995 /* The EP_Propagate mask is a set of properties that automatically propagate
2996 ** upwards into parent nodes.
2998 #define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
3000 /* Macros can be used to test, set, or clear bits in the
3001 ** Expr.flags field.
3003 #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
3004 #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
3005 #define ExprSetProperty(E,P) (E)->flags|=(P)
3006 #define ExprClearProperty(E,P) (E)->flags&=~(P)
3007 #define ExprAlwaysTrue(E) (((E)->flags&(EP_OuterON|EP_IsTrue))==EP_IsTrue)
3008 #define ExprAlwaysFalse(E) (((E)->flags&(EP_OuterON|EP_IsFalse))==EP_IsFalse)
3010 /* Macros used to ensure that the correct members of unions are accessed
3011 ** in Expr.
3013 #define ExprUseUToken(E) (((E)->flags&EP_IntValue)==0)
3014 #define ExprUseUValue(E) (((E)->flags&EP_IntValue)!=0)
3015 #define ExprUseXList(E) (((E)->flags&EP_xIsSelect)==0)
3016 #define ExprUseXSelect(E) (((E)->flags&EP_xIsSelect)!=0)
3017 #define ExprUseYTab(E) (((E)->flags&(EP_WinFunc|EP_Subrtn))==0)
3018 #define ExprUseYWin(E) (((E)->flags&EP_WinFunc)!=0)
3019 #define ExprUseYSub(E) (((E)->flags&EP_Subrtn)!=0)
3021 /* Flags for use with Expr.vvaFlags
3023 #define EP_NoReduce 0x01 /* Cannot EXPRDUP_REDUCE this Expr */
3024 #define EP_Immutable 0x02 /* Do not change this Expr node */
3026 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
3027 ** and Accreditation only. It works like ExprSetProperty() during VVA
3028 ** processes but is a no-op for delivery.
3030 #ifdef SQLITE_DEBUG
3031 # define ExprSetVVAProperty(E,P) (E)->vvaFlags|=(P)
3032 # define ExprHasVVAProperty(E,P) (((E)->vvaFlags&(P))!=0)
3033 # define ExprClearVVAProperties(E) (E)->vvaFlags = 0
3034 #else
3035 # define ExprSetVVAProperty(E,P)
3036 # define ExprHasVVAProperty(E,P) 0
3037 # define ExprClearVVAProperties(E)
3038 #endif
3041 ** Macros to determine the number of bytes required by a normal Expr
3042 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
3043 ** and an Expr struct with the EP_TokenOnly flag set.
3045 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
3046 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
3047 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
3050 ** Flags passed to the sqlite3ExprDup() function. See the header comment
3051 ** above sqlite3ExprDup() for details.
3053 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
3056 ** True if the expression passed as an argument was a function with
3057 ** an OVER() clause (a window function).
3059 #ifdef SQLITE_OMIT_WINDOWFUNC
3060 # define IsWindowFunc(p) 0
3061 #else
3062 # define IsWindowFunc(p) ( \
3063 ExprHasProperty((p), EP_WinFunc) && p->y.pWin->eFrmType!=TK_FILTER \
3065 #endif
3068 ** A list of expressions. Each expression may optionally have a
3069 ** name. An expr/name combination can be used in several ways, such
3070 ** as the list of "expr AS ID" fields following a "SELECT" or in the
3071 ** list of "ID = expr" items in an UPDATE. A list of expressions can
3072 ** also be used as the argument to a function, in which case the a.zName
3073 ** field is not used.
3075 ** In order to try to keep memory usage down, the Expr.a.zEName field
3076 ** is used for multiple purposes:
3078 ** eEName Usage
3079 ** ---------- -------------------------
3080 ** ENAME_NAME (1) the AS of result set column
3081 ** (2) COLUMN= of an UPDATE
3083 ** ENAME_TAB DB.TABLE.NAME used to resolve names
3084 ** of subqueries
3086 ** ENAME_SPAN Text of the original result set
3087 ** expression.
3089 struct ExprList {
3090 int nExpr; /* Number of expressions on the list */
3091 int nAlloc; /* Number of a[] slots allocated */
3092 struct ExprList_item { /* For each expression in the list */
3093 Expr *pExpr; /* The parse tree for this expression */
3094 char *zEName; /* Token associated with this expression */
3095 struct {
3096 u8 sortFlags; /* Mask of KEYINFO_ORDER_* flags */
3097 unsigned eEName :2; /* Meaning of zEName */
3098 unsigned done :1; /* Indicates when processing is finished */
3099 unsigned reusable :1; /* Constant expression is reusable */
3100 unsigned bSorterRef :1; /* Defer evaluation until after sorting */
3101 unsigned bNulls :1; /* True if explicit "NULLS FIRST/LAST" */
3102 unsigned bUsed :1; /* This column used in a SF_NestedFrom subquery */
3103 unsigned bUsingTerm:1; /* Term from the USING clause of a NestedFrom */
3104 unsigned bNoExpand: 1; /* Term is an auxiliary in NestedFrom and should
3105 ** not be expanded by "*" in parent queries */
3106 } fg;
3107 union {
3108 struct { /* Used by any ExprList other than Parse.pConsExpr */
3109 u16 iOrderByCol; /* For ORDER BY, column number in result set */
3110 u16 iAlias; /* Index into Parse.aAlias[] for zName */
3111 } x;
3112 int iConstExprReg; /* Register in which Expr value is cached. Used only
3113 ** by Parse.pConstExpr */
3114 } u;
3115 } a[1]; /* One slot for each expression in the list */
3119 ** Allowed values for Expr.a.eEName
3121 #define ENAME_NAME 0 /* The AS clause of a result set */
3122 #define ENAME_SPAN 1 /* Complete text of the result set expression */
3123 #define ENAME_TAB 2 /* "DB.TABLE.NAME" for the result set */
3126 ** An instance of this structure can hold a simple list of identifiers,
3127 ** such as the list "a,b,c" in the following statements:
3129 ** INSERT INTO t(a,b,c) VALUES ...;
3130 ** CREATE INDEX idx ON t(a,b,c);
3131 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
3133 ** The IdList.a.idx field is used when the IdList represents the list of
3134 ** column names after a table name in an INSERT statement. In the statement
3136 ** INSERT INTO t(a,b,c) ...
3138 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
3140 struct IdList {
3141 int nId; /* Number of identifiers on the list */
3142 u8 eU4; /* Which element of a.u4 is valid */
3143 struct IdList_item {
3144 char *zName; /* Name of the identifier */
3145 union {
3146 int idx; /* Index in some Table.aCol[] of a column named zName */
3147 Expr *pExpr; /* Expr to implement a USING variable -- NOT USED */
3148 } u4;
3149 } a[1];
3153 ** Allowed values for IdList.eType, which determines which value of the a.u4
3154 ** is valid.
3156 #define EU4_NONE 0 /* Does not use IdList.a.u4 */
3157 #define EU4_IDX 1 /* Uses IdList.a.u4.idx */
3158 #define EU4_EXPR 2 /* Uses IdList.a.u4.pExpr -- NOT CURRENTLY USED */
3161 ** The SrcItem object represents a single term in the FROM clause of a query.
3162 ** The SrcList object is mostly an array of SrcItems.
3164 ** The jointype starts out showing the join type between the current table
3165 ** and the next table on the list. The parser builds the list this way.
3166 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
3167 ** jointype expresses the join between the table and the previous table.
3169 ** In the colUsed field, the high-order bit (bit 63) is set if the table
3170 ** contains more than 63 columns and the 64-th or later column is used.
3172 ** Union member validity:
3174 ** u1.zIndexedBy fg.isIndexedBy && !fg.isTabFunc
3175 ** u1.pFuncArg fg.isTabFunc && !fg.isIndexedBy
3176 ** u2.pIBIndex fg.isIndexedBy && !fg.isCte
3177 ** u2.pCteUse fg.isCte && !fg.isIndexedBy
3179 struct SrcItem {
3180 Schema *pSchema; /* Schema to which this item is fixed */
3181 char *zDatabase; /* Name of database holding this table */
3182 char *zName; /* Name of the table */
3183 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
3184 Table *pTab; /* An SQL table corresponding to zName */
3185 Select *pSelect; /* A SELECT statement used in place of a table name */
3186 int addrFillSub; /* Address of subroutine to manifest a subquery */
3187 int regReturn; /* Register holding return address of addrFillSub */
3188 int regResult; /* Registers holding results of a co-routine */
3189 struct {
3190 u8 jointype; /* Type of join between this table and the previous */
3191 unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
3192 unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
3193 unsigned isTabFunc :1; /* True if table-valued-function syntax */
3194 unsigned isCorrelated :1; /* True if sub-query is correlated */
3195 unsigned isMaterialized:1; /* This is a materialized view */
3196 unsigned viaCoroutine :1; /* Implemented as a co-routine */
3197 unsigned isRecursive :1; /* True for recursive reference in WITH */
3198 unsigned fromDDL :1; /* Comes from sqlite_schema */
3199 unsigned isCte :1; /* This is a CTE */
3200 unsigned notCte :1; /* This item may not match a CTE */
3201 unsigned isUsing :1; /* u3.pUsing is valid */
3202 unsigned isOn :1; /* u3.pOn was once valid and non-NULL */
3203 unsigned isSynthUsing :1; /* u3.pUsing is synthensized from NATURAL */
3204 unsigned isNestedFrom :1; /* pSelect is a SF_NestedFrom subquery */
3205 } fg;
3206 int iCursor; /* The VDBE cursor number used to access this table */
3207 union {
3208 Expr *pOn; /* fg.isUsing==0 => The ON clause of a join */
3209 IdList *pUsing; /* fg.isUsing==1 => The USING clause of a join */
3210 } u3;
3211 Bitmask colUsed; /* Bit N set if column N used. Details above for N>62 */
3212 union {
3213 char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
3214 ExprList *pFuncArg; /* Arguments to table-valued-function */
3215 } u1;
3216 union {
3217 Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
3218 CteUse *pCteUse; /* CTE Usage info when fg.isCte is true */
3219 } u2;
3223 ** The OnOrUsing object represents either an ON clause or a USING clause.
3224 ** It can never be both at the same time, but it can be neither.
3226 struct OnOrUsing {
3227 Expr *pOn; /* The ON clause of a join */
3228 IdList *pUsing; /* The USING clause of a join */
3232 ** This object represents one or more tables that are the source of
3233 ** content for an SQL statement. For example, a single SrcList object
3234 ** is used to hold the FROM clause of a SELECT statement. SrcList also
3235 ** represents the target tables for DELETE, INSERT, and UPDATE statements.
3238 struct SrcList {
3239 int nSrc; /* Number of tables or subqueries in the FROM clause */
3240 u32 nAlloc; /* Number of entries allocated in a[] below */
3241 SrcItem a[1]; /* One entry for each identifier on the list */
3245 ** Permitted values of the SrcList.a.jointype field
3247 #define JT_INNER 0x01 /* Any kind of inner or cross join */
3248 #define JT_CROSS 0x02 /* Explicit use of the CROSS keyword */
3249 #define JT_NATURAL 0x04 /* True for a "natural" join */
3250 #define JT_LEFT 0x08 /* Left outer join */
3251 #define JT_RIGHT 0x10 /* Right outer join */
3252 #define JT_OUTER 0x20 /* The "OUTER" keyword is present */
3253 #define JT_LTORJ 0x40 /* One of the LEFT operands of a RIGHT JOIN
3254 ** Mnemonic: Left Table Of Right Join */
3255 #define JT_ERROR 0x80 /* unknown or unsupported join type */
3258 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
3259 ** and the WhereInfo.wctrlFlags member.
3261 ** Value constraints (enforced via assert()):
3262 ** WHERE_USE_LIMIT == SF_FixedLimit
3264 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
3265 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
3266 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
3267 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
3268 #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
3269 #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
3270 #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
3271 ** the OR optimization */
3272 #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
3273 #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
3274 #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
3275 #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
3276 #define WHERE_AGG_DISTINCT 0x0400 /* Query is "SELECT agg(DISTINCT ...)" */
3277 #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
3278 #define WHERE_RIGHT_JOIN 0x1000 /* Processing a RIGHT JOIN */
3279 /* 0x2000 not currently used */
3280 #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
3281 /* 0x8000 not currently used */
3283 /* Allowed return values from sqlite3WhereIsDistinct()
3285 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
3286 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
3287 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
3288 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
3291 ** A NameContext defines a context in which to resolve table and column
3292 ** names. The context consists of a list of tables (the pSrcList) field and
3293 ** a list of named expression (pEList). The named expression list may
3294 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
3295 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
3296 ** pEList corresponds to the result set of a SELECT and is NULL for
3297 ** other statements.
3299 ** NameContexts can be nested. When resolving names, the inner-most
3300 ** context is searched first. If no match is found, the next outer
3301 ** context is checked. If there is still no match, the next context
3302 ** is checked. This process continues until either a match is found
3303 ** or all contexts are check. When a match is found, the nRef member of
3304 ** the context containing the match is incremented.
3306 ** Each subquery gets a new NameContext. The pNext field points to the
3307 ** NameContext in the parent query. Thus the process of scanning the
3308 ** NameContext list corresponds to searching through successively outer
3309 ** subqueries looking for a match.
3311 struct NameContext {
3312 Parse *pParse; /* The parser */
3313 SrcList *pSrcList; /* One or more tables used to resolve names */
3314 union {
3315 ExprList *pEList; /* Optional list of result-set columns */
3316 AggInfo *pAggInfo; /* Information about aggregates at this level */
3317 Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */
3318 int iBaseReg; /* For TK_REGISTER when parsing RETURNING */
3319 } uNC;
3320 NameContext *pNext; /* Next outer name context. NULL for outermost */
3321 int nRef; /* Number of names resolved by this context */
3322 int nNcErr; /* Number of errors encountered while resolving names */
3323 int ncFlags; /* Zero or more NC_* flags defined below */
3324 Select *pWinSelect; /* SELECT statement for any window functions */
3328 ** Allowed values for the NameContext, ncFlags field.
3330 ** Value constraints (all checked via assert()):
3331 ** NC_HasAgg == SF_HasAgg == EP_Agg
3332 ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
3333 ** NC_OrderAgg == SF_OrderByReqd == SQLITE_FUNC_ANYORDER
3334 ** NC_HasWin == EP_Win
3337 #define NC_AllowAgg 0x000001 /* Aggregate functions are allowed here */
3338 #define NC_PartIdx 0x000002 /* True if resolving a partial index WHERE */
3339 #define NC_IsCheck 0x000004 /* True if resolving a CHECK constraint */
3340 #define NC_GenCol 0x000008 /* True for a GENERATED ALWAYS AS clause */
3341 #define NC_HasAgg 0x000010 /* One or more aggregate functions seen */
3342 #define NC_IdxExpr 0x000020 /* True if resolving columns of CREATE INDEX */
3343 #define NC_SelfRef 0x00002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
3344 #define NC_VarSelect 0x000040 /* A correlated subquery has been seen */
3345 #define NC_UEList 0x000080 /* True if uNC.pEList is used */
3346 #define NC_UAggInfo 0x000100 /* True if uNC.pAggInfo is used */
3347 #define NC_UUpsert 0x000200 /* True if uNC.pUpsert is used */
3348 #define NC_UBaseReg 0x000400 /* True if uNC.iBaseReg is used */
3349 #define NC_MinMaxAgg 0x001000 /* min/max aggregates seen. See note above */
3350 #define NC_Complex 0x002000 /* True if a function or subquery seen */
3351 #define NC_AllowWin 0x004000 /* Window functions are allowed here */
3352 #define NC_HasWin 0x008000 /* One or more window functions seen */
3353 #define NC_IsDDL 0x010000 /* Resolving names in a CREATE statement */
3354 #define NC_InAggFunc 0x020000 /* True if analyzing arguments to an agg func */
3355 #define NC_FromDDL 0x040000 /* SQL text comes from sqlite_schema */
3356 #define NC_NoSelect 0x080000 /* Do not descend into sub-selects */
3357 #define NC_OrderAgg 0x8000000 /* Has an aggregate other than count/min/max */
3360 ** An instance of the following object describes a single ON CONFLICT
3361 ** clause in an upsert.
3363 ** The pUpsertTarget field is only set if the ON CONFLICT clause includes
3364 ** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the
3365 ** conflict-target clause.) The pUpsertTargetWhere is the optional
3366 ** WHERE clause used to identify partial unique indexes.
3368 ** pUpsertSet is the list of column=expr terms of the UPDATE statement.
3369 ** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING. The
3370 ** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
3371 ** WHERE clause is omitted.
3373 struct Upsert {
3374 ExprList *pUpsertTarget; /* Optional description of conflict target */
3375 Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
3376 ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */
3377 Expr *pUpsertWhere; /* WHERE clause for the ON CONFLICT UPDATE */
3378 Upsert *pNextUpsert; /* Next ON CONFLICT clause in the list */
3379 u8 isDoUpdate; /* True for DO UPDATE. False for DO NOTHING */
3380 /* Above this point is the parse tree for the ON CONFLICT clauses.
3381 ** The next group of fields stores intermediate data. */
3382 void *pToFree; /* Free memory when deleting the Upsert object */
3383 /* All fields above are owned by the Upsert object and must be freed
3384 ** when the Upsert is destroyed. The fields below are used to transfer
3385 ** information from the INSERT processing down into the UPDATE processing
3386 ** while generating code. The fields below are owned by the INSERT
3387 ** statement and will be freed by INSERT processing. */
3388 Index *pUpsertIdx; /* UNIQUE constraint specified by pUpsertTarget */
3389 SrcList *pUpsertSrc; /* Table to be updated */
3390 int regData; /* First register holding array of VALUES */
3391 int iDataCur; /* Index of the data cursor */
3392 int iIdxCur; /* Index of the first index cursor */
3396 ** An instance of the following structure contains all information
3397 ** needed to generate code for a single SELECT statement.
3399 ** See the header comment on the computeLimitRegisters() routine for a
3400 ** detailed description of the meaning of the iLimit and iOffset fields.
3402 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
3403 ** These addresses must be stored so that we can go back and fill in
3404 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
3405 ** the number of columns in P2 can be computed at the same time
3406 ** as the OP_OpenEphm instruction is coded because not
3407 ** enough information about the compound query is known at that point.
3408 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
3409 ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
3410 ** sequences for the ORDER BY clause.
3412 struct Select {
3413 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
3414 LogEst nSelectRow; /* Estimated number of result rows */
3415 u32 selFlags; /* Various SF_* values */
3416 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
3417 u32 selId; /* Unique identifier number for this SELECT */
3418 int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
3419 ExprList *pEList; /* The fields of the result */
3420 SrcList *pSrc; /* The FROM clause */
3421 Expr *pWhere; /* The WHERE clause */
3422 ExprList *pGroupBy; /* The GROUP BY clause */
3423 Expr *pHaving; /* The HAVING clause */
3424 ExprList *pOrderBy; /* The ORDER BY clause */
3425 Select *pPrior; /* Prior select in a compound select statement */
3426 Select *pNext; /* Next select to the left in a compound */
3427 Expr *pLimit; /* LIMIT expression. NULL means not used. */
3428 With *pWith; /* WITH clause attached to this select. Or NULL. */
3429 #ifndef SQLITE_OMIT_WINDOWFUNC
3430 Window *pWin; /* List of window functions */
3431 Window *pWinDefn; /* List of named window definitions */
3432 #endif
3436 ** Allowed values for Select.selFlags. The "SF" prefix stands for
3437 ** "Select Flag".
3439 ** Value constraints (all checked via assert())
3440 ** SF_HasAgg == NC_HasAgg
3441 ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
3442 ** SF_OrderByReqd == NC_OrderAgg == SQLITE_FUNC_ANYORDER
3443 ** SF_FixedLimit == WHERE_USE_LIMIT
3445 #define SF_Distinct 0x0000001 /* Output should be DISTINCT */
3446 #define SF_All 0x0000002 /* Includes the ALL keyword */
3447 #define SF_Resolved 0x0000004 /* Identifiers have been resolved */
3448 #define SF_Aggregate 0x0000008 /* Contains agg functions or a GROUP BY */
3449 #define SF_HasAgg 0x0000010 /* Contains aggregate functions */
3450 #define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */
3451 #define SF_Expanded 0x0000040 /* sqlite3SelectExpand() called on this */
3452 #define SF_HasTypeInfo 0x0000080 /* FROM subqueries have Table metadata */
3453 #define SF_Compound 0x0000100 /* Part of a compound query */
3454 #define SF_Values 0x0000200 /* Synthesized from VALUES clause */
3455 #define SF_MultiValue 0x0000400 /* Single VALUES term with multiple rows */
3456 #define SF_NestedFrom 0x0000800 /* Part of a parenthesized FROM clause */
3457 #define SF_MinMaxAgg 0x0001000 /* Aggregate containing min() or max() */
3458 #define SF_Recursive 0x0002000 /* The recursive part of a recursive CTE */
3459 #define SF_FixedLimit 0x0004000 /* nSelectRow set by a constant LIMIT */
3460 #define SF_MaybeConvert 0x0008000 /* Need convertCompoundSelectToSubquery() */
3461 #define SF_Converted 0x0010000 /* By convertCompoundSelectToSubquery() */
3462 #define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */
3463 #define SF_ComplexResult 0x0040000 /* Result contains subquery or function */
3464 #define SF_WhereBegin 0x0080000 /* Really a WhereBegin() call. Debug Only */
3465 #define SF_WinRewrite 0x0100000 /* Window function rewrite accomplished */
3466 #define SF_View 0x0200000 /* SELECT statement is a view */
3467 #define SF_NoopOrderBy 0x0400000 /* ORDER BY is ignored for this query */
3468 #define SF_UFSrcCheck 0x0800000 /* Check pSrc as required by UPDATE...FROM */
3469 #define SF_PushDown 0x1000000 /* SELECT has be modified by push-down opt */
3470 #define SF_MultiPart 0x2000000 /* Has multiple incompatible PARTITIONs */
3471 #define SF_CopyCte 0x4000000 /* SELECT statement is a copy of a CTE */
3472 #define SF_OrderByReqd 0x8000000 /* The ORDER BY clause may not be omitted */
3473 #define SF_UpdateFrom 0x10000000 /* Query originates with UPDATE FROM */
3475 /* True if S exists and has SF_NestedFrom */
3476 #define IsNestedFrom(S) ((S)!=0 && ((S)->selFlags&SF_NestedFrom)!=0)
3479 ** The results of a SELECT can be distributed in several ways, as defined
3480 ** by one of the following macros. The "SRT" prefix means "SELECT Result
3481 ** Type".
3483 ** SRT_Union Store results as a key in a temporary index
3484 ** identified by pDest->iSDParm.
3486 ** SRT_Except Remove results from the temporary index pDest->iSDParm.
3488 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
3489 ** set is not empty.
3491 ** SRT_Discard Throw the results away. This is used by SELECT
3492 ** statements within triggers whose only purpose is
3493 ** the side-effects of functions.
3495 ** SRT_Output Generate a row of output (using the OP_ResultRow
3496 ** opcode) for each row in the result set.
3498 ** SRT_Mem Only valid if the result is a single column.
3499 ** Store the first column of the first result row
3500 ** in register pDest->iSDParm then abandon the rest
3501 ** of the query. This destination implies "LIMIT 1".
3503 ** SRT_Set The result must be a single column. Store each
3504 ** row of result as the key in table pDest->iSDParm.
3505 ** Apply the affinity pDest->affSdst before storing
3506 ** results. Used to implement "IN (SELECT ...)".
3508 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
3509 ** the result there. The cursor is left open after
3510 ** returning. This is like SRT_Table except that
3511 ** this destination uses OP_OpenEphemeral to create
3512 ** the table first.
3514 ** SRT_Coroutine Generate a co-routine that returns a new row of
3515 ** results each time it is invoked. The entry point
3516 ** of the co-routine is stored in register pDest->iSDParm
3517 ** and the result row is stored in pDest->nDest registers
3518 ** starting with pDest->iSdst.
3520 ** SRT_Table Store results in temporary table pDest->iSDParm.
3521 ** SRT_Fifo This is like SRT_EphemTab except that the table
3522 ** is assumed to already be open. SRT_Fifo has
3523 ** the additional property of being able to ignore
3524 ** the ORDER BY clause.
3526 ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
3527 ** But also use temporary table pDest->iSDParm+1 as
3528 ** a record of all prior results and ignore any duplicate
3529 ** rows. Name means: "Distinct Fifo".
3531 ** SRT_Queue Store results in priority queue pDest->iSDParm (really
3532 ** an index). Append a sequence number so that all entries
3533 ** are distinct.
3535 ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
3536 ** the same record has never been stored before. The
3537 ** index at pDest->iSDParm+1 hold all prior stores.
3539 ** SRT_Upfrom Store results in the temporary table already opened by
3540 ** pDest->iSDParm. If (pDest->iSDParm<0), then the temp
3541 ** table is an intkey table - in this case the first
3542 ** column returned by the SELECT is used as the integer
3543 ** key. If (pDest->iSDParm>0), then the table is an index
3544 ** table. (pDest->iSDParm) is the number of key columns in
3545 ** each index record in this case.
3547 #define SRT_Union 1 /* Store result as keys in an index */
3548 #define SRT_Except 2 /* Remove result from a UNION index */
3549 #define SRT_Exists 3 /* Store 1 if the result is not empty */
3550 #define SRT_Discard 4 /* Do not save the results anywhere */
3551 #define SRT_DistFifo 5 /* Like SRT_Fifo, but unique results only */
3552 #define SRT_DistQueue 6 /* Like SRT_Queue, but unique results only */
3554 /* The DISTINCT clause is ignored for all of the above. Not that
3555 ** IgnorableDistinct() implies IgnorableOrderby() */
3556 #define IgnorableDistinct(X) ((X->eDest)<=SRT_DistQueue)
3558 #define SRT_Queue 7 /* Store result in an queue */
3559 #define SRT_Fifo 8 /* Store result as data with an automatic rowid */
3561 /* The ORDER BY clause is ignored for all of the above */
3562 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Fifo)
3564 #define SRT_Output 9 /* Output each row of result */
3565 #define SRT_Mem 10 /* Store result in a memory cell */
3566 #define SRT_Set 11 /* Store results as keys in an index */
3567 #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
3568 #define SRT_Coroutine 13 /* Generate a single row of result */
3569 #define SRT_Table 14 /* Store result as data with an automatic rowid */
3570 #define SRT_Upfrom 15 /* Store result as data with rowid */
3573 ** An instance of this object describes where to put of the results of
3574 ** a SELECT statement.
3576 struct SelectDest {
3577 u8 eDest; /* How to dispose of the results. One of SRT_* above. */
3578 int iSDParm; /* A parameter used by the eDest disposal method */
3579 int iSDParm2; /* A second parameter for the eDest disposal method */
3580 int iSdst; /* Base register where results are written */
3581 int nSdst; /* Number of registers allocated */
3582 char *zAffSdst; /* Affinity used for SRT_Set */
3583 ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
3587 ** During code generation of statements that do inserts into AUTOINCREMENT
3588 ** tables, the following information is attached to the Table.u.autoInc.p
3589 ** pointer of each autoincrement table to record some side information that
3590 ** the code generator needs. We have to keep per-table autoincrement
3591 ** information in case inserts are done within triggers. Triggers do not
3592 ** normally coordinate their activities, but we do need to coordinate the
3593 ** loading and saving of autoincrement information.
3595 struct AutoincInfo {
3596 AutoincInfo *pNext; /* Next info block in a list of them all */
3597 Table *pTab; /* Table this info block refers to */
3598 int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
3599 int regCtr; /* Memory register holding the rowid counter */
3603 ** At least one instance of the following structure is created for each
3604 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
3605 ** statement. All such objects are stored in the linked list headed at
3606 ** Parse.pTriggerPrg and deleted once statement compilation has been
3607 ** completed.
3609 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
3610 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
3611 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
3612 ** The Parse.pTriggerPrg list never contains two entries with the same
3613 ** values for both pTrigger and orconf.
3615 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
3616 ** accessed (or set to 0 for triggers fired as a result of INSERT
3617 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
3618 ** a mask of new.* columns used by the program.
3620 struct TriggerPrg {
3621 Trigger *pTrigger; /* Trigger this program was coded from */
3622 TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
3623 SubProgram *pProgram; /* Program implementing pTrigger/orconf */
3624 int orconf; /* Default ON CONFLICT policy */
3625 u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
3629 ** The yDbMask datatype for the bitmask of all attached databases.
3631 #if SQLITE_MAX_ATTACHED>30
3632 typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
3633 # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
3634 # define DbMaskZero(M) memset((M),0,sizeof(M))
3635 # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
3636 # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
3637 # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
3638 #else
3639 typedef unsigned int yDbMask;
3640 # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
3641 # define DbMaskZero(M) ((M)=0)
3642 # define DbMaskSet(M,I) ((M)|=(((yDbMask)1)<<(I)))
3643 # define DbMaskAllZero(M) ((M)==0)
3644 # define DbMaskNonZero(M) ((M)!=0)
3645 #endif
3648 ** For each index X that has as one of its arguments either an expression
3649 ** or the name of a virtual generated column, and if X is in scope such that
3650 ** the value of the expression can simply be read from the index, then
3651 ** there is an instance of this object on the Parse.pIdxExpr list.
3653 ** During code generation, while generating code to evaluate expressions,
3654 ** this list is consulted and if a matching expression is found, the value
3655 ** is read from the index rather than being recomputed.
3657 struct IndexedExpr {
3658 Expr *pExpr; /* The expression contained in the index */
3659 int iDataCur; /* The data cursor associated with the index */
3660 int iIdxCur; /* The index cursor */
3661 int iIdxCol; /* The index column that contains value of pExpr */
3662 u8 bMaybeNullRow; /* True if we need an OP_IfNullRow check */
3663 u8 aff; /* Affinity of the pExpr expression */
3664 IndexedExpr *pIENext; /* Next in a list of all indexed expressions */
3665 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
3666 const char *zIdxName; /* Name of index, used only for bytecode comments */
3667 #endif
3671 ** An instance of the ParseCleanup object specifies an operation that
3672 ** should be performed after parsing to deallocation resources obtained
3673 ** during the parse and which are no longer needed.
3675 struct ParseCleanup {
3676 ParseCleanup *pNext; /* Next cleanup task */
3677 void *pPtr; /* Pointer to object to deallocate */
3678 void (*xCleanup)(sqlite3*,void*); /* Deallocation routine */
3682 ** An SQL parser context. A copy of this structure is passed through
3683 ** the parser and down into all the parser action routine in order to
3684 ** carry around information that is global to the entire parse.
3686 ** The structure is divided into two parts. When the parser and code
3687 ** generate call themselves recursively, the first part of the structure
3688 ** is constant but the second part is reset at the beginning and end of
3689 ** each recursion.
3691 ** The nTableLock and aTableLock variables are only used if the shared-cache
3692 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
3693 ** used to store the set of table-locks required by the statement being
3694 ** compiled. Function sqlite3TableLock() is used to add entries to the
3695 ** list.
3697 struct Parse {
3698 sqlite3 *db; /* The main database structure */
3699 char *zErrMsg; /* An error message */
3700 Vdbe *pVdbe; /* An engine for executing database bytecode */
3701 int rc; /* Return code from execution */
3702 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
3703 u8 checkSchema; /* Causes schema cookie check after an error */
3704 u8 nested; /* Number of nested calls to the parser/code generator */
3705 u8 nTempReg; /* Number of temporary registers in aTempReg[] */
3706 u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
3707 u8 mayAbort; /* True if statement may throw an ABORT exception */
3708 u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
3709 u8 okConstFactor; /* OK to factor out constants */
3710 u8 disableLookaside; /* Number of times lookaside has been disabled */
3711 u8 prepFlags; /* SQLITE_PREPARE_* flags */
3712 u8 withinRJSubrtn; /* Nesting level for RIGHT JOIN body subroutines */
3713 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
3714 u8 earlyCleanup; /* OOM inside sqlite3ParserAddCleanup() */
3715 #endif
3716 int nRangeReg; /* Size of the temporary register block */
3717 int iRangeReg; /* First register in temporary register block */
3718 int nErr; /* Number of errors seen */
3719 int nTab; /* Number of previously allocated VDBE cursors */
3720 int nMem; /* Number of memory cells used so far */
3721 int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
3722 int iSelfTab; /* Table associated with an index on expr, or negative
3723 ** of the base register during check-constraint eval */
3724 int nLabel; /* The *negative* of the number of labels used */
3725 int nLabelAlloc; /* Number of slots in aLabel */
3726 int *aLabel; /* Space to hold the labels */
3727 ExprList *pConstExpr;/* Constant expressions */
3728 IndexedExpr *pIdxEpr;/* List of expressions used by active indexes */
3729 Token constraintName;/* Name of the constraint currently being parsed */
3730 yDbMask writeMask; /* Start a write transaction on these databases */
3731 yDbMask cookieMask; /* Bitmask of schema verified databases */
3732 int regRowid; /* Register holding rowid of CREATE TABLE entry */
3733 int regRoot; /* Register holding root page number for new objects */
3734 int nMaxArg; /* Max args passed to user function by sub-program */
3735 int nSelect; /* Number of SELECT stmts. Counter for Select.selId */
3736 #ifndef SQLITE_OMIT_SHARED_CACHE
3737 int nTableLock; /* Number of locks in aTableLock */
3738 TableLock *aTableLock; /* Required table locks for shared-cache mode */
3739 #endif
3740 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
3741 Parse *pToplevel; /* Parse structure for main program (or NULL) */
3742 Table *pTriggerTab; /* Table triggers are being coded for */
3743 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
3744 ParseCleanup *pCleanup; /* List of cleanup operations to run after parse */
3745 union {
3746 int addrCrTab; /* Address of OP_CreateBtree on CREATE TABLE */
3747 Returning *pReturning; /* The RETURNING clause */
3748 } u1;
3749 u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
3750 u32 oldmask; /* Mask of old.* columns referenced */
3751 u32 newmask; /* Mask of new.* columns referenced */
3752 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
3753 u32 nProgressSteps; /* xProgress steps taken during sqlite3_prepare() */
3754 #endif
3755 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
3756 u8 bReturning; /* Coding a RETURNING trigger */
3757 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
3758 u8 disableTriggers; /* True to disable triggers */
3760 /**************************************************************************
3761 ** Fields above must be initialized to zero. The fields that follow,
3762 ** down to the beginning of the recursive section, do not need to be
3763 ** initialized as they will be set before being used. The boundary is
3764 ** determined by offsetof(Parse,aTempReg).
3765 **************************************************************************/
3767 int aTempReg[8]; /* Holding area for temporary registers */
3768 Parse *pOuterParse; /* Outer Parse object when nested */
3769 Token sNameToken; /* Token with unqualified schema object name */
3771 /************************************************************************
3772 ** Above is constant between recursions. Below is reset before and after
3773 ** each recursion. The boundary between these two regions is determined
3774 ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
3775 ** first field in the recursive region.
3776 ************************************************************************/
3778 Token sLastToken; /* The last token parsed */
3779 ynVar nVar; /* Number of '?' variables seen in the SQL so far */
3780 u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
3781 u8 explain; /* True if the EXPLAIN flag is found on the query */
3782 u8 eParseMode; /* PARSE_MODE_XXX constant */
3783 #ifndef SQLITE_OMIT_VIRTUALTABLE
3784 int nVtabLock; /* Number of virtual tables to lock */
3785 #endif
3786 int nHeight; /* Expression tree height of current sub-select */
3787 #ifndef SQLITE_OMIT_EXPLAIN
3788 int addrExplain; /* Address of current OP_Explain opcode */
3789 #endif
3790 VList *pVList; /* Mapping between variable names and numbers */
3791 Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
3792 const char *zTail; /* All SQL text past the last semicolon parsed */
3793 Table *pNewTable; /* A table being constructed by CREATE TABLE */
3794 Index *pNewIndex; /* An index being constructed by CREATE INDEX.
3795 ** Also used to hold redundant UNIQUE constraints
3796 ** during a RENAME COLUMN */
3797 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
3798 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
3799 #ifndef SQLITE_OMIT_VIRTUALTABLE
3800 Token sArg; /* Complete text of a module argument */
3801 Table **apVtabLock; /* Pointer to virtual tables needing locking */
3802 #endif
3803 With *pWith; /* Current WITH clause, or NULL */
3804 #ifndef SQLITE_OMIT_ALTERTABLE
3805 RenameToken *pRename; /* Tokens subject to renaming by ALTER TABLE */
3806 #endif
3809 /* Allowed values for Parse.eParseMode
3811 #define PARSE_MODE_NORMAL 0
3812 #define PARSE_MODE_DECLARE_VTAB 1
3813 #define PARSE_MODE_RENAME 2
3814 #define PARSE_MODE_UNMAP 3
3817 ** Sizes and pointers of various parts of the Parse object.
3819 #define PARSE_HDR(X) (((char*)(X))+offsetof(Parse,zErrMsg))
3820 #define PARSE_HDR_SZ (offsetof(Parse,aTempReg)-offsetof(Parse,zErrMsg)) /* Recursive part w/o aColCache*/
3821 #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
3822 #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
3823 #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
3826 ** Return true if currently inside an sqlite3_declare_vtab() call.
3828 #ifdef SQLITE_OMIT_VIRTUALTABLE
3829 #define IN_DECLARE_VTAB 0
3830 #else
3831 #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
3832 #endif
3834 #if defined(SQLITE_OMIT_ALTERTABLE)
3835 #define IN_RENAME_OBJECT 0
3836 #else
3837 #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME)
3838 #endif
3840 #if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
3841 #define IN_SPECIAL_PARSE 0
3842 #else
3843 #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
3844 #endif
3847 ** An instance of the following structure can be declared on a stack and used
3848 ** to save the Parse.zAuthContext value so that it can be restored later.
3850 struct AuthContext {
3851 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
3852 Parse *pParse; /* The Parse structure */
3856 ** Bitfield flags for P5 value in various opcodes.
3858 ** Value constraints (enforced via assert()):
3859 ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
3860 ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
3861 ** OPFLAG_BULKCSR == BTREE_BULKLOAD
3862 ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
3863 ** OPFLAG_FORDELETE == BTREE_FORDELETE
3864 ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
3865 ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
3867 #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
3868 /* Also used in P2 (not P5) of OP_Delete */
3869 #define OPFLAG_NOCHNG 0x01 /* OP_VColumn nochange for UPDATE */
3870 #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
3871 #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
3872 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
3873 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
3874 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
3875 #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
3876 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
3877 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
3878 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
3879 #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
3880 #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
3881 #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
3882 #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
3883 #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
3884 #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
3885 #define OPFLAG_NOCHNG_MAGIC 0x6d /* OP_MakeRecord: serialtype 10 is ok */
3886 #define OPFLAG_PREFORMAT 0x80 /* OP_Insert uses preformatted cell */
3889 ** Each trigger present in the database schema is stored as an instance of
3890 ** struct Trigger.
3892 ** Pointers to instances of struct Trigger are stored in two ways.
3893 ** 1. In the "trigHash" hash table (part of the sqlite3* that represents the
3894 ** database). This allows Trigger structures to be retrieved by name.
3895 ** 2. All triggers associated with a single table form a linked list, using the
3896 ** pNext member of struct Trigger. A pointer to the first element of the
3897 ** linked list is stored as the "pTrigger" member of the associated
3898 ** struct Table.
3900 ** The "step_list" member points to the first element of a linked list
3901 ** containing the SQL statements specified as the trigger program.
3903 struct Trigger {
3904 char *zName; /* The name of the trigger */
3905 char *table; /* The table or view to which the trigger applies */
3906 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
3907 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
3908 u8 bReturning; /* This trigger implements a RETURNING clause */
3909 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
3910 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
3911 the <column-list> is stored here */
3912 Schema *pSchema; /* Schema containing the trigger */
3913 Schema *pTabSchema; /* Schema containing the table */
3914 TriggerStep *step_list; /* Link list of trigger program steps */
3915 Trigger *pNext; /* Next trigger associated with the table */
3919 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
3920 ** determine which.
3922 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
3923 ** In that cases, the constants below can be ORed together.
3925 #define TRIGGER_BEFORE 1
3926 #define TRIGGER_AFTER 2
3929 ** An instance of struct TriggerStep is used to store a single SQL statement
3930 ** that is a part of a trigger-program.
3932 ** Instances of struct TriggerStep are stored in a singly linked list (linked
3933 ** using the "pNext" member) referenced by the "step_list" member of the
3934 ** associated struct Trigger instance. The first element of the linked list is
3935 ** the first step of the trigger-program.
3937 ** The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
3938 ** "SELECT" statement. The meanings of the other members is determined by the
3939 ** value of "op" as follows:
3941 ** (op == TK_INSERT)
3942 ** orconf -> stores the ON CONFLICT algorithm
3943 ** pSelect -> The content to be inserted - either a SELECT statement or
3944 ** a VALUES clause.
3945 ** zTarget -> Dequoted name of the table to insert into.
3946 ** pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
3947 ** statement, then this stores the column-names to be
3948 ** inserted into.
3949 ** pUpsert -> The ON CONFLICT clauses for an Upsert
3951 ** (op == TK_DELETE)
3952 ** zTarget -> Dequoted name of the table to delete from.
3953 ** pWhere -> The WHERE clause of the DELETE statement if one is specified.
3954 ** Otherwise NULL.
3956 ** (op == TK_UPDATE)
3957 ** zTarget -> Dequoted name of the table to update.
3958 ** pWhere -> The WHERE clause of the UPDATE statement if one is specified.
3959 ** Otherwise NULL.
3960 ** pExprList -> A list of the columns to update and the expressions to update
3961 ** them to. See sqlite3Update() documentation of "pChanges"
3962 ** argument.
3964 ** (op == TK_SELECT)
3965 ** pSelect -> The SELECT statement
3967 ** (op == TK_RETURNING)
3968 ** pExprList -> The list of expressions that follow the RETURNING keyword.
3971 struct TriggerStep {
3972 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT,
3973 ** or TK_RETURNING */
3974 u8 orconf; /* OE_Rollback etc. */
3975 Trigger *pTrig; /* The trigger that this step is a part of */
3976 Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
3977 char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
3978 SrcList *pFrom; /* FROM clause for UPDATE statement (if any) */
3979 Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
3980 ExprList *pExprList; /* SET clause for UPDATE, or RETURNING clause */
3981 IdList *pIdList; /* Column names for INSERT */
3982 Upsert *pUpsert; /* Upsert clauses on an INSERT */
3983 char *zSpan; /* Original SQL text of this command */
3984 TriggerStep *pNext; /* Next in the link-list */
3985 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
3989 ** Information about a RETURNING clause
3991 struct Returning {
3992 Parse *pParse; /* The parse that includes the RETURNING clause */
3993 ExprList *pReturnEL; /* List of expressions to return */
3994 Trigger retTrig; /* The transient trigger that implements RETURNING */
3995 TriggerStep retTStep; /* The trigger step */
3996 int iRetCur; /* Transient table holding RETURNING results */
3997 int nRetCol; /* Number of in pReturnEL after expansion */
3998 int iRetReg; /* Register array for holding a row of RETURNING */
4002 ** An objected used to accumulate the text of a string where we
4003 ** do not necessarily know how big the string will be in the end.
4005 struct sqlite3_str {
4006 sqlite3 *db; /* Optional database for lookaside. Can be NULL */
4007 char *zText; /* The string collected so far */
4008 u32 nAlloc; /* Amount of space allocated in zText */
4009 u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
4010 u32 nChar; /* Length of the string so far */
4011 u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */
4012 u8 printfFlags; /* SQLITE_PRINTF flags below */
4014 #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
4015 #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
4016 #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
4018 #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
4022 ** A pointer to this structure is used to communicate information
4023 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
4025 typedef struct {
4026 sqlite3 *db; /* The database being initialized */
4027 char **pzErrMsg; /* Error message stored here */
4028 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
4029 int rc; /* Result code stored here */
4030 u32 mInitFlags; /* Flags controlling error messages */
4031 u32 nInitRow; /* Number of rows processed */
4032 Pgno mxPage; /* Maximum page number. 0 for no limit. */
4033 } InitData;
4036 ** Allowed values for mInitFlags
4038 #define INITFLAG_AlterMask 0x0003 /* Types of ALTER */
4039 #define INITFLAG_AlterRename 0x0001 /* Reparse after a RENAME */
4040 #define INITFLAG_AlterDrop 0x0002 /* Reparse after a DROP COLUMN */
4041 #define INITFLAG_AlterAdd 0x0003 /* Reparse after an ADD COLUMN */
4043 /* Tuning parameters are set using SQLITE_TESTCTRL_TUNE and are controlled
4044 ** on debug-builds of the CLI using ".testctrl tune ID VALUE". Tuning
4045 ** parameters are for temporary use during development, to help find
4046 ** optimial values for parameters in the query planner. The should not
4047 ** be used on trunk check-ins. They are a temporary mechanism available
4048 ** for transient development builds only.
4050 ** Tuning parameters are numbered starting with 1.
4052 #define SQLITE_NTUNE 6 /* Should be zero for all trunk check-ins */
4053 #ifdef SQLITE_DEBUG
4054 # define Tuning(X) (sqlite3Config.aTune[(X)-1])
4055 #else
4056 # define Tuning(X) 0
4057 #endif
4060 ** Structure containing global configuration data for the SQLite library.
4062 ** This structure also contains some state information.
4064 struct Sqlite3Config {
4065 int bMemstat; /* True to enable memory status */
4066 u8 bCoreMutex; /* True to enable core mutexing */
4067 u8 bFullMutex; /* True to enable full mutexing */
4068 u8 bOpenUri; /* True to interpret filenames as URIs */
4069 u8 bUseCis; /* Use covering indices for full-scans */
4070 u8 bSmallMalloc; /* Avoid large memory allocations if true */
4071 u8 bExtraSchemaChecks; /* Verify type,name,tbl_name in schema */
4072 int mxStrlen; /* Maximum string length */
4073 int neverCorrupt; /* Database is always well-formed */
4074 int szLookaside; /* Default lookaside buffer size */
4075 int nLookaside; /* Default lookaside buffer count */
4076 int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
4077 sqlite3_mem_methods m; /* Low-level memory allocation interface */
4078 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
4079 sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
4080 void *pHeap; /* Heap storage space */
4081 int nHeap; /* Size of pHeap[] */
4082 int mnReq, mxReq; /* Min and max heap requests sizes */
4083 sqlite3_int64 szMmap; /* mmap() space per open file */
4084 sqlite3_int64 mxMmap; /* Maximum value for szMmap */
4085 void *pPage; /* Page cache memory */
4086 int szPage; /* Size of each page in pPage[] */
4087 int nPage; /* Number of pages in pPage[] */
4088 int mxParserStack; /* maximum depth of the parser stack */
4089 int sharedCacheEnabled; /* true if shared-cache mode enabled */
4090 u32 szPma; /* Maximum Sorter PMA size */
4091 /* The above might be initialized to non-zero. The following need to always
4092 ** initially be zero, however. */
4093 int isInit; /* True after initialization has finished */
4094 int inProgress; /* True while initialization in progress */
4095 int isMutexInit; /* True after mutexes are initialized */
4096 int isMallocInit; /* True after malloc is initialized */
4097 int isPCacheInit; /* True after malloc is initialized */
4098 int nRefInitMutex; /* Number of users of pInitMutex */
4099 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
4100 void (*xLog)(void*,int,const char*); /* Function for logging */
4101 void *pLogArg; /* First argument to xLog() */
4102 #ifdef SQLITE_ENABLE_SQLLOG
4103 void(*xSqllog)(void*,sqlite3*,const char*, int);
4104 void *pSqllogArg;
4105 #endif
4106 #ifdef SQLITE_VDBE_COVERAGE
4107 /* The following callback (if not NULL) is invoked on every VDBE branch
4108 ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
4110 void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx); /* Callback */
4111 void *pVdbeBranchArg; /* 1st argument */
4112 #endif
4113 #ifndef SQLITE_OMIT_DESERIALIZE
4114 sqlite3_int64 mxMemdbSize; /* Default max memdb size */
4115 #endif
4116 #ifndef SQLITE_UNTESTABLE
4117 int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
4118 #endif
4119 int bLocaltimeFault; /* True to fail localtime() calls */
4120 int (*xAltLocaltime)(const void*,void*); /* Alternative localtime() routine */
4121 int iOnceResetThreshold; /* When to reset OP_Once counters */
4122 u32 szSorterRef; /* Min size in bytes to use sorter-refs */
4123 unsigned int iPrngSeed; /* Alternative fixed seed for the PRNG */
4124 /* vvvv--- must be last ---vvv */
4125 #ifdef SQLITE_DEBUG
4126 sqlite3_int64 aTune[SQLITE_NTUNE]; /* Tuning parameters */
4127 #endif
4131 ** This macro is used inside of assert() statements to indicate that
4132 ** the assert is only valid on a well-formed database. Instead of:
4134 ** assert( X );
4136 ** One writes:
4138 ** assert( X || CORRUPT_DB );
4140 ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
4141 ** that the database is definitely corrupt, only that it might be corrupt.
4142 ** For most test cases, CORRUPT_DB is set to false using a special
4143 ** sqlite3_test_control(). This enables assert() statements to prove
4144 ** things that are always true for well-formed databases.
4146 #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
4149 ** Context pointer passed down through the tree-walk.
4151 struct Walker {
4152 Parse *pParse; /* Parser context. */
4153 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
4154 int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
4155 void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
4156 int walkerDepth; /* Number of subqueries */
4157 u16 eCode; /* A small processing code */
4158 union { /* Extra data for callback */
4159 NameContext *pNC; /* Naming context */
4160 int n; /* A counter */
4161 int iCur; /* A cursor number */
4162 SrcList *pSrcList; /* FROM clause */
4163 struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
4164 struct RefSrcList *pRefSrcList; /* sqlite3ReferencesSrcList() */
4165 int *aiCol; /* array of column indexes */
4166 struct IdxCover *pIdxCover; /* Check for index coverage */
4167 ExprList *pGroupBy; /* GROUP BY clause */
4168 Select *pSelect; /* HAVING to WHERE clause ctx */
4169 struct WindowRewrite *pRewrite; /* Window rewrite context */
4170 struct WhereConst *pConst; /* WHERE clause constants */
4171 struct RenameCtx *pRename; /* RENAME COLUMN context */
4172 struct Table *pTab; /* Table of generated column */
4173 struct CoveringIndexCheck *pCovIdxCk; /* Check for covering index */
4174 SrcItem *pSrcItem; /* A single FROM clause item */
4175 DbFixer *pFix; /* See sqlite3FixSelect() */
4176 } u;
4180 ** The following structure contains information used by the sqliteFix...
4181 ** routines as they walk the parse tree to make database references
4182 ** explicit.
4184 struct DbFixer {
4185 Parse *pParse; /* The parsing context. Error messages written here */
4186 Walker w; /* Walker object */
4187 Schema *pSchema; /* Fix items to this schema */
4188 u8 bTemp; /* True for TEMP schema entries */
4189 const char *zDb; /* Make sure all objects are contained in this database */
4190 const char *zType; /* Type of the container - used for error messages */
4191 const Token *pName; /* Name of the container - used for error messages */
4194 /* Forward declarations */
4195 int sqlite3WalkExpr(Walker*, Expr*);
4196 int sqlite3WalkExprList(Walker*, ExprList*);
4197 int sqlite3WalkSelect(Walker*, Select*);
4198 int sqlite3WalkSelectExpr(Walker*, Select*);
4199 int sqlite3WalkSelectFrom(Walker*, Select*);
4200 int sqlite3ExprWalkNoop(Walker*, Expr*);
4201 int sqlite3SelectWalkNoop(Walker*, Select*);
4202 int sqlite3SelectWalkFail(Walker*, Select*);
4203 int sqlite3WalkerDepthIncrease(Walker*,Select*);
4204 void sqlite3WalkerDepthDecrease(Walker*,Select*);
4205 void sqlite3WalkWinDefnDummyCallback(Walker*,Select*);
4207 #ifdef SQLITE_DEBUG
4208 void sqlite3SelectWalkAssert2(Walker*, Select*);
4209 #endif
4211 #ifndef SQLITE_OMIT_CTE
4212 void sqlite3SelectPopWith(Walker*, Select*);
4213 #else
4214 # define sqlite3SelectPopWith 0
4215 #endif
4218 ** Return code from the parse-tree walking primitives and their
4219 ** callbacks.
4221 #define WRC_Continue 0 /* Continue down into children */
4222 #define WRC_Prune 1 /* Omit children but continue walking siblings */
4223 #define WRC_Abort 2 /* Abandon the tree walk */
4226 ** A single common table expression
4228 struct Cte {
4229 char *zName; /* Name of this CTE */
4230 ExprList *pCols; /* List of explicit column names, or NULL */
4231 Select *pSelect; /* The definition of this CTE */
4232 const char *zCteErr; /* Error message for circular references */
4233 CteUse *pUse; /* Usage information for this CTE */
4234 u8 eM10d; /* The MATERIALIZED flag */
4238 ** Allowed values for the materialized flag (eM10d):
4240 #define M10d_Yes 0 /* AS MATERIALIZED */
4241 #define M10d_Any 1 /* Not specified. Query planner's choice */
4242 #define M10d_No 2 /* AS NOT MATERIALIZED */
4245 ** An instance of the With object represents a WITH clause containing
4246 ** one or more CTEs (common table expressions).
4248 struct With {
4249 int nCte; /* Number of CTEs in the WITH clause */
4250 int bView; /* Belongs to the outermost Select of a view */
4251 With *pOuter; /* Containing WITH clause, or NULL */
4252 Cte a[1]; /* For each CTE in the WITH clause.... */
4256 ** The Cte object is not guaranteed to persist for the entire duration
4257 ** of code generation. (The query flattener or other parser tree
4258 ** edits might delete it.) The following object records information
4259 ** about each Common Table Expression that must be preserved for the
4260 ** duration of the parse.
4262 ** The CteUse objects are freed using sqlite3ParserAddCleanup() rather
4263 ** than sqlite3SelectDelete(), which is what enables them to persist
4264 ** until the end of code generation.
4266 struct CteUse {
4267 int nUse; /* Number of users of this CTE */
4268 int addrM9e; /* Start of subroutine to compute materialization */
4269 int regRtn; /* Return address register for addrM9e subroutine */
4270 int iCur; /* Ephemeral table holding the materialization */
4271 LogEst nRowEst; /* Estimated number of rows in the table */
4272 u8 eM10d; /* The MATERIALIZED flag */
4276 #ifdef SQLITE_DEBUG
4278 ** An instance of the TreeView object is used for printing the content of
4279 ** data structures on sqlite3DebugPrintf() using a tree-like view.
4281 struct TreeView {
4282 int iLevel; /* Which level of the tree we are on */
4283 u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
4285 #endif /* SQLITE_DEBUG */
4288 ** This object is used in various ways, most (but not all) related to window
4289 ** functions.
4291 ** (1) A single instance of this structure is attached to the
4292 ** the Expr.y.pWin field for each window function in an expression tree.
4293 ** This object holds the information contained in the OVER clause,
4294 ** plus additional fields used during code generation.
4296 ** (2) All window functions in a single SELECT form a linked-list
4297 ** attached to Select.pWin. The Window.pFunc and Window.pExpr
4298 ** fields point back to the expression that is the window function.
4300 ** (3) The terms of the WINDOW clause of a SELECT are instances of this
4301 ** object on a linked list attached to Select.pWinDefn.
4303 ** (4) For an aggregate function with a FILTER clause, an instance
4304 ** of this object is stored in Expr.y.pWin with eFrmType set to
4305 ** TK_FILTER. In this case the only field used is Window.pFilter.
4307 ** The uses (1) and (2) are really the same Window object that just happens
4308 ** to be accessible in two different ways. Use case (3) are separate objects.
4310 struct Window {
4311 char *zName; /* Name of window (may be NULL) */
4312 char *zBase; /* Name of base window for chaining (may be NULL) */
4313 ExprList *pPartition; /* PARTITION BY clause */
4314 ExprList *pOrderBy; /* ORDER BY clause */
4315 u8 eFrmType; /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */
4316 u8 eStart; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
4317 u8 eEnd; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
4318 u8 bImplicitFrame; /* True if frame was implicitly specified */
4319 u8 eExclude; /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */
4320 Expr *pStart; /* Expression for "<expr> PRECEDING" */
4321 Expr *pEnd; /* Expression for "<expr> FOLLOWING" */
4322 Window **ppThis; /* Pointer to this object in Select.pWin list */
4323 Window *pNextWin; /* Next window function belonging to this SELECT */
4324 Expr *pFilter; /* The FILTER expression */
4325 FuncDef *pWFunc; /* The function */
4326 int iEphCsr; /* Partition buffer or Peer buffer */
4327 int regAccum; /* Accumulator */
4328 int regResult; /* Interim result */
4329 int csrApp; /* Function cursor (used by min/max) */
4330 int regApp; /* Function register (also used by min/max) */
4331 int regPart; /* Array of registers for PARTITION BY values */
4332 Expr *pOwner; /* Expression object this window is attached to */
4333 int nBufferCol; /* Number of columns in buffer table */
4334 int iArgCol; /* Offset of first argument for this function */
4335 int regOne; /* Register containing constant value 1 */
4336 int regStartRowid;
4337 int regEndRowid;
4338 u8 bExprArgs; /* Defer evaluation of window function arguments
4339 ** due to the SQLITE_SUBTYPE flag */
4342 #ifndef SQLITE_OMIT_WINDOWFUNC
4343 void sqlite3WindowDelete(sqlite3*, Window*);
4344 void sqlite3WindowUnlinkFromSelect(Window*);
4345 void sqlite3WindowListDelete(sqlite3 *db, Window *p);
4346 Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);
4347 void sqlite3WindowAttach(Parse*, Expr*, Window*);
4348 void sqlite3WindowLink(Select *pSel, Window *pWin);
4349 int sqlite3WindowCompare(const Parse*, const Window*, const Window*, int);
4350 void sqlite3WindowCodeInit(Parse*, Select*);
4351 void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
4352 int sqlite3WindowRewrite(Parse*, Select*);
4353 void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
4354 Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
4355 Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
4356 void sqlite3WindowFunctions(void);
4357 void sqlite3WindowChain(Parse*, Window*, Window*);
4358 Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*);
4359 #else
4360 # define sqlite3WindowDelete(a,b)
4361 # define sqlite3WindowFunctions()
4362 # define sqlite3WindowAttach(a,b,c)
4363 #endif
4366 ** Assuming zIn points to the first byte of a UTF-8 character,
4367 ** advance zIn to point to the first byte of the next UTF-8 character.
4369 #define SQLITE_SKIP_UTF8(zIn) { \
4370 if( (*(zIn++))>=0xc0 ){ \
4371 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
4376 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
4377 ** the same name but without the _BKPT suffix. These macros invoke
4378 ** routines that report the line-number on which the error originated
4379 ** using sqlite3_log(). The routines also provide a convenient place
4380 ** to set a debugger breakpoint.
4382 int sqlite3ReportError(int iErr, int lineno, const char *zType);
4383 int sqlite3CorruptError(int);
4384 int sqlite3MisuseError(int);
4385 int sqlite3CantopenError(int);
4386 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
4387 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
4388 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
4389 #ifdef SQLITE_DEBUG
4390 int sqlite3NomemError(int);
4391 int sqlite3IoerrnomemError(int);
4392 # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
4393 # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
4394 #else
4395 # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
4396 # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
4397 #endif
4398 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
4399 int sqlite3CorruptPgnoError(int,Pgno);
4400 # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
4401 #else
4402 # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
4403 #endif
4406 ** FTS3 and FTS4 both require virtual table support
4408 #if defined(SQLITE_OMIT_VIRTUALTABLE)
4409 # undef SQLITE_ENABLE_FTS3
4410 # undef SQLITE_ENABLE_FTS4
4411 #endif
4414 ** FTS4 is really an extension for FTS3. It is enabled using the
4415 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
4416 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
4418 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
4419 # define SQLITE_ENABLE_FTS3 1
4420 #endif
4423 ** The ctype.h header is needed for non-ASCII systems. It is also
4424 ** needed by FTS3 when FTS3 is included in the amalgamation.
4426 #if !defined(SQLITE_ASCII) || \
4427 (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
4428 # include <ctype.h>
4429 #endif
4432 ** The following macros mimic the standard library functions toupper(),
4433 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
4434 ** sqlite versions only work for ASCII characters, regardless of locale.
4436 #ifdef SQLITE_ASCII
4437 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
4438 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
4439 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
4440 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
4441 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
4442 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
4443 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
4444 # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
4445 #else
4446 # define sqlite3Toupper(x) toupper((unsigned char)(x))
4447 # define sqlite3Isspace(x) isspace((unsigned char)(x))
4448 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
4449 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
4450 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
4451 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
4452 # define sqlite3Tolower(x) tolower((unsigned char)(x))
4453 # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
4454 #endif
4455 int sqlite3IsIdChar(u8);
4458 ** Internal function prototypes
4460 int sqlite3StrICmp(const char*,const char*);
4461 int sqlite3Strlen30(const char*);
4462 #define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)
4463 char *sqlite3ColumnType(Column*,char*);
4464 #define sqlite3StrNICmp sqlite3_strnicmp
4466 int sqlite3MallocInit(void);
4467 void sqlite3MallocEnd(void);
4468 void *sqlite3Malloc(u64);
4469 void *sqlite3MallocZero(u64);
4470 void *sqlite3DbMallocZero(sqlite3*, u64);
4471 void *sqlite3DbMallocRaw(sqlite3*, u64);
4472 void *sqlite3DbMallocRawNN(sqlite3*, u64);
4473 char *sqlite3DbStrDup(sqlite3*,const char*);
4474 char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
4475 char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
4476 void *sqlite3Realloc(void*, u64);
4477 void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
4478 void *sqlite3DbRealloc(sqlite3 *, void *, u64);
4479 void sqlite3DbFree(sqlite3*, void*);
4480 void sqlite3DbFreeNN(sqlite3*, void*);
4481 void sqlite3DbNNFreeNN(sqlite3*, void*);
4482 int sqlite3MallocSize(const void*);
4483 int sqlite3DbMallocSize(sqlite3*, const void*);
4484 void *sqlite3PageMalloc(int);
4485 void sqlite3PageFree(void*);
4486 void sqlite3MemSetDefault(void);
4487 #ifndef SQLITE_UNTESTABLE
4488 void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
4489 #endif
4490 int sqlite3HeapNearlyFull(void);
4493 ** On systems with ample stack space and that support alloca(), make
4494 ** use of alloca() to obtain space for large automatic objects. By default,
4495 ** obtain space from malloc().
4497 ** The alloca() routine never returns NULL. This will cause code paths
4498 ** that deal with sqlite3StackAlloc() failures to be unreachable.
4500 #ifdef SQLITE_USE_ALLOCA
4501 # define sqlite3StackAllocRaw(D,N) alloca(N)
4502 # define sqlite3StackAllocRawNN(D,N) alloca(N)
4503 # define sqlite3StackFree(D,P)
4504 # define sqlite3StackFreeNN(D,P)
4505 #else
4506 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
4507 # define sqlite3StackAllocRawNN(D,N) sqlite3DbMallocRawNN(D,N)
4508 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
4509 # define sqlite3StackFreeNN(D,P) sqlite3DbFreeNN(D,P)
4510 #endif
4512 /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
4513 ** are, disable MEMSYS3
4515 #ifdef SQLITE_ENABLE_MEMSYS5
4516 const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
4517 #undef SQLITE_ENABLE_MEMSYS3
4518 #endif
4519 #ifdef SQLITE_ENABLE_MEMSYS3
4520 const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
4521 #endif
4524 #ifndef SQLITE_MUTEX_OMIT
4525 sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
4526 sqlite3_mutex_methods const *sqlite3NoopMutex(void);
4527 sqlite3_mutex *sqlite3MutexAlloc(int);
4528 int sqlite3MutexInit(void);
4529 int sqlite3MutexEnd(void);
4530 #endif
4531 #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
4532 void sqlite3MemoryBarrier(void);
4533 #else
4534 # define sqlite3MemoryBarrier()
4535 #endif
4537 sqlite3_int64 sqlite3StatusValue(int);
4538 void sqlite3StatusUp(int, int);
4539 void sqlite3StatusDown(int, int);
4540 void sqlite3StatusHighwater(int, int);
4541 int sqlite3LookasideUsed(sqlite3*,int*);
4543 /* Access to mutexes used by sqlite3_status() */
4544 sqlite3_mutex *sqlite3Pcache1Mutex(void);
4545 sqlite3_mutex *sqlite3MallocMutex(void);
4547 #if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
4548 void sqlite3MutexWarnOnContention(sqlite3_mutex*);
4549 #else
4550 # define sqlite3MutexWarnOnContention(x)
4551 #endif
4553 #ifndef SQLITE_OMIT_FLOATING_POINT
4554 # define EXP754 (((u64)0x7ff)<<52)
4555 # define MAN754 ((((u64)1)<<52)-1)
4556 # define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0)
4557 int sqlite3IsNaN(double);
4558 #else
4559 # define IsNaN(X) 0
4560 # define sqlite3IsNaN(X) 0
4561 #endif
4564 ** An instance of the following structure holds information about SQL
4565 ** functions arguments that are the parameters to the printf() function.
4567 struct PrintfArguments {
4568 int nArg; /* Total number of arguments */
4569 int nUsed; /* Number of arguments used so far */
4570 sqlite3_value **apArg; /* The argument values */
4573 char *sqlite3MPrintf(sqlite3*,const char*, ...);
4574 char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
4575 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
4576 void sqlite3DebugPrintf(const char*, ...);
4577 #endif
4578 #if defined(SQLITE_TEST)
4579 void *sqlite3TestTextToPtr(const char*);
4580 #endif
4582 #if defined(SQLITE_DEBUG)
4583 void sqlite3TreeViewLine(TreeView*, const char *zFormat, ...);
4584 void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
4585 void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
4586 void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
4587 void sqlite3TreeViewBareIdList(TreeView*, const IdList*, const char*);
4588 void sqlite3TreeViewIdList(TreeView*, const IdList*, u8, const char*);
4589 void sqlite3TreeViewColumnList(TreeView*, const Column*, int, u8);
4590 void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
4591 void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
4592 void sqlite3TreeViewWith(TreeView*, const With*, u8);
4593 void sqlite3TreeViewUpsert(TreeView*, const Upsert*, u8);
4594 #if TREETRACE_ENABLED
4595 void sqlite3TreeViewDelete(const With*, const SrcList*, const Expr*,
4596 const ExprList*,const Expr*, const Trigger*);
4597 void sqlite3TreeViewInsert(const With*, const SrcList*,
4598 const IdList*, const Select*, const ExprList*,
4599 int, const Upsert*, const Trigger*);
4600 void sqlite3TreeViewUpdate(const With*, const SrcList*, const ExprList*,
4601 const Expr*, int, const ExprList*, const Expr*,
4602 const Upsert*, const Trigger*);
4603 #endif
4604 #ifndef SQLITE_OMIT_TRIGGER
4605 void sqlite3TreeViewTriggerStep(TreeView*, const TriggerStep*, u8, u8);
4606 void sqlite3TreeViewTrigger(TreeView*, const Trigger*, u8, u8);
4607 #endif
4608 #ifndef SQLITE_OMIT_WINDOWFUNC
4609 void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
4610 void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
4611 #endif
4612 void sqlite3ShowExpr(const Expr*);
4613 void sqlite3ShowExprList(const ExprList*);
4614 void sqlite3ShowIdList(const IdList*);
4615 void sqlite3ShowSrcList(const SrcList*);
4616 void sqlite3ShowSelect(const Select*);
4617 void sqlite3ShowWith(const With*);
4618 void sqlite3ShowUpsert(const Upsert*);
4619 #ifndef SQLITE_OMIT_TRIGGER
4620 void sqlite3ShowTriggerStep(const TriggerStep*);
4621 void sqlite3ShowTriggerStepList(const TriggerStep*);
4622 void sqlite3ShowTrigger(const Trigger*);
4623 void sqlite3ShowTriggerList(const Trigger*);
4624 #endif
4625 #ifndef SQLITE_OMIT_WINDOWFUNC
4626 void sqlite3ShowWindow(const Window*);
4627 void sqlite3ShowWinFunc(const Window*);
4628 #endif
4629 #endif
4631 void sqlite3SetString(char **, sqlite3*, const char*);
4632 void sqlite3ProgressCheck(Parse*);
4633 void sqlite3ErrorMsg(Parse*, const char*, ...);
4634 int sqlite3ErrorToParser(sqlite3*,int);
4635 void sqlite3Dequote(char*);
4636 void sqlite3DequoteExpr(Expr*);
4637 void sqlite3DequoteToken(Token*);
4638 void sqlite3TokenInit(Token*,char*);
4639 int sqlite3KeywordCode(const unsigned char*, int);
4640 int sqlite3RunParser(Parse*, const char*);
4641 void sqlite3FinishCoding(Parse*);
4642 int sqlite3GetTempReg(Parse*);
4643 void sqlite3ReleaseTempReg(Parse*,int);
4644 int sqlite3GetTempRange(Parse*,int);
4645 void sqlite3ReleaseTempRange(Parse*,int,int);
4646 void sqlite3ClearTempRegCache(Parse*);
4647 #ifdef SQLITE_DEBUG
4648 int sqlite3NoTempsInRange(Parse*,int,int);
4649 #endif
4650 Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
4651 Expr *sqlite3Expr(sqlite3*,int,const char*);
4652 void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
4653 Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
4654 void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
4655 Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);
4656 Expr *sqlite3ExprSimplifiedAndOr(Expr*);
4657 Expr *sqlite3ExprFunction(Parse*,ExprList*, const Token*, int);
4658 void sqlite3ExprFunctionUsable(Parse*,const Expr*,const FuncDef*);
4659 void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
4660 void sqlite3ExprDelete(sqlite3*, Expr*);
4661 void sqlite3ExprDeferredDelete(Parse*, Expr*);
4662 void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
4663 ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
4664 ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
4665 Select *sqlite3ExprListToValues(Parse*, int, ExprList*);
4666 void sqlite3ExprListSetSortOrder(ExprList*,int,int);
4667 void sqlite3ExprListSetName(Parse*,ExprList*,const Token*,int);
4668 void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
4669 void sqlite3ExprListDelete(sqlite3*, ExprList*);
4670 u32 sqlite3ExprListFlags(const ExprList*);
4671 int sqlite3IndexHasDuplicateRootPage(Index*);
4672 int sqlite3Init(sqlite3*, char**);
4673 int sqlite3InitCallback(void*, int, char**, char**);
4674 int sqlite3InitOne(sqlite3*, int, char**, u32);
4675 void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
4676 #ifndef SQLITE_OMIT_VIRTUALTABLE
4677 Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
4678 #endif
4679 void sqlite3ResetAllSchemasOfConnection(sqlite3*);
4680 void sqlite3ResetOneSchema(sqlite3*,int);
4681 void sqlite3CollapseDatabaseArray(sqlite3*);
4682 void sqlite3CommitInternalChanges(sqlite3*);
4683 void sqlite3ColumnSetExpr(Parse*,Table*,Column*,Expr*);
4684 Expr *sqlite3ColumnExpr(Table*,Column*);
4685 void sqlite3ColumnSetColl(sqlite3*,Column*,const char*zColl);
4686 const char *sqlite3ColumnColl(Column*);
4687 void sqlite3DeleteColumnNames(sqlite3*,Table*);
4688 void sqlite3GenerateColumnNames(Parse *pParse, Select *pSelect);
4689 int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
4690 void sqlite3SubqueryColumnTypes(Parse*,Table*,Select*,char);
4691 Table *sqlite3ResultSetOfSelect(Parse*,Select*,char);
4692 void sqlite3OpenSchemaTable(Parse *, int);
4693 Index *sqlite3PrimaryKeyIndex(Table*);
4694 i16 sqlite3TableColumnToIndex(Index*, i16);
4695 #ifdef SQLITE_OMIT_GENERATED_COLUMNS
4696 # define sqlite3TableColumnToStorage(T,X) (X) /* No-op pass-through */
4697 # define sqlite3StorageColumnToTable(T,X) (X) /* No-op pass-through */
4698 #else
4699 i16 sqlite3TableColumnToStorage(Table*, i16);
4700 i16 sqlite3StorageColumnToTable(Table*, i16);
4701 #endif
4702 void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
4703 #if SQLITE_ENABLE_HIDDEN_COLUMNS
4704 void sqlite3ColumnPropertiesFromName(Table*, Column*);
4705 #else
4706 # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
4707 #endif
4708 void sqlite3AddColumn(Parse*,Token,Token);
4709 void sqlite3AddNotNull(Parse*, int);
4710 void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
4711 void sqlite3AddCheckConstraint(Parse*, Expr*, const char*, const char*);
4712 void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
4713 void sqlite3AddCollateType(Parse*, Token*);
4714 void sqlite3AddGenerated(Parse*,Expr*,Token*);
4715 void sqlite3EndTable(Parse*,Token*,Token*,u32,Select*);
4716 void sqlite3AddReturning(Parse*,ExprList*);
4717 int sqlite3ParseUri(const char*,const char*,unsigned int*,
4718 sqlite3_vfs**,char**,char **);
4719 /* BEGIN SQLCIPHER */
4720 #ifdef SQLITE_HAS_CODEC
4721 int sqlite3CodecQueryParameters(sqlite3*,const char*,const char*);
4722 #else
4723 # define sqlite3CodecQueryParameters(A,B,C) 0
4724 #endif
4725 /* END SQLCIPHER */
4726 Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
4728 #ifdef SQLITE_UNTESTABLE
4729 # define sqlite3FaultSim(X) SQLITE_OK
4730 #else
4731 int sqlite3FaultSim(int);
4732 #endif
4734 Bitvec *sqlite3BitvecCreate(u32);
4735 int sqlite3BitvecTest(Bitvec*, u32);
4736 int sqlite3BitvecTestNotNull(Bitvec*, u32);
4737 int sqlite3BitvecSet(Bitvec*, u32);
4738 void sqlite3BitvecClear(Bitvec*, u32, void*);
4739 void sqlite3BitvecDestroy(Bitvec*);
4740 u32 sqlite3BitvecSize(Bitvec*);
4741 #ifndef SQLITE_UNTESTABLE
4742 int sqlite3BitvecBuiltinTest(int,int*);
4743 #endif
4745 RowSet *sqlite3RowSetInit(sqlite3*);
4746 void sqlite3RowSetDelete(void*);
4747 void sqlite3RowSetClear(void*);
4748 void sqlite3RowSetInsert(RowSet*, i64);
4749 int sqlite3RowSetTest(RowSet*, int iBatch, i64);
4750 int sqlite3RowSetNext(RowSet*, i64*);
4752 void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
4754 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
4755 int sqlite3ViewGetColumnNames(Parse*,Table*);
4756 #else
4757 # define sqlite3ViewGetColumnNames(A,B) 0
4758 #endif
4760 #if SQLITE_MAX_ATTACHED>30
4761 int sqlite3DbMaskAllZero(yDbMask);
4762 #endif
4763 void sqlite3DropTable(Parse*, SrcList*, int, int);
4764 void sqlite3CodeDropTable(Parse*, Table*, int, int);
4765 void sqlite3DeleteTable(sqlite3*, Table*);
4766 void sqlite3FreeIndex(sqlite3*, Index*);
4767 #ifndef SQLITE_OMIT_AUTOINCREMENT
4768 void sqlite3AutoincrementBegin(Parse *pParse);
4769 void sqlite3AutoincrementEnd(Parse *pParse);
4770 #else
4771 # define sqlite3AutoincrementBegin(X)
4772 # define sqlite3AutoincrementEnd(X)
4773 #endif
4774 void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
4775 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4776 void sqlite3ComputeGeneratedColumns(Parse*, int, Table*);
4777 #endif
4778 void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
4779 IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
4780 int sqlite3IdListIndex(IdList*,const char*);
4781 SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);
4782 SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2);
4783 SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);
4784 SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
4785 Token*, Select*, OnOrUsing*);
4786 void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
4787 void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
4788 int sqlite3IndexedByLookup(Parse *, SrcItem *);
4789 void sqlite3SrcListShiftJoinType(Parse*,SrcList*);
4790 void sqlite3SrcListAssignCursors(Parse*, SrcList*);
4791 void sqlite3IdListDelete(sqlite3*, IdList*);
4792 void sqlite3ClearOnOrUsing(sqlite3*, OnOrUsing*);
4793 void sqlite3SrcListDelete(sqlite3*, SrcList*);
4794 Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
4795 void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
4796 Expr*, int, int, u8);
4797 void sqlite3DropIndex(Parse*, SrcList*, int);
4798 int sqlite3Select(Parse*, Select*, SelectDest*);
4799 Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
4800 Expr*,ExprList*,u32,Expr*);
4801 void sqlite3SelectDelete(sqlite3*, Select*);
4802 Table *sqlite3SrcListLookup(Parse*, SrcList*);
4803 int sqlite3IsReadOnly(Parse*, Table*, int);
4804 void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
4805 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
4806 Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
4807 #endif
4808 void sqlite3CodeChangeCount(Vdbe*,int,const char*);
4809 void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
4810 void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
4811 Upsert*);
4812 WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,
4813 ExprList*,Select*,u16,int);
4814 void sqlite3WhereEnd(WhereInfo*);
4815 LogEst sqlite3WhereOutputRowCount(WhereInfo*);
4816 int sqlite3WhereIsDistinct(WhereInfo*);
4817 int sqlite3WhereIsOrdered(WhereInfo*);
4818 int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
4819 void sqlite3WhereMinMaxOptEarlyOut(Vdbe*,WhereInfo*);
4820 int sqlite3WhereIsSorted(WhereInfo*);
4821 int sqlite3WhereContinueLabel(WhereInfo*);
4822 int sqlite3WhereBreakLabel(WhereInfo*);
4823 int sqlite3WhereOkOnePass(WhereInfo*, int*);
4824 #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
4825 #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
4826 #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
4827 int sqlite3WhereUsesDeferredSeek(WhereInfo*);
4828 void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
4829 int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
4830 void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
4831 void sqlite3ExprCodeMove(Parse*, int, int, int);
4832 void sqlite3ExprCode(Parse*, Expr*, int);
4833 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4834 void sqlite3ExprCodeGeneratedColumn(Parse*, Table*, Column*, int);
4835 #endif
4836 void sqlite3ExprCodeCopy(Parse*, Expr*, int);
4837 void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
4838 int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);
4839 int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
4840 int sqlite3ExprCodeTarget(Parse*, Expr*, int);
4841 int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
4842 #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
4843 #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
4844 #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
4845 #define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
4846 void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
4847 void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
4848 void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
4849 Table *sqlite3FindTable(sqlite3*,const char*, const char*);
4850 #define LOCATE_VIEW 0x01
4851 #define LOCATE_NOERR 0x02
4852 Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
4853 const char *sqlite3PreferredTableName(const char*);
4854 Table *sqlite3LocateTableItem(Parse*,u32 flags,SrcItem *);
4855 Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
4856 void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
4857 void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
4858 void sqlite3Vacuum(Parse*,Token*,Expr*);
4859 int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);
4860 char *sqlite3NameFromToken(sqlite3*, const Token*);
4861 int sqlite3ExprCompare(const Parse*,const Expr*,const Expr*, int);
4862 int sqlite3ExprCompareSkip(Expr*,Expr*,int);
4863 int sqlite3ExprListCompare(const ExprList*,const ExprList*, int);
4864 int sqlite3ExprImpliesExpr(const Parse*,const Expr*,const Expr*, int);
4865 int sqlite3ExprImpliesNonNullRow(Expr*,int);
4866 void sqlite3AggInfoPersistWalkerInit(Walker*,Parse*);
4867 void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
4868 void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
4869 int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
4870 int sqlite3ReferencesSrcList(Parse*, Expr*, SrcList*);
4871 Vdbe *sqlite3GetVdbe(Parse*);
4872 #ifndef SQLITE_UNTESTABLE
4873 void sqlite3PrngSaveState(void);
4874 void sqlite3PrngRestoreState(void);
4875 #endif
4876 void sqlite3RollbackAll(sqlite3*,int);
4877 void sqlite3CodeVerifySchema(Parse*, int);
4878 void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
4879 void sqlite3BeginTransaction(Parse*, int);
4880 void sqlite3EndTransaction(Parse*,int);
4881 void sqlite3Savepoint(Parse*, int, Token*);
4882 void sqlite3CloseSavepoints(sqlite3 *);
4883 void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
4884 u32 sqlite3IsTrueOrFalse(const char*);
4885 int sqlite3ExprIdToTrueFalse(Expr*);
4886 int sqlite3ExprTruthValue(const Expr*);
4887 int sqlite3ExprIsConstant(Expr*);
4888 int sqlite3ExprIsConstantNotJoin(Expr*);
4889 int sqlite3ExprIsConstantOrFunction(Expr*, u8);
4890 int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
4891 int sqlite3ExprIsTableConstant(Expr*,int);
4892 int sqlite3ExprIsTableConstraint(Expr*,const SrcItem*);
4893 #ifdef SQLITE_ENABLE_CURSOR_HINTS
4894 int sqlite3ExprContainsSubquery(Expr*);
4895 #endif
4896 int sqlite3ExprIsInteger(const Expr*, int*);
4897 int sqlite3ExprCanBeNull(const Expr*);
4898 int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
4899 int sqlite3IsRowid(const char*);
4900 void sqlite3GenerateRowDelete(
4901 Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
4902 void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
4903 int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
4904 void sqlite3ResolvePartIdxLabel(Parse*,int);
4905 int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
4906 void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
4907 u8,u8,int,int*,int*,Upsert*);
4908 #ifdef SQLITE_ENABLE_NULL_TRIM
4909 void sqlite3SetMakeRecordP5(Vdbe*,Table*);
4910 #else
4911 # define sqlite3SetMakeRecordP5(A,B)
4912 #endif
4913 void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
4914 int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
4915 void sqlite3BeginWriteOperation(Parse*, int, int);
4916 void sqlite3MultiWrite(Parse*);
4917 void sqlite3MayAbort(Parse*);
4918 void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
4919 void sqlite3UniqueConstraint(Parse*, int, Index*);
4920 void sqlite3RowidConstraint(Parse*, int, Table*);
4921 Expr *sqlite3ExprDup(sqlite3*,const Expr*,int);
4922 ExprList *sqlite3ExprListDup(sqlite3*,const ExprList*,int);
4923 SrcList *sqlite3SrcListDup(sqlite3*,const SrcList*,int);
4924 IdList *sqlite3IdListDup(sqlite3*,const IdList*);
4925 Select *sqlite3SelectDup(sqlite3*,const Select*,int);
4926 FuncDef *sqlite3FunctionSearch(int,const char*);
4927 void sqlite3InsertBuiltinFuncs(FuncDef*,int);
4928 FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
4929 void sqlite3QuoteValue(StrAccum*,sqlite3_value*);
4930 void sqlite3RegisterBuiltinFunctions(void);
4931 void sqlite3RegisterDateTimeFunctions(void);
4932 void sqlite3RegisterJsonFunctions(void);
4933 void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
4934 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
4935 int sqlite3JsonTableFunctions(sqlite3*);
4936 #endif
4937 int sqlite3SafetyCheckOk(sqlite3*);
4938 int sqlite3SafetyCheckSickOrOk(sqlite3*);
4939 void sqlite3ChangeCookie(Parse*, int);
4940 With *sqlite3WithDup(sqlite3 *db, With *p);
4942 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
4943 void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
4944 #endif
4946 #ifndef SQLITE_OMIT_TRIGGER
4947 void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
4948 Expr*,int, int);
4949 void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
4950 void sqlite3DropTrigger(Parse*, SrcList*, int);
4951 void sqlite3DropTriggerPtr(Parse*, Trigger*);
4952 Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
4953 Trigger *sqlite3TriggerList(Parse *, Table *);
4954 void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
4955 int, int, int);
4956 void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
4957 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
4958 void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
4959 TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
4960 const char*,const char*);
4961 TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
4962 Select*,u8,Upsert*,
4963 const char*,const char*);
4964 TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,SrcList*,ExprList*,
4965 Expr*, u8, const char*,const char*);
4966 TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
4967 const char*,const char*);
4968 void sqlite3DeleteTrigger(sqlite3*, Trigger*);
4969 void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
4970 u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
4971 SrcList *sqlite3TriggerStepSrc(Parse*, TriggerStep*);
4972 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
4973 # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
4974 #else
4975 # define sqlite3TriggersExist(B,C,D,E,F) 0
4976 # define sqlite3DeleteTrigger(A,B)
4977 # define sqlite3DropTriggerPtr(A,B)
4978 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
4979 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
4980 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
4981 # define sqlite3TriggerList(X, Y) 0
4982 # define sqlite3ParseToplevel(p) p
4983 # define sqlite3IsToplevel(p) 1
4984 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
4985 # define sqlite3TriggerStepSrc(A,B) 0
4986 #endif
4988 int sqlite3JoinType(Parse*, Token*, Token*, Token*);
4989 int sqlite3ColumnIndex(Table *pTab, const char *zCol);
4990 void sqlite3SrcItemColumnUsed(SrcItem*,int);
4991 void sqlite3SetJoinExpr(Expr*,int,u32);
4992 void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
4993 void sqlite3DeferForeignKey(Parse*, int);
4994 #ifndef SQLITE_OMIT_AUTHORIZATION
4995 void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
4996 int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
4997 void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
4998 void sqlite3AuthContextPop(AuthContext*);
4999 int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
5000 #else
5001 # define sqlite3AuthRead(a,b,c,d)
5002 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
5003 # define sqlite3AuthContextPush(a,b,c)
5004 # define sqlite3AuthContextPop(a) ((void)(a))
5005 #endif
5006 int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName);
5007 void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
5008 void sqlite3Detach(Parse*, Expr*);
5009 void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
5010 int sqlite3FixSrcList(DbFixer*, SrcList*);
5011 int sqlite3FixSelect(DbFixer*, Select*);
5012 int sqlite3FixExpr(DbFixer*, Expr*);
5013 int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
5014 int sqlite3RealSameAsInt(double,sqlite3_int64);
5015 i64 sqlite3RealToI64(double);
5016 int sqlite3Int64ToText(i64,char*);
5017 int sqlite3AtoF(const char *z, double*, int, u8);
5018 int sqlite3GetInt32(const char *, int*);
5019 int sqlite3GetUInt32(const char*, u32*);
5020 int sqlite3Atoi(const char*);
5021 #ifndef SQLITE_OMIT_UTF16
5022 int sqlite3Utf16ByteLen(const void *pData, int nChar);
5023 #endif
5024 int sqlite3Utf8CharLen(const char *pData, int nByte);
5025 u32 sqlite3Utf8Read(const u8**);
5026 LogEst sqlite3LogEst(u64);
5027 LogEst sqlite3LogEstAdd(LogEst,LogEst);
5028 LogEst sqlite3LogEstFromDouble(double);
5029 u64 sqlite3LogEstToInt(LogEst);
5030 VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
5031 const char *sqlite3VListNumToName(VList*,int);
5032 int sqlite3VListNameToNum(VList*,const char*,int);
5035 ** Routines to read and write variable-length integers. These used to
5036 ** be defined locally, but now we use the varint routines in the util.c
5037 ** file.
5039 int sqlite3PutVarint(unsigned char*, u64);
5040 u8 sqlite3GetVarint(const unsigned char *, u64 *);
5041 u8 sqlite3GetVarint32(const unsigned char *, u32 *);
5042 int sqlite3VarintLen(u64 v);
5045 ** The common case is for a varint to be a single byte. They following
5046 ** macros handle the common case without a procedure call, but then call
5047 ** the procedure for larger varints.
5049 #define getVarint32(A,B) \
5050 (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
5051 #define getVarint32NR(A,B) \
5052 B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&(B))
5053 #define putVarint32(A,B) \
5054 (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
5055 sqlite3PutVarint((A),(B)))
5056 #define getVarint sqlite3GetVarint
5057 #define putVarint sqlite3PutVarint
5060 const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
5061 char *sqlite3TableAffinityStr(sqlite3*,const Table*);
5062 void sqlite3TableAffinity(Vdbe*, Table*, int);
5063 char sqlite3CompareAffinity(const Expr *pExpr, char aff2);
5064 int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity);
5065 char sqlite3TableColumnAffinity(const Table*,int);
5066 char sqlite3ExprAffinity(const Expr *pExpr);
5067 int sqlite3ExprDataType(const Expr *pExpr);
5068 int sqlite3Atoi64(const char*, i64*, int, u8);
5069 int sqlite3DecOrHexToI64(const char*, i64*);
5070 void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
5071 void sqlite3Error(sqlite3*,int);
5072 void sqlite3ErrorClear(sqlite3*);
5073 void sqlite3SystemError(sqlite3*,int);
5074 void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
5075 u8 sqlite3HexToInt(int h);
5076 int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
5078 #if defined(SQLITE_NEED_ERR_NAME)
5079 const char *sqlite3ErrName(int);
5080 #endif
5082 #ifndef SQLITE_OMIT_DESERIALIZE
5083 int sqlite3MemdbInit(void);
5084 int sqlite3IsMemdb(const sqlite3_vfs*);
5085 #else
5086 # define sqlite3IsMemdb(X) 0
5087 #endif
5089 const char *sqlite3ErrStr(int);
5090 int sqlite3ReadSchema(Parse *pParse);
5091 CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
5092 int sqlite3IsBinary(const CollSeq*);
5093 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
5094 void sqlite3SetTextEncoding(sqlite3 *db, u8);
5095 CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr);
5096 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr);
5097 int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*);
5098 Expr *sqlite3ExprAddCollateToken(const Parse *pParse, Expr*, const Token*, int);
5099 Expr *sqlite3ExprAddCollateString(const Parse*,Expr*,const char*);
5100 Expr *sqlite3ExprSkipCollate(Expr*);
5101 Expr *sqlite3ExprSkipCollateAndLikely(Expr*);
5102 int sqlite3CheckCollSeq(Parse *, CollSeq *);
5103 int sqlite3WritableSchema(sqlite3*);
5104 int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*);
5105 void sqlite3VdbeSetChanges(sqlite3 *, i64);
5106 int sqlite3AddInt64(i64*,i64);
5107 int sqlite3SubInt64(i64*,i64);
5108 int sqlite3MulInt64(i64*,i64);
5109 int sqlite3AbsInt32(int);
5110 #ifdef SQLITE_ENABLE_8_3_NAMES
5111 void sqlite3FileSuffix3(const char*, char*);
5112 #else
5113 # define sqlite3FileSuffix3(X,Y)
5114 #endif
5115 u8 sqlite3GetBoolean(const char *z,u8);
5117 const void *sqlite3ValueText(sqlite3_value*, u8);
5118 int sqlite3ValueBytes(sqlite3_value*, u8);
5119 void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
5120 void(*)(void*));
5121 void sqlite3ValueSetNull(sqlite3_value*);
5122 void sqlite3ValueFree(sqlite3_value*);
5123 #ifndef SQLITE_UNTESTABLE
5124 void sqlite3ResultIntReal(sqlite3_context*);
5125 #endif
5126 sqlite3_value *sqlite3ValueNew(sqlite3 *);
5127 #ifndef SQLITE_OMIT_UTF16
5128 char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
5129 #endif
5130 int sqlite3ValueFromExpr(sqlite3 *, const Expr *, u8, u8, sqlite3_value **);
5131 void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
5132 #ifndef SQLITE_AMALGAMATION
5133 extern const unsigned char sqlite3OpcodeProperty[];
5134 extern const char sqlite3StrBINARY[];
5135 extern const unsigned char sqlite3StdTypeLen[];
5136 extern const char sqlite3StdTypeAffinity[];
5137 extern const char *sqlite3StdType[];
5138 extern const unsigned char sqlite3UpperToLower[];
5139 extern const unsigned char *sqlite3aLTb;
5140 extern const unsigned char *sqlite3aEQb;
5141 extern const unsigned char *sqlite3aGTb;
5142 extern const unsigned char sqlite3CtypeMap[];
5143 extern SQLITE_WSD struct Sqlite3Config sqlite3Config;
5144 extern FuncDefHash sqlite3BuiltinFunctions;
5145 #ifndef SQLITE_OMIT_WSD
5146 extern int sqlite3PendingByte;
5147 #endif
5148 #endif /* SQLITE_AMALGAMATION */
5149 #ifdef VDBE_PROFILE
5150 extern sqlite3_uint64 sqlite3NProfileCnt;
5151 #endif
5152 void sqlite3RootPageMoved(sqlite3*, int, Pgno, Pgno);
5153 void sqlite3Reindex(Parse*, Token*, Token*);
5154 void sqlite3AlterFunctions(void);
5155 void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
5156 void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
5157 int sqlite3GetToken(const unsigned char *, int *);
5158 void sqlite3NestedParse(Parse*, const char*, ...);
5159 void sqlite3ExpirePreparedStatements(sqlite3*, int);
5160 void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
5161 int sqlite3CodeSubselect(Parse*, Expr*);
5162 void sqlite3SelectPrep(Parse*, Select*, NameContext*);
5163 int sqlite3ExpandSubquery(Parse*, SrcItem*);
5164 void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
5165 int sqlite3MatchEName(
5166 const struct ExprList_item*,
5167 const char*,
5168 const char*,
5169 const char*
5171 Bitmask sqlite3ExprColUsed(Expr*);
5172 u8 sqlite3StrIHash(const char*);
5173 int sqlite3ResolveExprNames(NameContext*, Expr*);
5174 int sqlite3ResolveExprListNames(NameContext*, ExprList*);
5175 void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
5176 int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
5177 int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
5178 void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
5179 void sqlite3AlterFinishAddColumn(Parse *, Token *);
5180 void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
5181 void sqlite3AlterDropColumn(Parse*, SrcList*, const Token*);
5182 const void *sqlite3RenameTokenMap(Parse*, const void*, const Token*);
5183 void sqlite3RenameTokenRemap(Parse*, const void *pTo, const void *pFrom);
5184 void sqlite3RenameExprUnmap(Parse*, Expr*);
5185 void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
5186 CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
5187 char sqlite3AffinityType(const char*, Column*);
5188 void sqlite3Analyze(Parse*, Token*, Token*);
5189 int sqlite3InvokeBusyHandler(BusyHandler*);
5190 int sqlite3FindDb(sqlite3*, Token*);
5191 int sqlite3FindDbName(sqlite3 *, const char *);
5192 int sqlite3AnalysisLoad(sqlite3*,int iDB);
5193 void sqlite3DeleteIndexSamples(sqlite3*,Index*);
5194 void sqlite3DefaultRowEst(Index*);
5195 void sqlite3RegisterLikeFunctions(sqlite3*, int);
5196 int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
5197 void sqlite3SchemaClear(void *);
5198 Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
5199 int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
5200 KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
5201 void sqlite3KeyInfoUnref(KeyInfo*);
5202 KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
5203 KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
5204 KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
5205 const char *sqlite3SelectOpName(int);
5206 int sqlite3HasExplicitNulls(Parse*, ExprList*);
5208 #ifdef SQLITE_DEBUG
5209 int sqlite3KeyInfoIsWriteable(KeyInfo*);
5210 #endif
5211 int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
5212 void (*)(sqlite3_context*,int,sqlite3_value **),
5213 void (*)(sqlite3_context*,int,sqlite3_value **),
5214 void (*)(sqlite3_context*),
5215 void (*)(sqlite3_context*),
5216 void (*)(sqlite3_context*,int,sqlite3_value **),
5217 FuncDestructor *pDestructor
5219 void sqlite3NoopDestructor(void*);
5220 void *sqlite3OomFault(sqlite3*);
5221 void sqlite3OomClear(sqlite3*);
5222 int sqlite3ApiExit(sqlite3 *db, int);
5223 int sqlite3OpenTempDatabase(Parse *);
5225 void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
5226 int sqlite3StrAccumEnlarge(StrAccum*, i64);
5227 char *sqlite3StrAccumFinish(StrAccum*);
5228 void sqlite3StrAccumSetError(StrAccum*, u8);
5229 void sqlite3ResultStrAccum(sqlite3_context*,StrAccum*);
5230 void sqlite3SelectDestInit(SelectDest*,int,int);
5231 Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
5232 void sqlite3RecordErrorByteOffset(sqlite3*,const char*);
5233 void sqlite3RecordErrorOffsetOfExpr(sqlite3*,const Expr*);
5235 void sqlite3BackupRestart(sqlite3_backup *);
5236 void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
5238 #ifndef SQLITE_OMIT_SUBQUERY
5239 int sqlite3ExprCheckIN(Parse*, Expr*);
5240 #else
5241 # define sqlite3ExprCheckIN(x,y) SQLITE_OK
5242 #endif
5244 #ifdef SQLITE_ENABLE_STAT4
5245 int sqlite3Stat4ProbeSetValue(
5246 Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
5247 int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
5248 void sqlite3Stat4ProbeFree(UnpackedRecord*);
5249 int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
5250 char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
5251 #endif
5254 ** The interface to the LEMON-generated parser
5256 #ifndef SQLITE_AMALGAMATION
5257 void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
5258 void sqlite3ParserFree(void*, void(*)(void*));
5259 #endif
5260 void sqlite3Parser(void*, int, Token);
5261 int sqlite3ParserFallback(int);
5262 #ifdef YYTRACKMAXSTACKDEPTH
5263 int sqlite3ParserStackPeak(void*);
5264 #endif
5266 void sqlite3AutoLoadExtensions(sqlite3*);
5267 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5268 void sqlite3CloseExtensions(sqlite3*);
5269 #else
5270 # define sqlite3CloseExtensions(X)
5271 #endif
5273 #ifndef SQLITE_OMIT_SHARED_CACHE
5274 void sqlite3TableLock(Parse *, int, Pgno, u8, const char *);
5275 #else
5276 #define sqlite3TableLock(v,w,x,y,z)
5277 #endif
5279 #ifdef SQLITE_TEST
5280 int sqlite3Utf8To8(unsigned char*);
5281 #endif
5283 #ifdef SQLITE_OMIT_VIRTUALTABLE
5284 # define sqlite3VtabClear(D,T)
5285 # define sqlite3VtabSync(X,Y) SQLITE_OK
5286 # define sqlite3VtabRollback(X)
5287 # define sqlite3VtabCommit(X)
5288 # define sqlite3VtabInSync(db) 0
5289 # define sqlite3VtabLock(X)
5290 # define sqlite3VtabUnlock(X)
5291 # define sqlite3VtabModuleUnref(D,X)
5292 # define sqlite3VtabUnlockList(X)
5293 # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
5294 # define sqlite3GetVTable(X,Y) ((VTable*)0)
5295 #else
5296 void sqlite3VtabClear(sqlite3 *db, Table*);
5297 void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
5298 int sqlite3VtabSync(sqlite3 *db, Vdbe*);
5299 int sqlite3VtabRollback(sqlite3 *db);
5300 int sqlite3VtabCommit(sqlite3 *db);
5301 void sqlite3VtabLock(VTable *);
5302 void sqlite3VtabUnlock(VTable *);
5303 void sqlite3VtabModuleUnref(sqlite3*,Module*);
5304 void sqlite3VtabUnlockList(sqlite3*);
5305 int sqlite3VtabSavepoint(sqlite3 *, int, int);
5306 void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
5307 VTable *sqlite3GetVTable(sqlite3*, Table*);
5308 Module *sqlite3VtabCreateModule(
5309 sqlite3*,
5310 const char*,
5311 const sqlite3_module*,
5312 void*,
5313 void(*)(void*)
5315 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
5316 #endif
5317 int sqlite3ReadOnlyShadowTables(sqlite3 *db);
5318 #ifndef SQLITE_OMIT_VIRTUALTABLE
5319 int sqlite3ShadowTableName(sqlite3 *db, const char *zName);
5320 int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);
5321 void sqlite3MarkAllShadowTablesOf(sqlite3*, Table*);
5322 #else
5323 # define sqlite3ShadowTableName(A,B) 0
5324 # define sqlite3IsShadowTableOf(A,B,C) 0
5325 # define sqlite3MarkAllShadowTablesOf(A,B)
5326 #endif
5327 int sqlite3VtabEponymousTableInit(Parse*,Module*);
5328 void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
5329 void sqlite3VtabMakeWritable(Parse*,Table*);
5330 void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
5331 void sqlite3VtabFinishParse(Parse*, Token*);
5332 void sqlite3VtabArgInit(Parse*);
5333 void sqlite3VtabArgExtend(Parse*, Token*);
5334 int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
5335 int sqlite3VtabCallConnect(Parse*, Table*);
5336 int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
5337 int sqlite3VtabBegin(sqlite3 *, VTable *);
5339 FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
5340 #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
5341 && !defined(SQLITE_OMIT_VIRTUALTABLE)
5342 void sqlite3VtabUsesAllSchemas(sqlite3_index_info*);
5343 #endif
5344 sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
5345 int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
5346 int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
5347 void sqlite3ParseObjectInit(Parse*,sqlite3*);
5348 void sqlite3ParseObjectReset(Parse*);
5349 void *sqlite3ParserAddCleanup(Parse*,void(*)(sqlite3*,void*),void*);
5350 #ifdef SQLITE_ENABLE_NORMALIZE
5351 char *sqlite3Normalize(Vdbe*, const char*);
5352 #endif
5353 int sqlite3Reprepare(Vdbe*);
5354 void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
5355 CollSeq *sqlite3ExprCompareCollSeq(Parse*,const Expr*);
5356 CollSeq *sqlite3BinaryCompareCollSeq(Parse *, const Expr*, const Expr*);
5357 int sqlite3TempInMemory(const sqlite3*);
5358 const char *sqlite3JournalModename(int);
5359 #ifndef SQLITE_OMIT_WAL
5360 int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
5361 int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
5362 #endif
5363 #ifndef SQLITE_OMIT_CTE
5364 Cte *sqlite3CteNew(Parse*,Token*,ExprList*,Select*,u8);
5365 void sqlite3CteDelete(sqlite3*,Cte*);
5366 With *sqlite3WithAdd(Parse*,With*,Cte*);
5367 void sqlite3WithDelete(sqlite3*,With*);
5368 With *sqlite3WithPush(Parse*, With*, u8);
5369 #else
5370 # define sqlite3CteNew(P,T,E,S) ((void*)0)
5371 # define sqlite3CteDelete(D,C)
5372 # define sqlite3CteWithAdd(P,W,C) ((void*)0)
5373 # define sqlite3WithDelete(x,y)
5374 # define sqlite3WithPush(x,y,z) ((void*)0)
5375 #endif
5376 #ifndef SQLITE_OMIT_UPSERT
5377 Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*,Upsert*);
5378 void sqlite3UpsertDelete(sqlite3*,Upsert*);
5379 Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
5380 int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);
5381 void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
5382 Upsert *sqlite3UpsertOfIndex(Upsert*,Index*);
5383 int sqlite3UpsertNextIsIPK(Upsert*);
5384 #else
5385 #define sqlite3UpsertNew(u,v,w,x,y,z) ((Upsert*)0)
5386 #define sqlite3UpsertDelete(x,y)
5387 #define sqlite3UpsertDup(x,y) ((Upsert*)0)
5388 #define sqlite3UpsertOfIndex(x,y) ((Upsert*)0)
5389 #define sqlite3UpsertNextIsIPK(x) 0
5390 #endif
5393 /* Declarations for functions in fkey.c. All of these are replaced by
5394 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
5395 ** key functionality is available. If OMIT_TRIGGER is defined but
5396 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
5397 ** this case foreign keys are parsed, but no other functionality is
5398 ** provided (enforcement of FK constraints requires the triggers sub-system).
5400 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
5401 void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
5402 void sqlite3FkDropTable(Parse*, SrcList *, Table*);
5403 void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
5404 int sqlite3FkRequired(Parse*, Table*, int*, int);
5405 u32 sqlite3FkOldmask(Parse*, Table*);
5406 FKey *sqlite3FkReferences(Table *);
5407 void sqlite3FkClearTriggerCache(sqlite3*,int);
5408 #else
5409 #define sqlite3FkActions(a,b,c,d,e,f)
5410 #define sqlite3FkCheck(a,b,c,d,e,f)
5411 #define sqlite3FkDropTable(a,b,c)
5412 #define sqlite3FkOldmask(a,b) 0
5413 #define sqlite3FkRequired(a,b,c,d) 0
5414 #define sqlite3FkReferences(a) 0
5415 #define sqlite3FkClearTriggerCache(a,b)
5416 #endif
5417 #ifndef SQLITE_OMIT_FOREIGN_KEY
5418 void sqlite3FkDelete(sqlite3 *, Table*);
5419 int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
5420 #else
5421 #define sqlite3FkDelete(a,b)
5422 #define sqlite3FkLocateIndex(a,b,c,d,e)
5423 #endif
5427 ** Available fault injectors. Should be numbered beginning with 0.
5429 #define SQLITE_FAULTINJECTOR_MALLOC 0
5430 #define SQLITE_FAULTINJECTOR_COUNT 1
5433 ** The interface to the code in fault.c used for identifying "benign"
5434 ** malloc failures. This is only present if SQLITE_UNTESTABLE
5435 ** is not defined.
5437 #ifndef SQLITE_UNTESTABLE
5438 void sqlite3BeginBenignMalloc(void);
5439 void sqlite3EndBenignMalloc(void);
5440 #else
5441 #define sqlite3BeginBenignMalloc()
5442 #define sqlite3EndBenignMalloc()
5443 #endif
5446 ** Allowed return values from sqlite3FindInIndex()
5448 #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
5449 #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
5450 #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
5451 #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
5452 #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
5454 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
5456 #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
5457 #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
5458 #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
5459 int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);
5461 int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
5462 int sqlite3JournalSize(sqlite3_vfs *);
5463 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
5464 || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
5465 int sqlite3JournalCreate(sqlite3_file *);
5466 #endif
5468 int sqlite3JournalIsInMemory(sqlite3_file *p);
5469 void sqlite3MemJournalOpen(sqlite3_file *);
5471 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
5472 #if SQLITE_MAX_EXPR_DEPTH>0
5473 int sqlite3SelectExprHeight(const Select *);
5474 int sqlite3ExprCheckHeight(Parse*, int);
5475 #else
5476 #define sqlite3SelectExprHeight(x) 0
5477 #define sqlite3ExprCheckHeight(x,y)
5478 #endif
5480 u32 sqlite3Get4byte(const u8*);
5481 void sqlite3Put4byte(u8*, u32);
5483 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
5484 void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
5485 void sqlite3ConnectionUnlocked(sqlite3 *db);
5486 void sqlite3ConnectionClosed(sqlite3 *db);
5487 #else
5488 #define sqlite3ConnectionBlocked(x,y)
5489 #define sqlite3ConnectionUnlocked(x)
5490 #define sqlite3ConnectionClosed(x)
5491 #endif
5493 #ifdef SQLITE_DEBUG
5494 void sqlite3ParserTrace(FILE*, char *);
5495 #endif
5496 #if defined(YYCOVERAGE)
5497 int sqlite3ParserCoverage(FILE*);
5498 #endif
5501 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
5502 ** sqlite3IoTrace is a pointer to a printf-like routine used to
5503 ** print I/O tracing messages.
5505 #ifdef SQLITE_ENABLE_IOTRACE
5506 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
5507 void sqlite3VdbeIOTraceSql(Vdbe*);
5508 SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
5509 #else
5510 # define IOTRACE(A)
5511 # define sqlite3VdbeIOTraceSql(X)
5512 #endif
5515 ** These routines are available for the mem2.c debugging memory allocator
5516 ** only. They are used to verify that different "types" of memory
5517 ** allocations are properly tracked by the system.
5519 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
5520 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
5521 ** a single bit set.
5523 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
5524 ** argument match the type set by the previous sqlite3MemdebugSetType().
5525 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
5527 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
5528 ** argument match the type set by the previous sqlite3MemdebugSetType().
5530 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
5531 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
5532 ** it might have been allocated by lookaside, except the allocation was
5533 ** too large or lookaside was already full. It is important to verify
5534 ** that allocations that might have been satisfied by lookaside are not
5535 ** passed back to non-lookaside free() routines. Asserts such as the
5536 ** example above are placed on the non-lookaside free() routines to verify
5537 ** this constraint.
5539 ** All of this is no-op for a production build. It only comes into
5540 ** play when the SQLITE_MEMDEBUG compile-time option is used.
5542 #ifdef SQLITE_MEMDEBUG
5543 void sqlite3MemdebugSetType(void*,u8);
5544 int sqlite3MemdebugHasType(const void*,u8);
5545 int sqlite3MemdebugNoType(const void*,u8);
5546 #else
5547 # define sqlite3MemdebugSetType(X,Y) /* no-op */
5548 # define sqlite3MemdebugHasType(X,Y) 1
5549 # define sqlite3MemdebugNoType(X,Y) 1
5550 #endif
5551 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
5552 #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
5553 #define MEMTYPE_PCACHE 0x04 /* Page cache allocations */
5556 ** Threading interface
5558 #if SQLITE_MAX_WORKER_THREADS>0
5559 int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
5560 int sqlite3ThreadJoin(SQLiteThread*, void**);
5561 #endif
5563 #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
5564 int sqlite3DbpageRegister(sqlite3*);
5565 #endif
5566 #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
5567 int sqlite3DbstatRegister(sqlite3*);
5568 #endif
5570 int sqlite3ExprVectorSize(const Expr *pExpr);
5571 int sqlite3ExprIsVector(const Expr *pExpr);
5572 Expr *sqlite3VectorFieldSubexpr(Expr*, int);
5573 Expr *sqlite3ExprForVectorField(Parse*,Expr*,int,int);
5574 void sqlite3VectorErrorMsg(Parse*, Expr*);
5576 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
5577 const char **sqlite3CompileOptions(int *pnOpt);
5578 #endif
5580 #if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
5581 int sqlite3KvvfsInit(void);
5582 #endif
5584 #if defined(VDBE_PROFILE) \
5585 || defined(SQLITE_PERFORMANCE_TRACE) \
5586 || defined(SQLITE_ENABLE_STMT_SCANSTATUS)
5587 sqlite3_uint64 sqlite3Hwtime(void);
5588 #endif
5590 #endif /* SQLITEINT_H */