interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / sqliteInt.h

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