Bug Summary

File:3rdparty/sqlite3/sqlite3.c
Warning:line 205881, column 3
Null pointer passed to 1st parameter expecting 'nonnull'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-unknown-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name sqlite3.c -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 2 -pic-is-pie -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/home/liu/actions-runner/_work/ccv/ccv/lib -fcoverage-compilation-dir=/home/liu/actions-runner/_work/ccv/ccv/lib -resource-dir /usr/local/lib/clang/19 -D HAVE_USLEEP -D SQLITE_DQS=0 -D SQLITE_DEFAULT_CACHE_SIZE=128 -D SQLITE_DEFAULT_CKPTFULLFSYNC -D SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT=32768 -D SQLITE_DEFAULT_PAGE_SIZE=4096 -D SQLITE_DEFAULT_SYNCHRONOUS=2 -D SQLITE_DEFAULT_WAL_SYNCHRONOUS=1 -D SQLITE_ENABLE_API_ARMOR -D SQLITE_ENABLE_COLUMN_METADATA -D SQLITE_ENABLE_DBSTAT_VTAB -D SQLITE_ENABLE_FTS3 -D SQLITE_ENABLE_FTS3_PARENTHESIS -D SQLITE_ENABLE_FTS3_TOKENIZER -D SQLITE_ENABLE_FTS4 -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_JSON1 -D SQLITE_ENABLE_MATH_FUNCTIONS -D SQLITE_ENABLE_PREUPDATE_HOOK -D SQLITE_ENABLE_RTREE -D SQLITE_ENABLE_SESSION -D SQLITE_ENABLE_SNAPSHOT -D SQLITE_ENABLE_STMT_SCANSTATUS -D SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION -D SQLITE_ENABLE_UPDATE_DELETE_LIMIT -D SQLITE_HAS_CODEC_RESTRICTED -D SQLITE_HAVE_ISNAN -D SQLITE_MAX_LENGTH=2147483645 -D SQLITE_MAX_MMAP_SIZE=20971520 -D SQLITE_MAX_VARIABLE_NUMBER=500000 -D SQLITE_OMIT_AUTORESET -D SQLITE_OMIT_DEPRECATED -D SQLITE_OMIT_PROGRESS_CALLBACK -D SQLITE_OMIT_LOAD_EXTENSION -D SQLITE_STMTJRNL_SPILL=131072 -D SQLITE_SUBSTR_COMPATIBILITY -D SQLITE_THREADSAFE=2 -D SQLITE_USE_URI -internal-isystem /usr/local/lib/clang/19/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O3 -ferror-limit 19 -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -vectorize-loops -vectorize-slp -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/liu/actions-runner/_work/ccv/ccv/_analyze/2025-09-28-145715-25778-1 -x c 3rdparty/sqlite3/sqlite3.c
1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.50.3. By combining all the individual C code files into this
4** single large file, the entire code can be compiled as a single translation
5** unit. This allows many compilers to do optimizations that would not be
6** possible if the files were compiled separately. Performance improvements
7** of 5% or more are commonly seen when SQLite is compiled as a single
8** translation unit.
9**
10** This file is all you need to compile SQLite. To use SQLite in other
11** programs, you need this file and the "sqlite3.h" header file that defines
12** the programming interface to the SQLite library. (If you do not have
13** the "sqlite3.h" header file at hand, you will find a copy embedded within
14** the text of this file. Search for "Begin file sqlite3.h" to find the start
15** of the embedded sqlite3.h header file.) Additional code files may be needed
16** if you want a wrapper to interface SQLite with your choice of programming
17** language. The code for the "sqlite3" command-line shell is also in a
18** separate file. This file contains only code for the core SQLite library.
19**
20** The content in this amalgamation comes from Fossil check-in
21** 3ce993b8657d6d9deda380a93cdd6404a8c8 with changes in files:
22**
23**
24*/
25#ifndef SQLITE_AMALGAMATION1
26#define SQLITE_CORE1 1
27#define SQLITE_AMALGAMATION1 1
28#ifndef SQLITE_PRIVATEstatic
29# define SQLITE_PRIVATEstatic static
30#endif
31/************** Begin file sqliteInt.h ***************************************/
32/*
33** 2001 September 15
34**
35** The author disclaims copyright to this source code. In place of
36** a legal notice, here is a blessing:
37**
38** May you do good and not evil.
39** May you find forgiveness for yourself and forgive others.
40** May you share freely, never taking more than you give.
41**
42*************************************************************************
43** Internal interface definitions for SQLite.
44**
45*/
46#ifndef SQLITEINT_H
47#define SQLITEINT_H
48
49/* Special Comments:
50**
51** Some comments have special meaning to the tools that measure test
52** coverage:
53**
54** NO_TEST - The branches on this line are not
55** measured by branch coverage. This is
56** used on lines of code that actually
57** implement parts of coverage testing.
58**
59** OPTIMIZATION-IF-TRUE - This branch is allowed to always be false
60** and the correct answer is still obtained,
61** though perhaps more slowly.
62**
63** OPTIMIZATION-IF-FALSE - This branch is allowed to always be true
64** and the correct answer is still obtained,
65** though perhaps more slowly.
66**
67** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
68** that would be harmless and undetectable
69** if it did occur.
70**
71** In all cases, the special comment must be enclosed in the usual
72** slash-asterisk...asterisk-slash comment marks, with no spaces between the
73** asterisks and the comment text.
74*/
75
76/*
77** Make sure the Tcl calling convention macro is defined. This macro is
78** only used by test code and Tcl integration code.
79*/
80#ifndef SQLITE_TCLAPI
81# define SQLITE_TCLAPI
82#endif
83
84/*
85** Include the header file used to customize the compiler options for MSVC.
86** This should be done first so that it can successfully prevent spurious
87** compiler warnings due to subsequent content in this file and other files
88** that are included by this file.
89*/
90/************** Include msvc.h in the middle of sqliteInt.h ******************/
91/************** Begin file msvc.h ********************************************/
92/*
93** 2015 January 12
94**
95** The author disclaims copyright to this source code. In place of
96** a legal notice, here is a blessing:
97**
98** May you do good and not evil.
99** May you find forgiveness for yourself and forgive others.
100** May you share freely, never taking more than you give.
101**
102******************************************************************************
103**
104** This file contains code that is specific to MSVC.
105*/
106#ifndef SQLITE_MSVC_H
107#define SQLITE_MSVC_H
108
109#if defined(_MSC_VER)
110#pragma warning(disable : 4054)
111#pragma warning(disable : 4055)
112#pragma warning(disable : 4100)
113#pragma warning(disable : 4127)
114#pragma warning(disable : 4130)
115#pragma warning(disable : 4152)
116#pragma warning(disable : 4189)
117#pragma warning(disable : 4206)
118#pragma warning(disable : 4210)
119#pragma warning(disable : 4232)
120#pragma warning(disable : 4244)
121#pragma warning(disable : 4305)
122#pragma warning(disable : 4306)
123#pragma warning(disable : 4702)
124#pragma warning(disable : 4706)
125#endif /* defined(_MSC_VER) */
126
127#if defined(_MSC_VER) && !defined(_WIN64)
128#undef SQLITE_4_BYTE_ALIGNED_MALLOC
129#define SQLITE_4_BYTE_ALIGNED_MALLOC
130#endif /* defined(_MSC_VER) && !defined(_WIN64) */
131
132#if !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800
133#define HAVE_LOG2 0
134#endif /* !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800 */
135
136#endif /* SQLITE_MSVC_H */
137
138/************** End of msvc.h ************************************************/
139/************** Continuing where we left off in sqliteInt.h ******************/
140
141/*
142** Special setup for VxWorks
143*/
144/************** Include vxworks.h in the middle of sqliteInt.h ***************/
145/************** Begin file vxworks.h *****************************************/
146/*
147** 2015-03-02
148**
149** The author disclaims copyright to this source code. In place of
150** a legal notice, here is a blessing:
151**
152** May you do good and not evil.
153** May you find forgiveness for yourself and forgive others.
154** May you share freely, never taking more than you give.
155**
156******************************************************************************
157**
158** This file contains code that is specific to Wind River's VxWorks
159*/
160#if defined(__RTP__) || defined(_WRS_KERNEL)
161/* This is VxWorks. Set up things specially for that OS
162*/
163#include <vxWorks.h>
164#include <pthread.h> /* amalgamator: dontcache */
165#define OS_VXWORKS0 1
166#define SQLITE_OS_OTHER0 0
167#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
168#define SQLITE_OMIT_LOAD_EXTENSION1 1
169#define SQLITE_ENABLE_LOCKING_STYLE0 0
170#define HAVE_UTIME 1
171#else
172/* This is not VxWorks. */
173#define OS_VXWORKS0 0
174#define HAVE_FCHOWN1 1
175#define HAVE_READLINK1 1
176#define HAVE_LSTAT1 1
177#endif /* defined(_WRS_KERNEL) */
178
179/************** End of vxworks.h *********************************************/
180/************** Continuing where we left off in sqliteInt.h ******************/
181
182/*
183** These #defines should enable >2GB file support on POSIX if the
184** underlying operating system supports it. If the OS lacks
185** large file support, or if the OS is windows, these should be no-ops.
186**
187** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
188** system #includes. Hence, this block of code must be the very first
189** code in all source files.
190**
191** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
192** on the compiler command line. This is necessary if you are compiling
193** on a recent machine (ex: Red Hat 7.2) but you want your code to work
194** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
195** without this option, LFS is enable. But LFS does not exist in the kernel
196** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
197** portability you should omit LFS.
198**
199** The previous paragraph was written in 2005. (This paragraph is written
200** on 2008-11-28.) These days, all Linux kernels support large files, so
201** you should probably leave LFS enabled. But some embedded platforms might
202** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
203**
204** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
205*/
206#ifndef SQLITE_DISABLE_LFS
207# define _LARGE_FILE1 1
208# ifndef _FILE_OFFSET_BITS64
209# define _FILE_OFFSET_BITS64 64
210# endif
211# define _LARGEFILE_SOURCE1 1
212#endif
213
214/* The GCC_VERSION and MSVC_VERSION macros are used to
215** conditionally include optimizations for each of these compilers. A
216** value of 0 means that compiler is not being used. The
217** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
218** optimizations, and hence set all compiler macros to 0
219**
220** There was once also a CLANG_VERSION macro. However, we learn that the
221** version numbers in clang are for "marketing" only and are inconsistent
222** and unreliable. Fortunately, all versions of clang also recognize the
223** gcc version numbers and have reasonable settings for gcc version numbers,
224** so the GCC_VERSION macro will be set to a correct non-zero value even
225** when compiling with clang.
226*/
227#if defined(__GNUC__4) && !defined(SQLITE_DISABLE_INTRINSIC)
228# define GCC_VERSION(4*1000000+2*1000+1) (__GNUC__4*1000000+__GNUC_MINOR__2*1000+__GNUC_PATCHLEVEL__1)
229#else
230# define GCC_VERSION(4*1000000+2*1000+1) 0
231#endif
232#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
233# define MSVC_VERSION0 _MSC_VER
234#else
235# define MSVC_VERSION0 0
236#endif
237
238/*
239** Some C99 functions in "math.h" are only present for MSVC when its version
240** is associated with Visual Studio 2013 or higher.
241*/
242#ifndef SQLITE_HAVE_C99_MATH_FUNCS(1)
243# if MSVC_VERSION0==0 || MSVC_VERSION0>=1800
244# define SQLITE_HAVE_C99_MATH_FUNCS(1) (1)
245# else
246# define SQLITE_HAVE_C99_MATH_FUNCS(1) (0)
247# endif
248#endif
249
250/* Needed for various definitions... */
251#if defined(__GNUC__4) && !defined(_GNU_SOURCE)
252# define _GNU_SOURCE
253#endif
254
255#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
256# define _BSD_SOURCE
257#endif
258
259/*
260** Macro to disable warnings about missing "break" at the end of a "case".
261*/
262#if defined(__has_attribute)0
263# if __has_attribute(fallthrough)1
264# define deliberate_fall_through__attribute__((fallthrough)); __attribute__((fallthrough));
265# endif
266#endif
267#if !defined(deliberate_fall_through__attribute__((fallthrough));)
268# define deliberate_fall_through__attribute__((fallthrough));
269#endif
270
271/*
272** For MinGW, check to see if we can include the header file containing its
273** version information, among other things. Normally, this internal MinGW
274** header file would [only] be included automatically by other MinGW header
275** files; however, the contained version information is now required by this
276** header file to work around binary compatibility issues (see below) and
277** this is the only known way to reliably obtain it. This entire #if block
278** would be completely unnecessary if there was any other way of detecting
279** MinGW via their preprocessor (e.g. if they customized their GCC to define
280** some MinGW-specific macros). When compiling for MinGW, either the
281** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
282** defined; otherwise, detection of conditions specific to MinGW will be
283** disabled.
284*/
285#if defined(_HAVE_MINGW_H)
286# include "mingw.h"
287#elif defined(_HAVE__MINGW_H)
288# include "_mingw.h"
289#endif
290
291/*
292** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
293** define is required to maintain binary compatibility with the MSVC runtime
294** library in use (e.g. for Windows XP).
295*/
296#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
297 defined(_WIN32) && !defined(_WIN64) && \
298 defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
299 defined(__MSVCRT__)
300# define _USE_32BIT_TIME_T
301#endif
302
303/* Optionally #include a user-defined header, whereby compilation options
304** may be set prior to where they take effect, but after platform setup.
305** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
306** file.
307*/
308#ifdef SQLITE_CUSTOM_INCLUDE
309# define INC_STRINGIFY_(f) #f
310# define INC_STRINGIFY(f) INC_STRINGIFY_(f)
311# include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
312#endif
313
314/* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
315** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
316** MinGW.
317*/
318/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
319/************** Begin file sqlite3.h *****************************************/
320/*
321** 2001-09-15
322**
323** The author disclaims copyright to this source code. In place of
324** a legal notice, here is a blessing:
325**
326** May you do good and not evil.
327** May you find forgiveness for yourself and forgive others.
328** May you share freely, never taking more than you give.
329**
330*************************************************************************
331** This header file defines the interface that the SQLite library
332** presents to client programs. If a C-function, structure, datatype,
333** or constant definition does not appear in this file, then it is
334** not a published API of SQLite, is subject to change without
335** notice, and should not be referenced by programs that use SQLite.
336**
337** Some of the definitions that are in this file are marked as
338** "experimental". Experimental interfaces are normally new
339** features recently added to SQLite. We do not anticipate changes
340** to experimental interfaces but reserve the right to make minor changes
341** if experience from use "in the wild" suggest such changes are prudent.
342**
343** The official C-language API documentation for SQLite is derived
344** from comments in this file. This file is the authoritative source
345** on how SQLite interfaces are supposed to operate.
346**
347** The name of this file under configuration management is "sqlite.h.in".
348** The makefile makes some minor changes to this file (such as inserting
349** the version number) and changes its name to "sqlite3.h" as
350** part of the build process.
351*/
352#ifndef SQLITE3_H
353#define SQLITE3_H
354#include <stdarg.h> /* Needed for the definition of va_list */
355
356/*
357** Make sure we can call this stuff from C++.
358*/
359#if 0
360extern "C" {
361#endif
362
363
364/*
365** Facilitate override of interface linkage and calling conventions.
366** Be aware that these macros may not be used within this particular
367** translation of the amalgamation and its associated header file.
368**
369** The SQLITE_EXTERN and SQLITE_API macros are used to instruct the
370** compiler that the target identifier should have external linkage.
371**
372** The SQLITE_CDECL macro is used to set the calling convention for
373** public functions that accept a variable number of arguments.
374**
375** The SQLITE_APICALL macro is used to set the calling convention for
376** public functions that accept a fixed number of arguments.
377**
378** The SQLITE_STDCALL macro is no longer used and is now deprecated.
379**
380** The SQLITE_CALLBACK macro is used to set the calling convention for
381** function pointers.
382**
383** The SQLITE_SYSAPI macro is used to set the calling convention for
384** functions provided by the operating system.
385**
386** Currently, the SQLITE_CDECL, SQLITE_APICALL, SQLITE_CALLBACK, and
387** SQLITE_SYSAPI macros are used only when building for environments
388** that require non-default calling conventions.
389*/
390#ifndef SQLITE_EXTERNextern
391# define SQLITE_EXTERNextern extern
392#endif
393#ifndef SQLITE_API
394# define SQLITE_API
395#endif
396#ifndef SQLITE_CDECL
397# define SQLITE_CDECL
398#endif
399#ifndef SQLITE_APICALL
400# define SQLITE_APICALL
401#endif
402#ifndef SQLITE_STDCALL
403# define SQLITE_STDCALL SQLITE_APICALL
404#endif
405#ifndef SQLITE_CALLBACK
406# define SQLITE_CALLBACK
407#endif
408#ifndef SQLITE_SYSAPI
409# define SQLITE_SYSAPI
410#endif
411
412/*
413** These no-op macros are used in front of interfaces to mark those
414** interfaces as either deprecated or experimental. New applications
415** should not use deprecated interfaces - they are supported for backwards
416** compatibility only. Application writers should be aware that
417** experimental interfaces are subject to change in point releases.
418**
419** These macros used to resolve to various kinds of compiler magic that
420** would generate warning messages when they were used. But that
421** compiler magic ended up generating such a flurry of bug reports
422** that we have taken it all out and gone back to using simple
423** noop macros.
424*/
425#define SQLITE_DEPRECATED
426#define SQLITE_EXPERIMENTAL
427
428/*
429** Ensure these symbols were not defined by some previous header file.
430*/
431#ifdef SQLITE_VERSION"3.50.3"
432# undef SQLITE_VERSION"3.50.3"
433#endif
434#ifdef SQLITE_VERSION_NUMBER3050003
435# undef SQLITE_VERSION_NUMBER3050003
436#endif
437
438/*
439** CAPI3REF: Compile-Time Library Version Numbers
440**
441** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
442** evaluates to a string literal that is the SQLite version in the
443** format "X.Y.Z" where X is the major version number (always 3 for
444** SQLite3) and Y is the minor version number and Z is the release number.)^
445** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
446** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
447** numbers used in [SQLITE_VERSION].)^
448** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
449** be larger than the release from which it is derived. Either Y will
450** be held constant and Z will be incremented or else Y will be incremented
451** and Z will be reset to zero.
452**
453** Since [version 3.6.18] ([dateof:3.6.18]),
454** SQLite source code has been stored in the
455** <a href="http://fossil-scm.org/">Fossil configuration management
456** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
457** a string which identifies a particular check-in of SQLite
458** within its configuration management system. ^The SQLITE_SOURCE_ID
459** string contains the date and time of the check-in (UTC) and a SHA1
460** or SHA3-256 hash of the entire source tree. If the source code has
461** been edited in any way since it was last checked in, then the last
462** four hexadecimal digits of the hash may be modified.
463**
464** See also: [sqlite3_libversion()],
465** [sqlite3_libversion_number()], [sqlite3_sourceid()],
466** [sqlite_version()] and [sqlite_source_id()].
467*/
468#define SQLITE_VERSION"3.50.3" "3.50.3"
469#define SQLITE_VERSION_NUMBER3050003 3050003
470#define SQLITE_SOURCE_ID"2025-07-17 13:25:10 3ce993b8657d6d9deda380a93cdd6404a8c8ba1b185b2bc423703e41ae5f2543" "2025-07-17 13:25:10 3ce993b8657d6d9deda380a93cdd6404a8c8ba1b185b2bc423703e41ae5f2543"
471
472/*
473** CAPI3REF: Run-Time Library Version Numbers
474** KEYWORDS: sqlite3_version sqlite3_sourceid
475**
476** These interfaces provide the same information as the [SQLITE_VERSION],
477** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
478** but are associated with the library instead of the header file. ^(Cautious
479** programmers might include assert() statements in their application to
480** verify that values returned by these interfaces match the macros in
481** the header, and thus ensure that the application is
482** compiled with matching library and header files.
483**
484** <blockquote><pre>
485** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
486** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
487** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
488** </pre></blockquote>)^
489**
490** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
491** macro. ^The sqlite3_libversion() function returns a pointer to the
492** to the sqlite3_version[] string constant. The sqlite3_libversion()
493** function is provided for use in DLLs since DLL users usually do not have
494** direct access to string constants within the DLL. ^The
495** sqlite3_libversion_number() function returns an integer equal to
496** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
497** a pointer to a string constant whose value is the same as the
498** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
499** using an edited copy of [the amalgamation], then the last four characters
500** of the hash might be different from [SQLITE_SOURCE_ID].)^
501**
502** See also: [sqlite_version()] and [sqlite_source_id()].
503*/
504SQLITE_API const char sqlite3_version[] = SQLITE_VERSION"3.50.3";
505SQLITE_API const char *sqlite3_libversion(void);
506SQLITE_API const char *sqlite3_sourceid(void);
507SQLITE_API int sqlite3_libversion_number(void);
508
509/*
510** CAPI3REF: Run-Time Library Compilation Options Diagnostics
511**
512** ^The sqlite3_compileoption_used() function returns 0 or 1
513** indicating whether the specified option was defined at
514** compile time. ^The SQLITE_ prefix may be omitted from the
515** option name passed to sqlite3_compileoption_used().
516**
517** ^The sqlite3_compileoption_get() function allows iterating
518** over the list of options that were defined at compile time by
519** returning the N-th compile time option string. ^If N is out of range,
520** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
521** prefix is omitted from any strings returned by
522** sqlite3_compileoption_get().
523**
524** ^Support for the diagnostic functions sqlite3_compileoption_used()
525** and sqlite3_compileoption_get() may be omitted by specifying the
526** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
527**
528** See also: SQL functions [sqlite_compileoption_used()] and
529** [sqlite_compileoption_get()] and the [compile_options pragma].
530*/
531#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
532SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
533SQLITE_API const char *sqlite3_compileoption_get(int N);
534#else
535# define sqlite3_compileoption_used(X) 0
536# define sqlite3_compileoption_get(X) ((void*)0)
537#endif
538
539/*
540** CAPI3REF: Test To See If The Library Is Threadsafe
541**
542** ^The sqlite3_threadsafe() function returns zero if and only if
543** SQLite was compiled with mutexing code omitted due to the
544** [SQLITE_THREADSAFE] compile-time option being set to 0.
545**
546** SQLite can be compiled with or without mutexes. When
547** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
548** are enabled and SQLite is threadsafe. When the
549** [SQLITE_THREADSAFE] macro is 0,
550** the mutexes are omitted. Without the mutexes, it is not safe
551** to use SQLite concurrently from more than one thread.
552**
553** Enabling mutexes incurs a measurable performance penalty.
554** So if speed is of utmost importance, it makes sense to disable
555** the mutexes. But for maximum safety, mutexes should be enabled.
556** ^The default behavior is for mutexes to be enabled.
557**
558** This interface can be used by an application to make sure that the
559** version of SQLite that it is linking against was compiled with
560** the desired setting of the [SQLITE_THREADSAFE] macro.
561**
562** This interface only reports on the compile-time mutex setting
563** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
564** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
565** can be fully or partially disabled using a call to [sqlite3_config()]
566** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
567** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
568** sqlite3_threadsafe() function shows only the compile-time setting of
569** thread safety, not any run-time changes to that setting made by
570** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
571** is unchanged by calls to sqlite3_config().)^
572**
573** See the [threading mode] documentation for additional information.
574*/
575SQLITE_API int sqlite3_threadsafe(void);
576
577/*
578** CAPI3REF: Database Connection Handle
579** KEYWORDS: {database connection} {database connections}
580**
581** Each open SQLite database is represented by a pointer to an instance of
582** the opaque structure named "sqlite3". It is useful to think of an sqlite3
583** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
584** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
585** and [sqlite3_close_v2()] are its destructors. There are many other
586** interfaces (such as
587** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
588** [sqlite3_busy_timeout()] to name but three) that are methods on an
589** sqlite3 object.
590*/
591typedef struct sqlite3 sqlite3;
592
593/*
594** CAPI3REF: 64-Bit Integer Types
595** KEYWORDS: sqlite_int64 sqlite_uint64
596**
597** Because there is no cross-platform way to specify 64-bit integer types
598** SQLite includes typedefs for 64-bit signed and unsigned integers.
599**
600** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
601** The sqlite_int64 and sqlite_uint64 types are supported for backwards
602** compatibility only.
603**
604** ^The sqlite3_int64 and sqlite_int64 types can store integer values
605** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
606** sqlite3_uint64 and sqlite_uint64 types can store integer values
607** between 0 and +18446744073709551615 inclusive.
608*/
609#ifdef SQLITE_INT64_TYPE
610 typedef SQLITE_INT64_TYPE sqlite_int64;
611# ifdef SQLITE_UINT64_TYPE
612 typedef SQLITE_UINT64_TYPE sqlite_uint64;
613# else
614 typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
615# endif
616#elif defined(_MSC_VER) || defined(__BORLANDC__)
617 typedef __int64 sqlite_int64;
618 typedef unsigned __int64 sqlite_uint64;
619#else
620 typedef long long int sqlite_int64;
621 typedef unsigned long long int sqlite_uint64;
622#endif
623typedef sqlite_int64 sqlite3_int64;
624typedef sqlite_uint64 sqlite3_uint64;
625
626/*
627** If compiling for a processor that lacks floating point support,
628** substitute integer for floating-point.
629*/
630#ifdef SQLITE_OMIT_FLOATING_POINT
631# define double sqlite3_int64
632#endif
633
634/*
635** CAPI3REF: Closing A Database Connection
636** DESTRUCTOR: sqlite3
637**
638** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
639** for the [sqlite3] object.
640** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
641** the [sqlite3] object is successfully destroyed and all associated
642** resources are deallocated.
643**
644** Ideally, applications should [sqlite3_finalize | finalize] all
645** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and
646** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
647** with the [sqlite3] object prior to attempting to close the object.
648** ^If the database connection is associated with unfinalized prepared
649** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then
650** sqlite3_close() will leave the database connection open and return
651** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared
652** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,
653** it returns [SQLITE_OK] regardless, but instead of deallocating the database
654** connection immediately, it marks the database connection as an unusable
655** "zombie" and makes arrangements to automatically deallocate the database
656** connection after all prepared statements are finalized, all BLOB handles
657** are closed, and all backups have finished. The sqlite3_close_v2() interface
658** is intended for use with host languages that are garbage collected, and
659** where the order in which destructors are called is arbitrary.
660**
661** ^If an [sqlite3] object is destroyed while a transaction is open,
662** the transaction is automatically rolled back.
663**
664** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
665** must be either a NULL
666** pointer or an [sqlite3] object pointer obtained
667** from [sqlite3_open()], [sqlite3_open16()], or
668** [sqlite3_open_v2()], and not previously closed.
669** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
670** argument is a harmless no-op.
671*/
672SQLITE_API int sqlite3_close(sqlite3*);
673SQLITE_API int sqlite3_close_v2(sqlite3*);
674
675/*
676** The type for a callback function.
677** This is legacy and deprecated. It is included for historical
678** compatibility and is not documented.
679*/
680typedef int (*sqlite3_callback)(void*,int,char**, char**);
681
682/*
683** CAPI3REF: One-Step Query Execution Interface
684** METHOD: sqlite3
685**
686** The sqlite3_exec() interface is a convenience wrapper around
687** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
688** that allows an application to run multiple statements of SQL
689** without having to use a lot of C code.
690**
691** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
692** semicolon-separate SQL statements passed into its 2nd argument,
693** in the context of the [database connection] passed in as its 1st
694** argument. ^If the callback function of the 3rd argument to
695** sqlite3_exec() is not NULL, then it is invoked for each result row
696** coming out of the evaluated SQL statements. ^The 4th argument to
697** sqlite3_exec() is relayed through to the 1st argument of each
698** callback invocation. ^If the callback pointer to sqlite3_exec()
699** is NULL, then no callback is ever invoked and result rows are
700** ignored.
701**
702** ^If an error occurs while evaluating the SQL statements passed into
703** sqlite3_exec(), then execution of the current statement stops and
704** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
705** is not NULL then any error message is written into memory obtained
706** from [sqlite3_malloc()] and passed back through the 5th parameter.
707** To avoid memory leaks, the application should invoke [sqlite3_free()]
708** on error message strings returned through the 5th parameter of
709** sqlite3_exec() after the error message string is no longer needed.
710** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
711** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
712** NULL before returning.
713**
714** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
715** routine returns SQLITE_ABORT without invoking the callback again and
716** without running any subsequent SQL statements.
717**
718** ^The 2nd argument to the sqlite3_exec() callback function is the
719** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
720** callback is an array of pointers to strings obtained as if from
721** [sqlite3_column_text()], one for each column. ^If an element of a
722** result row is NULL then the corresponding string pointer for the
723** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
724** sqlite3_exec() callback is an array of pointers to strings where each
725** entry represents the name of corresponding result column as obtained
726** from [sqlite3_column_name()].
727**
728** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
729** to an empty string, or a pointer that contains only whitespace and/or
730** SQL comments, then no SQL statements are evaluated and the database
731** is not changed.
732**
733** Restrictions:
734**
735** <ul>
736** <li> The application must ensure that the 1st parameter to sqlite3_exec()
737** is a valid and open [database connection].
738** <li> The application must not close the [database connection] specified by
739** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
740** <li> The application must not modify the SQL statement text passed into
741** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
742** <li> The application must not dereference the arrays or string pointers
743** passed as the 3rd and 4th callback parameters after it returns.
744** </ul>
745*/
746SQLITE_API int sqlite3_exec(
747 sqlite3*, /* An open database */
748 const char *sql, /* SQL to be evaluated */
749 int (*callback)(void*,int,char**,char**), /* Callback function */
750 void *, /* 1st argument to callback */
751 char **errmsg /* Error msg written here */
752);
753
754/*
755** CAPI3REF: Result Codes
756** KEYWORDS: {result code definitions}
757**
758** Many SQLite functions return an integer result code from the set shown
759** here in order to indicate success or failure.
760**
761** New error codes may be added in future versions of SQLite.
762**
763** See also: [extended result code definitions]
764*/
765#define SQLITE_OK0 0 /* Successful result */
766/* beginning-of-error-codes */
767#define SQLITE_ERROR1 1 /* Generic error */
768#define SQLITE_INTERNAL2 2 /* Internal logic error in SQLite */
769#define SQLITE_PERM3 3 /* Access permission denied */
770#define SQLITE_ABORT4 4 /* Callback routine requested an abort */
771#define SQLITE_BUSY5 5 /* The database file is locked */
772#define SQLITE_LOCKED6 6 /* A table in the database is locked */
773#define SQLITE_NOMEM7 7 /* A malloc() failed */
774#define SQLITE_READONLY8 8 /* Attempt to write a readonly database */
775#define SQLITE_INTERRUPT9 9 /* Operation terminated by sqlite3_interrupt()*/
776#define SQLITE_IOERR10 10 /* Some kind of disk I/O error occurred */
777#define SQLITE_CORRUPT11 11 /* The database disk image is malformed */
778#define SQLITE_NOTFOUND12 12 /* Unknown opcode in sqlite3_file_control() */
779#define SQLITE_FULL13 13 /* Insertion failed because database is full */
780#define SQLITE_CANTOPEN14 14 /* Unable to open the database file */
781#define SQLITE_PROTOCOL15 15 /* Database lock protocol error */
782#define SQLITE_EMPTY16 16 /* Internal use only */
783#define SQLITE_SCHEMA17 17 /* The database schema changed */
784#define SQLITE_TOOBIG18 18 /* String or BLOB exceeds size limit */
785#define SQLITE_CONSTRAINT19 19 /* Abort due to constraint violation */
786#define SQLITE_MISMATCH20 20 /* Data type mismatch */
787#define SQLITE_MISUSE21 21 /* Library used incorrectly */
788#define SQLITE_NOLFS22 22 /* Uses OS features not supported on host */
789#define SQLITE_AUTH23 23 /* Authorization denied */
790#define SQLITE_FORMAT24 24 /* Not used */
791#define SQLITE_RANGE25 25 /* 2nd parameter to sqlite3_bind out of range */
792#define SQLITE_NOTADB26 26 /* File opened that is not a database file */
793#define SQLITE_NOTICE27 27 /* Notifications from sqlite3_log() */
794#define SQLITE_WARNING28 28 /* Warnings from sqlite3_log() */
795#define SQLITE_ROW100 100 /* sqlite3_step() has another row ready */
796#define SQLITE_DONE101 101 /* sqlite3_step() has finished executing */
797/* end-of-error-codes */
798
799/*
800** CAPI3REF: Extended Result Codes
801** KEYWORDS: {extended result code definitions}
802**
803** In its default configuration, SQLite API routines return one of 30 integer
804** [result codes]. However, experience has shown that many of
805** these result codes are too coarse-grained. They do not provide as
806** much information about problems as programmers might like. In an effort to
807** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
808** and later) include
809** support for additional result codes that provide more detailed information
810** about errors. These [extended result codes] are enabled or disabled
811** on a per database connection basis using the
812** [sqlite3_extended_result_codes()] API. Or, the extended code for
813** the most recent error can be obtained using
814** [sqlite3_extended_errcode()].
815*/
816#define SQLITE_ERROR_MISSING_COLLSEQ(1 | (1<<8)) (SQLITE_ERROR1 | (1<<8))
817#define SQLITE_ERROR_RETRY(1 | (2<<8)) (SQLITE_ERROR1 | (2<<8))
818#define SQLITE_ERROR_SNAPSHOT(1 | (3<<8)) (SQLITE_ERROR1 | (3<<8))
819#define SQLITE_IOERR_READ(10 | (1<<8)) (SQLITE_IOERR10 | (1<<8))
820#define SQLITE_IOERR_SHORT_READ(10 | (2<<8)) (SQLITE_IOERR10 | (2<<8))
821#define SQLITE_IOERR_WRITE(10 | (3<<8)) (SQLITE_IOERR10 | (3<<8))
822#define SQLITE_IOERR_FSYNC(10 | (4<<8)) (SQLITE_IOERR10 | (4<<8))
823#define SQLITE_IOERR_DIR_FSYNC(10 | (5<<8)) (SQLITE_IOERR10 | (5<<8))
824#define SQLITE_IOERR_TRUNCATE(10 | (6<<8)) (SQLITE_IOERR10 | (6<<8))
825#define SQLITE_IOERR_FSTAT(10 | (7<<8)) (SQLITE_IOERR10 | (7<<8))
826#define SQLITE_IOERR_UNLOCK(10 | (8<<8)) (SQLITE_IOERR10 | (8<<8))
827#define SQLITE_IOERR_RDLOCK(10 | (9<<8)) (SQLITE_IOERR10 | (9<<8))
828#define SQLITE_IOERR_DELETE(10 | (10<<8)) (SQLITE_IOERR10 | (10<<8))
829#define SQLITE_IOERR_BLOCKED(10 | (11<<8)) (SQLITE_IOERR10 | (11<<8))
830#define SQLITE_IOERR_NOMEM(10 | (12<<8)) (SQLITE_IOERR10 | (12<<8))
831#define SQLITE_IOERR_ACCESS(10 | (13<<8)) (SQLITE_IOERR10 | (13<<8))
832#define SQLITE_IOERR_CHECKRESERVEDLOCK(10 | (14<<8)) (SQLITE_IOERR10 | (14<<8))
833#define SQLITE_IOERR_LOCK(10 | (15<<8)) (SQLITE_IOERR10 | (15<<8))
834#define SQLITE_IOERR_CLOSE(10 | (16<<8)) (SQLITE_IOERR10 | (16<<8))
835#define SQLITE_IOERR_DIR_CLOSE(10 | (17<<8)) (SQLITE_IOERR10 | (17<<8))
836#define SQLITE_IOERR_SHMOPEN(10 | (18<<8)) (SQLITE_IOERR10 | (18<<8))
837#define SQLITE_IOERR_SHMSIZE(10 | (19<<8)) (SQLITE_IOERR10 | (19<<8))
838#define SQLITE_IOERR_SHMLOCK(10 | (20<<8)) (SQLITE_IOERR10 | (20<<8))
839#define SQLITE_IOERR_SHMMAP(10 | (21<<8)) (SQLITE_IOERR10 | (21<<8))
840#define SQLITE_IOERR_SEEK(10 | (22<<8)) (SQLITE_IOERR10 | (22<<8))
841#define SQLITE_IOERR_DELETE_NOENT(10 | (23<<8)) (SQLITE_IOERR10 | (23<<8))
842#define SQLITE_IOERR_MMAP(10 | (24<<8)) (SQLITE_IOERR10 | (24<<8))
843#define SQLITE_IOERR_GETTEMPPATH(10 | (25<<8)) (SQLITE_IOERR10 | (25<<8))
844#define SQLITE_IOERR_CONVPATH(10 | (26<<8)) (SQLITE_IOERR10 | (26<<8))
845#define SQLITE_IOERR_VNODE(10 | (27<<8)) (SQLITE_IOERR10 | (27<<8))
846#define SQLITE_IOERR_AUTH(10 | (28<<8)) (SQLITE_IOERR10 | (28<<8))
847#define SQLITE_IOERR_BEGIN_ATOMIC(10 | (29<<8)) (SQLITE_IOERR10 | (29<<8))
848#define SQLITE_IOERR_COMMIT_ATOMIC(10 | (30<<8)) (SQLITE_IOERR10 | (30<<8))
849#define SQLITE_IOERR_ROLLBACK_ATOMIC(10 | (31<<8)) (SQLITE_IOERR10 | (31<<8))
850#define SQLITE_IOERR_DATA(10 | (32<<8)) (SQLITE_IOERR10 | (32<<8))
851#define SQLITE_IOERR_CORRUPTFS(10 | (33<<8)) (SQLITE_IOERR10 | (33<<8))
852#define SQLITE_IOERR_IN_PAGE(10 | (34<<8)) (SQLITE_IOERR10 | (34<<8))
853#define SQLITE_LOCKED_SHAREDCACHE(6 | (1<<8)) (SQLITE_LOCKED6 | (1<<8))
854#define SQLITE_LOCKED_VTAB(6 | (2<<8)) (SQLITE_LOCKED6 | (2<<8))
855#define SQLITE_BUSY_RECOVERY(5 | (1<<8)) (SQLITE_BUSY5 | (1<<8))
856#define SQLITE_BUSY_SNAPSHOT(5 | (2<<8)) (SQLITE_BUSY5 | (2<<8))
857#define SQLITE_BUSY_TIMEOUT(5 | (3<<8)) (SQLITE_BUSY5 | (3<<8))
858#define SQLITE_CANTOPEN_NOTEMPDIR(14 | (1<<8)) (SQLITE_CANTOPEN14 | (1<<8))
859#define SQLITE_CANTOPEN_ISDIR(14 | (2<<8)) (SQLITE_CANTOPEN14 | (2<<8))
860#define SQLITE_CANTOPEN_FULLPATH(14 | (3<<8)) (SQLITE_CANTOPEN14 | (3<<8))
861#define SQLITE_CANTOPEN_CONVPATH(14 | (4<<8)) (SQLITE_CANTOPEN14 | (4<<8))
862#define SQLITE_CANTOPEN_DIRTYWAL(14 | (5<<8)) (SQLITE_CANTOPEN14 | (5<<8)) /* Not Used */
863#define SQLITE_CANTOPEN_SYMLINK(14 | (6<<8)) (SQLITE_CANTOPEN14 | (6<<8))
864#define SQLITE_CORRUPT_VTAB(11 | (1<<8)) (SQLITE_CORRUPT11 | (1<<8))
865#define SQLITE_CORRUPT_SEQUENCE(11 | (2<<8)) (SQLITE_CORRUPT11 | (2<<8))
866#define SQLITE_CORRUPT_INDEX(11 | (3<<8)) (SQLITE_CORRUPT11 | (3<<8))
867#define SQLITE_READONLY_RECOVERY(8 | (1<<8)) (SQLITE_READONLY8 | (1<<8))
868#define SQLITE_READONLY_CANTLOCK(8 | (2<<8)) (SQLITE_READONLY8 | (2<<8))
869#define SQLITE_READONLY_ROLLBACK(8 | (3<<8)) (SQLITE_READONLY8 | (3<<8))
870#define SQLITE_READONLY_DBMOVED(8 | (4<<8)) (SQLITE_READONLY8 | (4<<8))
871#define SQLITE_READONLY_CANTINIT(8 | (5<<8)) (SQLITE_READONLY8 | (5<<8))
872#define SQLITE_READONLY_DIRECTORY(8 | (6<<8)) (SQLITE_READONLY8 | (6<<8))
873#define SQLITE_ABORT_ROLLBACK(4 | (2<<8)) (SQLITE_ABORT4 | (2<<8))
874#define SQLITE_CONSTRAINT_CHECK(19 | (1<<8)) (SQLITE_CONSTRAINT19 | (1<<8))
875#define SQLITE_CONSTRAINT_COMMITHOOK(19 | (2<<8)) (SQLITE_CONSTRAINT19 | (2<<8))
876#define SQLITE_CONSTRAINT_FOREIGNKEY(19 | (3<<8)) (SQLITE_CONSTRAINT19 | (3<<8))
877#define SQLITE_CONSTRAINT_FUNCTION(19 | (4<<8)) (SQLITE_CONSTRAINT19 | (4<<8))
878#define SQLITE_CONSTRAINT_NOTNULL(19 | (5<<8)) (SQLITE_CONSTRAINT19 | (5<<8))
879#define SQLITE_CONSTRAINT_PRIMARYKEY(19 | (6<<8)) (SQLITE_CONSTRAINT19 | (6<<8))
880#define SQLITE_CONSTRAINT_TRIGGER(19 | (7<<8)) (SQLITE_CONSTRAINT19 | (7<<8))
881#define SQLITE_CONSTRAINT_UNIQUE(19 | (8<<8)) (SQLITE_CONSTRAINT19 | (8<<8))
882#define SQLITE_CONSTRAINT_VTAB(19 | (9<<8)) (SQLITE_CONSTRAINT19 | (9<<8))
883#define SQLITE_CONSTRAINT_ROWID(19 |(10<<8)) (SQLITE_CONSTRAINT19 |(10<<8))
884#define SQLITE_CONSTRAINT_PINNED(19 |(11<<8)) (SQLITE_CONSTRAINT19 |(11<<8))
885#define SQLITE_CONSTRAINT_DATATYPE(19 |(12<<8)) (SQLITE_CONSTRAINT19 |(12<<8))
886#define SQLITE_NOTICE_RECOVER_WAL(27 | (1<<8)) (SQLITE_NOTICE27 | (1<<8))
887#define SQLITE_NOTICE_RECOVER_ROLLBACK(27 | (2<<8)) (SQLITE_NOTICE27 | (2<<8))
888#define SQLITE_NOTICE_RBU(27 | (3<<8)) (SQLITE_NOTICE27 | (3<<8))
889#define SQLITE_WARNING_AUTOINDEX(28 | (1<<8)) (SQLITE_WARNING28 | (1<<8))
890#define SQLITE_AUTH_USER(23 | (1<<8)) (SQLITE_AUTH23 | (1<<8))
891#define SQLITE_OK_LOAD_PERMANENTLY(0 | (1<<8)) (SQLITE_OK0 | (1<<8))
892#define SQLITE_OK_SYMLINK(0 | (2<<8)) (SQLITE_OK0 | (2<<8)) /* internal use only */
893
894/*
895** CAPI3REF: Flags For File Open Operations
896**
897** These bit values are intended for use in the
898** 3rd parameter to the [sqlite3_open_v2()] interface and
899** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
900**
901** Only those flags marked as "Ok for sqlite3_open_v2()" may be
902** used as the third argument to the [sqlite3_open_v2()] interface.
903** The other flags have historically been ignored by sqlite3_open_v2(),
904** though future versions of SQLite might change so that an error is
905** raised if any of the disallowed bits are passed into sqlite3_open_v2().
906** Applications should not depend on the historical behavior.
907**
908** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into
909** [sqlite3_open_v2()] does *not* cause the underlying database file
910** to be opened using O_EXCL. Passing SQLITE_OPEN_EXCLUSIVE into
911** [sqlite3_open_v2()] has historically be a no-op and might become an
912** error in future versions of SQLite.
913*/
914#define SQLITE_OPEN_READONLY0x00000001 0x00000001 /* Ok for sqlite3_open_v2() */
915#define SQLITE_OPEN_READWRITE0x00000002 0x00000002 /* Ok for sqlite3_open_v2() */
916#define SQLITE_OPEN_CREATE0x00000004 0x00000004 /* Ok for sqlite3_open_v2() */
917#define SQLITE_OPEN_DELETEONCLOSE0x00000008 0x00000008 /* VFS only */
918#define SQLITE_OPEN_EXCLUSIVE0x00000010 0x00000010 /* VFS only */
919#define SQLITE_OPEN_AUTOPROXY0x00000020 0x00000020 /* VFS only */
920#define SQLITE_OPEN_URI0x00000040 0x00000040 /* Ok for sqlite3_open_v2() */
921#define SQLITE_OPEN_MEMORY0x00000080 0x00000080 /* Ok for sqlite3_open_v2() */
922#define SQLITE_OPEN_MAIN_DB0x00000100 0x00000100 /* VFS only */
923#define SQLITE_OPEN_TEMP_DB0x00000200 0x00000200 /* VFS only */
924#define SQLITE_OPEN_TRANSIENT_DB0x00000400 0x00000400 /* VFS only */
925#define SQLITE_OPEN_MAIN_JOURNAL0x00000800 0x00000800 /* VFS only */
926#define SQLITE_OPEN_TEMP_JOURNAL0x00001000 0x00001000 /* VFS only */
927#define SQLITE_OPEN_SUBJOURNAL0x00002000 0x00002000 /* VFS only */
928#define SQLITE_OPEN_SUPER_JOURNAL0x00004000 0x00004000 /* VFS only */
929#define SQLITE_OPEN_NOMUTEX0x00008000 0x00008000 /* Ok for sqlite3_open_v2() */
930#define SQLITE_OPEN_FULLMUTEX0x00010000 0x00010000 /* Ok for sqlite3_open_v2() */
931#define SQLITE_OPEN_SHAREDCACHE0x00020000 0x00020000 /* Ok for sqlite3_open_v2() */
932#define SQLITE_OPEN_PRIVATECACHE0x00040000 0x00040000 /* Ok for sqlite3_open_v2() */
933#define SQLITE_OPEN_WAL0x00080000 0x00080000 /* VFS only */
934#define SQLITE_OPEN_NOFOLLOW0x01000000 0x01000000 /* Ok for sqlite3_open_v2() */
935#define SQLITE_OPEN_EXRESCODE0x02000000 0x02000000 /* Extended result codes */
936
937/* Reserved: 0x00F00000 */
938/* Legacy compatibility: */
939#define SQLITE_OPEN_MASTER_JOURNAL0x00004000 0x00004000 /* VFS only */
940
941
942/*
943** CAPI3REF: Device Characteristics
944**
945** The xDeviceCharacteristics method of the [sqlite3_io_methods]
946** object returns an integer which is a vector of these
947** bit values expressing I/O characteristics of the mass storage
948** device that holds the file that the [sqlite3_io_methods]
949** refers to.
950**
951** The SQLITE_IOCAP_ATOMIC property means that all writes of
952** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
953** mean that writes of blocks that are nnn bytes in size and
954** are aligned to an address which is an integer multiple of
955** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
956** that when data is appended to a file, the data is appended
957** first then the size of the file is extended, never the other
958** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
959** information is written to disk in the same order as calls
960** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
961** after reboot following a crash or power loss, the only bytes in a
962** file that were written at the application level might have changed
963** and that adjacent bytes, even bytes within the same sector are
964** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
965** flag indicates that a file cannot be deleted when open. The
966** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
967** read-only media and cannot be changed even by processes with
968** elevated privileges.
969**
970** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
971** filesystem supports doing multiple write operations atomically when those
972** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
973** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
974**
975** The SQLITE_IOCAP_SUBPAGE_READ property means that it is ok to read
976** from the database file in amounts that are not a multiple of the
977** page size and that do not begin at a page boundary. Without this
978** property, SQLite is careful to only do full-page reads and write
979** on aligned pages, with the one exception that it will do a sub-page
980** read of the first page to access the database header.
981*/
982#define SQLITE_IOCAP_ATOMIC0x00000001 0x00000001
983#define SQLITE_IOCAP_ATOMIC5120x00000002 0x00000002
984#define SQLITE_IOCAP_ATOMIC1K0x00000004 0x00000004
985#define SQLITE_IOCAP_ATOMIC2K0x00000008 0x00000008
986#define SQLITE_IOCAP_ATOMIC4K0x00000010 0x00000010
987#define SQLITE_IOCAP_ATOMIC8K0x00000020 0x00000020
988#define SQLITE_IOCAP_ATOMIC16K0x00000040 0x00000040
989#define SQLITE_IOCAP_ATOMIC32K0x00000080 0x00000080
990#define SQLITE_IOCAP_ATOMIC64K0x00000100 0x00000100
991#define SQLITE_IOCAP_SAFE_APPEND0x00000200 0x00000200
992#define SQLITE_IOCAP_SEQUENTIAL0x00000400 0x00000400
993#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN0x00000800 0x00000800
994#define SQLITE_IOCAP_POWERSAFE_OVERWRITE0x00001000 0x00001000
995#define SQLITE_IOCAP_IMMUTABLE0x00002000 0x00002000
996#define SQLITE_IOCAP_BATCH_ATOMIC0x00004000 0x00004000
997#define SQLITE_IOCAP_SUBPAGE_READ0x00008000 0x00008000
998
999/*
1000** CAPI3REF: File Locking Levels
1001**
1002** SQLite uses one of these integer values as the second
1003** argument to calls it makes to the xLock() and xUnlock() methods
1004** of an [sqlite3_io_methods] object. These values are ordered from
1005** lest restrictive to most restrictive.
1006**
1007** The argument to xLock() is always SHARED or higher. The argument to
1008** xUnlock is either SHARED or NONE.
1009*/
1010#define SQLITE_LOCK_NONE0 0 /* xUnlock() only */
1011#define SQLITE_LOCK_SHARED1 1 /* xLock() or xUnlock() */
1012#define SQLITE_LOCK_RESERVED2 2 /* xLock() only */
1013#define SQLITE_LOCK_PENDING3 3 /* xLock() only */
1014#define SQLITE_LOCK_EXCLUSIVE4 4 /* xLock() only */
1015
1016/*
1017** CAPI3REF: Synchronization Type Flags
1018**
1019** When SQLite invokes the xSync() method of an
1020** [sqlite3_io_methods] object it uses a combination of
1021** these integer values as the second argument.
1022**
1023** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1024** sync operation only needs to flush data to mass storage. Inode
1025** information need not be flushed. If the lower four bits of the flag
1026** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1027** If the lower four bits equal SQLITE_SYNC_FULL, that means
1028** to use Mac OS X style fullsync instead of fsync().
1029**
1030** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1031** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1032** settings. The [synchronous pragma] determines when calls to the
1033** xSync VFS method occur and applies uniformly across all platforms.
1034** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1035** energetic or rigorous or forceful the sync operations are and
1036** only make a difference on Mac OSX for the default SQLite code.
1037** (Third-party VFS implementations might also make the distinction
1038** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1039** operating systems natively supported by SQLite, only Mac OSX
1040** cares about the difference.)
1041*/
1042#define SQLITE_SYNC_NORMAL0x00002 0x00002
1043#define SQLITE_SYNC_FULL0x00003 0x00003
1044#define SQLITE_SYNC_DATAONLY0x00010 0x00010
1045
1046/*
1047** CAPI3REF: OS Interface Open File Handle
1048**
1049** An [sqlite3_file] object represents an open file in the
1050** [sqlite3_vfs | OS interface layer]. Individual OS interface
1051** implementations will
1052** want to subclass this object by appending additional fields
1053** for their own use. The pMethods entry is a pointer to an
1054** [sqlite3_io_methods] object that defines methods for performing
1055** I/O operations on the open file.
1056*/
1057typedef struct sqlite3_file sqlite3_file;
1058struct sqlite3_file {
1059 const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
1060};
1061
1062/*
1063** CAPI3REF: OS Interface File Virtual Methods Object
1064**
1065** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1066** [sqlite3_file] object (or, more commonly, a subclass of the
1067** [sqlite3_file] object) with a pointer to an instance of this object.
1068** This object defines the methods used to perform various operations
1069** against the open file represented by the [sqlite3_file] object.
1070**
1071** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1072** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1073** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
1074** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1075** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1076** to NULL.
1077**
1078** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1079** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
1080** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
1081** flag may be ORed in to indicate that only the data of the file
1082** and not its inode needs to be synced.
1083**
1084** The integer values to xLock() and xUnlock() are one of
1085** <ul>
1086** <li> [SQLITE_LOCK_NONE],
1087** <li> [SQLITE_LOCK_SHARED],
1088** <li> [SQLITE_LOCK_RESERVED],
1089** <li> [SQLITE_LOCK_PENDING], or
1090** <li> [SQLITE_LOCK_EXCLUSIVE].
1091** </ul>
1092** xLock() upgrades the database file lock. In other words, xLock() moves the
1093** database file lock in the direction NONE toward EXCLUSIVE. The argument to
1094** xLock() is always one of SHARED, RESERVED, PENDING, or EXCLUSIVE, never
1095** SQLITE_LOCK_NONE. If the database file lock is already at or above the
1096** requested lock, then the call to xLock() is a no-op.
1097** xUnlock() downgrades the database file lock to either SHARED or NONE.
1098** If the lock is already at or below the requested lock state, then the call
1099** to xUnlock() is a no-op.
1100** The xCheckReservedLock() method checks whether any database connection,
1101** either in this process or in some other process, is holding a RESERVED,
1102** PENDING, or EXCLUSIVE lock on the file. It returns, via its output
1103** pointer parameter, true if such a lock exists and false otherwise.
1104**
1105** The xFileControl() method is a generic interface that allows custom
1106** VFS implementations to directly control an open file using the
1107** [sqlite3_file_control()] interface. The second "op" argument is an
1108** integer opcode. The third argument is a generic pointer intended to
1109** point to a structure that may contain arguments or space in which to
1110** write return values. Potential uses for xFileControl() might be
1111** functions to enable blocking locks with timeouts, to change the
1112** locking strategy (for example to use dot-file locks), to inquire
1113** about the status of a lock, or to break stale locks. The SQLite
1114** core reserves all opcodes less than 100 for its own use.
1115** A [file control opcodes | list of opcodes] less than 100 is available.
1116** Applications that define a custom xFileControl method should use opcodes
1117** greater than 100 to avoid conflicts. VFS implementations should
1118** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1119** recognize.
1120**
1121** The xSectorSize() method returns the sector size of the
1122** device that underlies the file. The sector size is the
1123** minimum write that can be performed without disturbing
1124** other bytes in the file. The xDeviceCharacteristics()
1125** method returns a bit vector describing behaviors of the
1126** underlying device:
1127**
1128** <ul>
1129** <li> [SQLITE_IOCAP_ATOMIC]
1130** <li> [SQLITE_IOCAP_ATOMIC512]
1131** <li> [SQLITE_IOCAP_ATOMIC1K]
1132** <li> [SQLITE_IOCAP_ATOMIC2K]
1133** <li> [SQLITE_IOCAP_ATOMIC4K]
1134** <li> [SQLITE_IOCAP_ATOMIC8K]
1135** <li> [SQLITE_IOCAP_ATOMIC16K]
1136** <li> [SQLITE_IOCAP_ATOMIC32K]
1137** <li> [SQLITE_IOCAP_ATOMIC64K]
1138** <li> [SQLITE_IOCAP_SAFE_APPEND]
1139** <li> [SQLITE_IOCAP_SEQUENTIAL]
1140** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
1141** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
1142** <li> [SQLITE_IOCAP_IMMUTABLE]
1143** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
1144** <li> [SQLITE_IOCAP_SUBPAGE_READ]
1145** </ul>
1146**
1147** The SQLITE_IOCAP_ATOMIC property means that all writes of
1148** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1149** mean that writes of blocks that are nnn bytes in size and
1150** are aligned to an address which is an integer multiple of
1151** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1152** that when data is appended to a file, the data is appended
1153** first then the size of the file is extended, never the other
1154** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1155** information is written to disk in the same order as calls
1156** to xWrite().
1157**
1158** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1159** in the unread portions of the buffer with zeros. A VFS that
1160** fails to zero-fill short reads might seem to work. However,
1161** failure to zero-fill short reads will eventually lead to
1162** database corruption.
1163*/
1164typedef struct sqlite3_io_methods sqlite3_io_methods;
1165struct sqlite3_io_methods {
1166 int iVersion;
1167 int (*xClose)(sqlite3_file*);
1168 int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1169 int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1170 int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1171 int (*xSync)(sqlite3_file*, int flags);
1172 int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1173 int (*xLock)(sqlite3_file*, int);
1174 int (*xUnlock)(sqlite3_file*, int);
1175 int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1176 int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1177 int (*xSectorSize)(sqlite3_file*);
1178 int (*xDeviceCharacteristics)(sqlite3_file*);
1179 /* Methods above are valid for version 1 */
1180 int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1181 int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1182 void (*xShmBarrier)(sqlite3_file*);
1183 int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1184 /* Methods above are valid for version 2 */
1185 int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1186 int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1187 /* Methods above are valid for version 3 */
1188 /* Additional methods may be added in future releases */
1189};
1190
1191/*
1192** CAPI3REF: Standard File Control Opcodes
1193** KEYWORDS: {file control opcodes} {file control opcode}
1194**
1195** These integer constants are opcodes for the xFileControl method
1196** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1197** interface.
1198**
1199** <ul>
1200** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1201** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
1202** opcode causes the xFileControl method to write the current state of
1203** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1204** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1205** into an integer that the pArg argument points to.
1206** This capability is only available if SQLite is compiled with [SQLITE_DEBUG].
1207**
1208** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1209** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1210** layer a hint of how large the database file will grow to be during the
1211** current transaction. This hint is not guaranteed to be accurate but it
1212** is often close. The underlying VFS might choose to preallocate database
1213** file space based on this hint in order to help writes to the database
1214** file run faster.
1215**
1216** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]
1217** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
1218** implements [sqlite3_deserialize()] to set an upper bound on the size
1219** of the in-memory database. The argument is a pointer to a [sqlite3_int64].
1220** If the integer pointed to is negative, then it is filled in with the
1221** current limit. Otherwise the limit is set to the larger of the value
1222** of the integer pointed to and the current database size. The integer
1223** pointed to is set to the new limit.
1224**
1225** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1226** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1227** extends and truncates the database file in chunks of a size specified
1228** by the user. The fourth argument to [sqlite3_file_control()] should
1229** point to an integer (type int) containing the new chunk-size to use
1230** for the nominated database. Allocating database file space in large
1231** chunks (say 1MB at a time), may reduce file-system fragmentation and
1232** improve performance on some systems.
1233**
1234** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1235** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1236** to the [sqlite3_file] object associated with a particular database
1237** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
1238**
1239** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1240** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1241** to the [sqlite3_file] object associated with the journal file (either
1242** the [rollback journal] or the [write-ahead log]) for a particular database
1243** connection. See also [SQLITE_FCNTL_FILE_POINTER].
1244**
1245** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1246** No longer in use.
1247**
1248** <li>[[SQLITE_FCNTL_SYNC]]
1249** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1250** sent to the VFS immediately before the xSync method is invoked on a
1251** database file descriptor. Or, if the xSync method is not invoked
1252** because the user has configured SQLite with
1253** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1254** of the xSync method. In most cases, the pointer argument passed with
1255** this file-control is NULL. However, if the database file is being synced
1256** as part of a multi-database commit, the argument points to a nul-terminated
1257** string containing the transactions super-journal file name. VFSes that
1258** do not need this signal should silently ignore this opcode. Applications
1259** should not call [sqlite3_file_control()] with this opcode as doing so may
1260** disrupt the operation of the specialized VFSes that do require it.
1261**
1262** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1263** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1264** and sent to the VFS after a transaction has been committed immediately
1265** but before the database is unlocked. VFSes that do not need this signal
1266** should silently ignore this opcode. Applications should not call
1267** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1268** operation of the specialized VFSes that do require it.
1269**
1270** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1271** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1272** retry counts and intervals for certain disk I/O operations for the
1273** windows [VFS] in order to provide robustness in the presence of
1274** anti-virus programs. By default, the windows VFS will retry file read,
1275** file write, and file delete operations up to 10 times, with a delay
1276** of 25 milliseconds before the first retry and with the delay increasing
1277** by an additional 25 milliseconds with each subsequent retry. This
1278** opcode allows these two values (10 retries and 25 milliseconds of delay)
1279** to be adjusted. The values are changed for all database connections
1280** within the same process. The argument is a pointer to an array of two
1281** integers where the first integer is the new retry count and the second
1282** integer is the delay. If either integer is negative, then the setting
1283** is not changed but instead the prior value of that setting is written
1284** into the array entry, allowing the current retry settings to be
1285** interrogated. The zDbName parameter is ignored.
1286**
1287** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1288** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1289** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
1290** write ahead log ([WAL file]) and shared memory
1291** files used for transaction control
1292** are automatically deleted when the latest connection to the database
1293** closes. Setting persistent WAL mode causes those files to persist after
1294** close. Persisting the files is useful when other processes that do not
1295** have write permission on the directory containing the database file want
1296** to read the database file, as the WAL and shared memory files must exist
1297** in order for the database to be readable. The fourth parameter to
1298** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1299** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1300** WAL mode. If the integer is -1, then it is overwritten with the current
1301** WAL persistence setting.
1302**
1303** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1304** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1305** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1306** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1307** xDeviceCharacteristics methods. The fourth parameter to
1308** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1309** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1310** mode. If the integer is -1, then it is overwritten with the current
1311** zero-damage mode setting.
1312**
1313** <li>[[SQLITE_FCNTL_OVERWRITE]]
1314** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1315** a write transaction to indicate that, unless it is rolled back for some
1316** reason, the entire database file will be overwritten by the current
1317** transaction. This is used by VACUUM operations.
1318**
1319** <li>[[SQLITE_FCNTL_VFSNAME]]
1320** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1321** all [VFSes] in the VFS stack. The names are of all VFS shims and the
1322** final bottom-level VFS are written into memory obtained from
1323** [sqlite3_malloc()] and the result is stored in the char* variable
1324** that the fourth parameter of [sqlite3_file_control()] points to.
1325** The caller is responsible for freeing the memory when done. As with
1326** all file-control actions, there is no guarantee that this will actually
1327** do anything. Callers should initialize the char* variable to a NULL
1328** pointer in case this file-control is not implemented. This file-control
1329** is intended for diagnostic use only.
1330**
1331** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1332** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1333** [VFSes] currently in use. ^(The argument X in
1334** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1335** of type "[sqlite3_vfs] **". This opcodes will set *X
1336** to a pointer to the top-level VFS.)^
1337** ^When there are multiple VFS shims in the stack, this opcode finds the
1338** upper-most shim only.
1339**
1340** <li>[[SQLITE_FCNTL_PRAGMA]]
1341** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1342** file control is sent to the open [sqlite3_file] object corresponding
1343** to the database file to which the pragma statement refers. ^The argument
1344** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1345** pointers to strings (char**) in which the second element of the array
1346** is the name of the pragma and the third element is the argument to the
1347** pragma or NULL if the pragma has no argument. ^The handler for an
1348** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1349** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1350** or the equivalent and that string will become the result of the pragma or
1351** the error message if the pragma fails. ^If the
1352** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1353** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
1354** file control returns [SQLITE_OK], then the parser assumes that the
1355** VFS has handled the PRAGMA itself and the parser generates a no-op
1356** prepared statement if result string is NULL, or that returns a copy
1357** of the result string if the string is non-NULL.
1358** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1359** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1360** that the VFS encountered an error while handling the [PRAGMA] and the
1361** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1362** file control occurs at the beginning of pragma statement analysis and so
1363** it is able to override built-in [PRAGMA] statements.
1364**
1365** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1366** ^The [SQLITE_FCNTL_BUSYHANDLER]
1367** file-control may be invoked by SQLite on the database file handle
1368** shortly after it is opened in order to provide a custom VFS with access
1369** to the connection's busy-handler callback. The argument is of type (void**)
1370** - an array of two (void *) values. The first (void *) actually points
1371** to a function of type (int (*)(void *)). In order to invoke the connection's
1372** busy-handler, this function should be invoked with the second (void *) in
1373** the array as the only argument. If it returns non-zero, then the operation
1374** should be retried. If it returns zero, the custom VFS should abandon the
1375** current operation.
1376**
1377** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1378** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1379** to have SQLite generate a
1380** temporary filename using the same algorithm that is followed to generate
1381** temporary filenames for TEMP tables and other internal uses. The
1382** argument should be a char** which will be filled with the filename
1383** written into memory obtained from [sqlite3_malloc()]. The caller should
1384** invoke [sqlite3_free()] on the result to avoid a memory leak.
1385**
1386** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1387** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1388** maximum number of bytes that will be used for memory-mapped I/O.
1389** The argument is a pointer to a value of type sqlite3_int64 that
1390** is an advisory maximum number of bytes in the file to memory map. The
1391** pointer is overwritten with the old value. The limit is not changed if
1392** the value originally pointed to is negative, and so the current limit
1393** can be queried by passing in a pointer to a negative number. This
1394** file-control is used internally to implement [PRAGMA mmap_size].
1395**
1396** <li>[[SQLITE_FCNTL_TRACE]]
1397** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1398** to the VFS about what the higher layers of the SQLite stack are doing.
1399** This file control is used by some VFS activity tracing [shims].
1400** The argument is a zero-terminated string. Higher layers in the
1401** SQLite stack may generate instances of this file control if
1402** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1403**
1404** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1405** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1406** pointer to an integer and it writes a boolean into that integer depending
1407** on whether or not the file has been renamed, moved, or deleted since it
1408** was first opened.
1409**
1410** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
1411** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
1412** underlying native file handle associated with a file handle. This file
1413** control interprets its argument as a pointer to a native file handle and
1414** writes the resulting value there.
1415**
1416** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1417** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
1418** opcode causes the xFileControl method to swap the file handle with the one
1419** pointed to by the pArg argument. This capability is used during testing
1420** and only needs to be supported when SQLITE_TEST is defined.
1421**
1422** <li>[[SQLITE_FCNTL_NULL_IO]]
1423** The [SQLITE_FCNTL_NULL_IO] opcode sets the low-level file descriptor
1424** or file handle for the [sqlite3_file] object such that it will no longer
1425** read or write to the database file.
1426**
1427** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1428** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1429** be advantageous to block on the next WAL lock if the lock is not immediately
1430** available. The WAL subsystem issues this signal during rare
1431** circumstances in order to fix a problem with priority inversion.
1432** Applications should <em>not</em> use this file-control.
1433**
1434** <li>[[SQLITE_FCNTL_ZIPVFS]]
1435** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1436** VFS should return SQLITE_NOTFOUND for this opcode.
1437**
1438** <li>[[SQLITE_FCNTL_RBU]]
1439** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1440** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
1441** this opcode.
1442**
1443** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
1444** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
1445** the file descriptor is placed in "batch write mode", which
1446** means all subsequent write operations will be deferred and done
1447** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
1448** that do not support batch atomic writes will return SQLITE_NOTFOUND.
1449** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
1450** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
1451** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
1452** no VFS interface calls on the same [sqlite3_file] file descriptor
1453** except for calls to the xWrite method and the xFileControl method
1454** with [SQLITE_FCNTL_SIZE_HINT].
1455**
1456** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
1457** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
1458** operations since the previous successful call to
1459** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
1460** This file control returns [SQLITE_OK] if and only if the writes were
1461** all performed successfully and have been committed to persistent storage.
1462** ^Regardless of whether or not it is successful, this file control takes
1463** the file descriptor out of batch write mode so that all subsequent
1464** write operations are independent.
1465** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
1466** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
1467**
1468** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
1469** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
1470** operations since the previous successful call to
1471** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
1472** ^This file control takes the file descriptor out of batch write mode
1473** so that all subsequent write operations are independent.
1474** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
1475** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
1476**
1477** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
1478** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS
1479** to block for up to M milliseconds before failing when attempting to
1480** obtain a file lock using the xLock or xShmLock methods of the VFS.
1481** The parameter is a pointer to a 32-bit signed integer that contains
1482** the value that M is to be set to. Before returning, the 32-bit signed
1483** integer is overwritten with the previous value of M.
1484**
1485** <li>[[SQLITE_FCNTL_BLOCK_ON_CONNECT]]
1486** The [SQLITE_FCNTL_BLOCK_ON_CONNECT] opcode is used to configure the
1487** VFS to block when taking a SHARED lock to connect to a wal mode database.
1488** This is used to implement the functionality associated with
1489** SQLITE_SETLK_BLOCK_ON_CONNECT.
1490**
1491** <li>[[SQLITE_FCNTL_DATA_VERSION]]
1492** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
1493** a database file. The argument is a pointer to a 32-bit unsigned integer.
1494** The "data version" for the pager is written into the pointer. The
1495** "data version" changes whenever any change occurs to the corresponding
1496** database file, either through SQL statements on the same database
1497** connection or through transactions committed by separate database
1498** connections possibly in other processes. The [sqlite3_total_changes()]
1499** interface can be used to find if any database on the connection has changed,
1500** but that interface responds to changes on TEMP as well as MAIN and does
1501** not provide a mechanism to detect changes to MAIN only. Also, the
1502** [sqlite3_total_changes()] interface responds to internal changes only and
1503** omits changes made by other database connections. The
1504** [PRAGMA data_version] command provides a mechanism to detect changes to
1505** a single attached database that occur due to other database connections,
1506** but omits changes implemented by the database connection on which it is
1507** called. This file control is the only mechanism to detect changes that
1508** happen either internally or externally and that are associated with
1509** a particular attached database.
1510**
1511** <li>[[SQLITE_FCNTL_CKPT_START]]
1512** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint
1513** in wal mode before the client starts to copy pages from the wal
1514** file to the database file.
1515**
1516** <li>[[SQLITE_FCNTL_CKPT_DONE]]
1517** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint
1518** in wal mode after the client has finished copying pages from the wal
1519** file to the database file, but before the *-shm file is updated to
1520** record the fact that the pages have been checkpointed.
1521**
1522** <li>[[SQLITE_FCNTL_EXTERNAL_READER]]
1523** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect
1524** whether or not there is a database client in another process with a wal-mode
1525** transaction open on the database or not. It is only available on unix.The
1526** (void*) argument passed with this file-control should be a pointer to a
1527** value of type (int). The integer value is set to 1 if the database is a wal
1528** mode database and there exists at least one client in another process that
1529** currently has an SQL transaction open on the database. It is set to 0 if
1530** the database is not a wal-mode db, or if there is no such connection in any
1531** other process. This opcode cannot be used to detect transactions opened
1532** by clients within the current process, only within other processes.
1533**
1534** <li>[[SQLITE_FCNTL_CKSM_FILE]]
1535** The [SQLITE_FCNTL_CKSM_FILE] opcode is for use internally by the
1536** [checksum VFS shim] only.
1537**
1538** <li>[[SQLITE_FCNTL_RESET_CACHE]]
1539** If there is currently no transaction open on the database, and the
1540** database is not a temp db, then the [SQLITE_FCNTL_RESET_CACHE] file-control
1541** purges the contents of the in-memory page cache. If there is an open
1542** transaction, or if the db is a temp-db, this opcode is a no-op, not an error.
1543** </ul>
1544*/
1545#define SQLITE_FCNTL_LOCKSTATE1 1
1546#define SQLITE_FCNTL_GET_LOCKPROXYFILE2 2
1547#define SQLITE_FCNTL_SET_LOCKPROXYFILE3 3
1548#define SQLITE_FCNTL_LAST_ERRNO4 4
1549#define SQLITE_FCNTL_SIZE_HINT5 5
1550#define SQLITE_FCNTL_CHUNK_SIZE6 6
1551#define SQLITE_FCNTL_FILE_POINTER7 7
1552#define SQLITE_FCNTL_SYNC_OMITTED8 8
1553#define SQLITE_FCNTL_WIN32_AV_RETRY9 9
1554#define SQLITE_FCNTL_PERSIST_WAL10 10
1555#define SQLITE_FCNTL_OVERWRITE11 11
1556#define SQLITE_FCNTL_VFSNAME12 12
1557#define SQLITE_FCNTL_POWERSAFE_OVERWRITE13 13
1558#define SQLITE_FCNTL_PRAGMA14 14
1559#define SQLITE_FCNTL_BUSYHANDLER15 15
1560#define SQLITE_FCNTL_TEMPFILENAME16 16
1561#define SQLITE_FCNTL_MMAP_SIZE18 18
1562#define SQLITE_FCNTL_TRACE19 19
1563#define SQLITE_FCNTL_HAS_MOVED20 20
1564#define SQLITE_FCNTL_SYNC21 21
1565#define SQLITE_FCNTL_COMMIT_PHASETWO22 22
1566#define SQLITE_FCNTL_WIN32_SET_HANDLE23 23
1567#define SQLITE_FCNTL_WAL_BLOCK24 24
1568#define SQLITE_FCNTL_ZIPVFS25 25
1569#define SQLITE_FCNTL_RBU26 26
1570#define SQLITE_FCNTL_VFS_POINTER27 27
1571#define SQLITE_FCNTL_JOURNAL_POINTER28 28
1572#define SQLITE_FCNTL_WIN32_GET_HANDLE29 29
1573#define SQLITE_FCNTL_PDB30 30
1574#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE31 31
1575#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE32 32
1576#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE33 33
1577#define SQLITE_FCNTL_LOCK_TIMEOUT34 34
1578#define SQLITE_FCNTL_DATA_VERSION35 35
1579#define SQLITE_FCNTL_SIZE_LIMIT36 36
1580#define SQLITE_FCNTL_CKPT_DONE37 37
1581#define SQLITE_FCNTL_RESERVE_BYTES38 38
1582#define SQLITE_FCNTL_CKPT_START39 39
1583#define SQLITE_FCNTL_EXTERNAL_READER40 40
1584#define SQLITE_FCNTL_CKSM_FILE41 41
1585#define SQLITE_FCNTL_RESET_CACHE42 42
1586#define SQLITE_FCNTL_NULL_IO43 43
1587#define SQLITE_FCNTL_BLOCK_ON_CONNECT44 44
1588
1589/* deprecated names */
1590#define SQLITE_GET_LOCKPROXYFILE2 SQLITE_FCNTL_GET_LOCKPROXYFILE2
1591#define SQLITE_SET_LOCKPROXYFILE3 SQLITE_FCNTL_SET_LOCKPROXYFILE3
1592#define SQLITE_LAST_ERRNO4 SQLITE_FCNTL_LAST_ERRNO4
1593
1594
1595/*
1596** CAPI3REF: Mutex Handle
1597**
1598** The mutex module within SQLite defines [sqlite3_mutex] to be an
1599** abstract type for a mutex object. The SQLite core never looks
1600** at the internal representation of an [sqlite3_mutex]. It only
1601** deals with pointers to the [sqlite3_mutex] object.
1602**
1603** Mutexes are created using [sqlite3_mutex_alloc()].
1604*/
1605typedef struct sqlite3_mutex sqlite3_mutex;
1606
1607/*
1608** CAPI3REF: Loadable Extension Thunk
1609**
1610** A pointer to the opaque sqlite3_api_routines structure is passed as
1611** the third parameter to entry points of [loadable extensions]. This
1612** structure must be typedefed in order to work around compiler warnings
1613** on some platforms.
1614*/
1615typedef struct sqlite3_api_routines sqlite3_api_routines;
1616
1617/*
1618** CAPI3REF: File Name
1619**
1620** Type [sqlite3_filename] is used by SQLite to pass filenames to the
1621** xOpen method of a [VFS]. It may be cast to (const char*) and treated
1622** as a normal, nul-terminated, UTF-8 buffer containing the filename, but
1623** may also be passed to special APIs such as:
1624**
1625** <ul>
1626** <li> sqlite3_filename_database()
1627** <li> sqlite3_filename_journal()
1628** <li> sqlite3_filename_wal()
1629** <li> sqlite3_uri_parameter()
1630** <li> sqlite3_uri_boolean()
1631** <li> sqlite3_uri_int64()
1632** <li> sqlite3_uri_key()
1633** </ul>
1634*/
1635typedef const char *sqlite3_filename;
1636
1637/*
1638** CAPI3REF: OS Interface Object
1639**
1640** An instance of the sqlite3_vfs object defines the interface between
1641** the SQLite core and the underlying operating system. The "vfs"
1642** in the name of the object stands for "virtual file system". See
1643** the [VFS | VFS documentation] for further information.
1644**
1645** The VFS interface is sometimes extended by adding new methods onto
1646** the end. Each time such an extension occurs, the iVersion field
1647** is incremented. The iVersion value started out as 1 in
1648** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
1649** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
1650** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields
1651** may be appended to the sqlite3_vfs object and the iVersion value
1652** may increase again in future versions of SQLite.
1653** Note that due to an oversight, the structure
1654** of the sqlite3_vfs object changed in the transition from
1655** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
1656** and yet the iVersion field was not increased.
1657**
1658** The szOsFile field is the size of the subclassed [sqlite3_file]
1659** structure used by this VFS. mxPathname is the maximum length of
1660** a pathname in this VFS.
1661**
1662** Registered sqlite3_vfs objects are kept on a linked list formed by
1663** the pNext pointer. The [sqlite3_vfs_register()]
1664** and [sqlite3_vfs_unregister()] interfaces manage this list
1665** in a thread-safe way. The [sqlite3_vfs_find()] interface
1666** searches the list. Neither the application code nor the VFS
1667** implementation should use the pNext pointer.
1668**
1669** The pNext field is the only field in the sqlite3_vfs
1670** structure that SQLite will ever modify. SQLite will only access
1671** or modify this field while holding a particular static mutex.
1672** The application should never modify anything within the sqlite3_vfs
1673** object once the object has been registered.
1674**
1675** The zName field holds the name of the VFS module. The name must
1676** be unique across all VFS modules.
1677**
1678** [[sqlite3_vfs.xOpen]]
1679** ^SQLite guarantees that the zFilename parameter to xOpen
1680** is either a NULL pointer or string obtained
1681** from xFullPathname() with an optional suffix added.
1682** ^If a suffix is added to the zFilename parameter, it will
1683** consist of a single "-" character followed by no more than
1684** 11 alphanumeric and/or "-" characters.
1685** ^SQLite further guarantees that
1686** the string will be valid and unchanged until xClose() is
1687** called. Because of the previous sentence,
1688** the [sqlite3_file] can safely store a pointer to the
1689** filename if it needs to remember the filename for some reason.
1690** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1691** must invent its own temporary name for the file. ^Whenever the
1692** xFilename parameter is NULL it will also be the case that the
1693** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1694**
1695** The flags argument to xOpen() includes all bits set in
1696** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
1697** or [sqlite3_open16()] is used, then flags includes at least
1698** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1699** If xOpen() opens a file read-only then it sets *pOutFlags to
1700** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1701**
1702** ^(SQLite will also add one of the following flags to the xOpen()
1703** call, depending on the object being opened:
1704**
1705** <ul>
1706** <li> [SQLITE_OPEN_MAIN_DB]
1707** <li> [SQLITE_OPEN_MAIN_JOURNAL]
1708** <li> [SQLITE_OPEN_TEMP_DB]
1709** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1710** <li> [SQLITE_OPEN_TRANSIENT_DB]
1711** <li> [SQLITE_OPEN_SUBJOURNAL]
1712** <li> [SQLITE_OPEN_SUPER_JOURNAL]
1713** <li> [SQLITE_OPEN_WAL]
1714** </ul>)^
1715**
1716** The file I/O implementation can use the object type flags to
1717** change the way it deals with files. For example, an application
1718** that does not care about crash recovery or rollback might make
1719** the open of a journal file a no-op. Writes to this journal would
1720** also be no-ops, and any attempt to read the journal would return
1721** SQLITE_IOERR. Or the implementation might recognize that a database
1722** file will be doing page-aligned sector reads and writes in a random
1723** order and set up its I/O subsystem accordingly.
1724**
1725** SQLite might also add one of the following flags to the xOpen method:
1726**
1727** <ul>
1728** <li> [SQLITE_OPEN_DELETEONCLOSE]
1729** <li> [SQLITE_OPEN_EXCLUSIVE]
1730** </ul>
1731**
1732** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1733** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1734** will be set for TEMP databases and their journals, transient
1735** databases, and subjournals.
1736**
1737** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1738** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1739** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1740** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1741** SQLITE_OPEN_CREATE, is used to indicate that file should always
1742** be created, and that it is an error if it already exists.
1743** It is <i>not</i> used to indicate the file should be opened
1744** for exclusive access.
1745**
1746** ^At least szOsFile bytes of memory are allocated by SQLite
1747** to hold the [sqlite3_file] structure passed as the third
1748** argument to xOpen. The xOpen method does not have to
1749** allocate the structure; it should just fill it in. Note that
1750** the xOpen method must set the sqlite3_file.pMethods to either
1751** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1752** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1753** element will be valid after xOpen returns regardless of the success
1754** or failure of the xOpen call.
1755**
1756** [[sqlite3_vfs.xAccess]]
1757** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1758** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1759** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1760** to test whether a file is at least readable. The SQLITE_ACCESS_READ
1761** flag is never actually used and is not implemented in the built-in
1762** VFSes of SQLite. The file is named by the second argument and can be a
1763** directory. The xAccess method returns [SQLITE_OK] on success or some
1764** non-zero error code if there is an I/O error or if the name of
1765** the file given in the second argument is illegal. If SQLITE_OK
1766** is returned, then non-zero or zero is written into *pResOut to indicate
1767** whether or not the file is accessible.
1768**
1769** ^SQLite will always allocate at least mxPathname+1 bytes for the
1770** output buffer xFullPathname. The exact size of the output buffer
1771** is also passed as a parameter to both methods. If the output buffer
1772** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1773** handled as a fatal error by SQLite, vfs implementations should endeavor
1774** to prevent this by setting mxPathname to a sufficiently large value.
1775**
1776** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1777** interfaces are not strictly a part of the filesystem, but they are
1778** included in the VFS structure for completeness.
1779** The xRandomness() function attempts to return nBytes bytes
1780** of good-quality randomness into zOut. The return value is
1781** the actual number of bytes of randomness obtained.
1782** The xSleep() method causes the calling thread to sleep for at
1783** least the number of microseconds given. ^The xCurrentTime()
1784** method returns a Julian Day Number for the current date and time as
1785** a floating point value.
1786** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1787** Day Number multiplied by 86400000 (the number of milliseconds in
1788** a 24-hour day).
1789** ^SQLite will use the xCurrentTimeInt64() method to get the current
1790** date and time if that method is available (if iVersion is 2 or
1791** greater and the function pointer is not NULL) and will fall back
1792** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1793**
1794** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1795** are not used by the SQLite core. These optional interfaces are provided
1796** by some VFSes to facilitate testing of the VFS code. By overriding
1797** system calls with functions under its control, a test program can
1798** simulate faults and error conditions that would otherwise be difficult
1799** or impossible to induce. The set of system calls that can be overridden
1800** varies from one VFS to another, and from one version of the same VFS to the
1801** next. Applications that use these interfaces must be prepared for any
1802** or all of these interfaces to be NULL or for their behavior to change
1803** from one release to the next. Applications must not attempt to access
1804** any of these methods if the iVersion of the VFS is less than 3.
1805*/
1806typedef struct sqlite3_vfs sqlite3_vfs;
1807typedef void (*sqlite3_syscall_ptr)(void);
1808struct sqlite3_vfs {
1809 int iVersion; /* Structure version number (currently 3) */
1810 int szOsFile; /* Size of subclassed sqlite3_file */
1811 int mxPathname; /* Maximum file pathname length */
1812 sqlite3_vfs *pNext; /* Next registered VFS */
1813 const char *zName; /* Name of this virtual file system */
1814 void *pAppData; /* Pointer to application-specific data */
1815 int (*xOpen)(sqlite3_vfs*, sqlite3_filename zName, sqlite3_file*,
1816 int flags, int *pOutFlags);
1817 int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1818 int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1819 int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1820 void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1821 void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1822 void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1823 void (*xDlClose)(sqlite3_vfs*, void*);
1824 int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1825 int (*xSleep)(sqlite3_vfs*, int microseconds);
1826 int (*xCurrentTime)(sqlite3_vfs*, double*);
1827 int (*xGetLastError)(sqlite3_vfs*, int, char *);
1828 /*
1829 ** The methods above are in version 1 of the sqlite_vfs object
1830 ** definition. Those that follow are added in version 2 or later
1831 */
1832 int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1833 /*
1834 ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1835 ** Those below are for version 3 and greater.
1836 */
1837 int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1838 sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1839 const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1840 /*
1841 ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1842 ** New fields may be appended in future versions. The iVersion
1843 ** value will increment whenever this happens.
1844 */
1845};
1846
1847/*
1848** CAPI3REF: Flags for the xAccess VFS method
1849**
1850** These integer constants can be used as the third parameter to
1851** the xAccess method of an [sqlite3_vfs] object. They determine
1852** what kind of permissions the xAccess method is looking for.
1853** With SQLITE_ACCESS_EXISTS, the xAccess method
1854** simply checks whether the file exists.
1855** With SQLITE_ACCESS_READWRITE, the xAccess method
1856** checks whether the named directory is both readable and writable
1857** (in other words, if files can be added, removed, and renamed within
1858** the directory).
1859** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1860** [temp_store_directory pragma], though this could change in a future
1861** release of SQLite.
1862** With SQLITE_ACCESS_READ, the xAccess method
1863** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
1864** currently unused, though it might be used in a future release of
1865** SQLite.
1866*/
1867#define SQLITE_ACCESS_EXISTS0 0
1868#define SQLITE_ACCESS_READWRITE1 1 /* Used by PRAGMA temp_store_directory */
1869#define SQLITE_ACCESS_READ2 2 /* Unused */
1870
1871/*
1872** CAPI3REF: Flags for the xShmLock VFS method
1873**
1874** These integer constants define the various locking operations
1875** allowed by the xShmLock method of [sqlite3_io_methods]. The
1876** following are the only legal combinations of flags to the
1877** xShmLock method:
1878**
1879** <ul>
1880** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1881** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1882** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1883** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1884** </ul>
1885**
1886** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1887** was given on the corresponding lock.
1888**
1889** The xShmLock method can transition between unlocked and SHARED or
1890** between unlocked and EXCLUSIVE. It cannot transition between SHARED
1891** and EXCLUSIVE.
1892*/
1893#define SQLITE_SHM_UNLOCK1 1
1894#define SQLITE_SHM_LOCK2 2
1895#define SQLITE_SHM_SHARED4 4
1896#define SQLITE_SHM_EXCLUSIVE8 8
1897
1898/*
1899** CAPI3REF: Maximum xShmLock index
1900**
1901** The xShmLock method on [sqlite3_io_methods] may use values
1902** between 0 and this upper bound as its "offset" argument.
1903** The SQLite core will never attempt to acquire or release a
1904** lock outside of this range
1905*/
1906#define SQLITE_SHM_NLOCK8 8
1907
1908
1909/*
1910** CAPI3REF: Initialize The SQLite Library
1911**
1912** ^The sqlite3_initialize() routine initializes the
1913** SQLite library. ^The sqlite3_shutdown() routine
1914** deallocates any resources that were allocated by sqlite3_initialize().
1915** These routines are designed to aid in process initialization and
1916** shutdown on embedded systems. Workstation applications using
1917** SQLite normally do not need to invoke either of these routines.
1918**
1919** A call to sqlite3_initialize() is an "effective" call if it is
1920** the first time sqlite3_initialize() is invoked during the lifetime of
1921** the process, or if it is the first time sqlite3_initialize() is invoked
1922** following a call to sqlite3_shutdown(). ^(Only an effective call
1923** of sqlite3_initialize() does any initialization. All other calls
1924** are harmless no-ops.)^
1925**
1926** A call to sqlite3_shutdown() is an "effective" call if it is the first
1927** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
1928** an effective call to sqlite3_shutdown() does any deinitialization.
1929** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1930**
1931** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1932** is not. The sqlite3_shutdown() interface must only be called from a
1933** single thread. All open [database connections] must be closed and all
1934** other SQLite resources must be deallocated prior to invoking
1935** sqlite3_shutdown().
1936**
1937** Among other things, ^sqlite3_initialize() will invoke
1938** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
1939** will invoke sqlite3_os_end().
1940**
1941** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1942** ^If for some reason, sqlite3_initialize() is unable to initialize
1943** the library (perhaps it is unable to allocate a needed resource such
1944** as a mutex) it returns an [error code] other than [SQLITE_OK].
1945**
1946** ^The sqlite3_initialize() routine is called internally by many other
1947** SQLite interfaces so that an application usually does not need to
1948** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
1949** calls sqlite3_initialize() so the SQLite library will be automatically
1950** initialized when [sqlite3_open()] is called if it has not be initialized
1951** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1952** compile-time option, then the automatic calls to sqlite3_initialize()
1953** are omitted and the application must call sqlite3_initialize() directly
1954** prior to using any other SQLite interface. For maximum portability,
1955** it is recommended that applications always invoke sqlite3_initialize()
1956** directly prior to using any other SQLite interface. Future releases
1957** of SQLite may require this. In other words, the behavior exhibited
1958** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1959** default behavior in some future release of SQLite.
1960**
1961** The sqlite3_os_init() routine does operating-system specific
1962** initialization of the SQLite library. The sqlite3_os_end()
1963** routine undoes the effect of sqlite3_os_init(). Typical tasks
1964** performed by these routines include allocation or deallocation
1965** of static resources, initialization of global variables,
1966** setting up a default [sqlite3_vfs] module, or setting up
1967** a default configuration using [sqlite3_config()].
1968**
1969** The application should never invoke either sqlite3_os_init()
1970** or sqlite3_os_end() directly. The application should only invoke
1971** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
1972** interface is called automatically by sqlite3_initialize() and
1973** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
1974** implementations for sqlite3_os_init() and sqlite3_os_end()
1975** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1976** When [custom builds | built for other platforms]
1977** (using the [SQLITE_OS_OTHER=1] compile-time
1978** option) the application must supply a suitable implementation for
1979** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1980** implementation of sqlite3_os_init() or sqlite3_os_end()
1981** must return [SQLITE_OK] on success and some other [error code] upon
1982** failure.
1983*/
1984SQLITE_API int sqlite3_initialize(void);
1985SQLITE_API int sqlite3_shutdown(void);
1986SQLITE_API int sqlite3_os_init(void);
1987SQLITE_API int sqlite3_os_end(void);
1988
1989/*
1990** CAPI3REF: Configuring The SQLite Library
1991**
1992** The sqlite3_config() interface is used to make global configuration
1993** changes to SQLite in order to tune SQLite to the specific needs of
1994** the application. The default configuration is recommended for most
1995** applications and so this routine is usually not necessary. It is
1996** provided to support rare applications with unusual needs.
1997**
1998** <b>The sqlite3_config() interface is not threadsafe. The application
1999** must ensure that no other SQLite interfaces are invoked by other
2000** threads while sqlite3_config() is running.</b>
2001**
2002** The first argument to sqlite3_config() is an integer
2003** [configuration option] that determines
2004** what property of SQLite is to be configured. Subsequent arguments
2005** vary depending on the [configuration option]
2006** in the first argument.
2007**
2008** For most configuration options, the sqlite3_config() interface
2009** may only be invoked prior to library initialization using
2010** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
2011** The exceptional configuration options that may be invoked at any time
2012** are called "anytime configuration options".
2013** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
2014** [sqlite3_shutdown()] with a first argument that is not an anytime
2015** configuration option, then the sqlite3_config() call will return SQLITE_MISUSE.
2016** Note, however, that ^sqlite3_config() can be called as part of the
2017** implementation of an application-defined [sqlite3_os_init()].
2018**
2019** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
2020** ^If the option is unknown or SQLite is unable to set the option
2021** then this routine returns a non-zero [error code].
2022*/
2023SQLITE_API int sqlite3_config(int, ...);
2024
2025/*
2026** CAPI3REF: Configure database connections
2027** METHOD: sqlite3
2028**
2029** The sqlite3_db_config() interface is used to make configuration
2030** changes to a [database connection]. The interface is similar to
2031** [sqlite3_config()] except that the changes apply to a single
2032** [database connection] (specified in the first argument).
2033**
2034** The second argument to sqlite3_db_config(D,V,...) is the
2035** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
2036** that indicates what aspect of the [database connection] is being configured.
2037** Subsequent arguments vary depending on the configuration verb.
2038**
2039** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
2040** the call is considered successful.
2041*/
2042SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
2043
2044/*
2045** CAPI3REF: Memory Allocation Routines
2046**
2047** An instance of this object defines the interface between SQLite
2048** and low-level memory allocation routines.
2049**
2050** This object is used in only one place in the SQLite interface.
2051** A pointer to an instance of this object is the argument to
2052** [sqlite3_config()] when the configuration option is
2053** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
2054** By creating an instance of this object
2055** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
2056** during configuration, an application can specify an alternative
2057** memory allocation subsystem for SQLite to use for all of its
2058** dynamic memory needs.
2059**
2060** Note that SQLite comes with several [built-in memory allocators]
2061** that are perfectly adequate for the overwhelming majority of applications
2062** and that this object is only useful to a tiny minority of applications
2063** with specialized memory allocation requirements. This object is
2064** also used during testing of SQLite in order to specify an alternative
2065** memory allocator that simulates memory out-of-memory conditions in
2066** order to verify that SQLite recovers gracefully from such
2067** conditions.
2068**
2069** The xMalloc, xRealloc, and xFree methods must work like the
2070** malloc(), realloc() and free() functions from the standard C library.
2071** ^SQLite guarantees that the second argument to
2072** xRealloc is always a value returned by a prior call to xRoundup.
2073**
2074** xSize should return the allocated size of a memory allocation
2075** previously obtained from xMalloc or xRealloc. The allocated size
2076** is always at least as big as the requested size but may be larger.
2077**
2078** The xRoundup method returns what would be the allocated size of
2079** a memory allocation given a particular requested size. Most memory
2080** allocators round up memory allocations at least to the next multiple
2081** of 8. Some allocators round up to a larger multiple or to a power of 2.
2082** Every memory allocation request coming in through [sqlite3_malloc()]
2083** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
2084** that causes the corresponding memory allocation to fail.
2085**
2086** The xInit method initializes the memory allocator. For example,
2087** it might allocate any required mutexes or initialize internal data
2088** structures. The xShutdown method is invoked (indirectly) by
2089** [sqlite3_shutdown()] and should deallocate any resources acquired
2090** by xInit. The pAppData pointer is used as the only parameter to
2091** xInit and xShutdown.
2092**
2093** SQLite holds the [SQLITE_MUTEX_STATIC_MAIN] mutex when it invokes
2094** the xInit method, so the xInit method need not be threadsafe. The
2095** xShutdown method is only called from [sqlite3_shutdown()] so it does
2096** not need to be threadsafe either. For all other methods, SQLite
2097** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
2098** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
2099** it is by default) and so the methods are automatically serialized.
2100** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
2101** methods must be threadsafe or else make their own arrangements for
2102** serialization.
2103**
2104** SQLite will never invoke xInit() more than once without an intervening
2105** call to xShutdown().
2106*/
2107typedef struct sqlite3_mem_methods sqlite3_mem_methods;
2108struct sqlite3_mem_methods {
2109 void *(*xMalloc)(int); /* Memory allocation function */
2110 void (*xFree)(void*); /* Free a prior allocation */
2111 void *(*xRealloc)(void*,int); /* Resize an allocation */
2112 int (*xSize)(void*); /* Return the size of an allocation */
2113 int (*xRoundup)(int); /* Round up request size to allocation size */
2114 int (*xInit)(void*); /* Initialize the memory allocator */
2115 void (*xShutdown)(void*); /* Deinitialize the memory allocator */
2116 void *pAppData; /* Argument to xInit() and xShutdown() */
2117};
2118
2119/*
2120** CAPI3REF: Configuration Options
2121** KEYWORDS: {configuration option}
2122**
2123** These constants are the available integer configuration options that
2124** can be passed as the first argument to the [sqlite3_config()] interface.
2125**
2126** Most of the configuration options for sqlite3_config()
2127** will only work if invoked prior to [sqlite3_initialize()] or after
2128** [sqlite3_shutdown()]. The few exceptions to this rule are called
2129** "anytime configuration options".
2130** ^Calling [sqlite3_config()] with a first argument that is not an
2131** anytime configuration option in between calls to [sqlite3_initialize()] and
2132** [sqlite3_shutdown()] is a no-op that returns SQLITE_MISUSE.
2133**
2134** The set of anytime configuration options can change (by insertions
2135** and/or deletions) from one release of SQLite to the next.
2136** As of SQLite version 3.42.0, the complete set of anytime configuration
2137** options is:
2138** <ul>
2139** <li> SQLITE_CONFIG_LOG
2140** <li> SQLITE_CONFIG_PCACHE_HDRSZ
2141** </ul>
2142**
2143** New configuration options may be added in future releases of SQLite.
2144** Existing configuration options might be discontinued. Applications
2145** should check the return code from [sqlite3_config()] to make sure that
2146** the call worked. The [sqlite3_config()] interface will return a
2147** non-zero [error code] if a discontinued or unsupported configuration option
2148** is invoked.
2149**
2150** <dl>
2151** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
2152** <dd>There are no arguments to this option. ^This option sets the
2153** [threading mode] to Single-thread. In other words, it disables
2154** all mutexing and puts SQLite into a mode where it can only be used
2155** by a single thread. ^If SQLite is compiled with
2156** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2157** it is not possible to change the [threading mode] from its default
2158** value of Single-thread and so [sqlite3_config()] will return
2159** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
2160** configuration option.</dd>
2161**
2162** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
2163** <dd>There are no arguments to this option. ^This option sets the
2164** [threading mode] to Multi-thread. In other words, it disables
2165** mutexing on [database connection] and [prepared statement] objects.
2166** The application is responsible for serializing access to
2167** [database connections] and [prepared statements]. But other mutexes
2168** are enabled so that SQLite will be safe to use in a multi-threaded
2169** environment as long as no two threads attempt to use the same
2170** [database connection] at the same time. ^If SQLite is compiled with
2171** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2172** it is not possible to set the Multi-thread [threading mode] and
2173** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2174** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
2175**
2176** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
2177** <dd>There are no arguments to this option. ^This option sets the
2178** [threading mode] to Serialized. In other words, this option enables
2179** all mutexes including the recursive
2180** mutexes on [database connection] and [prepared statement] objects.
2181** In this mode (which is the default when SQLite is compiled with
2182** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
2183** to [database connections] and [prepared statements] so that the
2184** application is free to use the same [database connection] or the
2185** same [prepared statement] in different threads at the same time.
2186** ^If SQLite is compiled with
2187** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2188** it is not possible to set the Serialized [threading mode] and
2189** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2190** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
2191**
2192** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
2193** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
2194** a pointer to an instance of the [sqlite3_mem_methods] structure.
2195** The argument specifies
2196** alternative low-level memory allocation routines to be used in place of
2197** the memory allocation routines built into SQLite.)^ ^SQLite makes
2198** its own private copy of the content of the [sqlite3_mem_methods] structure
2199** before the [sqlite3_config()] call returns.</dd>
2200**
2201** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
2202** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
2203** is a pointer to an instance of the [sqlite3_mem_methods] structure.
2204** The [sqlite3_mem_methods]
2205** structure is filled with the currently defined memory allocation routines.)^
2206** This option can be used to overload the default memory allocation
2207** routines with a wrapper that simulations memory allocation failure or
2208** tracks memory usage, for example. </dd>
2209**
2210** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
2211** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
2212** type int, interpreted as a boolean, which if true provides a hint to
2213** SQLite that it should avoid large memory allocations if possible.
2214** SQLite will run faster if it is free to make large memory allocations,
2215** but some application might prefer to run slower in exchange for
2216** guarantees about memory fragmentation that are possible if large
2217** allocations are avoided. This hint is normally off.
2218** </dd>
2219**
2220** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
2221** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
2222** interpreted as a boolean, which enables or disables the collection of
2223** memory allocation statistics. ^(When memory allocation statistics are
2224** disabled, the following SQLite interfaces become non-operational:
2225** <ul>
2226** <li> [sqlite3_hard_heap_limit64()]
2227** <li> [sqlite3_memory_used()]
2228** <li> [sqlite3_memory_highwater()]
2229** <li> [sqlite3_soft_heap_limit64()]
2230** <li> [sqlite3_status64()]
2231** </ul>)^
2232** ^Memory allocation statistics are enabled by default unless SQLite is
2233** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
2234** allocation statistics are disabled by default.
2235** </dd>
2236**
2237** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
2238** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
2239** </dd>
2240**
2241** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
2242** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
2243** that SQLite can use for the database page cache with the default page
2244** cache implementation.
2245** This configuration option is a no-op if an application-defined page
2246** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
2247** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
2248** 8-byte aligned memory (pMem), the size of each page cache line (sz),
2249** and the number of cache lines (N).
2250** The sz argument should be the size of the largest database page
2251** (a power of two between 512 and 65536) plus some extra bytes for each
2252** page header. ^The number of extra bytes needed by the page header
2253** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
2254** ^It is harmless, apart from the wasted memory,
2255** for the sz parameter to be larger than necessary. The pMem
2256** argument must be either a NULL pointer or a pointer to an 8-byte
2257** aligned block of memory of at least sz*N bytes, otherwise
2258** subsequent behavior is undefined.
2259** ^When pMem is not NULL, SQLite will strive to use the memory provided
2260** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
2261** a page cache line is larger than sz bytes or if all of the pMem buffer
2262** is exhausted.
2263** ^If pMem is NULL and N is non-zero, then each database connection
2264** does an initial bulk allocation for page cache memory
2265** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
2266** of -1024*N bytes if N is negative, . ^If additional
2267** page cache memory is needed beyond what is provided by the initial
2268** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
2269** additional cache line. </dd>
2270**
2271** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2272** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
2273** that SQLite will use for all of its dynamic memory allocation needs
2274** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
2275** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
2276** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
2277** [SQLITE_ERROR] if invoked otherwise.
2278** ^There are three arguments to SQLITE_CONFIG_HEAP:
2279** An 8-byte aligned pointer to the memory,
2280** the number of bytes in the memory buffer, and the minimum allocation size.
2281** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2282** to using its default memory allocator (the system malloc() implementation),
2283** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
2284** memory pointer is not NULL then the alternative memory
2285** allocator is engaged to handle all of SQLites memory allocation needs.
2286** The first pointer (the memory pointer) must be aligned to an 8-byte
2287** boundary or subsequent behavior of SQLite will be undefined.
2288** The minimum allocation size is capped at 2**12. Reasonable values
2289** for the minimum allocation size are 2**5 through 2**8.</dd>
2290**
2291** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2292** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
2293** pointer to an instance of the [sqlite3_mutex_methods] structure.
2294** The argument specifies alternative low-level mutex routines to be used
2295** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
2296** the content of the [sqlite3_mutex_methods] structure before the call to
2297** [sqlite3_config()] returns. ^If SQLite is compiled with
2298** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2299** the entire mutexing subsystem is omitted from the build and hence calls to
2300** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2301** return [SQLITE_ERROR].</dd>
2302**
2303** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2304** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
2305** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
2306** [sqlite3_mutex_methods]
2307** structure is filled with the currently defined mutex routines.)^
2308** This option can be used to overload the default mutex allocation
2309** routines with a wrapper used to track mutex usage for performance
2310** profiling or testing, for example. ^If SQLite is compiled with
2311** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2312** the entire mutexing subsystem is omitted from the build and hence calls to
2313** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2314** return [SQLITE_ERROR].</dd>
2315**
2316** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2317** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
2318** the default size of [lookaside memory] on each [database connection].
2319** The first argument is the
2320** size of each lookaside buffer slot ("sz") and the second is the number of
2321** slots allocated to each database connection ("cnt").)^
2322** ^(SQLITE_CONFIG_LOOKASIDE sets the <i>default</i> lookaside size.
2323** The [SQLITE_DBCONFIG_LOOKASIDE] option to [sqlite3_db_config()] can
2324** be used to change the lookaside configuration on individual connections.)^
2325** The [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to change the
2326** default lookaside configuration at compile-time.
2327** </dd>
2328**
2329** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2330** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
2331** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
2332** the interface to a custom page cache implementation.)^
2333** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
2334**
2335** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2336** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
2337** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
2338** the current page cache implementation into that object.)^ </dd>
2339**
2340** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2341** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
2342** global [error log].
2343** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2344** function with a call signature of void(*)(void*,int,const char*),
2345** and a pointer to void. ^If the function pointer is not NULL, it is
2346** invoked by [sqlite3_log()] to process each logging event. ^If the
2347** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2348** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2349** passed through as the first parameter to the application-defined logger
2350** function whenever that function is invoked. ^The second parameter to
2351** the logger function is a copy of the first parameter to the corresponding
2352** [sqlite3_log()] call and is intended to be a [result code] or an
2353** [extended result code]. ^The third parameter passed to the logger is
2354** log message after formatting via [sqlite3_snprintf()].
2355** The SQLite logging interface is not reentrant; the logger function
2356** supplied by the application must not invoke any SQLite interface.
2357** In a multi-threaded application, the application-defined logger
2358** function must be threadsafe. </dd>
2359**
2360** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2361** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
2362** If non-zero, then URI handling is globally enabled. If the parameter is zero,
2363** then URI handling is globally disabled.)^ ^If URI handling is globally
2364** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
2365** [sqlite3_open16()] or
2366** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2367** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2368** connection is opened. ^If it is globally disabled, filenames are
2369** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2370** database connection is opened. ^(By default, URI handling is globally
2371** disabled. The default value may be changed by compiling with the
2372** [SQLITE_USE_URI] symbol defined.)^
2373**
2374** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2375** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
2376** argument which is interpreted as a boolean in order to enable or disable
2377** the use of covering indices for full table scans in the query optimizer.
2378** ^The default setting is determined
2379** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2380** if that compile-time option is omitted.
2381** The ability to disable the use of covering indices for full table scans
2382** is because some incorrectly coded legacy applications might malfunction
2383** when the optimization is enabled. Providing the ability to
2384** disable the optimization allows the older, buggy application code to work
2385** without change even with newer versions of SQLite.
2386**
2387** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2388** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2389** <dd> These options are obsolete and should not be used by new code.
2390** They are retained for backwards compatibility but are now no-ops.
2391** </dd>
2392**
2393** [[SQLITE_CONFIG_SQLLOG]]
2394** <dt>SQLITE_CONFIG_SQLLOG
2395** <dd>This option is only available if sqlite is compiled with the
2396** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2397** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2398** The second should be of type (void*). The callback is invoked by the library
2399** in three separate circumstances, identified by the value passed as the
2400** fourth parameter. If the fourth parameter is 0, then the database connection
2401** passed as the second argument has just been opened. The third argument
2402** points to a buffer containing the name of the main database file. If the
2403** fourth parameter is 1, then the SQL statement that the third parameter
2404** points to has just been executed. Or, if the fourth parameter is 2, then
2405** the connection being passed as the second parameter is being closed. The
2406** third parameter is passed NULL In this case. An example of using this
2407** configuration option can be seen in the "test_sqllog.c" source file in
2408** the canonical SQLite source tree.</dd>
2409**
2410** [[SQLITE_CONFIG_MMAP_SIZE]]
2411** <dt>SQLITE_CONFIG_MMAP_SIZE
2412** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2413** that are the default mmap size limit (the default setting for
2414** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2415** ^The default setting can be overridden by each database connection using
2416** either the [PRAGMA mmap_size] command, or by using the
2417** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
2418** will be silently truncated if necessary so that it does not exceed the
2419** compile-time maximum mmap size set by the
2420** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2421** ^If either argument to this option is negative, then that argument is
2422** changed to its compile-time default.
2423**
2424** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
2425** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
2426** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
2427** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2428** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2429** that specifies the maximum size of the created heap.
2430**
2431** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
2432** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
2433** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2434** is a pointer to an integer and writes into that integer the number of extra
2435** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2436** The amount of extra space required can change depending on the compiler,
2437** target platform, and SQLite version.
2438**
2439** [[SQLITE_CONFIG_PMASZ]]
2440** <dt>SQLITE_CONFIG_PMASZ
2441** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2442** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2443** sorter to that integer. The default minimum PMA Size is set by the
2444** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
2445** to help with sort operations when multithreaded sorting
2446** is enabled (using the [PRAGMA threads] command) and the amount of content
2447** to be sorted exceeds the page size times the minimum of the
2448** [PRAGMA cache_size] setting and this value.
2449**
2450** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
2451** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
2452** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
2453** becomes the [statement journal] spill-to-disk threshold.
2454** [Statement journals] are held in memory until their size (in bytes)
2455** exceeds this threshold, at which point they are written to disk.
2456** Or if the threshold is -1, statement journals are always held
2457** exclusively in memory.
2458** Since many statement journals never become large, setting the spill
2459** threshold to a value such as 64KiB can greatly reduce the amount of
2460** I/O required to support statement rollback.
2461** The default value for this setting is controlled by the
2462** [SQLITE_STMTJRNL_SPILL] compile-time option.
2463**
2464** [[SQLITE_CONFIG_SORTERREF_SIZE]]
2465** <dt>SQLITE_CONFIG_SORTERREF_SIZE
2466** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter
2467** of type (int) - the new value of the sorter-reference size threshold.
2468** Usually, when SQLite uses an external sort to order records according
2469** to an ORDER BY clause, all fields required by the caller are present in the
2470** sorted records. However, if SQLite determines based on the declared type
2471** of a table column that its values are likely to be very large - larger
2472** than the configured sorter-reference size threshold - then a reference
2473** is stored in each sorted record and the required column values loaded
2474** from the database as records are returned in sorted order. The default
2475** value for this option is to never use this optimization. Specifying a
2476** negative value for this option restores the default behavior.
2477** This option is only available if SQLite is compiled with the
2478** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
2479**
2480** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]
2481** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE
2482** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter
2483** [sqlite3_int64] parameter which is the default maximum size for an in-memory
2484** database created using [sqlite3_deserialize()]. This default maximum
2485** size can be adjusted up or down for individual databases using the
2486** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control]. If this
2487** configuration setting is never used, then the default maximum is determined
2488** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that
2489** compile-time option is not set, then the default maximum is 1073741824.
2490**
2491** [[SQLITE_CONFIG_ROWID_IN_VIEW]]
2492** <dt>SQLITE_CONFIG_ROWID_IN_VIEW
2493** <dd>The SQLITE_CONFIG_ROWID_IN_VIEW option enables or disables the ability
2494** for VIEWs to have a ROWID. The capability can only be enabled if SQLite is
2495** compiled with -DSQLITE_ALLOW_ROWID_IN_VIEW, in which case the capability
2496** defaults to on. This configuration option queries the current setting or
2497** changes the setting to off or on. The argument is a pointer to an integer.
2498** If that integer initially holds a value of 1, then the ability for VIEWs to
2499** have ROWIDs is activated. If the integer initially holds zero, then the
2500** ability is deactivated. Any other initial value for the integer leaves the
2501** setting unchanged. After changes, if any, the integer is written with
2502** a 1 or 0, if the ability for VIEWs to have ROWIDs is on or off. If SQLite
2503** is compiled without -DSQLITE_ALLOW_ROWID_IN_VIEW (which is the usual and
2504** recommended case) then the integer is always filled with zero, regardless
2505** if its initial value.
2506** </dl>
2507*/
2508#define SQLITE_CONFIG_SINGLETHREAD1 1 /* nil */
2509#define SQLITE_CONFIG_MULTITHREAD2 2 /* nil */
2510#define SQLITE_CONFIG_SERIALIZED3 3 /* nil */
2511#define SQLITE_CONFIG_MALLOC4 4 /* sqlite3_mem_methods* */
2512#define SQLITE_CONFIG_GETMALLOC5 5 /* sqlite3_mem_methods* */
2513#define SQLITE_CONFIG_SCRATCH6 6 /* No longer used */
2514#define SQLITE_CONFIG_PAGECACHE7 7 /* void*, int sz, int N */
2515#define SQLITE_CONFIG_HEAP8 8 /* void*, int nByte, int min */
2516#define SQLITE_CONFIG_MEMSTATUS9 9 /* boolean */
2517#define SQLITE_CONFIG_MUTEX10 10 /* sqlite3_mutex_methods* */
2518#define SQLITE_CONFIG_GETMUTEX11 11 /* sqlite3_mutex_methods* */
2519/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2520#define SQLITE_CONFIG_LOOKASIDE13 13 /* int int */
2521#define SQLITE_CONFIG_PCACHE14 14 /* no-op */
2522#define SQLITE_CONFIG_GETPCACHE15 15 /* no-op */
2523#define SQLITE_CONFIG_LOG16 16 /* xFunc, void* */
2524#define SQLITE_CONFIG_URI17 17 /* int */
2525#define SQLITE_CONFIG_PCACHE218 18 /* sqlite3_pcache_methods2* */
2526#define SQLITE_CONFIG_GETPCACHE219 19 /* sqlite3_pcache_methods2* */
2527#define SQLITE_CONFIG_COVERING_INDEX_SCAN20 20 /* int */
2528#define SQLITE_CONFIG_SQLLOG21 21 /* xSqllog, void* */
2529#define SQLITE_CONFIG_MMAP_SIZE22 22 /* sqlite3_int64, sqlite3_int64 */
2530#define SQLITE_CONFIG_WIN32_HEAPSIZE23 23 /* int nByte */
2531#define SQLITE_CONFIG_PCACHE_HDRSZ24 24 /* int *psz */
2532#define SQLITE_CONFIG_PMASZ25 25 /* unsigned int szPma */
2533#define SQLITE_CONFIG_STMTJRNL_SPILL26 26 /* int nByte */
2534#define SQLITE_CONFIG_SMALL_MALLOC27 27 /* boolean */
2535#define SQLITE_CONFIG_SORTERREF_SIZE28 28 /* int nByte */
2536#define SQLITE_CONFIG_MEMDB_MAXSIZE29 29 /* sqlite3_int64 */
2537#define SQLITE_CONFIG_ROWID_IN_VIEW30 30 /* int* */
2538
2539/*
2540** CAPI3REF: Database Connection Configuration Options
2541**
2542** These constants are the available integer configuration options that
2543** can be passed as the second parameter to the [sqlite3_db_config()] interface.
2544**
2545** The [sqlite3_db_config()] interface is a var-args functions. It takes a
2546** variable number of parameters, though always at least two. The number of
2547** parameters passed into sqlite3_db_config() depends on which of these
2548** constants is given as the second parameter. This documentation page
2549** refers to parameters beyond the second as "arguments". Thus, when this
2550** page says "the N-th argument" it means "the N-th parameter past the
2551** configuration option" or "the (N+2)-th parameter to sqlite3_db_config()".
2552**
2553** New configuration options may be added in future releases of SQLite.
2554** Existing configuration options might be discontinued. Applications
2555** should check the return code from [sqlite3_db_config()] to make sure that
2556** the call worked. ^The [sqlite3_db_config()] interface will return a
2557** non-zero [error code] if a discontinued or unsupported configuration option
2558** is invoked.
2559**
2560** <dl>
2561** [[SQLITE_DBCONFIG_LOOKASIDE]]
2562** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2563** <dd> The SQLITE_DBCONFIG_LOOKASIDE option is used to adjust the
2564** configuration of the [lookaside memory allocator] within a database
2565** connection.
2566** The arguments to the SQLITE_DBCONFIG_LOOKASIDE option are <i>not</i>
2567** in the [DBCONFIG arguments|usual format].
2568** The SQLITE_DBCONFIG_LOOKASIDE option takes three arguments, not two,
2569** so that a call to [sqlite3_db_config()] that uses SQLITE_DBCONFIG_LOOKASIDE
2570** should have a total of five parameters.
2571** <ol>
2572** <li><p>The first argument ("buf") is a
2573** pointer to a memory buffer to use for lookaside memory.
2574** The first argument may be NULL in which case SQLite will allocate the
2575** lookaside buffer itself using [sqlite3_malloc()].
2576** <li><P>The second argument ("sz") is the
2577** size of each lookaside buffer slot. Lookaside is disabled if "sz"
2578** is less than 8. The "sz" argument should be a multiple of 8 less than
2579** 65536. If "sz" does not meet this constraint, it is reduced in size until
2580** it does.
2581** <li><p>The third argument ("cnt") is the number of slots. Lookaside is disabled
2582** if "cnt"is less than 1. The "cnt" value will be reduced, if necessary, so
2583** that the product of "sz" and "cnt" does not exceed 2,147,418,112. The "cnt"
2584** parameter is usually chosen so that the product of "sz" and "cnt" is less
2585** than 1,000,000.
2586** </ol>
2587** <p>If the "buf" argument is not NULL, then it must
2588** point to a memory buffer with a size that is greater than
2589** or equal to the product of "sz" and "cnt".
2590** The buffer must be aligned to an 8-byte boundary.
2591** The lookaside memory
2592** configuration for a database connection can only be changed when that
2593** connection is not currently using lookaside memory, or in other words
2594** when the value returned by [SQLITE_DBSTATUS_LOOKASIDE_USED] is zero.
2595** Any attempt to change the lookaside memory configuration when lookaside
2596** memory is in use leaves the configuration unchanged and returns
2597** [SQLITE_BUSY].
2598** If the "buf" argument is NULL and an attempt
2599** to allocate memory based on "sz" and "cnt" fails, then
2600** lookaside is silently disabled.
2601** <p>
2602** The [SQLITE_CONFIG_LOOKASIDE] configuration option can be used to set the
2603** default lookaside configuration at initialization. The
2604** [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to set the default lookaside
2605** configuration at compile-time. Typical values for lookaside are 1200 for
2606** "sz" and 40 to 100 for "cnt".
2607** </dd>
2608**
2609** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
2610** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2611** <dd> ^This option is used to enable or disable the enforcement of
2612** [foreign key constraints]. This is the same setting that is
2613** enabled or disabled by the [PRAGMA foreign_keys] statement.
2614** The first argument is an integer which is 0 to disable FK enforcement,
2615** positive to enable FK enforcement or negative to leave FK enforcement
2616** unchanged. The second parameter is a pointer to an integer into which
2617** is written 0 or 1 to indicate whether FK enforcement is off or on
2618** following this call. The second parameter may be a NULL pointer, in
2619** which case the FK enforcement setting is not reported back. </dd>
2620**
2621** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]
2622** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2623** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2624** There should be two additional arguments.
2625** The first argument is an integer which is 0 to disable triggers,
2626** positive to enable triggers or negative to leave the setting unchanged.
2627** The second parameter is a pointer to an integer into which
2628** is written 0 or 1 to indicate whether triggers are disabled or enabled
2629** following this call. The second parameter may be a NULL pointer, in
2630** which case the trigger setting is not reported back.
2631**
2632** <p>Originally this option disabled all triggers. ^(However, since
2633** SQLite version 3.35.0, TEMP triggers are still allowed even if
2634** this option is off. So, in other words, this option now only disables
2635** triggers in the main database schema or in the schemas of [ATTACH]-ed
2636** databases.)^ </dd>
2637**
2638** [[SQLITE_DBCONFIG_ENABLE_VIEW]]
2639** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt>
2640** <dd> ^This option is used to enable or disable [CREATE VIEW | views].
2641** There must be two additional arguments.
2642** The first argument is an integer which is 0 to disable views,
2643** positive to enable views or negative to leave the setting unchanged.
2644** The second parameter is a pointer to an integer into which
2645** is written 0 or 1 to indicate whether views are disabled or enabled
2646** following this call. The second parameter may be a NULL pointer, in
2647** which case the view setting is not reported back.
2648**
2649** <p>Originally this option disabled all views. ^(However, since
2650** SQLite version 3.35.0, TEMP views are still allowed even if
2651** this option is off. So, in other words, this option now only disables
2652** views in the main database schema or in the schemas of ATTACH-ed
2653** databases.)^ </dd>
2654**
2655** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
2656** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
2657** <dd> ^This option is used to enable or disable the
2658** [fts3_tokenizer()] function which is part of the
2659** [FTS3] full-text search engine extension.
2660** There must be two additional arguments.
2661** The first argument is an integer which is 0 to disable fts3_tokenizer() or
2662** positive to enable fts3_tokenizer() or negative to leave the setting
2663** unchanged.
2664** The second parameter is a pointer to an integer into which
2665** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
2666** following this call. The second parameter may be a NULL pointer, in
2667** which case the new setting is not reported back. </dd>
2668**
2669** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]
2670** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
2671** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
2672** interface independently of the [load_extension()] SQL function.
2673** The [sqlite3_enable_load_extension()] API enables or disables both the
2674** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2675** There must be two additional arguments.
2676** When the first argument to this interface is 1, then only the C-API is
2677** enabled and the SQL function remains disabled. If the first argument to
2678** this interface is 0, then both the C-API and the SQL function are disabled.
2679** If the first argument is -1, then no changes are made to state of either the
2680** C-API or the SQL function.
2681** The second parameter is a pointer to an integer into which
2682** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
2683** is disabled or enabled following this call. The second parameter may
2684** be a NULL pointer, in which case the new setting is not reported back.
2685** </dd>
2686**
2687** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
2688** <dd> ^This option is used to change the name of the "main" database
2689** schema. This option does not follow the
2690** [DBCONFIG arguments|usual SQLITE_DBCONFIG argument format].
2691** This option takes exactly one additional argument so that the
2692** [sqlite3_db_config()] call has a total of three parameters. The
2693** extra argument must be a pointer to a constant UTF8 string which
2694** will become the new schema name in place of "main". ^SQLite does
2695** not make a copy of the new main schema name string, so the application
2696** must ensure that the argument passed into SQLITE_DBCONFIG MAINDBNAME
2697** is unchanged until after the database connection closes.
2698** </dd>
2699**
2700** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]
2701** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
2702** <dd> Usually, when a database in [WAL mode] is closed or detached from a
2703** database handle, SQLite checks if if there are other connections to the
2704** same database, and if there are no other database connection (if the
2705** connection being closed is the last open connection to the database),
2706** then SQLite performs a [checkpoint] before closing the connection and
2707** deletes the WAL file. The SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE option can
2708** be used to override that behavior. The first argument passed to this
2709** operation (the third parameter to [sqlite3_db_config()]) is an integer
2710** which is positive to disable checkpoints-on-close, or zero (the default)
2711** to enable them, and negative to leave the setting unchanged.
2712** The second argument (the fourth parameter) is a pointer to an integer
2713** into which is written 0 or 1 to indicate whether checkpoints-on-close
2714** have been disabled - 0 if they are not disabled, 1 if they are.
2715** </dd>
2716**
2717** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
2718** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
2719** the [query planner stability guarantee] (QPSG). When the QPSG is active,
2720** a single SQL query statement will always use the same algorithm regardless
2721** of values of [bound parameters].)^ The QPSG disables some query optimizations
2722** that look at the values of bound parameters, which can make some queries
2723** slower. But the QPSG has the advantage of more predictable behavior. With
2724** the QPSG active, SQLite will always use the same query plan in the field as
2725** was used during testing in the lab.
2726** The first argument to this setting is an integer which is 0 to disable
2727** the QPSG, positive to enable QPSG, or negative to leave the setting
2728** unchanged. The second parameter is a pointer to an integer into which
2729** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
2730** following this call.
2731** </dd>
2732**
2733** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
2734** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
2735** include output for any operations performed by trigger programs. This
2736** option is used to set or clear (the default) a flag that governs this
2737** behavior. The first parameter passed to this operation is an integer -
2738** positive to enable output for trigger programs, or zero to disable it,
2739** or negative to leave the setting unchanged.
2740** The second parameter is a pointer to an integer into which is written
2741** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
2742** it is not disabled, 1 if it is.
2743** </dd>
2744**
2745** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
2746** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
2747** [VACUUM] in order to reset a database back to an empty database
2748** with no schema and no content. The following process works even for
2749** a badly corrupted database file:
2750** <ol>
2751** <li> If the database connection is newly opened, make sure it has read the
2752** database schema by preparing then discarding some query against the
2753** database, or calling sqlite3_table_column_metadata(), ignoring any
2754** errors. This step is only necessary if the application desires to keep
2755** the database in WAL mode after the reset if it was in WAL mode before
2756** the reset.
2757** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
2758** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
2759** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
2760** </ol>
2761** Because resetting a database is destructive and irreversible, the
2762** process requires the use of this obscure API and multiple steps to
2763** help ensure that it does not happen by accident. Because this
2764** feature must be capable of resetting corrupt databases, and
2765** shutting down virtual tables may require access to that corrupt
2766** storage, the library must abandon any installed virtual tables
2767** without calling their xDestroy() methods.
2768**
2769** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
2770** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
2771** "defensive" flag for a database connection. When the defensive
2772** flag is enabled, language features that allow ordinary SQL to
2773** deliberately corrupt the database file are disabled. The disabled
2774** features include but are not limited to the following:
2775** <ul>
2776** <li> The [PRAGMA writable_schema=ON] statement.
2777** <li> The [PRAGMA journal_mode=OFF] statement.
2778** <li> The [PRAGMA schema_version=N] statement.
2779** <li> Writes to the [sqlite_dbpage] virtual table.
2780** <li> Direct writes to [shadow tables].
2781** </ul>
2782** </dd>
2783**
2784** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt>
2785** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the
2786** "writable_schema" flag. This has the same effect and is logically equivalent
2787** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].
2788** The first argument to this setting is an integer which is 0 to disable
2789** the writable_schema, positive to enable writable_schema, or negative to
2790** leave the setting unchanged. The second parameter is a pointer to an
2791** integer into which is written 0 or 1 to indicate whether the writable_schema
2792** is enabled or disabled following this call.
2793** </dd>
2794**
2795** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]
2796** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt>
2797** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates
2798** the legacy behavior of the [ALTER TABLE RENAME] command such it
2799** behaves as it did prior to [version 3.24.0] (2018-06-04). See the
2800** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for
2801** additional information. This feature can also be turned on and off
2802** using the [PRAGMA legacy_alter_table] statement.
2803** </dd>
2804**
2805** [[SQLITE_DBCONFIG_DQS_DML]]
2806** <dt>SQLITE_DBCONFIG_DQS_DML</dt>
2807** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
2808** the legacy [double-quoted string literal] misfeature for DML statements
2809** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
2810** default value of this setting is determined by the [-DSQLITE_DQS]
2811** compile-time option.
2812** </dd>
2813**
2814** [[SQLITE_DBCONFIG_DQS_DDL]]
2815** <dt>SQLITE_DBCONFIG_DQS_DDL</dt>
2816** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates
2817** the legacy [double-quoted string literal] misfeature for DDL statements,
2818** such as CREATE TABLE and CREATE INDEX. The
2819** default value of this setting is determined by the [-DSQLITE_DQS]
2820** compile-time option.
2821** </dd>
2822**
2823** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]
2824** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</dt>
2825** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
2826** assume that database schemas are untainted by malicious content.
2827** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
2828** takes additional defensive steps to protect the application from harm
2829** including:
2830** <ul>
2831** <li> Prohibit the use of SQL functions inside triggers, views,
2832** CHECK constraints, DEFAULT clauses, expression indexes,
2833** partial indexes, or generated columns
2834** unless those functions are tagged with [SQLITE_INNOCUOUS].
2835** <li> Prohibit the use of virtual tables inside of triggers or views
2836** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].
2837** </ul>
2838** This setting defaults to "on" for legacy compatibility, however
2839** all applications are advised to turn it off if possible. This setting
2840** can also be controlled using the [PRAGMA trusted_schema] statement.
2841** </dd>
2842**
2843** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]
2844** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</dt>
2845** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
2846** the legacy file format flag. When activated, this flag causes all newly
2847** created database file to have a schema format version number (the 4-byte
2848** integer found at offset 44 into the database header) of 1. This in turn
2849** means that the resulting database file will be readable and writable by
2850** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting,
2851** newly created databases are generally not understandable by SQLite versions
2852** prior to 3.3.0 ([dateof:3.3.0]). As these words are written, there
2853** is now scarcely any need to generate database files that are compatible
2854** all the way back to version 3.0.0, and so this setting is of little
2855** practical use, but is provided so that SQLite can continue to claim the
2856** ability to generate new database files that are compatible with version
2857** 3.0.0.
2858** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
2859** the [VACUUM] command will fail with an obscure error when attempting to
2860** process a table with generated columns and a descending index. This is
2861** not considered a bug since SQLite versions 3.3.0 and earlier do not support
2862** either generated columns or descending indexes.
2863** </dd>
2864**
2865** [[SQLITE_DBCONFIG_STMT_SCANSTATUS]]
2866** <dt>SQLITE_DBCONFIG_STMT_SCANSTATUS</dt>
2867** <dd>The SQLITE_DBCONFIG_STMT_SCANSTATUS option is only useful in
2868** SQLITE_ENABLE_STMT_SCANSTATUS builds. In this case, it sets or clears
2869** a flag that enables collection of the sqlite3_stmt_scanstatus_v2()
2870** statistics. For statistics to be collected, the flag must be set on
2871** the database handle both when the SQL statement is prepared and when it
2872** is stepped. The flag is set (collection of statistics is enabled)
2873** by default. <p>This option takes two arguments: an integer and a pointer to
2874** an integer.. The first argument is 1, 0, or -1 to enable, disable, or
2875** leave unchanged the statement scanstatus option. If the second argument
2876** is not NULL, then the value of the statement scanstatus setting after
2877** processing the first argument is written into the integer that the second
2878** argument points to.
2879** </dd>
2880**
2881** [[SQLITE_DBCONFIG_REVERSE_SCANORDER]]
2882** <dt>SQLITE_DBCONFIG_REVERSE_SCANORDER</dt>
2883** <dd>The SQLITE_DBCONFIG_REVERSE_SCANORDER option changes the default order
2884** in which tables and indexes are scanned so that the scans start at the end
2885** and work toward the beginning rather than starting at the beginning and
2886** working toward the end. Setting SQLITE_DBCONFIG_REVERSE_SCANORDER is the
2887** same as setting [PRAGMA reverse_unordered_selects]. <p>This option takes
2888** two arguments which are an integer and a pointer to an integer. The first
2889** argument is 1, 0, or -1 to enable, disable, or leave unchanged the
2890** reverse scan order flag, respectively. If the second argument is not NULL,
2891** then 0 or 1 is written into the integer that the second argument points to
2892** depending on if the reverse scan order flag is set after processing the
2893** first argument.
2894** </dd>
2895**
2896** [[SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE]]
2897** <dt>SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE</dt>
2898** <dd>The SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE option enables or disables
2899** the ability of the [ATTACH DATABASE] SQL command to create a new database
2900** file if the database filed named in the ATTACH command does not already
2901** exist. This ability of ATTACH to create a new database is enabled by
2902** default. Applications can disable or reenable the ability for ATTACH to
2903** create new database files using this DBCONFIG option.<p>
2904** This option takes two arguments which are an integer and a pointer
2905** to an integer. The first argument is 1, 0, or -1 to enable, disable, or
2906** leave unchanged the attach-create flag, respectively. If the second
2907** argument is not NULL, then 0 or 1 is written into the integer that the
2908** second argument points to depending on if the attach-create flag is set
2909** after processing the first argument.
2910** </dd>
2911**
2912** [[SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE]]
2913** <dt>SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE</dt>
2914** <dd>The SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE option enables or disables the
2915** ability of the [ATTACH DATABASE] SQL command to open a database for writing.
2916** This capability is enabled by default. Applications can disable or
2917** reenable this capability using the current DBCONFIG option. If the
2918** the this capability is disabled, the [ATTACH] command will still work,
2919** but the database will be opened read-only. If this option is disabled,
2920** then the ability to create a new database using [ATTACH] is also disabled,
2921** regardless of the value of the [SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE]
2922** option.<p>
2923** This option takes two arguments which are an integer and a pointer
2924** to an integer. The first argument is 1, 0, or -1 to enable, disable, or
2925** leave unchanged the ability to ATTACH another database for writing,
2926** respectively. If the second argument is not NULL, then 0 or 1 is written
2927** into the integer to which the second argument points, depending on whether
2928** the ability to ATTACH a read/write database is enabled or disabled
2929** after processing the first argument.
2930** </dd>
2931**
2932** [[SQLITE_DBCONFIG_ENABLE_COMMENTS]]
2933** <dt>SQLITE_DBCONFIG_ENABLE_COMMENTS</dt>
2934** <dd>The SQLITE_DBCONFIG_ENABLE_COMMENTS option enables or disables the
2935** ability to include comments in SQL text. Comments are enabled by default.
2936** An application can disable or reenable comments in SQL text using this
2937** DBCONFIG option.<p>
2938** This option takes two arguments which are an integer and a pointer
2939** to an integer. The first argument is 1, 0, or -1 to enable, disable, or
2940** leave unchanged the ability to use comments in SQL text,
2941** respectively. If the second argument is not NULL, then 0 or 1 is written
2942** into the integer that the second argument points to depending on if
2943** comments are allowed in SQL text after processing the first argument.
2944** </dd>
2945**
2946** </dl>
2947**
2948** [[DBCONFIG arguments]] <h3>Arguments To SQLITE_DBCONFIG Options</h3>
2949**
2950** <p>Most of the SQLITE_DBCONFIG options take two arguments, so that the
2951** overall call to [sqlite3_db_config()] has a total of four parameters.
2952** The first argument (the third parameter to sqlite3_db_config()) is a integer.
2953** The second argument is a pointer to an integer. If the first argument is 1,
2954** then the option becomes enabled. If the first integer argument is 0, then the
2955** option is disabled. If the first argument is -1, then the option setting
2956** is unchanged. The second argument, the pointer to an integer, may be NULL.
2957** If the second argument is not NULL, then a value of 0 or 1 is written into
2958** the integer to which the second argument points, depending on whether the
2959** setting is disabled or enabled after applying any changes specified by
2960** the first argument.
2961**
2962** <p>While most SQLITE_DBCONFIG options use the argument format
2963** described in the previous paragraph, the [SQLITE_DBCONFIG_MAINDBNAME]
2964** and [SQLITE_DBCONFIG_LOOKASIDE] options are different. See the
2965** documentation of those exceptional options for details.
2966*/
2967#define SQLITE_DBCONFIG_MAINDBNAME1000 1000 /* const char* */
2968#define SQLITE_DBCONFIG_LOOKASIDE1001 1001 /* void* int int */
2969#define SQLITE_DBCONFIG_ENABLE_FKEY1002 1002 /* int int* */
2970#define SQLITE_DBCONFIG_ENABLE_TRIGGER1003 1003 /* int int* */
2971#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER1004 1004 /* int int* */
2972#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION1005 1005 /* int int* */
2973#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE1006 1006 /* int int* */
2974#define SQLITE_DBCONFIG_ENABLE_QPSG1007 1007 /* int int* */
2975#define SQLITE_DBCONFIG_TRIGGER_EQP1008 1008 /* int int* */
2976#define SQLITE_DBCONFIG_RESET_DATABASE1009 1009 /* int int* */
2977#define SQLITE_DBCONFIG_DEFENSIVE1010 1010 /* int int* */
2978#define SQLITE_DBCONFIG_WRITABLE_SCHEMA1011 1011 /* int int* */
2979#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE1012 1012 /* int int* */
2980#define SQLITE_DBCONFIG_DQS_DML1013 1013 /* int int* */
2981#define SQLITE_DBCONFIG_DQS_DDL1014 1014 /* int int* */
2982#define SQLITE_DBCONFIG_ENABLE_VIEW1015 1015 /* int int* */
2983#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT1016 1016 /* int int* */
2984#define SQLITE_DBCONFIG_TRUSTED_SCHEMA1017 1017 /* int int* */
2985#define SQLITE_DBCONFIG_STMT_SCANSTATUS1018 1018 /* int int* */
2986#define SQLITE_DBCONFIG_REVERSE_SCANORDER1019 1019 /* int int* */
2987#define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE1020 1020 /* int int* */
2988#define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE1021 1021 /* int int* */
2989#define SQLITE_DBCONFIG_ENABLE_COMMENTS1022 1022 /* int int* */
2990#define SQLITE_DBCONFIG_MAX1022 1022 /* Largest DBCONFIG */
2991
2992/*
2993** CAPI3REF: Enable Or Disable Extended Result Codes
2994** METHOD: sqlite3
2995**
2996** ^The sqlite3_extended_result_codes() routine enables or disables the
2997** [extended result codes] feature of SQLite. ^The extended result
2998** codes are disabled by default for historical compatibility.
2999*/
3000SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
3001
3002/*
3003** CAPI3REF: Last Insert Rowid
3004** METHOD: sqlite3
3005**
3006** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
3007** has a unique 64-bit signed
3008** integer key called the [ROWID | "rowid"]. ^The rowid is always available
3009** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
3010** names are not also used by explicitly declared columns. ^If
3011** the table has a column of type [INTEGER PRIMARY KEY] then that column
3012** is another alias for the rowid.
3013**
3014** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
3015** the most recent successful [INSERT] into a rowid table or [virtual table]
3016** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
3017** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
3018** on the database connection D, then sqlite3_last_insert_rowid(D) returns
3019** zero.
3020**
3021** As well as being set automatically as rows are inserted into database
3022** tables, the value returned by this function may be set explicitly by
3023** [sqlite3_set_last_insert_rowid()]
3024**
3025** Some virtual table implementations may INSERT rows into rowid tables as
3026** part of committing a transaction (e.g. to flush data accumulated in memory
3027** to disk). In this case subsequent calls to this function return the rowid
3028** associated with these internal INSERT operations, which leads to
3029** unintuitive results. Virtual table implementations that do write to rowid
3030** tables in this way can avoid this problem by restoring the original
3031** rowid value using [sqlite3_set_last_insert_rowid()] before returning
3032** control to the user.
3033**
3034** ^(If an [INSERT] occurs within a trigger then this routine will
3035** return the [rowid] of the inserted row as long as the trigger is
3036** running. Once the trigger program ends, the value returned
3037** by this routine reverts to what it was before the trigger was fired.)^
3038**
3039** ^An [INSERT] that fails due to a constraint violation is not a
3040** successful [INSERT] and does not change the value returned by this
3041** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
3042** and INSERT OR ABORT make no changes to the return value of this
3043** routine when their insertion fails. ^(When INSERT OR REPLACE
3044** encounters a constraint violation, it does not fail. The
3045** INSERT continues to completion after deleting rows that caused
3046** the constraint problem so INSERT OR REPLACE will always change
3047** the return value of this interface.)^
3048**
3049** ^For the purposes of this routine, an [INSERT] is considered to
3050** be successful even if it is subsequently rolled back.
3051**
3052** This function is accessible to SQL statements via the
3053** [last_insert_rowid() SQL function].
3054**
3055** If a separate thread performs a new [INSERT] on the same
3056** database connection while the [sqlite3_last_insert_rowid()]
3057** function is running and thus changes the last insert [rowid],
3058** then the value returned by [sqlite3_last_insert_rowid()] is
3059** unpredictable and might not equal either the old or the new
3060** last insert [rowid].
3061*/
3062SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
3063
3064/*
3065** CAPI3REF: Set the Last Insert Rowid value.
3066** METHOD: sqlite3
3067**
3068** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
3069** set the value returned by calling sqlite3_last_insert_rowid(D) to R
3070** without inserting a row into the database.
3071*/
3072SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
3073
3074/*
3075** CAPI3REF: Count The Number Of Rows Modified
3076** METHOD: sqlite3
3077**
3078** ^These functions return the number of rows modified, inserted or
3079** deleted by the most recently completed INSERT, UPDATE or DELETE
3080** statement on the database connection specified by the only parameter.
3081** The two functions are identical except for the type of the return value
3082** and that if the number of rows modified by the most recent INSERT, UPDATE,
3083** or DELETE is greater than the maximum value supported by type "int", then
3084** the return value of sqlite3_changes() is undefined. ^Executing any other
3085** type of SQL statement does not modify the value returned by these functions.
3086** For the purposes of this interface, a CREATE TABLE AS SELECT statement
3087** does not count as an INSERT, UPDATE or DELETE statement and hence the rows
3088** added to the new table by the CREATE TABLE AS SELECT statement are not
3089** counted.
3090**
3091** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
3092** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
3093** [foreign key actions] or [REPLACE] constraint resolution are not counted.
3094**
3095** Changes to a view that are intercepted by
3096** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
3097** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
3098** DELETE statement run on a view is always zero. Only changes made to real
3099** tables are counted.
3100**
3101** Things are more complicated if the sqlite3_changes() function is
3102** executed while a trigger program is running. This may happen if the
3103** program uses the [changes() SQL function], or if some other callback
3104** function invokes sqlite3_changes() directly. Essentially:
3105**
3106** <ul>
3107** <li> ^(Before entering a trigger program the value returned by
3108** sqlite3_changes() function is saved. After the trigger program
3109** has finished, the original value is restored.)^
3110**
3111** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
3112** statement sets the value returned by sqlite3_changes()
3113** upon completion as normal. Of course, this value will not include
3114** any changes performed by sub-triggers, as the sqlite3_changes()
3115** value will be saved and restored after each sub-trigger has run.)^
3116** </ul>
3117**
3118** ^This means that if the changes() SQL function (or similar) is used
3119** by the first INSERT, UPDATE or DELETE statement within a trigger, it
3120** returns the value as set when the calling statement began executing.
3121** ^If it is used by the second or subsequent such statement within a trigger
3122** program, the value returned reflects the number of rows modified by the
3123** previous INSERT, UPDATE or DELETE statement within the same trigger.
3124**
3125** If a separate thread makes changes on the same database connection
3126** while [sqlite3_changes()] is running then the value returned
3127** is unpredictable and not meaningful.
3128**
3129** See also:
3130** <ul>
3131** <li> the [sqlite3_total_changes()] interface
3132** <li> the [count_changes pragma]
3133** <li> the [changes() SQL function]
3134** <li> the [data_version pragma]
3135** </ul>
3136*/
3137SQLITE_API int sqlite3_changes(sqlite3*);
3138SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3*);
3139
3140/*
3141** CAPI3REF: Total Number Of Rows Modified
3142** METHOD: sqlite3
3143**
3144** ^These functions return the total number of rows inserted, modified or
3145** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
3146** since the database connection was opened, including those executed as
3147** part of trigger programs. The two functions are identical except for the
3148** type of the return value and that if the number of rows modified by the
3149** connection exceeds the maximum value supported by type "int", then
3150** the return value of sqlite3_total_changes() is undefined. ^Executing
3151** any other type of SQL statement does not affect the value returned by
3152** sqlite3_total_changes().
3153**
3154** ^Changes made as part of [foreign key actions] are included in the
3155** count, but those made as part of REPLACE constraint resolution are
3156** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
3157** are not counted.
3158**
3159** The [sqlite3_total_changes(D)] interface only reports the number
3160** of rows that changed due to SQL statement run against database
3161** connection D. Any changes by other database connections are ignored.
3162** To detect changes against a database file from other database
3163** connections use the [PRAGMA data_version] command or the
3164** [SQLITE_FCNTL_DATA_VERSION] [file control].
3165**
3166** If a separate thread makes changes on the same database connection
3167** while [sqlite3_total_changes()] is running then the value
3168** returned is unpredictable and not meaningful.
3169**
3170** See also:
3171** <ul>
3172** <li> the [sqlite3_changes()] interface
3173** <li> the [count_changes pragma]
3174** <li> the [changes() SQL function]
3175** <li> the [data_version pragma]
3176** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]
3177** </ul>
3178*/
3179SQLITE_API int sqlite3_total_changes(sqlite3*);
3180SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3*);
3181
3182/*
3183** CAPI3REF: Interrupt A Long-Running Query
3184** METHOD: sqlite3
3185**
3186** ^This function causes any pending database operation to abort and
3187** return at its earliest opportunity. This routine is typically
3188** called in response to a user action such as pressing "Cancel"
3189** or Ctrl-C where the user wants a long query operation to halt
3190** immediately.
3191**
3192** ^It is safe to call this routine from a thread different from the
3193** thread that is currently running the database operation. But it
3194** is not safe to call this routine with a [database connection] that
3195** is closed or might close before sqlite3_interrupt() returns.
3196**
3197** ^If an SQL operation is very nearly finished at the time when
3198** sqlite3_interrupt() is called, then it might not have an opportunity
3199** to be interrupted and might continue to completion.
3200**
3201** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
3202** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
3203** that is inside an explicit transaction, then the entire transaction
3204** will be rolled back automatically.
3205**
3206** ^The sqlite3_interrupt(D) call is in effect until all currently running
3207** SQL statements on [database connection] D complete. ^Any new SQL statements
3208** that are started after the sqlite3_interrupt() call and before the
3209** running statement count reaches zero are interrupted as if they had been
3210** running prior to the sqlite3_interrupt() call. ^New SQL statements
3211** that are started after the running statement count reaches zero are
3212** not effected by the sqlite3_interrupt().
3213** ^A call to sqlite3_interrupt(D) that occurs when there are no running
3214** SQL statements is a no-op and has no effect on SQL statements
3215** that are started after the sqlite3_interrupt() call returns.
3216**
3217** ^The [sqlite3_is_interrupted(D)] interface can be used to determine whether
3218** or not an interrupt is currently in effect for [database connection] D.
3219** It returns 1 if an interrupt is currently in effect, or 0 otherwise.
3220*/
3221SQLITE_API void sqlite3_interrupt(sqlite3*);
3222SQLITE_API int sqlite3_is_interrupted(sqlite3*);
3223
3224/*
3225** CAPI3REF: Determine If An SQL Statement Is Complete
3226**
3227** These routines are useful during command-line input to determine if the
3228** currently entered text seems to form a complete SQL statement or
3229** if additional input is needed before sending the text into
3230** SQLite for parsing. ^These routines return 1 if the input string
3231** appears to be a complete SQL statement. ^A statement is judged to be
3232** complete if it ends with a semicolon token and is not a prefix of a
3233** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
3234** string literals or quoted identifier names or comments are not
3235** independent tokens (they are part of the token in which they are
3236** embedded) and thus do not count as a statement terminator. ^Whitespace
3237** and comments that follow the final semicolon are ignored.
3238**
3239** ^These routines return 0 if the statement is incomplete. ^If a
3240** memory allocation fails, then SQLITE_NOMEM is returned.
3241**
3242** ^These routines do not parse the SQL statements thus
3243** will not detect syntactically incorrect SQL.
3244**
3245** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
3246** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
3247** automatically by sqlite3_complete16(). If that initialization fails,
3248** then the return value from sqlite3_complete16() will be non-zero
3249** regardless of whether or not the input SQL is complete.)^
3250**
3251** The input to [sqlite3_complete()] must be a zero-terminated
3252** UTF-8 string.
3253**
3254** The input to [sqlite3_complete16()] must be a zero-terminated
3255** UTF-16 string in native byte order.
3256*/
3257SQLITE_API int sqlite3_complete(const char *sql);
3258SQLITE_API int sqlite3_complete16(const void *sql);
3259
3260/*
3261** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
3262** KEYWORDS: {busy-handler callback} {busy handler}
3263** METHOD: sqlite3
3264**
3265** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
3266** that might be invoked with argument P whenever
3267** an attempt is made to access a database table associated with
3268** [database connection] D when another thread
3269** or process has the table locked.
3270** The sqlite3_busy_handler() interface is used to implement
3271** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
3272**
3273** ^If the busy callback is NULL, then [SQLITE_BUSY]
3274** is returned immediately upon encountering the lock. ^If the busy callback
3275** is not NULL, then the callback might be invoked with two arguments.
3276**
3277** ^The first argument to the busy handler is a copy of the void* pointer which
3278** is the third argument to sqlite3_busy_handler(). ^The second argument to
3279** the busy handler callback is the number of times that the busy handler has
3280** been invoked previously for the same locking event. ^If the
3281** busy callback returns 0, then no additional attempts are made to
3282** access the database and [SQLITE_BUSY] is returned
3283** to the application.
3284** ^If the callback returns non-zero, then another attempt
3285** is made to access the database and the cycle repeats.
3286**
3287** The presence of a busy handler does not guarantee that it will be invoked
3288** when there is lock contention. ^If SQLite determines that invoking the busy
3289** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
3290** to the application instead of invoking the
3291** busy handler.
3292** Consider a scenario where one process is holding a read lock that
3293** it is trying to promote to a reserved lock and
3294** a second process is holding a reserved lock that it is trying
3295** to promote to an exclusive lock. The first process cannot proceed
3296** because it is blocked by the second and the second process cannot
3297** proceed because it is blocked by the first. If both processes
3298** invoke the busy handlers, neither will make any progress. Therefore,
3299** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
3300** will induce the first process to release its read lock and allow
3301** the second process to proceed.
3302**
3303** ^The default busy callback is NULL.
3304**
3305** ^(There can only be a single busy handler defined for each
3306** [database connection]. Setting a new busy handler clears any
3307** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
3308** or evaluating [PRAGMA busy_timeout=N] will change the
3309** busy handler and thus clear any previously set busy handler.
3310**
3311** The busy callback should not take any actions which modify the
3312** database connection that invoked the busy handler. In other words,
3313** the busy handler is not reentrant. Any such actions
3314** result in undefined behavior.
3315**
3316** A busy handler must not close the database connection
3317** or [prepared statement] that invoked the busy handler.
3318*/
3319SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
3320
3321/*
3322** CAPI3REF: Set A Busy Timeout
3323** METHOD: sqlite3
3324**
3325** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
3326** for a specified amount of time when a table is locked. ^The handler
3327** will sleep multiple times until at least "ms" milliseconds of sleeping
3328** have accumulated. ^After at least "ms" milliseconds of sleeping,
3329** the handler returns 0 which causes [sqlite3_step()] to return
3330** [SQLITE_BUSY].
3331**
3332** ^Calling this routine with an argument less than or equal to zero
3333** turns off all busy handlers.
3334**
3335** ^(There can only be a single busy handler for a particular
3336** [database connection] at any given moment. If another busy handler
3337** was defined (using [sqlite3_busy_handler()]) prior to calling
3338** this routine, that other busy handler is cleared.)^
3339**
3340** See also: [PRAGMA busy_timeout]
3341*/
3342SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
3343
3344/*
3345** CAPI3REF: Set the Setlk Timeout
3346** METHOD: sqlite3
3347**
3348** This routine is only useful in SQLITE_ENABLE_SETLK_TIMEOUT builds. If
3349** the VFS supports blocking locks, it sets the timeout in ms used by
3350** eligible locks taken on wal mode databases by the specified database
3351** handle. In non-SQLITE_ENABLE_SETLK_TIMEOUT builds, or if the VFS does
3352** not support blocking locks, this function is a no-op.
3353**
3354** Passing 0 to this function disables blocking locks altogether. Passing
3355** -1 to this function requests that the VFS blocks for a long time -
3356** indefinitely if possible. The results of passing any other negative value
3357** are undefined.
3358**
3359** Internally, each SQLite database handle store two timeout values - the
3360** busy-timeout (used for rollback mode databases, or if the VFS does not
3361** support blocking locks) and the setlk-timeout (used for blocking locks
3362** on wal-mode databases). The sqlite3_busy_timeout() method sets both
3363** values, this function sets only the setlk-timeout value. Therefore,
3364** to configure separate busy-timeout and setlk-timeout values for a single
3365** database handle, call sqlite3_busy_timeout() followed by this function.
3366**
3367** Whenever the number of connections to a wal mode database falls from
3368** 1 to 0, the last connection takes an exclusive lock on the database,
3369** then checkpoints and deletes the wal file. While it is doing this, any
3370** new connection that tries to read from the database fails with an
3371** SQLITE_BUSY error. Or, if the SQLITE_SETLK_BLOCK_ON_CONNECT flag is
3372** passed to this API, the new connection blocks until the exclusive lock
3373** has been released.
3374*/
3375SQLITE_API int sqlite3_setlk_timeout(sqlite3*, int ms, int flags);
3376
3377/*
3378** CAPI3REF: Flags for sqlite3_setlk_timeout()
3379*/
3380#define SQLITE_SETLK_BLOCK_ON_CONNECT0x01 0x01
3381
3382/*
3383** CAPI3REF: Convenience Routines For Running Queries
3384** METHOD: sqlite3
3385**
3386** This is a legacy interface that is preserved for backwards compatibility.
3387** Use of this interface is not recommended.
3388**
3389** Definition: A <b>result table</b> is memory data structure created by the
3390** [sqlite3_get_table()] interface. A result table records the
3391** complete query results from one or more queries.
3392**
3393** The table conceptually has a number of rows and columns. But
3394** these numbers are not part of the result table itself. These
3395** numbers are obtained separately. Let N be the number of rows
3396** and M be the number of columns.
3397**
3398** A result table is an array of pointers to zero-terminated UTF-8 strings.
3399** There are (N+1)*M elements in the array. The first M pointers point
3400** to zero-terminated strings that contain the names of the columns.
3401** The remaining entries all point to query results. NULL values result
3402** in NULL pointers. All other values are in their UTF-8 zero-terminated
3403** string representation as returned by [sqlite3_column_text()].
3404**
3405** A result table might consist of one or more memory allocations.
3406** It is not safe to pass a result table directly to [sqlite3_free()].
3407** A result table should be deallocated using [sqlite3_free_table()].
3408**
3409** ^(As an example of the result table format, suppose a query result
3410** is as follows:
3411**
3412** <blockquote><pre>
3413** Name | Age
3414** -----------------------
3415** Alice | 43
3416** Bob | 28
3417** Cindy | 21
3418** </pre></blockquote>
3419**
3420** There are two columns (M==2) and three rows (N==3). Thus the
3421** result table has 8 entries. Suppose the result table is stored
3422** in an array named azResult. Then azResult holds this content:
3423**
3424** <blockquote><pre>
3425** azResult&#91;0] = "Name";
3426** azResult&#91;1] = "Age";
3427** azResult&#91;2] = "Alice";
3428** azResult&#91;3] = "43";
3429** azResult&#91;4] = "Bob";
3430** azResult&#91;5] = "28";
3431** azResult&#91;6] = "Cindy";
3432** azResult&#91;7] = "21";
3433** </pre></blockquote>)^
3434**
3435** ^The sqlite3_get_table() function evaluates one or more
3436** semicolon-separated SQL statements in the zero-terminated UTF-8
3437** string of its 2nd parameter and returns a result table to the
3438** pointer given in its 3rd parameter.
3439**
3440** After the application has finished with the result from sqlite3_get_table(),
3441** it must pass the result table pointer to sqlite3_free_table() in order to
3442** release the memory that was malloced. Because of the way the
3443** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
3444** function must not try to call [sqlite3_free()] directly. Only
3445** [sqlite3_free_table()] is able to release the memory properly and safely.
3446**
3447** The sqlite3_get_table() interface is implemented as a wrapper around
3448** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
3449** to any internal data structures of SQLite. It uses only the public
3450** interface defined here. As a consequence, errors that occur in the
3451** wrapper layer outside of the internal [sqlite3_exec()] call are not
3452** reflected in subsequent calls to [sqlite3_errcode()] or
3453** [sqlite3_errmsg()].
3454*/
3455SQLITE_API int sqlite3_get_table(
3456 sqlite3 *db, /* An open database */
3457 const char *zSql, /* SQL to be evaluated */
3458 char ***pazResult, /* Results of the query */
3459 int *pnRow, /* Number of result rows written here */
3460 int *pnColumn, /* Number of result columns written here */
3461 char **pzErrmsg /* Error msg written here */
3462);
3463SQLITE_API void sqlite3_free_table(char **result);
3464
3465/*
3466** CAPI3REF: Formatted String Printing Functions
3467**
3468** These routines are work-alikes of the "printf()" family of functions
3469** from the standard C library.
3470** These routines understand most of the common formatting options from
3471** the standard library printf()
3472** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
3473** See the [built-in printf()] documentation for details.
3474**
3475** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
3476** results into memory obtained from [sqlite3_malloc64()].
3477** The strings returned by these two routines should be
3478** released by [sqlite3_free()]. ^Both routines return a
3479** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough
3480** memory to hold the resulting string.
3481**
3482** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
3483** the standard C library. The result is written into the
3484** buffer supplied as the second parameter whose size is given by
3485** the first parameter. Note that the order of the
3486** first two parameters is reversed from snprintf().)^ This is an
3487** historical accident that cannot be fixed without breaking
3488** backwards compatibility. ^(Note also that sqlite3_snprintf()
3489** returns a pointer to its buffer instead of the number of
3490** characters actually written into the buffer.)^ We admit that
3491** the number of characters written would be a more useful return
3492** value but we cannot change the implementation of sqlite3_snprintf()
3493** now without breaking compatibility.
3494**
3495** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
3496** guarantees that the buffer is always zero-terminated. ^The first
3497** parameter "n" is the total size of the buffer, including space for
3498** the zero terminator. So the longest string that can be completely
3499** written will be n-1 characters.
3500**
3501** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
3502**
3503** See also: [built-in printf()], [printf() SQL function]
3504*/
3505SQLITE_API char *sqlite3_mprintf(const char*,...);
3506SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
3507SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
3508SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
3509
3510/*
3511** CAPI3REF: Memory Allocation Subsystem
3512**
3513** The SQLite core uses these three routines for all of its own
3514** internal memory allocation needs. "Core" in the previous sentence
3515** does not include operating-system specific [VFS] implementation. The
3516** Windows VFS uses native malloc() and free() for some operations.
3517**
3518** ^The sqlite3_malloc() routine returns a pointer to a block
3519** of memory at least N bytes in length, where N is the parameter.
3520** ^If sqlite3_malloc() is unable to obtain sufficient free
3521** memory, it returns a NULL pointer. ^If the parameter N to
3522** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
3523** a NULL pointer.
3524**
3525** ^The sqlite3_malloc64(N) routine works just like
3526** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
3527** of a signed 32-bit integer.
3528**
3529** ^Calling sqlite3_free() with a pointer previously returned
3530** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
3531** that it might be reused. ^The sqlite3_free() routine is
3532** a no-op if is called with a NULL pointer. Passing a NULL pointer
3533** to sqlite3_free() is harmless. After being freed, memory
3534** should neither be read nor written. Even reading previously freed
3535** memory might result in a segmentation fault or other severe error.
3536** Memory corruption, a segmentation fault, or other severe error
3537** might result if sqlite3_free() is called with a non-NULL pointer that
3538** was not obtained from sqlite3_malloc() or sqlite3_realloc().
3539**
3540** ^The sqlite3_realloc(X,N) interface attempts to resize a
3541** prior memory allocation X to be at least N bytes.
3542** ^If the X parameter to sqlite3_realloc(X,N)
3543** is a NULL pointer then its behavior is identical to calling
3544** sqlite3_malloc(N).
3545** ^If the N parameter to sqlite3_realloc(X,N) is zero or
3546** negative then the behavior is exactly the same as calling
3547** sqlite3_free(X).
3548** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
3549** of at least N bytes in size or NULL if insufficient memory is available.
3550** ^If M is the size of the prior allocation, then min(N,M) bytes
3551** of the prior allocation are copied into the beginning of buffer returned
3552** by sqlite3_realloc(X,N) and the prior allocation is freed.
3553** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
3554** prior allocation is not freed.
3555**
3556** ^The sqlite3_realloc64(X,N) interfaces works the same as
3557** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
3558** of a 32-bit signed integer.
3559**
3560** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
3561** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
3562** sqlite3_msize(X) returns the size of that memory allocation in bytes.
3563** ^The value returned by sqlite3_msize(X) might be larger than the number
3564** of bytes requested when X was allocated. ^If X is a NULL pointer then
3565** sqlite3_msize(X) returns zero. If X points to something that is not
3566** the beginning of memory allocation, or if it points to a formerly
3567** valid memory allocation that has now been freed, then the behavior
3568** of sqlite3_msize(X) is undefined and possibly harmful.
3569**
3570** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
3571** sqlite3_malloc64(), and sqlite3_realloc64()
3572** is always aligned to at least an 8 byte boundary, or to a
3573** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
3574** option is used.
3575**
3576** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
3577** must be either NULL or else pointers obtained from a prior
3578** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
3579** not yet been released.
3580**
3581** The application must not read or write any part of
3582** a block of memory after it has been released using
3583** [sqlite3_free()] or [sqlite3_realloc()].
3584*/
3585SQLITE_API void *sqlite3_malloc(int);
3586SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
3587SQLITE_API void *sqlite3_realloc(void*, int);
3588SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
3589SQLITE_API void sqlite3_free(void*);
3590SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
3591
3592/*
3593** CAPI3REF: Memory Allocator Statistics
3594**
3595** SQLite provides these two interfaces for reporting on the status
3596** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
3597** routines, which form the built-in memory allocation subsystem.
3598**
3599** ^The [sqlite3_memory_used()] routine returns the number of bytes
3600** of memory currently outstanding (malloced but not freed).
3601** ^The [sqlite3_memory_highwater()] routine returns the maximum
3602** value of [sqlite3_memory_used()] since the high-water mark
3603** was last reset. ^The values returned by [sqlite3_memory_used()] and
3604** [sqlite3_memory_highwater()] include any overhead
3605** added by SQLite in its implementation of [sqlite3_malloc()],
3606** but not overhead added by the any underlying system library
3607** routines that [sqlite3_malloc()] may call.
3608**
3609** ^The memory high-water mark is reset to the current value of
3610** [sqlite3_memory_used()] if and only if the parameter to
3611** [sqlite3_memory_highwater()] is true. ^The value returned
3612** by [sqlite3_memory_highwater(1)] is the high-water mark
3613** prior to the reset.
3614*/
3615SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
3616SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
3617
3618/*
3619** CAPI3REF: Pseudo-Random Number Generator
3620**
3621** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
3622** select random [ROWID | ROWIDs] when inserting new records into a table that
3623** already uses the largest possible [ROWID]. The PRNG is also used for
3624** the built-in random() and randomblob() SQL functions. This interface allows
3625** applications to access the same PRNG for other purposes.
3626**
3627** ^A call to this routine stores N bytes of randomness into buffer P.
3628** ^The P parameter can be a NULL pointer.
3629**
3630** ^If this routine has not been previously called or if the previous
3631** call had N less than one or a NULL pointer for P, then the PRNG is
3632** seeded using randomness obtained from the xRandomness method of
3633** the default [sqlite3_vfs] object.
3634** ^If the previous call to this routine had an N of 1 or more and a
3635** non-NULL P then the pseudo-randomness is generated
3636** internally and without recourse to the [sqlite3_vfs] xRandomness
3637** method.
3638*/
3639SQLITE_API void sqlite3_randomness(int N, void *P);
3640
3641/*
3642** CAPI3REF: Compile-Time Authorization Callbacks
3643** METHOD: sqlite3
3644** KEYWORDS: {authorizer callback}
3645**
3646** ^This routine registers an authorizer callback with a particular
3647** [database connection], supplied in the first argument.
3648** ^The authorizer callback is invoked as SQL statements are being compiled
3649** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
3650** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
3651** and [sqlite3_prepare16_v3()]. ^At various
3652** points during the compilation process, as logic is being created
3653** to perform various actions, the authorizer callback is invoked to
3654** see if those actions are allowed. ^The authorizer callback should
3655** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
3656** specific action but allow the SQL statement to continue to be
3657** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
3658** rejected with an error. ^If the authorizer callback returns
3659** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
3660** then the [sqlite3_prepare_v2()] or equivalent call that triggered
3661** the authorizer will fail with an error message.
3662**
3663** When the callback returns [SQLITE_OK], that means the operation
3664** requested is ok. ^When the callback returns [SQLITE_DENY], the
3665** [sqlite3_prepare_v2()] or equivalent call that triggered the
3666** authorizer will fail with an error message explaining that
3667** access is denied.
3668**
3669** ^The first parameter to the authorizer callback is a copy of the third
3670** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
3671** to the callback is an integer [SQLITE_COPY | action code] that specifies
3672** the particular action to be authorized. ^The third through sixth parameters
3673** to the callback are either NULL pointers or zero-terminated strings
3674** that contain additional details about the action to be authorized.
3675** Applications must always be prepared to encounter a NULL pointer in any
3676** of the third through the sixth parameters of the authorization callback.
3677**
3678** ^If the action code is [SQLITE_READ]
3679** and the callback returns [SQLITE_IGNORE] then the
3680** [prepared statement] statement is constructed to substitute
3681** a NULL value in place of the table column that would have
3682** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
3683** return can be used to deny an untrusted user access to individual
3684** columns of a table.
3685** ^When a table is referenced by a [SELECT] but no column values are
3686** extracted from that table (for example in a query like
3687** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
3688** is invoked once for that table with a column name that is an empty string.
3689** ^If the action code is [SQLITE_DELETE] and the callback returns
3690** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
3691** [truncate optimization] is disabled and all rows are deleted individually.
3692**
3693** An authorizer is used when [sqlite3_prepare | preparing]
3694** SQL statements from an untrusted source, to ensure that the SQL statements
3695** do not try to access data they are not allowed to see, or that they do not
3696** try to execute malicious statements that damage the database. For
3697** example, an application may allow a user to enter arbitrary
3698** SQL queries for evaluation by a database. But the application does
3699** not want the user to be able to make arbitrary changes to the
3700** database. An authorizer could then be put in place while the
3701** user-entered SQL is being [sqlite3_prepare | prepared] that
3702** disallows everything except [SELECT] statements.
3703**
3704** Applications that need to process SQL from untrusted sources
3705** might also consider lowering resource limits using [sqlite3_limit()]
3706** and limiting database size using the [max_page_count] [PRAGMA]
3707** in addition to using an authorizer.
3708**
3709** ^(Only a single authorizer can be in place on a database connection
3710** at a time. Each call to sqlite3_set_authorizer overrides the
3711** previous call.)^ ^Disable the authorizer by installing a NULL callback.
3712** The authorizer is disabled by default.
3713**
3714** The authorizer callback must not do anything that will modify
3715** the database connection that invoked the authorizer callback.
3716** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3717** database connections for the meaning of "modify" in this paragraph.
3718**
3719** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3720** statement might be re-prepared during [sqlite3_step()] due to a
3721** schema change. Hence, the application should ensure that the
3722** correct authorizer callback remains in place during the [sqlite3_step()].
3723**
3724** ^Note that the authorizer callback is invoked only during
3725** [sqlite3_prepare()] or its variants. Authorization is not
3726** performed during statement evaluation in [sqlite3_step()], unless
3727** as stated in the previous paragraph, sqlite3_step() invokes
3728** sqlite3_prepare_v2() to reprepare a statement after a schema change.
3729*/
3730SQLITE_API int sqlite3_set_authorizer(
3731 sqlite3*,
3732 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
3733 void *pUserData
3734);
3735
3736/*
3737** CAPI3REF: Authorizer Return Codes
3738**
3739** The [sqlite3_set_authorizer | authorizer callback function] must
3740** return either [SQLITE_OK] or one of these two constants in order
3741** to signal SQLite whether or not the action is permitted. See the
3742** [sqlite3_set_authorizer | authorizer documentation] for additional
3743** information.
3744**
3745** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
3746** returned from the [sqlite3_vtab_on_conflict()] interface.
3747*/
3748#define SQLITE_DENY1 1 /* Abort the SQL statement with an error */
3749#define SQLITE_IGNORE2 2 /* Don't allow access, but don't generate an error */
3750
3751/*
3752** CAPI3REF: Authorizer Action Codes
3753**
3754** The [sqlite3_set_authorizer()] interface registers a callback function
3755** that is invoked to authorize certain SQL statement actions. The
3756** second parameter to the callback is an integer code that specifies
3757** what action is being authorized. These are the integer action codes that
3758** the authorizer callback may be passed.
3759**
3760** These action code values signify what kind of operation is to be
3761** authorized. The 3rd and 4th parameters to the authorization
3762** callback function will be parameters or NULL depending on which of these
3763** codes is used as the second parameter. ^(The 5th parameter to the
3764** authorizer callback is the name of the database ("main", "temp",
3765** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
3766** is the name of the inner-most trigger or view that is responsible for
3767** the access attempt or NULL if this access attempt is directly from
3768** top-level SQL code.
3769*/
3770/******************************************* 3rd ************ 4th ***********/
3771#define SQLITE_CREATE_INDEX1 1 /* Index Name Table Name */
3772#define SQLITE_CREATE_TABLE2 2 /* Table Name NULL */
3773#define SQLITE_CREATE_TEMP_INDEX3 3 /* Index Name Table Name */
3774#define SQLITE_CREATE_TEMP_TABLE4 4 /* Table Name NULL */
3775#define SQLITE_CREATE_TEMP_TRIGGER5 5 /* Trigger Name Table Name */
3776#define SQLITE_CREATE_TEMP_VIEW6 6 /* View Name NULL */
3777#define SQLITE_CREATE_TRIGGER7 7 /* Trigger Name Table Name */
3778#define SQLITE_CREATE_VIEW8 8 /* View Name NULL */
3779#define SQLITE_DELETE9 9 /* Table Name NULL */
3780#define SQLITE_DROP_INDEX10 10 /* Index Name Table Name */
3781#define SQLITE_DROP_TABLE11 11 /* Table Name NULL */
3782#define SQLITE_DROP_TEMP_INDEX12 12 /* Index Name Table Name */
3783#define SQLITE_DROP_TEMP_TABLE13 13 /* Table Name NULL */
3784#define SQLITE_DROP_TEMP_TRIGGER14 14 /* Trigger Name Table Name */
3785#define SQLITE_DROP_TEMP_VIEW15 15 /* View Name NULL */
3786#define SQLITE_DROP_TRIGGER16 16 /* Trigger Name Table Name */
3787#define SQLITE_DROP_VIEW17 17 /* View Name NULL */
3788#define SQLITE_INSERT18 18 /* Table Name NULL */
3789#define SQLITE_PRAGMA19 19 /* Pragma Name 1st arg or NULL */
3790#define SQLITE_READ20 20 /* Table Name Column Name */
3791#define SQLITE_SELECT21 21 /* NULL NULL */
3792#define SQLITE_TRANSACTION22 22 /* Operation NULL */
3793#define SQLITE_UPDATE23 23 /* Table Name Column Name */
3794#define SQLITE_ATTACH24 24 /* Filename NULL */
3795#define SQLITE_DETACH25 25 /* Database Name NULL */
3796#define SQLITE_ALTER_TABLE26 26 /* Database Name Table Name */
3797#define SQLITE_REINDEX27 27 /* Index Name NULL */
3798#define SQLITE_ANALYZE28 28 /* Table Name NULL */
3799#define SQLITE_CREATE_VTABLE29 29 /* Table Name Module Name */
3800#define SQLITE_DROP_VTABLE30 30 /* Table Name Module Name */
3801#define SQLITE_FUNCTION31 31 /* NULL Function Name */
3802#define SQLITE_SAVEPOINT32 32 /* Operation Savepoint Name */
3803#define SQLITE_COPY0 0 /* No longer used */
3804#define SQLITE_RECURSIVE33 33 /* NULL NULL */
3805
3806/*
3807** CAPI3REF: Deprecated Tracing And Profiling Functions
3808** DEPRECATED
3809**
3810** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
3811** instead of the routines described here.
3812**
3813** These routines register callback functions that can be used for
3814** tracing and profiling the execution of SQL statements.
3815**
3816** ^The callback function registered by sqlite3_trace() is invoked at
3817** various times when an SQL statement is being run by [sqlite3_step()].
3818** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3819** SQL statement text as the statement first begins executing.
3820** ^(Additional sqlite3_trace() callbacks might occur
3821** as each triggered subprogram is entered. The callbacks for triggers
3822** contain a UTF-8 SQL comment that identifies the trigger.)^
3823**
3824** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3825** the length of [bound parameter] expansion in the output of sqlite3_trace().
3826**
3827** ^The callback function registered by sqlite3_profile() is invoked
3828** as each SQL statement finishes. ^The profile callback contains
3829** the original statement text and an estimate of wall-clock time
3830** of how long that statement took to run. ^The profile callback
3831** time is in units of nanoseconds, however the current implementation
3832** is only capable of millisecond resolution so the six least significant
3833** digits in the time are meaningless. Future versions of SQLite
3834** might provide greater resolution on the profiler callback. Invoking
3835** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the
3836** profile callback.
3837*/
3838SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
3839 void(*xTrace)(void*,const char*), void*);
3840SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
3841 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3842
3843/*
3844** CAPI3REF: SQL Trace Event Codes
3845** KEYWORDS: SQLITE_TRACE
3846**
3847** These constants identify classes of events that can be monitored
3848** using the [sqlite3_trace_v2()] tracing logic. The M argument
3849** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
3850** the following constants. ^The first argument to the trace callback
3851** is one of the following constants.
3852**
3853** New tracing constants may be added in future releases.
3854**
3855** ^A trace callback has four arguments: xCallback(T,C,P,X).
3856** ^The T argument is one of the integer type codes above.
3857** ^The C argument is a copy of the context pointer passed in as the
3858** fourth argument to [sqlite3_trace_v2()].
3859** The P and X arguments are pointers whose meanings depend on T.
3860**
3861** <dl>
3862** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
3863** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
3864** first begins running and possibly at other times during the
3865** execution of the prepared statement, such as at the start of each
3866** trigger subprogram. ^The P argument is a pointer to the
3867** [prepared statement]. ^The X argument is a pointer to a string which
3868** is the unexpanded SQL text of the prepared statement or an SQL comment
3869** that indicates the invocation of a trigger. ^The callback can compute
3870** the same text that would have been returned by the legacy [sqlite3_trace()]
3871** interface by using the X argument when X begins with "--" and invoking
3872** [sqlite3_expanded_sql(P)] otherwise.
3873**
3874** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
3875** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
3876** information as is provided by the [sqlite3_profile()] callback.
3877** ^The P argument is a pointer to the [prepared statement] and the
3878** X argument points to a 64-bit integer which is approximately
3879** the number of nanoseconds that the prepared statement took to run.
3880** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
3881**
3882** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
3883** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
3884** statement generates a single row of result.
3885** ^The P argument is a pointer to the [prepared statement] and the
3886** X argument is unused.
3887**
3888** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
3889** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
3890** connection closes.
3891** ^The P argument is a pointer to the [database connection] object
3892** and the X argument is unused.
3893** </dl>
3894*/
3895#define SQLITE_TRACE_STMT0x01 0x01
3896#define SQLITE_TRACE_PROFILE0x02 0x02
3897#define SQLITE_TRACE_ROW0x04 0x04
3898#define SQLITE_TRACE_CLOSE0x08 0x08
3899
3900/*
3901** CAPI3REF: SQL Trace Hook
3902** METHOD: sqlite3
3903**
3904** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
3905** function X against [database connection] D, using property mask M
3906** and context pointer P. ^If the X callback is
3907** NULL or if the M mask is zero, then tracing is disabled. The
3908** M argument should be the bitwise OR-ed combination of
3909** zero or more [SQLITE_TRACE] constants.
3910**
3911** ^Each call to either sqlite3_trace(D,X,P) or sqlite3_trace_v2(D,M,X,P)
3912** overrides (cancels) all prior calls to sqlite3_trace(D,X,P) or
3913** sqlite3_trace_v2(D,M,X,P) for the [database connection] D. Each
3914** database connection may have at most one trace callback.
3915**
3916** ^The X callback is invoked whenever any of the events identified by
3917** mask M occur. ^The integer return value from the callback is currently
3918** ignored, though this may change in future releases. Callback
3919** implementations should return zero to ensure future compatibility.
3920**
3921** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
3922** ^The T argument is one of the [SQLITE_TRACE]
3923** constants to indicate why the callback was invoked.
3924** ^The C argument is a copy of the context pointer.
3925** The P and X arguments are pointers whose meanings depend on T.
3926**
3927** The sqlite3_trace_v2() interface is intended to replace the legacy
3928** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
3929** are deprecated.
3930*/
3931SQLITE_API int sqlite3_trace_v2(
3932 sqlite3*,
3933 unsigned uMask,
3934 int(*xCallback)(unsigned,void*,void*,void*),
3935 void *pCtx
3936);
3937
3938/*
3939** CAPI3REF: Query Progress Callbacks
3940** METHOD: sqlite3
3941**
3942** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3943** function X to be invoked periodically during long running calls to
3944** [sqlite3_step()] and [sqlite3_prepare()] and similar for
3945** database connection D. An example use for this
3946** interface is to keep a GUI updated during a large query.
3947**
3948** ^The parameter P is passed through as the only parameter to the
3949** callback function X. ^The parameter N is the approximate number of
3950** [virtual machine instructions] that are evaluated between successive
3951** invocations of the callback X. ^If N is less than one then the progress
3952** handler is disabled.
3953**
3954** ^Only a single progress handler may be defined at one time per
3955** [database connection]; setting a new progress handler cancels the
3956** old one. ^Setting parameter X to NULL disables the progress handler.
3957** ^The progress handler is also disabled by setting N to a value less
3958** than 1.
3959**
3960** ^If the progress callback returns non-zero, the operation is
3961** interrupted. This feature can be used to implement a
3962** "Cancel" button on a GUI progress dialog box.
3963**
3964** The progress handler callback must not do anything that will modify
3965** the database connection that invoked the progress handler.
3966** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3967** database connections for the meaning of "modify" in this paragraph.
3968**
3969** The progress handler callback would originally only be invoked from the
3970** bytecode engine. It still might be invoked during [sqlite3_prepare()]
3971** and similar because those routines might force a reparse of the schema
3972** which involves running the bytecode engine. However, beginning with
3973** SQLite version 3.41.0, the progress handler callback might also be
3974** invoked directly from [sqlite3_prepare()] while analyzing and generating
3975** code for complex queries.
3976*/
3977SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3978
3979/*
3980** CAPI3REF: Opening A New Database Connection
3981** CONSTRUCTOR: sqlite3
3982**
3983** ^These routines open an SQLite database file as specified by the
3984** filename argument. ^The filename argument is interpreted as UTF-8 for
3985** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3986** order for sqlite3_open16(). ^(A [database connection] handle is usually
3987** returned in *ppDb, even if an error occurs. The only exception is that
3988** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3989** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3990** object.)^ ^(If the database is opened (and/or created) successfully, then
3991** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
3992** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3993** an English language description of the error following a failure of any
3994** of the sqlite3_open() routines.
3995**
3996** ^The default encoding will be UTF-8 for databases created using
3997** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
3998** created using sqlite3_open16() will be UTF-16 in the native byte order.
3999**
4000** Whether or not an error occurs when it is opened, resources
4001** associated with the [database connection] handle should be released by
4002** passing it to [sqlite3_close()] when it is no longer required.
4003**
4004** The sqlite3_open_v2() interface works like sqlite3_open()
4005** except that it accepts two additional parameters for additional control
4006** over the new database connection. ^(The flags parameter to
4007** sqlite3_open_v2() must include, at a minimum, one of the following
4008** three flag combinations:)^
4009**
4010** <dl>
4011** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
4012** <dd>The database is opened in read-only mode. If the database does
4013** not already exist, an error is returned.</dd>)^
4014**
4015** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
4016** <dd>The database is opened for reading and writing if possible, or
4017** reading only if the file is write protected by the operating
4018** system. In either case the database must already exist, otherwise
4019** an error is returned. For historical reasons, if opening in
4020** read-write mode fails due to OS-level permissions, an attempt is
4021** made to open it in read-only mode. [sqlite3_db_readonly()] can be
4022** used to determine whether the database is actually
4023** read-write.</dd>)^
4024**
4025** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
4026** <dd>The database is opened for reading and writing, and is created if
4027** it does not already exist. This is the behavior that is always used for
4028** sqlite3_open() and sqlite3_open16().</dd>)^
4029** </dl>
4030**
4031** In addition to the required flags, the following optional flags are
4032** also supported:
4033**
4034** <dl>
4035** ^(<dt>[SQLITE_OPEN_URI]</dt>
4036** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^
4037**
4038** ^(<dt>[SQLITE_OPEN_MEMORY]</dt>
4039** <dd>The database will be opened as an in-memory database. The database
4040** is named by the "filename" argument for the purposes of cache-sharing,
4041** if shared cache mode is enabled, but the "filename" is otherwise ignored.
4042** </dd>)^
4043**
4044** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt>
4045** <dd>The new database connection will use the "multi-thread"
4046** [threading mode].)^ This means that separate threads are allowed
4047** to use SQLite at the same time, as long as each thread is using
4048** a different [database connection].
4049**
4050** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt>
4051** <dd>The new database connection will use the "serialized"
4052** [threading mode].)^ This means the multiple threads can safely
4053** attempt to use the same database connection at the same time.
4054** (Mutexes will block any actual concurrency, but in this mode
4055** there is no harm in trying.)
4056**
4057** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>
4058** <dd>The database is opened [shared cache] enabled, overriding
4059** the default shared cache setting provided by
4060** [sqlite3_enable_shared_cache()].)^
4061** The [use of shared cache mode is discouraged] and hence shared cache
4062** capabilities may be omitted from many builds of SQLite. In such cases,
4063** this option is a no-op.
4064**
4065** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
4066** <dd>The database is opened [shared cache] disabled, overriding
4067** the default shared cache setting provided by
4068** [sqlite3_enable_shared_cache()].)^
4069**
4070** [[OPEN_EXRESCODE]] ^(<dt>[SQLITE_OPEN_EXRESCODE]</dt>
4071** <dd>The database connection comes up in "extended result code mode".
4072** In other words, the database behaves as if
4073** [sqlite3_extended_result_codes(db,1)] were called on the database
4074** connection as soon as the connection is created. In addition to setting
4075** the extended result code mode, this flag also causes [sqlite3_open_v2()]
4076** to return an extended result code.</dd>
4077**
4078** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
4079** <dd>The database filename is not allowed to contain a symbolic link</dd>
4080** </dl>)^
4081**
4082** If the 3rd parameter to sqlite3_open_v2() is not one of the
4083** required combinations shown above optionally combined with other
4084** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
4085** then the behavior is undefined. Historic versions of SQLite
4086** have silently ignored surplus bits in the flags parameter to
4087** sqlite3_open_v2(), however that behavior might not be carried through
4088** into future versions of SQLite and so applications should not rely
4089** upon it. Note in particular that the SQLITE_OPEN_EXCLUSIVE flag is a no-op
4090** for sqlite3_open_v2(). The SQLITE_OPEN_EXCLUSIVE does *not* cause
4091** the open to fail if the database already exists. The SQLITE_OPEN_EXCLUSIVE
4092** flag is intended for use by the [sqlite3_vfs|VFS interface] only, and not
4093** by sqlite3_open_v2().
4094**
4095** ^The fourth parameter to sqlite3_open_v2() is the name of the
4096** [sqlite3_vfs] object that defines the operating system interface that
4097** the new database connection should use. ^If the fourth parameter is
4098** a NULL pointer then the default [sqlite3_vfs] object is used.
4099**
4100** ^If the filename is ":memory:", then a private, temporary in-memory database
4101** is created for the connection. ^This in-memory database will vanish when
4102** the database connection is closed. Future versions of SQLite might
4103** make use of additional special filenames that begin with the ":" character.
4104** It is recommended that when a database filename actually does begin with
4105** a ":" character you should prefix the filename with a pathname such as
4106** "./" to avoid ambiguity.
4107**
4108** ^If the filename is an empty string, then a private, temporary
4109** on-disk database will be created. ^This private database will be
4110** automatically deleted as soon as the database connection is closed.
4111**
4112** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
4113**
4114** ^If [URI filename] interpretation is enabled, and the filename argument
4115** begins with "file:", then the filename is interpreted as a URI. ^URI
4116** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
4117** set in the third argument to sqlite3_open_v2(), or if it has
4118** been enabled globally using the [SQLITE_CONFIG_URI] option with the
4119** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
4120** URI filename interpretation is turned off
4121** by default, but future releases of SQLite might enable URI filename
4122** interpretation by default. See "[URI filenames]" for additional
4123** information.
4124**
4125** URI filenames are parsed according to RFC 3986. ^If the URI contains an
4126** authority, then it must be either an empty string or the string
4127** "localhost". ^If the authority is not an empty string or "localhost", an
4128** error is returned to the caller. ^The fragment component of a URI, if
4129** present, is ignored.
4130**
4131** ^SQLite uses the path component of the URI as the name of the disk file
4132** which contains the database. ^If the path begins with a '/' character,
4133** then it is interpreted as an absolute path. ^If the path does not begin
4134** with a '/' (meaning that the authority section is omitted from the URI)
4135** then the path is interpreted as a relative path.
4136** ^(On windows, the first component of an absolute path
4137** is a drive specification (e.g. "C:").)^
4138**
4139** [[core URI query parameters]]
4140** The query component of a URI may contain parameters that are interpreted
4141** either by SQLite itself, or by a [VFS | custom VFS implementation].
4142** SQLite and its built-in [VFSes] interpret the
4143** following query parameters:
4144**
4145** <ul>
4146** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
4147** a VFS object that provides the operating system interface that should
4148** be used to access the database file on disk. ^If this option is set to
4149** an empty string the default VFS object is used. ^Specifying an unknown
4150** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
4151** present, then the VFS specified by the option takes precedence over
4152** the value passed as the fourth parameter to sqlite3_open_v2().
4153**
4154** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
4155** "rwc", or "memory". Attempting to set it to any other value is
4156** an error)^.
4157** ^If "ro" is specified, then the database is opened for read-only
4158** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
4159** third argument to sqlite3_open_v2(). ^If the mode option is set to
4160** "rw", then the database is opened for read-write (but not create)
4161** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
4162** been set. ^Value "rwc" is equivalent to setting both
4163** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
4164** set to "memory" then a pure [in-memory database] that never reads
4165** or writes from disk is used. ^It is an error to specify a value for
4166** the mode parameter that is less restrictive than that specified by
4167** the flags passed in the third parameter to sqlite3_open_v2().
4168**
4169** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
4170** "private". ^Setting it to "shared" is equivalent to setting the
4171** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
4172** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
4173** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
4174** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
4175** a URI filename, its value overrides any behavior requested by setting
4176** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
4177**
4178** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
4179** [powersafe overwrite] property does or does not apply to the
4180** storage media on which the database file resides.
4181**
4182** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
4183** which if set disables file locking in rollback journal modes. This
4184** is useful for accessing a database on a filesystem that does not
4185** support locking. Caution: Database corruption might result if two
4186** or more processes write to the same database and any one of those
4187** processes uses nolock=1.
4188**
4189** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
4190** parameter that indicates that the database file is stored on
4191** read-only media. ^When immutable is set, SQLite assumes that the
4192** database file cannot be changed, even by a process with higher
4193** privilege, and so the database is opened read-only and all locking
4194** and change detection is disabled. Caution: Setting the immutable
4195** property on a database file that does in fact change can result
4196** in incorrect query results and/or [SQLITE_CORRUPT] errors.
4197** See also: [SQLITE_IOCAP_IMMUTABLE].
4198**
4199** </ul>
4200**
4201** ^Specifying an unknown parameter in the query component of a URI is not an
4202** error. Future versions of SQLite might understand additional query
4203** parameters. See "[query parameters with special meaning to SQLite]" for
4204** additional information.
4205**
4206** [[URI filename examples]] <h3>URI filename examples</h3>
4207**
4208** <table border="1" align=center cellpadding=5>
4209** <tr><th> URI filenames <th> Results
4210** <tr><td> file:data.db <td>
4211** Open the file "data.db" in the current directory.
4212** <tr><td> file:/home/fred/data.db<br>
4213** file:///home/fred/data.db <br>
4214** file://localhost/home/fred/data.db <br> <td>
4215** Open the database file "/home/fred/data.db".
4216** <tr><td> file://darkstar/home/fred/data.db <td>
4217** An error. "darkstar" is not a recognized authority.
4218** <tr><td style="white-space:nowrap">
4219** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
4220** <td> Windows only: Open the file "data.db" on fred's desktop on drive
4221** C:. Note that the %20 escaping in this example is not strictly
4222** necessary - space characters can be used literally
4223** in URI filenames.
4224** <tr><td> file:data.db?mode=ro&cache=private <td>
4225** Open file "data.db" in the current directory for read-only access.
4226** Regardless of whether or not shared-cache mode is enabled by
4227** default, use a private cache.
4228** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
4229** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
4230** that uses dot-files in place of posix advisory locking.
4231** <tr><td> file:data.db?mode=readonly <td>
4232** An error. "readonly" is not a valid option for the "mode" parameter.
4233** Use "ro" instead: "file:data.db?mode=ro".
4234** </table>
4235**
4236** ^URI hexadecimal escape sequences (%HH) are supported within the path and
4237** query components of a URI. A hexadecimal escape sequence consists of a
4238** percent sign - "%" - followed by exactly two hexadecimal digits
4239** specifying an octet value. ^Before the path or query components of a
4240** URI filename are interpreted, they are encoded using UTF-8 and all
4241** hexadecimal escape sequences replaced by a single byte containing the
4242** corresponding octet. If this process generates an invalid UTF-8 encoding,
4243** the results are undefined.
4244**
4245** <b>Note to Windows users:</b> The encoding used for the filename argument
4246** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
4247** codepage is currently defined. Filenames containing international
4248** characters must be converted to UTF-8 prior to passing them into
4249** sqlite3_open() or sqlite3_open_v2().
4250**
4251** <b>Note to Windows Runtime users:</b> The temporary directory must be set
4252** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
4253** features that require the use of temporary files may fail.
4254**
4255** See also: [sqlite3_temp_directory]
4256*/
4257SQLITE_API int sqlite3_open(
4258 const char *filename, /* Database filename (UTF-8) */
4259 sqlite3 **ppDb /* OUT: SQLite db handle */
4260);
4261SQLITE_API int sqlite3_open16(
4262 const void *filename, /* Database filename (UTF-16) */
4263 sqlite3 **ppDb /* OUT: SQLite db handle */
4264);
4265SQLITE_API int sqlite3_open_v2(
4266 const char *filename, /* Database filename (UTF-8) */
4267 sqlite3 **ppDb, /* OUT: SQLite db handle */
4268 int flags, /* Flags */
4269 const char *zVfs /* Name of VFS module to use */
4270);
4271
4272/*
4273** CAPI3REF: Obtain Values For URI Parameters
4274**
4275** These are utility routines, useful to [VFS|custom VFS implementations],
4276** that check if a database file was a URI that contained a specific query
4277** parameter, and if so obtains the value of that query parameter.
4278**
4279** The first parameter to these interfaces (hereafter referred to
4280** as F) must be one of:
4281** <ul>
4282** <li> A database filename pointer created by the SQLite core and
4283** passed into the xOpen() method of a VFS implementation, or
4284** <li> A filename obtained from [sqlite3_db_filename()], or
4285** <li> A new filename constructed using [sqlite3_create_filename()].
4286** </ul>
4287** If the F parameter is not one of the above, then the behavior is
4288** undefined and probably undesirable. Older versions of SQLite were
4289** more tolerant of invalid F parameters than newer versions.
4290**
4291** If F is a suitable filename (as described in the previous paragraph)
4292** and if P is the name of the query parameter, then
4293** sqlite3_uri_parameter(F,P) returns the value of the P
4294** parameter if it exists or a NULL pointer if P does not appear as a
4295** query parameter on F. If P is a query parameter of F and it
4296** has no explicit value, then sqlite3_uri_parameter(F,P) returns
4297** a pointer to an empty string.
4298**
4299** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
4300** parameter and returns true (1) or false (0) according to the value
4301** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
4302** value of query parameter P is one of "yes", "true", or "on" in any
4303** case or if the value begins with a non-zero number. The
4304** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
4305** query parameter P is one of "no", "false", or "off" in any case or
4306** if the value begins with a numeric zero. If P is not a query
4307** parameter on F or if the value of P does not match any of the
4308** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
4309**
4310** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
4311** 64-bit signed integer and returns that integer, or D if P does not
4312** exist. If the value of P is something other than an integer, then
4313** zero is returned.
4314**
4315** The sqlite3_uri_key(F,N) returns a pointer to the name (not
4316** the value) of the N-th query parameter for filename F, or a NULL
4317** pointer if N is less than zero or greater than the number of query
4318** parameters minus 1. The N value is zero-based so N should be 0 to obtain
4319** the name of the first query parameter, 1 for the second parameter, and
4320** so forth.
4321**
4322** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
4323** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
4324** is not a database file pathname pointer that the SQLite core passed
4325** into the xOpen VFS method, then the behavior of this routine is undefined
4326** and probably undesirable.
4327**
4328** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F
4329** parameter can also be the name of a rollback journal file or WAL file
4330** in addition to the main database file. Prior to version 3.31.0, these
4331** routines would only work if F was the name of the main database file.
4332** When the F parameter is the name of the rollback journal or WAL file,
4333** it has access to all the same query parameters as were found on the
4334** main database file.
4335**
4336** See the [URI filename] documentation for additional information.
4337*/
4338SQLITE_API const char *sqlite3_uri_parameter(sqlite3_filename z, const char *zParam);
4339SQLITE_API int sqlite3_uri_boolean(sqlite3_filename z, const char *zParam, int bDefault);
4340SQLITE_API sqlite3_int64 sqlite3_uri_int64(sqlite3_filename, const char*, sqlite3_int64);
4341SQLITE_API const char *sqlite3_uri_key(sqlite3_filename z, int N);
4342
4343/*
4344** CAPI3REF: Translate filenames
4345**
4346** These routines are available to [VFS|custom VFS implementations] for
4347** translating filenames between the main database file, the journal file,
4348** and the WAL file.
4349**
4350** If F is the name of an sqlite database file, journal file, or WAL file
4351** passed by the SQLite core into the VFS, then sqlite3_filename_database(F)
4352** returns the name of the corresponding database file.
4353**
4354** If F is the name of an sqlite database file, journal file, or WAL file
4355** passed by the SQLite core into the VFS, or if F is a database filename
4356** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F)
4357** returns the name of the corresponding rollback journal file.
4358**
4359** If F is the name of an sqlite database file, journal file, or WAL file
4360** that was passed by the SQLite core into the VFS, or if F is a database
4361** filename obtained from [sqlite3_db_filename()], then
4362** sqlite3_filename_wal(F) returns the name of the corresponding
4363** WAL file.
4364**
4365** In all of the above, if F is not the name of a database, journal or WAL
4366** filename passed into the VFS from the SQLite core and F is not the
4367** return value from [sqlite3_db_filename()], then the result is
4368** undefined and is likely a memory access violation.
4369*/
4370SQLITE_API const char *sqlite3_filename_database(sqlite3_filename);
4371SQLITE_API const char *sqlite3_filename_journal(sqlite3_filename);
4372SQLITE_API const char *sqlite3_filename_wal(sqlite3_filename);
4373
4374/*
4375** CAPI3REF: Database File Corresponding To A Journal
4376**
4377** ^If X is the name of a rollback or WAL-mode journal file that is
4378** passed into the xOpen method of [sqlite3_vfs], then
4379** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file]
4380** object that represents the main database file.
4381**
4382** This routine is intended for use in custom [VFS] implementations
4383** only. It is not a general-purpose interface.
4384** The argument sqlite3_file_object(X) must be a filename pointer that
4385** has been passed into [sqlite3_vfs].xOpen method where the
4386** flags parameter to xOpen contains one of the bits
4387** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL]. Any other use
4388** of this routine results in undefined and probably undesirable
4389** behavior.
4390*/
4391SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);
4392
4393/*
4394** CAPI3REF: Create and Destroy VFS Filenames
4395**
4396** These interfaces are provided for use by [VFS shim] implementations and
4397** are not useful outside of that context.
4398**
4399** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of
4400** database filename D with corresponding journal file J and WAL file W and
4401** an array P of N URI Key/Value pairs. The result from
4402** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that
4403** is safe to pass to routines like:
4404** <ul>
4405** <li> [sqlite3_uri_parameter()],
4406** <li> [sqlite3_uri_boolean()],
4407** <li> [sqlite3_uri_int64()],
4408** <li> [sqlite3_uri_key()],
4409** <li> [sqlite3_filename_database()],
4410** <li> [sqlite3_filename_journal()], or
4411** <li> [sqlite3_filename_wal()].
4412** </ul>
4413** If a memory allocation error occurs, sqlite3_create_filename() might
4414** return a NULL pointer. The memory obtained from sqlite3_create_filename(X)
4415** must be released by a corresponding call to sqlite3_free_filename(Y).
4416**
4417** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array
4418** of 2*N pointers to strings. Each pair of pointers in this array corresponds
4419** to a key and value for a query parameter. The P parameter may be a NULL
4420** pointer if N is zero. None of the 2*N pointers in the P array may be
4421** NULL pointers and key pointers should not be empty strings.
4422** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may
4423** be NULL pointers, though they can be empty strings.
4424**
4425** The sqlite3_free_filename(Y) routine releases a memory allocation
4426** previously obtained from sqlite3_create_filename(). Invoking
4427** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.
4428**
4429** If the Y parameter to sqlite3_free_filename(Y) is anything other
4430** than a NULL pointer or a pointer previously acquired from
4431** sqlite3_create_filename(), then bad things such as heap
4432** corruption or segfaults may occur. The value Y should not be
4433** used again after sqlite3_free_filename(Y) has been called. This means
4434** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y,
4435** then the corresponding [sqlite3_module.xClose() method should also be
4436** invoked prior to calling sqlite3_free_filename(Y).
4437*/
4438SQLITE_API sqlite3_filename sqlite3_create_filename(
4439 const char *zDatabase,
4440 const char *zJournal,
4441 const char *zWal,
4442 int nParam,
4443 const char **azParam
4444);
4445SQLITE_API void sqlite3_free_filename(sqlite3_filename);
4446
4447/*
4448** CAPI3REF: Error Codes And Messages
4449** METHOD: sqlite3
4450**
4451** ^If the most recent sqlite3_* API call associated with
4452** [database connection] D failed, then the sqlite3_errcode(D) interface
4453** returns the numeric [result code] or [extended result code] for that
4454** API call.
4455** ^The sqlite3_extended_errcode()
4456** interface is the same except that it always returns the
4457** [extended result code] even when extended result codes are
4458** disabled.
4459**
4460** The values returned by sqlite3_errcode() and/or
4461** sqlite3_extended_errcode() might change with each API call.
4462** Except, there are some interfaces that are guaranteed to never
4463** change the value of the error code. The error-code preserving
4464** interfaces include the following:
4465**
4466** <ul>
4467** <li> sqlite3_errcode()
4468** <li> sqlite3_extended_errcode()
4469** <li> sqlite3_errmsg()
4470** <li> sqlite3_errmsg16()
4471** <li> sqlite3_error_offset()
4472** </ul>
4473**
4474** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
4475** text that describes the error, as either UTF-8 or UTF-16 respectively,
4476** or NULL if no error message is available.
4477** (See how SQLite handles [invalid UTF] for exceptions to this rule.)
4478** ^(Memory to hold the error message string is managed internally.
4479** The application does not need to worry about freeing the result.
4480** However, the error string might be overwritten or deallocated by
4481** subsequent calls to other SQLite interface functions.)^
4482**
4483** ^The sqlite3_errstr(E) interface returns the English-language text
4484** that describes the [result code] E, as UTF-8, or NULL if E is not an
4485** result code for which a text error message is available.
4486** ^(Memory to hold the error message string is managed internally
4487** and must not be freed by the application)^.
4488**
4489** ^If the most recent error references a specific token in the input
4490** SQL, the sqlite3_error_offset() interface returns the byte offset
4491** of the start of that token. ^The byte offset returned by
4492** sqlite3_error_offset() assumes that the input SQL is UTF8.
4493** ^If the most recent error does not reference a specific token in the input
4494** SQL, then the sqlite3_error_offset() function returns -1.
4495**
4496** When the serialized [threading mode] is in use, it might be the
4497** case that a second error occurs on a separate thread in between
4498** the time of the first error and the call to these interfaces.
4499** When that happens, the second error will be reported since these
4500** interfaces always report the most recent result. To avoid
4501** this, each thread can obtain exclusive use of the [database connection] D
4502** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
4503** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
4504** all calls to the interfaces listed here are completed.
4505**
4506** If an interface fails with SQLITE_MISUSE, that means the interface
4507** was invoked incorrectly by the application. In that case, the
4508** error code and message may or may not be set.
4509*/
4510SQLITE_API int sqlite3_errcode(sqlite3 *db);
4511SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
4512SQLITE_API const char *sqlite3_errmsg(sqlite3*);
4513SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
4514SQLITE_API const char *sqlite3_errstr(int);
4515SQLITE_API int sqlite3_error_offset(sqlite3 *db);
4516
4517/*
4518** CAPI3REF: Prepared Statement Object
4519** KEYWORDS: {prepared statement} {prepared statements}
4520**
4521** An instance of this object represents a single SQL statement that
4522** has been compiled into binary form and is ready to be evaluated.
4523**
4524** Think of each SQL statement as a separate computer program. The
4525** original SQL text is source code. A prepared statement object
4526** is the compiled object code. All SQL must be converted into a
4527** prepared statement before it can be run.
4528**
4529** The life-cycle of a prepared statement object usually goes like this:
4530**
4531** <ol>
4532** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
4533** <li> Bind values to [parameters] using the sqlite3_bind_*()
4534** interfaces.
4535** <li> Run the SQL by calling [sqlite3_step()] one or more times.
4536** <li> Reset the prepared statement using [sqlite3_reset()] then go back
4537** to step 2. Do this zero or more times.
4538** <li> Destroy the object using [sqlite3_finalize()].
4539** </ol>
4540*/
4541typedef struct sqlite3_stmt sqlite3_stmt;
4542
4543/*
4544** CAPI3REF: Run-time Limits
4545** METHOD: sqlite3
4546**
4547** ^(This interface allows the size of various constructs to be limited
4548** on a connection by connection basis. The first parameter is the
4549** [database connection] whose limit is to be set or queried. The
4550** second parameter is one of the [limit categories] that define a
4551** class of constructs to be size limited. The third parameter is the
4552** new limit for that construct.)^
4553**
4554** ^If the new limit is a negative number, the limit is unchanged.
4555** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
4556** [limits | hard upper bound]
4557** set at compile-time by a C preprocessor macro called
4558** [limits | SQLITE_MAX_<i>NAME</i>].
4559** (The "_LIMIT_" in the name is changed to "_MAX_".))^
4560** ^Attempts to increase a limit above its hard upper bound are
4561** silently truncated to the hard upper bound.
4562**
4563** ^Regardless of whether or not the limit was changed, the
4564** [sqlite3_limit()] interface returns the prior value of the limit.
4565** ^Hence, to find the current value of a limit without changing it,
4566** simply invoke this interface with the third parameter set to -1.
4567**
4568** Run-time limits are intended for use in applications that manage
4569** both their own internal database and also databases that are controlled
4570** by untrusted external sources. An example application might be a
4571** web browser that has its own databases for storing history and
4572** separate databases controlled by JavaScript applications downloaded
4573** off the Internet. The internal databases can be given the
4574** large, default limits. Databases managed by external sources can
4575** be given much smaller limits designed to prevent a denial of service
4576** attack. Developers might also want to use the [sqlite3_set_authorizer()]
4577** interface to further control untrusted SQL. The size of the database
4578** created by an untrusted script can be contained using the
4579** [max_page_count] [PRAGMA].
4580**
4581** New run-time limit categories may be added in future releases.
4582*/
4583SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
4584
4585/*
4586** CAPI3REF: Run-Time Limit Categories
4587** KEYWORDS: {limit category} {*limit categories}
4588**
4589** These constants define various performance limits
4590** that can be lowered at run-time using [sqlite3_limit()].
4591** The synopsis of the meanings of the various limits is shown below.
4592** Additional information is available at [limits | Limits in SQLite].
4593**
4594** <dl>
4595** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
4596** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
4597**
4598** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
4599** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
4600**
4601** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
4602** <dd>The maximum number of columns in a table definition or in the
4603** result set of a [SELECT] or the maximum number of columns in an index
4604** or in an ORDER BY or GROUP BY clause.</dd>)^
4605**
4606** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
4607** <dd>The maximum depth of the parse tree on any expression.</dd>)^
4608**
4609** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
4610** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
4611**
4612** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
4613** <dd>The maximum number of instructions in a virtual machine program
4614** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
4615** the equivalent tries to allocate space for more than this many opcodes
4616** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
4617**
4618** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
4619** <dd>The maximum number of arguments on a function.</dd>)^
4620**
4621** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
4622** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
4623**
4624** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
4625** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
4626** <dd>The maximum length of the pattern argument to the [LIKE] or
4627** [GLOB] operators.</dd>)^
4628**
4629** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
4630** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
4631** <dd>The maximum index number of any [parameter] in an SQL statement.)^
4632**
4633** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
4634** <dd>The maximum depth of recursion for triggers.</dd>)^
4635**
4636** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4637** <dd>The maximum number of auxiliary worker threads that a single
4638** [prepared statement] may start.</dd>)^
4639** </dl>
4640*/
4641#define SQLITE_LIMIT_LENGTH0 0
4642#define SQLITE_LIMIT_SQL_LENGTH1 1
4643#define SQLITE_LIMIT_COLUMN2 2
4644#define SQLITE_LIMIT_EXPR_DEPTH3 3
4645#define SQLITE_LIMIT_COMPOUND_SELECT4 4
4646#define SQLITE_LIMIT_VDBE_OP5 5
4647#define SQLITE_LIMIT_FUNCTION_ARG6 6
4648#define SQLITE_LIMIT_ATTACHED7 7
4649#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH8 8
4650#define SQLITE_LIMIT_VARIABLE_NUMBER9 9
4651#define SQLITE_LIMIT_TRIGGER_DEPTH10 10
4652#define SQLITE_LIMIT_WORKER_THREADS11 11
4653
4654/*
4655** CAPI3REF: Prepare Flags
4656**
4657** These constants define various flags that can be passed into
4658** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
4659** [sqlite3_prepare16_v3()] interfaces.
4660**
4661** New flags may be added in future releases of SQLite.
4662**
4663** <dl>
4664** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
4665** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
4666** that the prepared statement will be retained for a long time and
4667** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
4668** and [sqlite3_prepare16_v3()] assume that the prepared statement will
4669** be used just once or at most a few times and then destroyed using
4670** [sqlite3_finalize()] relatively soon. The current implementation acts
4671** on this hint by avoiding the use of [lookaside memory] so as not to
4672** deplete the limited store of lookaside memory. Future versions of
4673** SQLite may act on this hint differently.
4674**
4675** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt>
4676** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
4677** to be required for any prepared statement that wanted to use the
4678** [sqlite3_normalized_sql()] interface. However, the
4679** [sqlite3_normalized_sql()] interface is now available to all
4680** prepared statements, regardless of whether or not they use this
4681** flag.
4682**
4683** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt>
4684** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler
4685** to return an error (error code SQLITE_ERROR) if the statement uses
4686** any virtual tables.
4687**
4688** [[SQLITE_PREPARE_DONT_LOG]] <dt>SQLITE_PREPARE_DONT_LOG</dt>
4689** <dd>The SQLITE_PREPARE_DONT_LOG flag prevents SQL compiler
4690** errors from being sent to the error log defined by
4691** [SQLITE_CONFIG_LOG]. This can be used, for example, to do test
4692** compiles to see if some SQL syntax is well-formed, without generating
4693** messages on the global error log when it is not. If the test compile
4694** fails, the sqlite3_prepare_v3() call returns the same error indications
4695** with or without this flag; it just omits the call to [sqlite3_log()] that
4696** logs the error.
4697** </dl>
4698*/
4699#define SQLITE_PREPARE_PERSISTENT0x01 0x01
4700#define SQLITE_PREPARE_NORMALIZE0x02 0x02
4701#define SQLITE_PREPARE_NO_VTAB0x04 0x04
4702#define SQLITE_PREPARE_DONT_LOG0x10 0x10
4703
4704/*
4705** CAPI3REF: Compiling An SQL Statement
4706** KEYWORDS: {SQL statement compiler}
4707** METHOD: sqlite3
4708** CONSTRUCTOR: sqlite3_stmt
4709**
4710** To execute an SQL statement, it must first be compiled into a byte-code
4711** program using one of these routines. Or, in other words, these routines
4712** are constructors for the [prepared statement] object.
4713**
4714** The preferred routine to use is [sqlite3_prepare_v2()]. The
4715** [sqlite3_prepare()] interface is legacy and should be avoided.
4716** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
4717** for special purposes.
4718**
4719** The use of the UTF-8 interfaces is preferred, as SQLite currently
4720** does all parsing using UTF-8. The UTF-16 interfaces are provided
4721** as a convenience. The UTF-16 interfaces work by converting the
4722** input text into UTF-8, then invoking the corresponding UTF-8 interface.
4723**
4724** The first argument, "db", is a [database connection] obtained from a
4725** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
4726** [sqlite3_open16()]. The database connection must not have been closed.
4727**
4728** The second argument, "zSql", is the statement to be compiled, encoded
4729** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
4730** and sqlite3_prepare_v3()
4731** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
4732** and sqlite3_prepare16_v3() use UTF-16.
4733**
4734** ^If the nByte argument is negative, then zSql is read up to the
4735** first zero terminator. ^If nByte is positive, then it is the maximum
4736** number of bytes read from zSql. When nByte is positive, zSql is read
4737** up to the first zero terminator or until the nByte bytes have been read,
4738** whichever comes first. ^If nByte is zero, then no prepared
4739** statement is generated.
4740** If the caller knows that the supplied string is nul-terminated, then
4741** there is a small performance advantage to passing an nByte parameter that
4742** is the number of bytes in the input string <i>including</i>
4743** the nul-terminator.
4744** Note that nByte measure the length of the input in bytes, not
4745** characters, even for the UTF-16 interfaces.
4746**
4747** ^If pzTail is not NULL then *pzTail is made to point to the first byte
4748** past the end of the first SQL statement in zSql. These routines only
4749** compile the first statement in zSql, so *pzTail is left pointing to
4750** what remains uncompiled.
4751**
4752** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
4753** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
4754** to NULL. ^If the input text contains no SQL (if the input is an empty
4755** string or a comment) then *ppStmt is set to NULL.
4756** The calling procedure is responsible for deleting the compiled
4757** SQL statement using [sqlite3_finalize()] after it has finished with it.
4758** ppStmt may not be NULL.
4759**
4760** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
4761** otherwise an [error code] is returned.
4762**
4763** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
4764** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
4765** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
4766** are retained for backwards compatibility, but their use is discouraged.
4767** ^In the "vX" interfaces, the prepared statement
4768** that is returned (the [sqlite3_stmt] object) contains a copy of the
4769** original SQL text. This causes the [sqlite3_step()] interface to
4770** behave differently in three ways:
4771**
4772** <ol>
4773** <li>
4774** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
4775** always used to do, [sqlite3_step()] will automatically recompile the SQL
4776** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
4777** retries will occur before sqlite3_step() gives up and returns an error.
4778** </li>
4779**
4780** <li>
4781** ^When an error occurs, [sqlite3_step()] will return one of the detailed
4782** [error codes] or [extended error codes]. ^The legacy behavior was that
4783** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
4784** and the application would have to make a second call to [sqlite3_reset()]
4785** in order to find the underlying cause of the problem. With the "v2" prepare
4786** interfaces, the underlying reason for the error is returned immediately.
4787** </li>
4788**
4789** <li>
4790** ^If the specific value bound to a [parameter | host parameter] in the
4791** WHERE clause might influence the choice of query plan for a statement,
4792** then the statement will be automatically recompiled, as if there had been
4793** a schema change, on the first [sqlite3_step()] call following any change
4794** to the [sqlite3_bind_text | bindings] of that [parameter].
4795** ^The specific value of a WHERE-clause [parameter] might influence the
4796** choice of query plan if the parameter is the left-hand side of a [LIKE]
4797** or [GLOB] operator or if the parameter is compared to an indexed column
4798** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.
4799** </li>
4800** </ol>
4801**
4802** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
4803** the extra prepFlags parameter, which is a bit array consisting of zero or
4804** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
4805** sqlite3_prepare_v2() interface works exactly the same as
4806** sqlite3_prepare_v3() with a zero prepFlags parameter.
4807*/
4808SQLITE_API int sqlite3_prepare(
4809 sqlite3 *db, /* Database handle */
4810 const char *zSql, /* SQL statement, UTF-8 encoded */
4811 int nByte, /* Maximum length of zSql in bytes. */
4812 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4813 const char **pzTail /* OUT: Pointer to unused portion of zSql */
4814);
4815SQLITE_API int sqlite3_prepare_v2(
4816 sqlite3 *db, /* Database handle */
4817 const char *zSql, /* SQL statement, UTF-8 encoded */
4818 int nByte, /* Maximum length of zSql in bytes. */
4819 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4820 const char **pzTail /* OUT: Pointer to unused portion of zSql */
4821);
4822SQLITE_API int sqlite3_prepare_v3(
4823 sqlite3 *db, /* Database handle */
4824 const char *zSql, /* SQL statement, UTF-8 encoded */
4825 int nByte, /* Maximum length of zSql in bytes. */
4826 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
4827 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4828 const char **pzTail /* OUT: Pointer to unused portion of zSql */
4829);
4830SQLITE_API int sqlite3_prepare16(
4831 sqlite3 *db, /* Database handle */
4832 const void *zSql, /* SQL statement, UTF-16 encoded */
4833 int nByte, /* Maximum length of zSql in bytes. */
4834 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4835 const void **pzTail /* OUT: Pointer to unused portion of zSql */
4836);
4837SQLITE_API int sqlite3_prepare16_v2(
4838 sqlite3 *db, /* Database handle */
4839 const void *zSql, /* SQL statement, UTF-16 encoded */
4840 int nByte, /* Maximum length of zSql in bytes. */
4841 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4842 const void **pzTail /* OUT: Pointer to unused portion of zSql */
4843);
4844SQLITE_API int sqlite3_prepare16_v3(
4845 sqlite3 *db, /* Database handle */
4846 const void *zSql, /* SQL statement, UTF-16 encoded */
4847 int nByte, /* Maximum length of zSql in bytes. */
4848 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
4849 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4850 const void **pzTail /* OUT: Pointer to unused portion of zSql */
4851);
4852
4853/*
4854** CAPI3REF: Retrieving Statement SQL
4855** METHOD: sqlite3_stmt
4856**
4857** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
4858** SQL text used to create [prepared statement] P if P was
4859** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
4860** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
4861** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
4862** string containing the SQL text of prepared statement P with
4863** [bound parameters] expanded.
4864** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
4865** string containing the normalized SQL text of prepared statement P. The
4866** semantics used to normalize a SQL statement are unspecified and subject
4867** to change. At a minimum, literal values will be replaced with suitable
4868** placeholders.
4869**
4870** ^(For example, if a prepared statement is created using the SQL
4871** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
4872** and parameter :xyz is unbound, then sqlite3_sql() will return
4873** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
4874** will return "SELECT 2345,NULL".)^
4875**
4876** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
4877** is available to hold the result, or if the result would exceed the
4878** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
4879**
4880** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
4881** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
4882** option causes sqlite3_expanded_sql() to always return NULL.
4883**
4884** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
4885** are managed by SQLite and are automatically freed when the prepared
4886** statement is finalized.
4887** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
4888** is obtained from [sqlite3_malloc()] and must be freed by the application
4889** by passing it to [sqlite3_free()].
4890**
4891** ^The sqlite3_normalized_sql() interface is only available if
4892** the [SQLITE_ENABLE_NORMALIZE] compile-time option is defined.
4893*/
4894SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
4895SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
4896#ifdef SQLITE_ENABLE_NORMALIZE
4897SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
4898#endif
4899
4900/*
4901** CAPI3REF: Determine If An SQL Statement Writes The Database
4902** METHOD: sqlite3_stmt
4903**
4904** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
4905** and only if the [prepared statement] X makes no direct changes to
4906** the content of the database file.
4907**
4908** Note that [application-defined SQL functions] or
4909** [virtual tables] might change the database indirectly as a side effect.
4910** ^(For example, if an application defines a function "eval()" that
4911** calls [sqlite3_exec()], then the following SQL statement would
4912** change the database file through side-effects:
4913**
4914** <blockquote><pre>
4915** SELECT eval('DELETE FROM t1') FROM t2;
4916** </pre></blockquote>
4917**
4918** But because the [SELECT] statement does not change the database file
4919** directly, sqlite3_stmt_readonly() would still return true.)^
4920**
4921** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
4922** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
4923** since the statements themselves do not actually modify the database but
4924** rather they control the timing of when other statements modify the
4925** database. ^The [ATTACH] and [DETACH] statements also cause
4926** sqlite3_stmt_readonly() to return true since, while those statements
4927** change the configuration of a database connection, they do not make
4928** changes to the content of the database files on disk.
4929** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
4930** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
4931** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
4932** sqlite3_stmt_readonly() returns false for those commands.
4933**
4934** ^This routine returns false if there is any possibility that the
4935** statement might change the database file. ^A false return does
4936** not guarantee that the statement will change the database file.
4937** ^For example, an UPDATE statement might have a WHERE clause that
4938** makes it a no-op, but the sqlite3_stmt_readonly() result would still
4939** be false. ^Similarly, a CREATE TABLE IF NOT EXISTS statement is a
4940** read-only no-op if the table already exists, but
4941** sqlite3_stmt_readonly() still returns false for such a statement.
4942**
4943** ^If prepared statement X is an [EXPLAIN] or [EXPLAIN QUERY PLAN]
4944** statement, then sqlite3_stmt_readonly(X) returns the same value as
4945** if the EXPLAIN or EXPLAIN QUERY PLAN prefix were omitted.
4946*/
4947SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
4948
4949/*
4950** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement
4951** METHOD: sqlite3_stmt
4952**
4953** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the
4954** prepared statement S is an EXPLAIN statement, or 2 if the
4955** statement S is an EXPLAIN QUERY PLAN.
4956** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is
4957** an ordinary statement or a NULL pointer.
4958*/
4959SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);
4960
4961/*
4962** CAPI3REF: Change The EXPLAIN Setting For A Prepared Statement
4963** METHOD: sqlite3_stmt
4964**
4965** The sqlite3_stmt_explain(S,E) interface changes the EXPLAIN
4966** setting for [prepared statement] S. If E is zero, then S becomes
4967** a normal prepared statement. If E is 1, then S behaves as if
4968** its SQL text began with "[EXPLAIN]". If E is 2, then S behaves as if
4969** its SQL text began with "[EXPLAIN QUERY PLAN]".
4970**
4971** Calling sqlite3_stmt_explain(S,E) might cause S to be reprepared.
4972** SQLite tries to avoid a reprepare, but a reprepare might be necessary
4973** on the first transition into EXPLAIN or EXPLAIN QUERY PLAN mode.
4974**
4975** Because of the potential need to reprepare, a call to
4976** sqlite3_stmt_explain(S,E) will fail with SQLITE_ERROR if S cannot be
4977** reprepared because it was created using [sqlite3_prepare()] instead of
4978** the newer [sqlite3_prepare_v2()] or [sqlite3_prepare_v3()] interfaces and
4979** hence has no saved SQL text with which to reprepare.
4980**
4981** Changing the explain setting for a prepared statement does not change
4982** the original SQL text for the statement. Hence, if the SQL text originally
4983** began with EXPLAIN or EXPLAIN QUERY PLAN, but sqlite3_stmt_explain(S,0)
4984** is called to convert the statement into an ordinary statement, the EXPLAIN
4985** or EXPLAIN QUERY PLAN keywords will still appear in the sqlite3_sql(S)
4986** output, even though the statement now acts like a normal SQL statement.
4987**
4988** This routine returns SQLITE_OK if the explain mode is successfully
4989** changed, or an error code if the explain mode could not be changed.
4990** The explain mode cannot be changed while a statement is active.
4991** Hence, it is good practice to call [sqlite3_reset(S)]
4992** immediately prior to calling sqlite3_stmt_explain(S,E).
4993*/
4994SQLITE_API int sqlite3_stmt_explain(sqlite3_stmt *pStmt, int eMode);
4995
4996/*
4997** CAPI3REF: Determine If A Prepared Statement Has Been Reset
4998** METHOD: sqlite3_stmt
4999**
5000** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
5001** [prepared statement] S has been stepped at least once using
5002** [sqlite3_step(S)] but has neither run to completion (returned
5003** [SQLITE_DONE] from [sqlite3_step(S)]) nor
5004** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
5005** interface returns false if S is a NULL pointer. If S is not a
5006** NULL pointer and is not a pointer to a valid [prepared statement]
5007** object, then the behavior is undefined and probably undesirable.
5008**
5009** This interface can be used in combination [sqlite3_next_stmt()]
5010** to locate all prepared statements associated with a database
5011** connection that are in need of being reset. This can be used,
5012** for example, in diagnostic routines to search for prepared
5013** statements that are holding a transaction open.
5014*/
5015SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
5016
5017/*
5018** CAPI3REF: Dynamically Typed Value Object
5019** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
5020**
5021** SQLite uses the sqlite3_value object to represent all values
5022** that can be stored in a database table. SQLite uses dynamic typing
5023** for the values it stores. ^Values stored in sqlite3_value objects
5024** can be integers, floating point values, strings, BLOBs, or NULL.
5025**
5026** An sqlite3_value object may be either "protected" or "unprotected".
5027** Some interfaces require a protected sqlite3_value. Other interfaces
5028** will accept either a protected or an unprotected sqlite3_value.
5029** Every interface that accepts sqlite3_value arguments specifies
5030** whether or not it requires a protected sqlite3_value. The
5031** [sqlite3_value_dup()] interface can be used to construct a new
5032** protected sqlite3_value from an unprotected sqlite3_value.
5033**
5034** The terms "protected" and "unprotected" refer to whether or not
5035** a mutex is held. An internal mutex is held for a protected
5036** sqlite3_value object but no mutex is held for an unprotected
5037** sqlite3_value object. If SQLite is compiled to be single-threaded
5038** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
5039** or if SQLite is run in one of reduced mutex modes
5040** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
5041** then there is no distinction between protected and unprotected
5042** sqlite3_value objects and they can be used interchangeably. However,
5043** for maximum code portability it is recommended that applications
5044** still make the distinction between protected and unprotected
5045** sqlite3_value objects even when not strictly required.
5046**
5047** ^The sqlite3_value objects that are passed as parameters into the
5048** implementation of [application-defined SQL functions] are protected.
5049** ^The sqlite3_value objects returned by [sqlite3_vtab_rhs_value()]
5050** are protected.
5051** ^The sqlite3_value object returned by
5052** [sqlite3_column_value()] is unprotected.
5053** Unprotected sqlite3_value objects may only be used as arguments
5054** to [sqlite3_result_value()], [sqlite3_bind_value()], and
5055** [sqlite3_value_dup()].
5056** The [sqlite3_value_blob | sqlite3_value_type()] family of
5057** interfaces require protected sqlite3_value objects.
5058*/
5059typedef struct sqlite3_value sqlite3_value;
5060
5061/*
5062** CAPI3REF: SQL Function Context Object
5063**
5064** The context in which an SQL function executes is stored in an
5065** sqlite3_context object. ^A pointer to an sqlite3_context object
5066** is always first parameter to [application-defined SQL functions].
5067** The application-defined SQL function implementation will pass this
5068** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
5069** [sqlite3_aggregate_context()], [sqlite3_user_data()],
5070** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
5071** and/or [sqlite3_set_auxdata()].
5072*/
5073typedef struct sqlite3_context sqlite3_context;
5074
5075/*
5076** CAPI3REF: Binding Values To Prepared Statements
5077** KEYWORDS: {host parameter} {host parameters} {host parameter name}
5078** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
5079** METHOD: sqlite3_stmt
5080**
5081** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
5082** literals may be replaced by a [parameter] that matches one of the following
5083** templates:
5084**
5085** <ul>
5086** <li> ?
5087** <li> ?NNN
5088** <li> :VVV
5089** <li> @VVV
5090** <li> $VVV
5091** </ul>
5092**
5093** In the templates above, NNN represents an integer literal,
5094** and VVV represents an alphanumeric identifier.)^ ^The values of these
5095** parameters (also called "host parameter names" or "SQL parameters")
5096** can be set using the sqlite3_bind_*() routines defined here.
5097**
5098** ^The first argument to the sqlite3_bind_*() routines is always
5099** a pointer to the [sqlite3_stmt] object returned from
5100** [sqlite3_prepare_v2()] or its variants.
5101**
5102** ^The second argument is the index of the SQL parameter to be set.
5103** ^The leftmost SQL parameter has an index of 1. ^When the same named
5104** SQL parameter is used more than once, second and subsequent
5105** occurrences have the same index as the first occurrence.
5106** ^The index for named parameters can be looked up using the
5107** [sqlite3_bind_parameter_index()] API if desired. ^The index
5108** for "?NNN" parameters is the value of NNN.
5109** ^The NNN value must be between 1 and the [sqlite3_limit()]
5110** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766).
5111**
5112** ^The third argument is the value to bind to the parameter.
5113** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
5114** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
5115** is ignored and the end result is the same as sqlite3_bind_null().
5116** ^If the third parameter to sqlite3_bind_text() is not NULL, then
5117** it should be a pointer to well-formed UTF8 text.
5118** ^If the third parameter to sqlite3_bind_text16() is not NULL, then
5119** it should be a pointer to well-formed UTF16 text.
5120** ^If the third parameter to sqlite3_bind_text64() is not NULL, then
5121** it should be a pointer to a well-formed unicode string that is
5122** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16
5123** otherwise.
5124**
5125** [[byte-order determination rules]] ^The byte-order of
5126** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)
5127** found in the first character, which is removed, or in the absence of a BOM
5128** the byte order is the native byte order of the host
5129** machine for sqlite3_bind_text16() or the byte order specified in
5130** the 6th parameter for sqlite3_bind_text64().)^
5131** ^If UTF16 input text contains invalid unicode
5132** characters, then SQLite might change those invalid characters
5133** into the unicode replacement character: U+FFFD.
5134**
5135** ^(In those routines that have a fourth argument, its value is the
5136** number of bytes in the parameter. To be clear: the value is the
5137** number of <u>bytes</u> in the value, not the number of characters.)^
5138** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
5139** is negative, then the length of the string is
5140** the number of bytes up to the first zero terminator.
5141** If the fourth parameter to sqlite3_bind_blob() is negative, then
5142** the behavior is undefined.
5143** If a non-negative fourth parameter is provided to sqlite3_bind_text()
5144** or sqlite3_bind_text16() or sqlite3_bind_text64() then
5145** that parameter must be the byte offset
5146** where the NUL terminator would occur assuming the string were NUL
5147** terminated. If any NUL characters occur at byte offsets less than
5148** the value of the fourth parameter then the resulting string value will
5149** contain embedded NULs. The result of expressions involving strings
5150** with embedded NULs is undefined.
5151**
5152** ^The fifth argument to the BLOB and string binding interfaces controls
5153** or indicates the lifetime of the object referenced by the third parameter.
5154** These three options exist:
5155** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished
5156** with it may be passed. ^It is called to dispose of the BLOB or string even
5157** if the call to the bind API fails, except the destructor is not called if
5158** the third parameter is a NULL pointer or the fourth parameter is negative.
5159** ^ (2) The special constant, [SQLITE_STATIC], may be passed to indicate that
5160** the application remains responsible for disposing of the object. ^In this
5161** case, the object and the provided pointer to it must remain valid until
5162** either the prepared statement is finalized or the same SQL parameter is
5163** bound to something else, whichever occurs sooner.
5164** ^ (3) The constant, [SQLITE_TRANSIENT], may be passed to indicate that the
5165** object is to be copied prior to the return from sqlite3_bind_*(). ^The
5166** object and pointer to it must remain valid until then. ^SQLite will then
5167** manage the lifetime of its private copy.
5168**
5169** ^The sixth argument to sqlite3_bind_text64() must be one of
5170** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
5171** to specify the encoding of the text in the third parameter. If
5172** the sixth argument to sqlite3_bind_text64() is not one of the
5173** allowed values shown above, or if the text encoding is different
5174** from the encoding specified by the sixth parameter, then the behavior
5175** is undefined.
5176**
5177** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
5178** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
5179** (just an integer to hold its size) while it is being processed.
5180** Zeroblobs are intended to serve as placeholders for BLOBs whose
5181** content is later written using
5182** [sqlite3_blob_open | incremental BLOB I/O] routines.
5183** ^A negative value for the zeroblob results in a zero-length BLOB.
5184**
5185** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
5186** [prepared statement] S to have an SQL value of NULL, but to also be
5187** associated with the pointer P of type T. ^D is either a NULL pointer or
5188** a pointer to a destructor function for P. ^SQLite will invoke the
5189** destructor D with a single argument of P when it is finished using
5190** P. The T parameter should be a static string, preferably a string
5191** literal. The sqlite3_bind_pointer() routine is part of the
5192** [pointer passing interface] added for SQLite 3.20.0.
5193**
5194** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
5195** for the [prepared statement] or with a prepared statement for which
5196** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
5197** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
5198** routine is passed a [prepared statement] that has been finalized, the
5199** result is undefined and probably harmful.
5200**
5201** ^Bindings are not cleared by the [sqlite3_reset()] routine.
5202** ^Unbound parameters are interpreted as NULL.
5203**
5204** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
5205** [error code] if anything goes wrong.
5206** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
5207** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
5208** [SQLITE_MAX_LENGTH].
5209** ^[SQLITE_RANGE] is returned if the parameter
5210** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
5211**
5212** See also: [sqlite3_bind_parameter_count()],
5213** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
5214*/
5215SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
5216SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
5217 void(*)(void*));
5218SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
5219SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
5220SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
5221SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
5222SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
5223SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
5224SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
5225 void(*)(void*), unsigned char encoding);
5226SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
5227SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
5228SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
5229SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
5230
5231/*
5232** CAPI3REF: Number Of SQL Parameters
5233** METHOD: sqlite3_stmt
5234**
5235** ^This routine can be used to find the number of [SQL parameters]
5236** in a [prepared statement]. SQL parameters are tokens of the
5237** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
5238** placeholders for values that are [sqlite3_bind_blob | bound]
5239** to the parameters at a later time.
5240**
5241** ^(This routine actually returns the index of the largest (rightmost)
5242** parameter. For all forms except ?NNN, this will correspond to the
5243** number of unique parameters. If parameters of the ?NNN form are used,
5244** there may be gaps in the list.)^
5245**
5246** See also: [sqlite3_bind_blob|sqlite3_bind()],
5247** [sqlite3_bind_parameter_name()], and
5248** [sqlite3_bind_parameter_index()].
5249*/
5250SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
5251
5252/*
5253** CAPI3REF: Name Of A Host Parameter
5254** METHOD: sqlite3_stmt
5255**
5256** ^The sqlite3_bind_parameter_name(P,N) interface returns
5257** the name of the N-th [SQL parameter] in the [prepared statement] P.
5258** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
5259** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
5260** respectively.
5261** In other words, the initial ":" or "$" or "@" or "?"
5262** is included as part of the name.)^
5263** ^Parameters of the form "?" without a following integer have no name
5264** and are referred to as "nameless" or "anonymous parameters".
5265**
5266** ^The first host parameter has an index of 1, not 0.
5267**
5268** ^If the value N is out of range or if the N-th parameter is
5269** nameless, then NULL is returned. ^The returned string is
5270** always in UTF-8 encoding even if the named parameter was
5271** originally specified as UTF-16 in [sqlite3_prepare16()],
5272** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
5273**
5274** See also: [sqlite3_bind_blob|sqlite3_bind()],
5275** [sqlite3_bind_parameter_count()], and
5276** [sqlite3_bind_parameter_index()].
5277*/
5278SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
5279
5280/*
5281** CAPI3REF: Index Of A Parameter With A Given Name
5282** METHOD: sqlite3_stmt
5283**
5284** ^Return the index of an SQL parameter given its name. ^The
5285** index value returned is suitable for use as the second
5286** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
5287** is returned if no matching parameter is found. ^The parameter
5288** name must be given in UTF-8 even if the original statement
5289** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
5290** [sqlite3_prepare16_v3()].
5291**
5292** See also: [sqlite3_bind_blob|sqlite3_bind()],
5293** [sqlite3_bind_parameter_count()], and
5294** [sqlite3_bind_parameter_name()].
5295*/
5296SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
5297
5298/*
5299** CAPI3REF: Reset All Bindings On A Prepared Statement
5300** METHOD: sqlite3_stmt
5301**
5302** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
5303** the [sqlite3_bind_blob | bindings] on a [prepared statement].
5304** ^Use this routine to reset all host parameters to NULL.
5305*/
5306SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
5307
5308/*
5309** CAPI3REF: Number Of Columns In A Result Set
5310** METHOD: sqlite3_stmt
5311**
5312** ^Return the number of columns in the result set returned by the
5313** [prepared statement]. ^If this routine returns 0, that means the
5314** [prepared statement] returns no data (for example an [UPDATE]).
5315** ^However, just because this routine returns a positive number does not
5316** mean that one or more rows of data will be returned. ^A SELECT statement
5317** will always have a positive sqlite3_column_count() but depending on the
5318** WHERE clause constraints and the table content, it might return no rows.
5319**
5320** See also: [sqlite3_data_count()]
5321*/
5322SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
5323
5324/*
5325** CAPI3REF: Column Names In A Result Set
5326** METHOD: sqlite3_stmt
5327**
5328** ^These routines return the name assigned to a particular column
5329** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
5330** interface returns a pointer to a zero-terminated UTF-8 string
5331** and sqlite3_column_name16() returns a pointer to a zero-terminated
5332** UTF-16 string. ^The first parameter is the [prepared statement]
5333** that implements the [SELECT] statement. ^The second parameter is the
5334** column number. ^The leftmost column is number 0.
5335**
5336** ^The returned string pointer is valid until either the [prepared statement]
5337** is destroyed by [sqlite3_finalize()] or until the statement is automatically
5338** reprepared by the first call to [sqlite3_step()] for a particular run
5339** or until the next call to
5340** sqlite3_column_name() or sqlite3_column_name16() on the same column.
5341**
5342** ^If sqlite3_malloc() fails during the processing of either routine
5343** (for example during a conversion from UTF-8 to UTF-16) then a
5344** NULL pointer is returned.
5345**
5346** ^The name of a result column is the value of the "AS" clause for
5347** that column, if there is an AS clause. If there is no AS clause
5348** then the name of the column is unspecified and may change from
5349** one release of SQLite to the next.
5350*/
5351SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
5352SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
5353
5354/*
5355** CAPI3REF: Source Of Data In A Query Result
5356** METHOD: sqlite3_stmt
5357**
5358** ^These routines provide a means to determine the database, table, and
5359** table column that is the origin of a particular result column in a
5360** [SELECT] statement.
5361** ^The name of the database or table or column can be returned as
5362** either a UTF-8 or UTF-16 string. ^The _database_ routines return
5363** the database name, the _table_ routines return the table name, and
5364** the origin_ routines return the column name.
5365** ^The returned string is valid until the [prepared statement] is destroyed
5366** using [sqlite3_finalize()] or until the statement is automatically
5367** reprepared by the first call to [sqlite3_step()] for a particular run
5368** or until the same information is requested
5369** again in a different encoding.
5370**
5371** ^The names returned are the original un-aliased names of the
5372** database, table, and column.
5373**
5374** ^The first argument to these interfaces is a [prepared statement].
5375** ^These functions return information about the Nth result column returned by
5376** the statement, where N is the second function argument.
5377** ^The left-most column is column 0 for these routines.
5378**
5379** ^If the Nth column returned by the statement is an expression or
5380** subquery and is not a column value, then all of these functions return
5381** NULL. ^These routines might also return NULL if a memory allocation error
5382** occurs. ^Otherwise, they return the name of the attached database, table,
5383** or column that query result column was extracted from.
5384**
5385** ^As with all other SQLite APIs, those whose names end with "16" return
5386** UTF-16 encoded strings and the other functions return UTF-8.
5387**
5388** ^These APIs are only available if the library was compiled with the
5389** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
5390**
5391** If two or more threads call one or more
5392** [sqlite3_column_database_name | column metadata interfaces]
5393** for the same [prepared statement] and result column
5394** at the same time then the results are undefined.
5395*/
5396SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
5397SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
5398SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
5399SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
5400SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
5401SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
5402
5403/*
5404** CAPI3REF: Declared Datatype Of A Query Result
5405** METHOD: sqlite3_stmt
5406**
5407** ^(The first parameter is a [prepared statement].
5408** If this statement is a [SELECT] statement and the Nth column of the
5409** returned result set of that [SELECT] is a table column (not an
5410** expression or subquery) then the declared type of the table
5411** column is returned.)^ ^If the Nth column of the result set is an
5412** expression or subquery, then a NULL pointer is returned.
5413** ^The returned string is always UTF-8 encoded.
5414**
5415** ^(For example, given the database schema:
5416**
5417** CREATE TABLE t1(c1 VARIANT);
5418**
5419** and the following statement to be compiled:
5420**
5421** SELECT c1 + 1, c1 FROM t1;
5422**
5423** this routine would return the string "VARIANT" for the second result
5424** column (i==1), and a NULL pointer for the first result column (i==0).)^
5425**
5426** ^SQLite uses dynamic run-time typing. ^So just because a column
5427** is declared to contain a particular type does not mean that the
5428** data stored in that column is of the declared type. SQLite is
5429** strongly typed, but the typing is dynamic not static. ^Type
5430** is associated with individual values, not with the containers
5431** used to hold those values.
5432*/
5433SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
5434SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
5435
5436/*
5437** CAPI3REF: Evaluate An SQL Statement
5438** METHOD: sqlite3_stmt
5439**
5440** After a [prepared statement] has been prepared using any of
5441** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
5442** or [sqlite3_prepare16_v3()] or one of the legacy
5443** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
5444** must be called one or more times to evaluate the statement.
5445**
5446** The details of the behavior of the sqlite3_step() interface depend
5447** on whether the statement was prepared using the newer "vX" interfaces
5448** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
5449** [sqlite3_prepare16_v2()] or the older legacy
5450** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
5451** new "vX" interface is recommended for new applications but the legacy
5452** interface will continue to be supported.
5453**
5454** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
5455** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
5456** ^With the "v2" interface, any of the other [result codes] or
5457** [extended result codes] might be returned as well.
5458**
5459** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
5460** database locks it needs to do its job. ^If the statement is a [COMMIT]
5461** or occurs outside of an explicit transaction, then you can retry the
5462** statement. If the statement is not a [COMMIT] and occurs within an
5463** explicit transaction then you should rollback the transaction before
5464** continuing.
5465**
5466** ^[SQLITE_DONE] means that the statement has finished executing
5467** successfully. sqlite3_step() should not be called again on this virtual
5468** machine without first calling [sqlite3_reset()] to reset the virtual
5469** machine back to its initial state.
5470**
5471** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
5472** is returned each time a new row of data is ready for processing by the
5473** caller. The values may be accessed using the [column access functions].
5474** sqlite3_step() is called again to retrieve the next row of data.
5475**
5476** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
5477** violation) has occurred. sqlite3_step() should not be called again on
5478** the VM. More information may be found by calling [sqlite3_errmsg()].
5479** ^With the legacy interface, a more specific error code (for example,
5480** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
5481** can be obtained by calling [sqlite3_reset()] on the
5482** [prepared statement]. ^In the "v2" interface,
5483** the more specific error code is returned directly by sqlite3_step().
5484**
5485** [SQLITE_MISUSE] means that the this routine was called inappropriately.
5486** Perhaps it was called on a [prepared statement] that has
5487** already been [sqlite3_finalize | finalized] or on one that had
5488** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
5489** be the case that the same database connection is being used by two or
5490** more threads at the same moment in time.
5491**
5492** For all versions of SQLite up to and including 3.6.23.1, a call to
5493** [sqlite3_reset()] was required after sqlite3_step() returned anything
5494** other than [SQLITE_ROW] before any subsequent invocation of
5495** sqlite3_step(). Failure to reset the prepared statement using
5496** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
5497** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1]),
5498** sqlite3_step() began
5499** calling [sqlite3_reset()] automatically in this circumstance rather
5500** than returning [SQLITE_MISUSE]. This is not considered a compatibility
5501** break because any application that ever receives an SQLITE_MISUSE error
5502** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
5503** can be used to restore the legacy behavior.
5504**
5505** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
5506** API always returns a generic error code, [SQLITE_ERROR], following any
5507** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
5508** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
5509** specific [error codes] that better describes the error.
5510** We admit that this is a goofy design. The problem has been fixed
5511** with the "v2" interface. If you prepare all of your SQL statements
5512** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
5513** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
5514** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
5515** then the more specific [error codes] are returned directly
5516** by sqlite3_step(). The use of the "vX" interfaces is recommended.
5517*/
5518SQLITE_API int sqlite3_step(sqlite3_stmt*);
5519
5520/*
5521** CAPI3REF: Number of columns in a result set
5522** METHOD: sqlite3_stmt
5523**
5524** ^The sqlite3_data_count(P) interface returns the number of columns in the
5525** current row of the result set of [prepared statement] P.
5526** ^If prepared statement P does not have results ready to return
5527** (via calls to the [sqlite3_column_int | sqlite3_column()] family of
5528** interfaces) then sqlite3_data_count(P) returns 0.
5529** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
5530** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
5531** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
5532** will return non-zero if previous call to [sqlite3_step](P) returned
5533** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
5534** where it always returns zero since each step of that multi-step
5535** pragma returns 0 columns of data.
5536**
5537** See also: [sqlite3_column_count()]
5538*/
5539SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
5540
5541/*
5542** CAPI3REF: Fundamental Datatypes
5543** KEYWORDS: SQLITE_TEXT
5544**
5545** ^(Every value in SQLite has one of five fundamental datatypes:
5546**
5547** <ul>
5548** <li> 64-bit signed integer
5549** <li> 64-bit IEEE floating point number
5550** <li> string
5551** <li> BLOB
5552** <li> NULL
5553** </ul>)^
5554**
5555** These constants are codes for each of those types.
5556**
5557** Note that the SQLITE_TEXT constant was also used in SQLite version 2
5558** for a completely different meaning. Software that links against both
5559** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
5560** SQLITE_TEXT.
5561*/
5562#define SQLITE_INTEGER1 1
5563#define SQLITE_FLOAT2 2
5564#define SQLITE_BLOB4 4
5565#define SQLITE_NULL5 5
5566#ifdef SQLITE_TEXT3
5567# undef SQLITE_TEXT3
5568#else
5569# define SQLITE_TEXT3 3
5570#endif
5571#define SQLITE3_TEXT3 3
5572
5573/*
5574** CAPI3REF: Result Values From A Query
5575** KEYWORDS: {column access functions}
5576** METHOD: sqlite3_stmt
5577**
5578** <b>Summary:</b>
5579** <blockquote><table border=0 cellpadding=0 cellspacing=0>
5580** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
5581** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
5582** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
5583** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
5584** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
5585** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
5586** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
5587** [sqlite3_value|unprotected sqlite3_value] object.
5588** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
5589** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
5590** or a UTF-8 TEXT result in bytes
5591** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
5592** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
5593** TEXT in bytes
5594** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
5595** datatype of the result
5596** </table></blockquote>
5597**
5598** <b>Details:</b>
5599**
5600** ^These routines return information about a single column of the current
5601** result row of a query. ^In every case the first argument is a pointer
5602** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
5603** that was returned from [sqlite3_prepare_v2()] or one of its variants)
5604** and the second argument is the index of the column for which information
5605** should be returned. ^The leftmost column of the result set has the index 0.
5606** ^The number of columns in the result can be determined using
5607** [sqlite3_column_count()].
5608**
5609** If the SQL statement does not currently point to a valid row, or if the
5610** column index is out of range, the result is undefined.
5611** These routines may only be called when the most recent call to
5612** [sqlite3_step()] has returned [SQLITE_ROW] and neither
5613** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
5614** If any of these routines are called after [sqlite3_reset()] or
5615** [sqlite3_finalize()] or after [sqlite3_step()] has returned
5616** something other than [SQLITE_ROW], the results are undefined.
5617** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
5618** are called from a different thread while any of these routines
5619** are pending, then the results are undefined.
5620**
5621** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
5622** each return the value of a result column in a specific data format. If
5623** the result column is not initially in the requested format (for example,
5624** if the query returns an integer but the sqlite3_column_text() interface
5625** is used to extract the value) then an automatic type conversion is performed.
5626**
5627** ^The sqlite3_column_type() routine returns the
5628** [SQLITE_INTEGER | datatype code] for the initial data type
5629** of the result column. ^The returned value is one of [SQLITE_INTEGER],
5630** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
5631** The return value of sqlite3_column_type() can be used to decide which
5632** of the first six interface should be used to extract the column value.
5633** The value returned by sqlite3_column_type() is only meaningful if no
5634** automatic type conversions have occurred for the value in question.
5635** After a type conversion, the result of calling sqlite3_column_type()
5636** is undefined, though harmless. Future
5637** versions of SQLite may change the behavior of sqlite3_column_type()
5638** following a type conversion.
5639**
5640** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
5641** or sqlite3_column_bytes16() interfaces can be used to determine the size
5642** of that BLOB or string.
5643**
5644** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
5645** routine returns the number of bytes in that BLOB or string.
5646** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
5647** the string to UTF-8 and then returns the number of bytes.
5648** ^If the result is a numeric value then sqlite3_column_bytes() uses
5649** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
5650** the number of bytes in that string.
5651** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
5652**
5653** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
5654** routine returns the number of bytes in that BLOB or string.
5655** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
5656** the string to UTF-16 and then returns the number of bytes.
5657** ^If the result is a numeric value then sqlite3_column_bytes16() uses
5658** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
5659** the number of bytes in that string.
5660** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
5661**
5662** ^The values returned by [sqlite3_column_bytes()] and
5663** [sqlite3_column_bytes16()] do not include the zero terminators at the end
5664** of the string. ^For clarity: the values returned by
5665** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
5666** bytes in the string, not the number of characters.
5667**
5668** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
5669** even empty strings, are always zero-terminated. ^The return
5670** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
5671**
5672** ^Strings returned by sqlite3_column_text16() always have the endianness
5673** which is native to the platform, regardless of the text encoding set
5674** for the database.
5675**
5676** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
5677** [unprotected sqlite3_value] object. In a multithreaded environment,
5678** an unprotected sqlite3_value object may only be used safely with
5679** [sqlite3_bind_value()] and [sqlite3_result_value()].
5680** If the [unprotected sqlite3_value] object returned by
5681** [sqlite3_column_value()] is used in any other way, including calls
5682** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
5683** or [sqlite3_value_bytes()], the behavior is not threadsafe.
5684** Hence, the sqlite3_column_value() interface
5685** is normally only useful within the implementation of
5686** [application-defined SQL functions] or [virtual tables], not within
5687** top-level application code.
5688**
5689** These routines may attempt to convert the datatype of the result.
5690** ^For example, if the internal representation is FLOAT and a text result
5691** is requested, [sqlite3_snprintf()] is used internally to perform the
5692** conversion automatically. ^(The following table details the conversions
5693** that are applied:
5694**
5695** <blockquote>
5696** <table border="1">
5697** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
5698**
5699** <tr><td> NULL <td> INTEGER <td> Result is 0
5700** <tr><td> NULL <td> FLOAT <td> Result is 0.0
5701** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
5702** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
5703** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
5704** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
5705** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
5706** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
5707** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
5708** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
5709** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
5710** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
5711** <tr><td> TEXT <td> BLOB <td> No change
5712** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
5713** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
5714** <tr><td> BLOB <td> TEXT <td> [CAST] to TEXT, ensure zero terminator
5715** </table>
5716** </blockquote>)^
5717**
5718** Note that when type conversions occur, pointers returned by prior
5719** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
5720** sqlite3_column_text16() may be invalidated.
5721** Type conversions and pointer invalidations might occur
5722** in the following cases:
5723**
5724** <ul>
5725** <li> The initial content is a BLOB and sqlite3_column_text() or
5726** sqlite3_column_text16() is called. A zero-terminator might
5727** need to be added to the string.</li>
5728** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
5729** sqlite3_column_text16() is called. The content must be converted
5730** to UTF-16.</li>
5731** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
5732** sqlite3_column_text() is called. The content must be converted
5733** to UTF-8.</li>
5734** </ul>
5735**
5736** ^Conversions between UTF-16be and UTF-16le are always done in place and do
5737** not invalidate a prior pointer, though of course the content of the buffer
5738** that the prior pointer references will have been modified. Other kinds
5739** of conversion are done in place when it is possible, but sometimes they
5740** are not possible and in those cases prior pointers are invalidated.
5741**
5742** The safest policy is to invoke these routines
5743** in one of the following ways:
5744**
5745** <ul>
5746** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
5747** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
5748** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
5749** </ul>
5750**
5751** In other words, you should call sqlite3_column_text(),
5752** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
5753** into the desired format, then invoke sqlite3_column_bytes() or
5754** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
5755** to sqlite3_column_text() or sqlite3_column_blob() with calls to
5756** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
5757** with calls to sqlite3_column_bytes().
5758**
5759** ^The pointers returned are valid until a type conversion occurs as
5760** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
5761** [sqlite3_finalize()] is called. ^The memory space used to hold strings
5762** and BLOBs is freed automatically. Do not pass the pointers returned
5763** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
5764** [sqlite3_free()].
5765**
5766** As long as the input parameters are correct, these routines will only
5767** fail if an out-of-memory error occurs during a format conversion.
5768** Only the following subset of interfaces are subject to out-of-memory
5769** errors:
5770**
5771** <ul>
5772** <li> sqlite3_column_blob()
5773** <li> sqlite3_column_text()
5774** <li> sqlite3_column_text16()
5775** <li> sqlite3_column_bytes()
5776** <li> sqlite3_column_bytes16()
5777** </ul>
5778**
5779** If an out-of-memory error occurs, then the return value from these
5780** routines is the same as if the column had contained an SQL NULL value.
5781** Valid SQL NULL returns can be distinguished from out-of-memory errors
5782** by invoking the [sqlite3_errcode()] immediately after the suspect
5783** return value is obtained and before any
5784** other SQLite interface is called on the same [database connection].
5785*/
5786SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
5787SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
5788SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
5789SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
5790SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
5791SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
5792SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
5793SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
5794SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
5795SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
5796
5797/*
5798** CAPI3REF: Destroy A Prepared Statement Object
5799** DESTRUCTOR: sqlite3_stmt
5800**
5801** ^The sqlite3_finalize() function is called to delete a [prepared statement].
5802** ^If the most recent evaluation of the statement encountered no errors
5803** or if the statement is never been evaluated, then sqlite3_finalize() returns
5804** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
5805** sqlite3_finalize(S) returns the appropriate [error code] or
5806** [extended error code].
5807**
5808** ^The sqlite3_finalize(S) routine can be called at any point during
5809** the life cycle of [prepared statement] S:
5810** before statement S is ever evaluated, after
5811** one or more calls to [sqlite3_reset()], or after any call
5812** to [sqlite3_step()] regardless of whether or not the statement has
5813** completed execution.
5814**
5815** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
5816**
5817** The application must finalize every [prepared statement] in order to avoid
5818** resource leaks. It is a grievous error for the application to try to use
5819** a prepared statement after it has been finalized. Any use of a prepared
5820** statement after it has been finalized can result in undefined and
5821** undesirable behavior such as segfaults and heap corruption.
5822*/
5823SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
5824
5825/*
5826** CAPI3REF: Reset A Prepared Statement Object
5827** METHOD: sqlite3_stmt
5828**
5829** The sqlite3_reset() function is called to reset a [prepared statement]
5830** object back to its initial state, ready to be re-executed.
5831** ^Any SQL statement variables that had values bound to them using
5832** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
5833** Use [sqlite3_clear_bindings()] to reset the bindings.
5834**
5835** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
5836** back to the beginning of its program.
5837**
5838** ^The return code from [sqlite3_reset(S)] indicates whether or not
5839** the previous evaluation of prepared statement S completed successfully.
5840** ^If [sqlite3_step(S)] has never before been called on S or if
5841** [sqlite3_step(S)] has not been called since the previous call
5842** to [sqlite3_reset(S)], then [sqlite3_reset(S)] will return
5843** [SQLITE_OK].
5844**
5845** ^If the most recent call to [sqlite3_step(S)] for the
5846** [prepared statement] S indicated an error, then
5847** [sqlite3_reset(S)] returns an appropriate [error code].
5848** ^The [sqlite3_reset(S)] interface might also return an [error code]
5849** if there were no prior errors but the process of resetting
5850** the prepared statement caused a new error. ^For example, if an
5851** [INSERT] statement with a [RETURNING] clause is only stepped one time,
5852** that one call to [sqlite3_step(S)] might return SQLITE_ROW but
5853** the overall statement might still fail and the [sqlite3_reset(S)] call
5854** might return SQLITE_BUSY if locking constraints prevent the
5855** database change from committing. Therefore, it is important that
5856** applications check the return code from [sqlite3_reset(S)] even if
5857** no prior call to [sqlite3_step(S)] indicated a problem.
5858**
5859** ^The [sqlite3_reset(S)] interface does not change the values
5860** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
5861*/
5862SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
5863
5864
5865/*
5866** CAPI3REF: Create Or Redefine SQL Functions
5867** KEYWORDS: {function creation routines}
5868** METHOD: sqlite3
5869**
5870** ^These functions (collectively known as "function creation routines")
5871** are used to add SQL functions or aggregates or to redefine the behavior
5872** of existing SQL functions or aggregates. The only differences between
5873** the three "sqlite3_create_function*" routines are the text encoding
5874** expected for the second parameter (the name of the function being
5875** created) and the presence or absence of a destructor callback for
5876** the application data pointer. Function sqlite3_create_window_function()
5877** is similar, but allows the user to supply the extra callback functions
5878** needed by [aggregate window functions].
5879**
5880** ^The first parameter is the [database connection] to which the SQL
5881** function is to be added. ^If an application uses more than one database
5882** connection then application-defined SQL functions must be added
5883** to each database connection separately.
5884**
5885** ^The second parameter is the name of the SQL function to be created or
5886** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
5887** representation, exclusive of the zero-terminator. ^Note that the name
5888** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
5889** ^Any attempt to create a function with a longer name
5890** will result in [SQLITE_MISUSE] being returned.
5891**
5892** ^The third parameter (nArg)
5893** is the number of arguments that the SQL function or
5894** aggregate takes. ^If this parameter is -1, then the SQL function or
5895** aggregate may take any number of arguments between 0 and the limit
5896** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
5897** parameter is less than -1 or greater than 127 then the behavior is
5898** undefined.
5899**
5900** ^The fourth parameter, eTextRep, specifies what
5901** [SQLITE_UTF8 | text encoding] this SQL function prefers for
5902** its parameters. The application should set this parameter to
5903** [SQLITE_UTF16LE] if the function implementation invokes
5904** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
5905** implementation invokes [sqlite3_value_text16be()] on an input, or
5906** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
5907** otherwise. ^The same SQL function may be registered multiple times using
5908** different preferred text encodings, with different implementations for
5909** each encoding.
5910** ^When multiple implementations of the same function are available, SQLite
5911** will pick the one that involves the least amount of data conversion.
5912**
5913** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
5914** to signal that the function will always return the same result given
5915** the same inputs within a single SQL statement. Most SQL functions are
5916** deterministic. The built-in [random()] SQL function is an example of a
5917** function that is not deterministic. The SQLite query planner is able to
5918** perform additional optimizations on deterministic functions, so use
5919** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
5920**
5921** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY]
5922** flag, which if present prevents the function from being invoked from
5923** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,
5924** index expressions, or the WHERE clause of partial indexes.
5925**
5926** For best security, the [SQLITE_DIRECTONLY] flag is recommended for
5927** all application-defined SQL functions that do not need to be
5928** used inside of triggers, views, CHECK constraints, or other elements of
5929** the database schema. This flag is especially recommended for SQL
5930** functions that have side effects or reveal internal application state.
5931** Without this flag, an attacker might be able to modify the schema of
5932** a database file to include invocations of the function with parameters
5933** chosen by the attacker, which the application will then execute when
5934** the database file is opened and read.
5935**
5936** ^(The fifth parameter is an arbitrary pointer. The implementation of the
5937** function can gain access to this pointer using [sqlite3_user_data()].)^
5938**
5939** ^The sixth, seventh and eighth parameters passed to the three
5940** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are
5941** pointers to C-language functions that implement the SQL function or
5942** aggregate. ^A scalar SQL function requires an implementation of the xFunc
5943** callback only; NULL pointers must be passed as the xStep and xFinal
5944** parameters. ^An aggregate SQL function requires an implementation of xStep
5945** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
5946** SQL function or aggregate, pass NULL pointers for all three function
5947** callbacks.
5948**
5949** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
5950** and xInverse) passed to sqlite3_create_window_function are pointers to
5951** C-language callbacks that implement the new function. xStep and xFinal
5952** must both be non-NULL. xValue and xInverse may either both be NULL, in
5953** which case a regular aggregate function is created, or must both be
5954** non-NULL, in which case the new function may be used as either an aggregate
5955** or aggregate window function. More details regarding the implementation
5956** of aggregate window functions are
5957** [user-defined window functions|available here].
5958**
5959** ^(If the final parameter to sqlite3_create_function_v2() or
5960** sqlite3_create_window_function() is not NULL, then it is the destructor for
5961** the application data pointer. The destructor is invoked when the function
5962** is deleted, either by being overloaded or when the database connection
5963** closes.)^ ^The destructor is also invoked if the call to
5964** sqlite3_create_function_v2() fails. ^When the destructor callback is
5965** invoked, it is passed a single argument which is a copy of the application
5966** data pointer which was the fifth parameter to sqlite3_create_function_v2().
5967**
5968** ^It is permitted to register multiple implementations of the same
5969** functions with the same name but with either differing numbers of
5970** arguments or differing preferred text encodings. ^SQLite will use
5971** the implementation that most closely matches the way in which the
5972** SQL function is used. ^A function implementation with a non-negative
5973** nArg parameter is a better match than a function implementation with
5974** a negative nArg. ^A function where the preferred text encoding
5975** matches the database encoding is a better
5976** match than a function where the encoding is different.
5977** ^A function where the encoding difference is between UTF16le and UTF16be
5978** is a closer match than a function where the encoding difference is
5979** between UTF8 and UTF16.
5980**
5981** ^Built-in functions may be overloaded by new application-defined functions.
5982**
5983** ^An application-defined function is permitted to call other
5984** SQLite interfaces. However, such calls must not
5985** close the database connection nor finalize or reset the prepared
5986** statement in which the function is running.
5987*/
5988SQLITE_API int sqlite3_create_function(
5989 sqlite3 *db,
5990 const char *zFunctionName,
5991 int nArg,
5992 int eTextRep,
5993 void *pApp,
5994 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5995 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5996 void (*xFinal)(sqlite3_context*)
5997);
5998SQLITE_API int sqlite3_create_function16(
5999 sqlite3 *db,
6000 const void *zFunctionName,
6001 int nArg,
6002 int eTextRep,
6003 void *pApp,
6004 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
6005 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
6006 void (*xFinal)(sqlite3_context*)
6007);
6008SQLITE_API int sqlite3_create_function_v2(
6009 sqlite3 *db,
6010 const char *zFunctionName,
6011 int nArg,
6012 int eTextRep,
6013 void *pApp,
6014 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
6015 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
6016 void (*xFinal)(sqlite3_context*),
6017 void(*xDestroy)(void*)
6018);
6019SQLITE_API int sqlite3_create_window_function(
6020 sqlite3 *db,
6021 const char *zFunctionName,
6022 int nArg,
6023 int eTextRep,
6024 void *pApp,
6025 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
6026 void (*xFinal)(sqlite3_context*),
6027 void (*xValue)(sqlite3_context*),
6028 void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
6029 void(*xDestroy)(void*)
6030);
6031
6032/*
6033** CAPI3REF: Text Encodings
6034**
6035** These constant define integer codes that represent the various
6036** text encodings supported by SQLite.
6037*/
6038#define SQLITE_UTF81 1 /* IMP: R-37514-35566 */
6039#define SQLITE_UTF16LE2 2 /* IMP: R-03371-37637 */
6040#define SQLITE_UTF16BE3 3 /* IMP: R-51971-34154 */
6041#define SQLITE_UTF164 4 /* Use native byte order */
6042#define SQLITE_ANY5 5 /* Deprecated */
6043#define SQLITE_UTF16_ALIGNED8 8 /* sqlite3_create_collation only */
6044
6045/*
6046** CAPI3REF: Function Flags
6047**
6048** These constants may be ORed together with the
6049** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
6050** to [sqlite3_create_function()], [sqlite3_create_function16()], or
6051** [sqlite3_create_function_v2()].
6052**
6053** <dl>
6054** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd>
6055** The SQLITE_DETERMINISTIC flag means that the new function always gives
6056** the same output when the input parameters are the same.
6057** The [abs|abs() function] is deterministic, for example, but
6058** [randomblob|randomblob()] is not. Functions must
6059** be deterministic in order to be used in certain contexts such as
6060** with the WHERE clause of [partial indexes] or in [generated columns].
6061** SQLite might also optimize deterministic functions by factoring them
6062** out of inner loops.
6063** </dd>
6064**
6065** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd>
6066** The SQLITE_DIRECTONLY flag means that the function may only be invoked
6067** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in
6068** schema structures such as [CHECK constraints], [DEFAULT clauses],
6069** [expression indexes], [partial indexes], or [generated columns].
6070** <p>
6071** The SQLITE_DIRECTONLY flag is recommended for any
6072** [application-defined SQL function]
6073** that has side-effects or that could potentially leak sensitive information.
6074** This will prevent attacks in which an application is tricked
6075** into using a database file that has had its schema surreptitiously
6076** modified to invoke the application-defined function in ways that are
6077** harmful.
6078** <p>
6079** Some people say it is good practice to set SQLITE_DIRECTONLY on all
6080** [application-defined SQL functions], regardless of whether or not they
6081** are security sensitive, as doing so prevents those functions from being used
6082** inside of the database schema, and thus ensures that the database
6083** can be inspected and modified using generic tools (such as the [CLI])
6084** that do not have access to the application-defined functions.
6085** </dd>
6086**
6087** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd>
6088** The SQLITE_INNOCUOUS flag means that the function is unlikely
6089** to cause problems even if misused. An innocuous function should have
6090** no side effects and should not depend on any values other than its
6091** input parameters. The [abs|abs() function] is an example of an
6092** innocuous function.
6093** The [load_extension() SQL function] is not innocuous because of its
6094** side effects.
6095** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not
6096** exactly the same. The [random|random() function] is an example of a
6097** function that is innocuous but not deterministic.
6098** <p>Some heightened security settings
6099** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF])
6100** disable the use of SQL functions inside views and triggers and in
6101** schema structures such as [CHECK constraints], [DEFAULT clauses],
6102** [expression indexes], [partial indexes], and [generated columns] unless
6103** the function is tagged with SQLITE_INNOCUOUS. Most built-in functions
6104** are innocuous. Developers are advised to avoid using the
6105** SQLITE_INNOCUOUS flag for application-defined functions unless the
6106** function has been carefully audited and found to be free of potentially
6107** security-adverse side-effects and information-leaks.
6108** </dd>
6109**
6110** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>
6111** The SQLITE_SUBTYPE flag indicates to SQLite that a function might call
6112** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
6113** This flag instructs SQLite to omit some corner-case optimizations that
6114** might disrupt the operation of the [sqlite3_value_subtype()] function,
6115** causing it to return zero rather than the correct subtype().
6116** All SQL functions that invoke [sqlite3_value_subtype()] should have this
6117** property. If the SQLITE_SUBTYPE property is omitted, then the return
6118** value from [sqlite3_value_subtype()] might sometimes be zero even though
6119** a non-zero subtype was specified by the function argument expression.
6120**
6121** [[SQLITE_RESULT_SUBTYPE]] <dt>SQLITE_RESULT_SUBTYPE</dt><dd>
6122** The SQLITE_RESULT_SUBTYPE flag indicates to SQLite that a function might call
6123** [sqlite3_result_subtype()] to cause a sub-type to be associated with its
6124** result.
6125** Every function that invokes [sqlite3_result_subtype()] should have this
6126** property. If it does not, then the call to [sqlite3_result_subtype()]
6127** might become a no-op if the function is used as term in an
6128** [expression index]. On the other hand, SQL functions that never invoke
6129** [sqlite3_result_subtype()] should avoid setting this property, as the
6130** purpose of this property is to disable certain optimizations that are
6131** incompatible with subtypes.
6132**
6133** [[SQLITE_SELFORDER1]] <dt>SQLITE_SELFORDER1</dt><dd>
6134** The SQLITE_SELFORDER1 flag indicates that the function is an aggregate
6135** that internally orders the values provided to the first argument. The
6136** ordered-set aggregate SQL notation with a single ORDER BY term can be
6137** used to invoke this function. If the ordered-set aggregate notation is
6138** used on a function that lacks this flag, then an error is raised. Note
6139** that the ordered-set aggregate syntax is only available if SQLite is
6140** built using the -DSQLITE_ENABLE_ORDERED_SET_AGGREGATES compile-time option.
6141** </dd>
6142** </dl>
6143*/
6144#define SQLITE_DETERMINISTIC0x000000800 0x000000800
6145#define SQLITE_DIRECTONLY0x000080000 0x000080000
6146#define SQLITE_SUBTYPE0x000100000 0x000100000
6147#define SQLITE_INNOCUOUS0x000200000 0x000200000
6148#define SQLITE_RESULT_SUBTYPE0x001000000 0x001000000
6149#define SQLITE_SELFORDER10x002000000 0x002000000
6150
6151/*
6152** CAPI3REF: Deprecated Functions
6153** DEPRECATED
6154**
6155** These functions are [deprecated]. In order to maintain
6156** backwards compatibility with older code, these functions continue
6157** to be supported. However, new applications should avoid
6158** the use of these functions. To encourage programmers to avoid
6159** these functions, we will not explain what they do.
6160*/
6161#ifndef SQLITE_OMIT_DEPRECATED1
6162SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
6163SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
6164SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
6165SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
6166SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
6167SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
6168 void*,sqlite3_int64);
6169#endif
6170
6171/*
6172** CAPI3REF: Obtaining SQL Values
6173** METHOD: sqlite3_value
6174**
6175** <b>Summary:</b>
6176** <blockquote><table border=0 cellpadding=0 cellspacing=0>
6177** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
6178** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
6179** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
6180** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
6181** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
6182** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
6183** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
6184** the native byteorder
6185** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
6186** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
6187** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
6188** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
6189** or a UTF-8 TEXT in bytes
6190** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
6191** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
6192** TEXT in bytes
6193** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
6194** datatype of the value
6195** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
6196** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
6197** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
6198** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
6199** against a virtual table.
6200** <tr><td><b>sqlite3_value_frombind&nbsp;&nbsp;</b>
6201** <td>&rarr;&nbsp;&nbsp;<td>True if value originated from a [bound parameter]
6202** </table></blockquote>
6203**
6204** <b>Details:</b>
6205**
6206** These routines extract type, size, and content information from
6207** [protected sqlite3_value] objects. Protected sqlite3_value objects
6208** are used to pass parameter information into the functions that
6209** implement [application-defined SQL functions] and [virtual tables].
6210**
6211** These routines work only with [protected sqlite3_value] objects.
6212** Any attempt to use these routines on an [unprotected sqlite3_value]
6213** is not threadsafe.
6214**
6215** ^These routines work just like the corresponding [column access functions]
6216** except that these routines take a single [protected sqlite3_value] object
6217** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
6218**
6219** ^The sqlite3_value_text16() interface extracts a UTF-16 string
6220** in the native byte-order of the host machine. ^The
6221** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
6222** extract UTF-16 strings as big-endian and little-endian respectively.
6223**
6224** ^If [sqlite3_value] object V was initialized
6225** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
6226** and if X and Y are strings that compare equal according to strcmp(X,Y),
6227** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
6228** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
6229** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
6230**
6231** ^(The sqlite3_value_type(V) interface returns the
6232** [SQLITE_INTEGER | datatype code] for the initial datatype of the
6233** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
6234** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
6235** Other interfaces might change the datatype for an sqlite3_value object.
6236** For example, if the datatype is initially SQLITE_INTEGER and
6237** sqlite3_value_text(V) is called to extract a text value for that
6238** integer, then subsequent calls to sqlite3_value_type(V) might return
6239** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
6240** occurs is undefined and may change from one release of SQLite to the next.
6241**
6242** ^(The sqlite3_value_numeric_type() interface attempts to apply
6243** numeric affinity to the value. This means that an attempt is
6244** made to convert the value to an integer or floating point. If
6245** such a conversion is possible without loss of information (in other
6246** words, if the value is a string that looks like a number)
6247** then the conversion is performed. Otherwise no conversion occurs.
6248** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
6249**
6250** ^Within the [xUpdate] method of a [virtual table], the
6251** sqlite3_value_nochange(X) interface returns true if and only if
6252** the column corresponding to X is unchanged by the UPDATE operation
6253** that the xUpdate method call was invoked to implement and if
6254** and the prior [xColumn] method call that was invoked to extracted
6255** the value for that column returned without setting a result (probably
6256** because it queried [sqlite3_vtab_nochange()] and found that the column
6257** was unchanging). ^Within an [xUpdate] method, any value for which
6258** sqlite3_value_nochange(X) is true will in all other respects appear
6259** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other
6260** than within an [xUpdate] method call for an UPDATE statement, then
6261** the return value is arbitrary and meaningless.
6262**
6263** ^The sqlite3_value_frombind(X) interface returns non-zero if the
6264** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]
6265** interfaces. ^If X comes from an SQL literal value, or a table column,
6266** or an expression, then sqlite3_value_frombind(X) returns zero.
6267**
6268** Please pay particular attention to the fact that the pointer returned
6269** from [sqlite3_value_blob()], [sqlite3_value_text()], or
6270** [sqlite3_value_text16()] can be invalidated by a subsequent call to
6271** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
6272** or [sqlite3_value_text16()].
6273**
6274** These routines must be called from the same thread as
6275** the SQL function that supplied the [sqlite3_value*] parameters.
6276**
6277** As long as the input parameter is correct, these routines can only
6278** fail if an out-of-memory error occurs during a format conversion.
6279** Only the following subset of interfaces are subject to out-of-memory
6280** errors:
6281**
6282** <ul>
6283** <li> sqlite3_value_blob()
6284** <li> sqlite3_value_text()
6285** <li> sqlite3_value_text16()
6286** <li> sqlite3_value_text16le()
6287** <li> sqlite3_value_text16be()
6288** <li> sqlite3_value_bytes()
6289** <li> sqlite3_value_bytes16()
6290** </ul>
6291**
6292** If an out-of-memory error occurs, then the return value from these
6293** routines is the same as if the column had contained an SQL NULL value.
6294** Valid SQL NULL returns can be distinguished from out-of-memory errors
6295** by invoking the [sqlite3_errcode()] immediately after the suspect
6296** return value is obtained and before any
6297** other SQLite interface is called on the same [database connection].
6298*/
6299SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
6300SQLITE_API double sqlite3_value_double(sqlite3_value*);
6301SQLITE_API int sqlite3_value_int(sqlite3_value*);
6302SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
6303SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
6304SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
6305SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
6306SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
6307SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
6308SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
6309SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
6310SQLITE_API int sqlite3_value_type(sqlite3_value*);
6311SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
6312SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
6313SQLITE_API int sqlite3_value_frombind(sqlite3_value*);
6314
6315/*
6316** CAPI3REF: Report the internal text encoding state of an sqlite3_value object
6317** METHOD: sqlite3_value
6318**
6319** ^(The sqlite3_value_encoding(X) interface returns one of [SQLITE_UTF8],
6320** [SQLITE_UTF16BE], or [SQLITE_UTF16LE] according to the current text encoding
6321** of the value X, assuming that X has type TEXT.)^ If sqlite3_value_type(X)
6322** returns something other than SQLITE_TEXT, then the return value from
6323** sqlite3_value_encoding(X) is meaningless. ^Calls to
6324** [sqlite3_value_text(X)], [sqlite3_value_text16(X)], [sqlite3_value_text16be(X)],
6325** [sqlite3_value_text16le(X)], [sqlite3_value_bytes(X)], or
6326** [sqlite3_value_bytes16(X)] might change the encoding of the value X and
6327** thus change the return from subsequent calls to sqlite3_value_encoding(X).
6328**
6329** This routine is intended for used by applications that test and validate
6330** the SQLite implementation. This routine is inquiring about the opaque
6331** internal state of an [sqlite3_value] object. Ordinary applications should
6332** not need to know what the internal state of an sqlite3_value object is and
6333** hence should not need to use this interface.
6334*/
6335SQLITE_API int sqlite3_value_encoding(sqlite3_value*);
6336
6337/*
6338** CAPI3REF: Finding The Subtype Of SQL Values
6339** METHOD: sqlite3_value
6340**
6341** The sqlite3_value_subtype(V) function returns the subtype for
6342** an [application-defined SQL function] argument V. The subtype
6343** information can be used to pass a limited amount of context from
6344** one SQL function to another. Use the [sqlite3_result_subtype()]
6345** routine to set the subtype for the return value of an SQL function.
6346**
6347** Every [application-defined SQL function] that invokes this interface
6348** should include the [SQLITE_SUBTYPE] property in the text
6349** encoding argument when the function is [sqlite3_create_function|registered].
6350** If the [SQLITE_SUBTYPE] property is omitted, then sqlite3_value_subtype()
6351** might return zero instead of the upstream subtype in some corner cases.
6352*/
6353SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
6354
6355/*
6356** CAPI3REF: Copy And Free SQL Values
6357** METHOD: sqlite3_value
6358**
6359** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
6360** object V and returns a pointer to that copy. ^The [sqlite3_value] returned
6361** is a [protected sqlite3_value] object even if the input is not.
6362** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
6363** memory allocation fails. ^If V is a [pointer value], then the result
6364** of sqlite3_value_dup(V) is a NULL value.
6365**
6366** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
6367** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
6368** then sqlite3_value_free(V) is a harmless no-op.
6369*/
6370SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
6371SQLITE_API void sqlite3_value_free(sqlite3_value*);
6372
6373/*
6374** CAPI3REF: Obtain Aggregate Function Context
6375** METHOD: sqlite3_context
6376**
6377** Implementations of aggregate SQL functions use this
6378** routine to allocate memory for storing their state.
6379**
6380** ^The first time the sqlite3_aggregate_context(C,N) routine is called
6381** for a particular aggregate function, SQLite allocates
6382** N bytes of memory, zeroes out that memory, and returns a pointer
6383** to the new memory. ^On second and subsequent calls to
6384** sqlite3_aggregate_context() for the same aggregate function instance,
6385** the same buffer is returned. Sqlite3_aggregate_context() is normally
6386** called once for each invocation of the xStep callback and then one
6387** last time when the xFinal callback is invoked. ^(When no rows match
6388** an aggregate query, the xStep() callback of the aggregate function
6389** implementation is never called and xFinal() is called exactly once.
6390** In those cases, sqlite3_aggregate_context() might be called for the
6391** first time from within xFinal().)^
6392**
6393** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
6394** when first called if N is less than or equal to zero or if a memory
6395** allocation error occurs.
6396**
6397** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
6398** determined by the N parameter on the first successful call. Changing the
6399** value of N in any subsequent call to sqlite3_aggregate_context() within
6400** the same aggregate function instance will not resize the memory
6401** allocation.)^ Within the xFinal callback, it is customary to set
6402** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
6403** pointless memory allocations occur.
6404**
6405** ^SQLite automatically frees the memory allocated by
6406** sqlite3_aggregate_context() when the aggregate query concludes.
6407**
6408** The first parameter must be a copy of the
6409** [sqlite3_context | SQL function context] that is the first parameter
6410** to the xStep or xFinal callback routine that implements the aggregate
6411** function.
6412**
6413** This routine must be called from the same thread in which
6414** the aggregate SQL function is running.
6415*/
6416SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
6417
6418/*
6419** CAPI3REF: User Data For Functions
6420** METHOD: sqlite3_context
6421**
6422** ^The sqlite3_user_data() interface returns a copy of
6423** the pointer that was the pUserData parameter (the 5th parameter)
6424** of the [sqlite3_create_function()]
6425** and [sqlite3_create_function16()] routines that originally
6426** registered the application defined function.
6427**
6428** This routine must be called from the same thread in which
6429** the application-defined function is running.
6430*/
6431SQLITE_API void *sqlite3_user_data(sqlite3_context*);
6432
6433/*
6434** CAPI3REF: Database Connection For Functions
6435** METHOD: sqlite3_context
6436**
6437** ^The sqlite3_context_db_handle() interface returns a copy of
6438** the pointer to the [database connection] (the 1st parameter)
6439** of the [sqlite3_create_function()]
6440** and [sqlite3_create_function16()] routines that originally
6441** registered the application defined function.
6442*/
6443SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
6444
6445/*
6446** CAPI3REF: Function Auxiliary Data
6447** METHOD: sqlite3_context
6448**
6449** These functions may be used by (non-aggregate) SQL functions to
6450** associate auxiliary data with argument values. If the same argument
6451** value is passed to multiple invocations of the same SQL function during
6452** query execution, under some circumstances the associated auxiliary data
6453** might be preserved. An example of where this might be useful is in a
6454** regular-expression matching function. The compiled version of the regular
6455** expression can be stored as auxiliary data associated with the pattern string.
6456** Then as long as the pattern string remains the same,
6457** the compiled regular expression can be reused on multiple
6458** invocations of the same function.
6459**
6460** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the auxiliary data
6461** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
6462** value to the application-defined function. ^N is zero for the left-most
6463** function argument. ^If there is no auxiliary data
6464** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
6465** returns a NULL pointer.
6466**
6467** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as auxiliary data for the
6468** N-th argument of the application-defined function. ^Subsequent
6469** calls to sqlite3_get_auxdata(C,N) return P from the most recent
6470** sqlite3_set_auxdata(C,N,P,X) call if the auxiliary data is still valid or
6471** NULL if the auxiliary data has been discarded.
6472** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
6473** SQLite will invoke the destructor function X with parameter P exactly
6474** once, when the auxiliary data is discarded.
6475** SQLite is free to discard the auxiliary data at any time, including: <ul>
6476** <li> ^(when the corresponding function parameter changes)^, or
6477** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
6478** SQL statement)^, or
6479** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
6480** parameter)^, or
6481** <li> ^(during the original sqlite3_set_auxdata() call when a memory
6482** allocation error occurs.)^
6483** <li> ^(during the original sqlite3_set_auxdata() call if the function
6484** is evaluated during query planning instead of during query execution,
6485** as sometimes happens with [SQLITE_ENABLE_STAT4].)^ </ul>
6486**
6487** Note the last two bullets in particular. The destructor X in
6488** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
6489** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
6490** should be called near the end of the function implementation and the
6491** function implementation should not make any use of P after
6492** sqlite3_set_auxdata() has been called. Furthermore, a call to
6493** sqlite3_get_auxdata() that occurs immediately after a corresponding call
6494** to sqlite3_set_auxdata() might still return NULL if an out-of-memory
6495** condition occurred during the sqlite3_set_auxdata() call or if the
6496** function is being evaluated during query planning rather than during
6497** query execution.
6498**
6499** ^(In practice, auxiliary data is preserved between function calls for
6500** function parameters that are compile-time constants, including literal
6501** values and [parameters] and expressions composed from the same.)^
6502**
6503** The value of the N parameter to these interfaces should be non-negative.
6504** Future enhancements may make use of negative N values to define new
6505** kinds of function caching behavior.
6506**
6507** These routines must be called from the same thread in which
6508** the SQL function is running.
6509**
6510** See also: [sqlite3_get_clientdata()] and [sqlite3_set_clientdata()].
6511*/
6512SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
6513SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
6514
6515/*
6516** CAPI3REF: Database Connection Client Data
6517** METHOD: sqlite3
6518**
6519** These functions are used to associate one or more named pointers
6520** with a [database connection].
6521** A call to sqlite3_set_clientdata(D,N,P,X) causes the pointer P
6522** to be attached to [database connection] D using name N. Subsequent
6523** calls to sqlite3_get_clientdata(D,N) will return a copy of pointer P
6524** or a NULL pointer if there were no prior calls to
6525** sqlite3_set_clientdata() with the same values of D and N.
6526** Names are compared using strcmp() and are thus case sensitive.
6527**
6528** If P and X are both non-NULL, then the destructor X is invoked with
6529** argument P on the first of the following occurrences:
6530** <ul>
6531** <li> An out-of-memory error occurs during the call to
6532** sqlite3_set_clientdata() which attempts to register pointer P.
6533** <li> A subsequent call to sqlite3_set_clientdata(D,N,P,X) is made
6534** with the same D and N parameters.
6535** <li> The database connection closes. SQLite does not make any guarantees
6536** about the order in which destructors are called, only that all
6537** destructors will be called exactly once at some point during the
6538** database connection closing process.
6539** </ul>
6540**
6541** SQLite does not do anything with client data other than invoke
6542** destructors on the client data at the appropriate time. The intended
6543** use for client data is to provide a mechanism for wrapper libraries
6544** to store additional information about an SQLite database connection.
6545**
6546** There is no limit (other than available memory) on the number of different
6547** client data pointers (with different names) that can be attached to a
6548** single database connection. However, the implementation is optimized
6549** for the case of having only one or two different client data names.
6550** Applications and wrapper libraries are discouraged from using more than
6551** one client data name each.
6552**
6553** There is no way to enumerate the client data pointers
6554** associated with a database connection. The N parameter can be thought
6555** of as a secret key such that only code that knows the secret key is able
6556** to access the associated data.
6557**
6558** Security Warning: These interfaces should not be exposed in scripting
6559** languages or in other circumstances where it might be possible for an
6560** attacker to invoke them. Any agent that can invoke these interfaces
6561** can probably also take control of the process.
6562**
6563** Database connection client data is only available for SQLite
6564** version 3.44.0 ([dateof:3.44.0]) and later.
6565**
6566** See also: [sqlite3_set_auxdata()] and [sqlite3_get_auxdata()].
6567*/
6568SQLITE_API void *sqlite3_get_clientdata(sqlite3*,const char*);
6569SQLITE_API int sqlite3_set_clientdata(sqlite3*, const char*, void*, void(*)(void*));
6570
6571/*
6572** CAPI3REF: Constants Defining Special Destructor Behavior
6573**
6574** These are special values for the destructor that is passed in as the
6575** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
6576** argument is SQLITE_STATIC, it means that the content pointer is constant
6577** and will never change. It does not need to be destroyed. ^The
6578** SQLITE_TRANSIENT value means that the content will likely change in
6579** the near future and that SQLite should make its own private copy of
6580** the content before returning.
6581**
6582** The typedef is necessary to work around problems in certain
6583** C++ compilers.
6584*/
6585typedef void (*sqlite3_destructor_type)(void*);
6586#define SQLITE_STATIC((sqlite3_destructor_type)0) ((sqlite3_destructor_type)0)
6587#define SQLITE_TRANSIENT((sqlite3_destructor_type)-1) ((sqlite3_destructor_type)-1)
6588
6589/*
6590** CAPI3REF: Setting The Result Of An SQL Function
6591** METHOD: sqlite3_context
6592**
6593** These routines are used by the xFunc or xFinal callbacks that
6594** implement SQL functions and aggregates. See
6595** [sqlite3_create_function()] and [sqlite3_create_function16()]
6596** for additional information.
6597**
6598** These functions work very much like the [parameter binding] family of
6599** functions used to bind values to host parameters in prepared statements.
6600** Refer to the [SQL parameter] documentation for additional information.
6601**
6602** ^The sqlite3_result_blob() interface sets the result from
6603** an application-defined function to be the BLOB whose content is pointed
6604** to by the second parameter and which is N bytes long where N is the
6605** third parameter.
6606**
6607** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
6608** interfaces set the result of the application-defined function to be
6609** a BLOB containing all zero bytes and N bytes in size.
6610**
6611** ^The sqlite3_result_double() interface sets the result from
6612** an application-defined function to be a floating point value specified
6613** by its 2nd argument.
6614**
6615** ^The sqlite3_result_error() and sqlite3_result_error16() functions
6616** cause the implemented SQL function to throw an exception.
6617** ^SQLite uses the string pointed to by the
6618** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
6619** as the text of an error message. ^SQLite interprets the error
6620** message string from sqlite3_result_error() as UTF-8. ^SQLite
6621** interprets the string from sqlite3_result_error16() as UTF-16 using
6622** the same [byte-order determination rules] as [sqlite3_bind_text16()].
6623** ^If the third parameter to sqlite3_result_error()
6624** or sqlite3_result_error16() is negative then SQLite takes as the error
6625** message all text up through the first zero character.
6626** ^If the third parameter to sqlite3_result_error() or
6627** sqlite3_result_error16() is non-negative then SQLite takes that many
6628** bytes (not characters) from the 2nd parameter as the error message.
6629** ^The sqlite3_result_error() and sqlite3_result_error16()
6630** routines make a private copy of the error message text before
6631** they return. Hence, the calling function can deallocate or
6632** modify the text after they return without harm.
6633** ^The sqlite3_result_error_code() function changes the error code
6634** returned by SQLite as a result of an error in a function. ^By default,
6635** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
6636** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
6637**
6638** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
6639** error indicating that a string or BLOB is too long to represent.
6640**
6641** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
6642** error indicating that a memory allocation failed.
6643**
6644** ^The sqlite3_result_int() interface sets the return value
6645** of the application-defined function to be the 32-bit signed integer
6646** value given in the 2nd argument.
6647** ^The sqlite3_result_int64() interface sets the return value
6648** of the application-defined function to be the 64-bit signed integer
6649** value given in the 2nd argument.
6650**
6651** ^The sqlite3_result_null() interface sets the return value
6652** of the application-defined function to be NULL.
6653**
6654** ^The sqlite3_result_text(), sqlite3_result_text16(),
6655** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
6656** set the return value of the application-defined function to be
6657** a text string which is represented as UTF-8, UTF-16 native byte order,
6658** UTF-16 little endian, or UTF-16 big endian, respectively.
6659** ^The sqlite3_result_text64() interface sets the return value of an
6660** application-defined function to be a text string in an encoding
6661** specified by the fifth (and last) parameter, which must be one
6662** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
6663** ^SQLite takes the text result from the application from
6664** the 2nd parameter of the sqlite3_result_text* interfaces.
6665** ^If the 3rd parameter to any of the sqlite3_result_text* interfaces
6666** other than sqlite3_result_text64() is negative, then SQLite computes
6667** the string length itself by searching the 2nd parameter for the first
6668** zero character.
6669** ^If the 3rd parameter to the sqlite3_result_text* interfaces
6670** is non-negative, then as many bytes (not characters) of the text
6671** pointed to by the 2nd parameter are taken as the application-defined
6672** function result. If the 3rd parameter is non-negative, then it
6673** must be the byte offset into the string where the NUL terminator would
6674** appear if the string were NUL terminated. If any NUL characters occur
6675** in the string at a byte offset that is less than the value of the 3rd
6676** parameter, then the resulting string will contain embedded NULs and the
6677** result of expressions operating on strings with embedded NULs is undefined.
6678** ^If the 4th parameter to the sqlite3_result_text* interfaces
6679** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
6680** function as the destructor on the text or BLOB result when it has
6681** finished using that result.
6682** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
6683** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
6684** assumes that the text or BLOB result is in constant space and does not
6685** copy the content of the parameter nor call a destructor on the content
6686** when it has finished using that result.
6687** ^If the 4th parameter to the sqlite3_result_text* interfaces
6688** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
6689** then SQLite makes a copy of the result into space obtained
6690** from [sqlite3_malloc()] before it returns.
6691**
6692** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and
6693** sqlite3_result_text16be() routines, and for sqlite3_result_text64()
6694** when the encoding is not UTF8, if the input UTF16 begins with a
6695** byte-order mark (BOM, U+FEFF) then the BOM is removed from the
6696** string and the rest of the string is interpreted according to the
6697** byte-order specified by the BOM. ^The byte-order specified by
6698** the BOM at the beginning of the text overrides the byte-order
6699** specified by the interface procedure. ^So, for example, if
6700** sqlite3_result_text16le() is invoked with text that begins
6701** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the
6702** first two bytes of input are skipped and the remaining input
6703** is interpreted as UTF16BE text.
6704**
6705** ^For UTF16 input text to the sqlite3_result_text16(),
6706** sqlite3_result_text16be(), sqlite3_result_text16le(), and
6707** sqlite3_result_text64() routines, if the text contains invalid
6708** UTF16 characters, the invalid characters might be converted
6709** into the unicode replacement character, U+FFFD.
6710**
6711** ^The sqlite3_result_value() interface sets the result of
6712** the application-defined function to be a copy of the
6713** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
6714** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
6715** so that the [sqlite3_value] specified in the parameter may change or
6716** be deallocated after sqlite3_result_value() returns without harm.
6717** ^A [protected sqlite3_value] object may always be used where an
6718** [unprotected sqlite3_value] object is required, so either
6719** kind of [sqlite3_value] object can be used with this interface.
6720**
6721** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
6722** SQL NULL value, just like [sqlite3_result_null(C)], except that it
6723** also associates the host-language pointer P or type T with that
6724** NULL value such that the pointer can be retrieved within an
6725** [application-defined SQL function] using [sqlite3_value_pointer()].
6726** ^If the D parameter is not NULL, then it is a pointer to a destructor
6727** for the P parameter. ^SQLite invokes D with P as its only argument
6728** when SQLite is finished with P. The T parameter should be a static
6729** string and preferably a string literal. The sqlite3_result_pointer()
6730** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
6731**
6732** If these routines are called from within a different thread
6733** than the one containing the application-defined function that received
6734** the [sqlite3_context] pointer, the results are undefined.
6735*/
6736SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
6737SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
6738 sqlite3_uint64,void(*)(void*));
6739SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
6740SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
6741SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
6742SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
6743SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
6744SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
6745SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
6746SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
6747SQLITE_API void sqlite3_result_null(sqlite3_context*);
6748SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
6749SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
6750 void(*)(void*), unsigned char encoding);
6751SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
6752SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
6753SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
6754SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
6755SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
6756SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
6757SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
6758
6759
6760/*
6761** CAPI3REF: Setting The Subtype Of An SQL Function
6762** METHOD: sqlite3_context
6763**
6764** The sqlite3_result_subtype(C,T) function causes the subtype of
6765** the result from the [application-defined SQL function] with
6766** [sqlite3_context] C to be the value T. Only the lower 8 bits
6767** of the subtype T are preserved in current versions of SQLite;
6768** higher order bits are discarded.
6769** The number of subtype bytes preserved by SQLite might increase
6770** in future releases of SQLite.
6771**
6772** Every [application-defined SQL function] that invokes this interface
6773** should include the [SQLITE_RESULT_SUBTYPE] property in its
6774** text encoding argument when the SQL function is
6775** [sqlite3_create_function|registered]. If the [SQLITE_RESULT_SUBTYPE]
6776** property is omitted from the function that invokes sqlite3_result_subtype(),
6777** then in some cases the sqlite3_result_subtype() might fail to set
6778** the result subtype.
6779**
6780** If SQLite is compiled with -DSQLITE_STRICT_SUBTYPE=1, then any
6781** SQL function that invokes the sqlite3_result_subtype() interface
6782** and that does not have the SQLITE_RESULT_SUBTYPE property will raise
6783** an error. Future versions of SQLite might enable -DSQLITE_STRICT_SUBTYPE=1
6784** by default.
6785*/
6786SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
6787
6788/*
6789** CAPI3REF: Define New Collating Sequences
6790** METHOD: sqlite3
6791**
6792** ^These functions add, remove, or modify a [collation] associated
6793** with the [database connection] specified as the first argument.
6794**
6795** ^The name of the collation is a UTF-8 string
6796** for sqlite3_create_collation() and sqlite3_create_collation_v2()
6797** and a UTF-16 string in native byte order for sqlite3_create_collation16().
6798** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
6799** considered to be the same name.
6800**
6801** ^(The third argument (eTextRep) must be one of the constants:
6802** <ul>
6803** <li> [SQLITE_UTF8],
6804** <li> [SQLITE_UTF16LE],
6805** <li> [SQLITE_UTF16BE],
6806** <li> [SQLITE_UTF16], or
6807** <li> [SQLITE_UTF16_ALIGNED].
6808** </ul>)^
6809** ^The eTextRep argument determines the encoding of strings passed
6810** to the collating function callback, xCompare.
6811** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
6812** force strings to be UTF16 with native byte order.
6813** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
6814** on an even byte address.
6815**
6816** ^The fourth argument, pArg, is an application data pointer that is passed
6817** through as the first argument to the collating function callback.
6818**
6819** ^The fifth argument, xCompare, is a pointer to the collating function.
6820** ^Multiple collating functions can be registered using the same name but
6821** with different eTextRep parameters and SQLite will use whichever
6822** function requires the least amount of data transformation.
6823** ^If the xCompare argument is NULL then the collating function is
6824** deleted. ^When all collating functions having the same name are deleted,
6825** that collation is no longer usable.
6826**
6827** ^The collating function callback is invoked with a copy of the pArg
6828** application data pointer and with two strings in the encoding specified
6829** by the eTextRep argument. The two integer parameters to the collating
6830** function callback are the length of the two strings, in bytes. The collating
6831** function must return an integer that is negative, zero, or positive
6832** if the first string is less than, equal to, or greater than the second,
6833** respectively. A collating function must always return the same answer
6834** given the same inputs. If two or more collating functions are registered
6835** to the same collation name (using different eTextRep values) then all
6836** must give an equivalent answer when invoked with equivalent strings.
6837** The collating function must obey the following properties for all
6838** strings A, B, and C:
6839**
6840** <ol>
6841** <li> If A==B then B==A.
6842** <li> If A==B and B==C then A==C.
6843** <li> If A&lt;B THEN B&gt;A.
6844** <li> If A&lt;B and B&lt;C then A&lt;C.
6845** </ol>
6846**
6847** If a collating function fails any of the above constraints and that
6848** collating function is registered and used, then the behavior of SQLite
6849** is undefined.
6850**
6851** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
6852** with the addition that the xDestroy callback is invoked on pArg when
6853** the collating function is deleted.
6854** ^Collating functions are deleted when they are overridden by later
6855** calls to the collation creation functions or when the
6856** [database connection] is closed using [sqlite3_close()].
6857**
6858** ^The xDestroy callback is <u>not</u> called if the
6859** sqlite3_create_collation_v2() function fails. Applications that invoke
6860** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
6861** check the return code and dispose of the application data pointer
6862** themselves rather than expecting SQLite to deal with it for them.
6863** This is different from every other SQLite interface. The inconsistency
6864** is unfortunate but cannot be changed without breaking backwards
6865** compatibility.
6866**
6867** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
6868*/
6869SQLITE_API int sqlite3_create_collation(
6870 sqlite3*,
6871 const char *zName,
6872 int eTextRep,
6873 void *pArg,
6874 int(*xCompare)(void*,int,const void*,int,const void*)
6875);
6876SQLITE_API int sqlite3_create_collation_v2(
6877 sqlite3*,
6878 const char *zName,
6879 int eTextRep,
6880 void *pArg,
6881 int(*xCompare)(void*,int,const void*,int,const void*),
6882 void(*xDestroy)(void*)
6883);
6884SQLITE_API int sqlite3_create_collation16(
6885 sqlite3*,
6886 const void *zName,
6887 int eTextRep,
6888 void *pArg,
6889 int(*xCompare)(void*,int,const void*,int,const void*)
6890);
6891
6892/*
6893** CAPI3REF: Collation Needed Callbacks
6894** METHOD: sqlite3
6895**
6896** ^To avoid having to register all collation sequences before a database
6897** can be used, a single callback function may be registered with the
6898** [database connection] to be invoked whenever an undefined collation
6899** sequence is required.
6900**
6901** ^If the function is registered using the sqlite3_collation_needed() API,
6902** then it is passed the names of undefined collation sequences as strings
6903** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
6904** the names are passed as UTF-16 in machine native byte order.
6905** ^A call to either function replaces the existing collation-needed callback.
6906**
6907** ^(When the callback is invoked, the first argument passed is a copy
6908** of the second argument to sqlite3_collation_needed() or
6909** sqlite3_collation_needed16(). The second argument is the database
6910** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
6911** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
6912** sequence function required. The fourth parameter is the name of the
6913** required collation sequence.)^
6914**
6915** The callback function should register the desired collation using
6916** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
6917** [sqlite3_create_collation_v2()].
6918*/
6919SQLITE_API int sqlite3_collation_needed(
6920 sqlite3*,
6921 void*,
6922 void(*)(void*,sqlite3*,int eTextRep,const char*)
6923);
6924SQLITE_API int sqlite3_collation_needed16(
6925 sqlite3*,
6926 void*,
6927 void(*)(void*,sqlite3*,int eTextRep,const void*)
6928);
6929
6930#ifdef SQLITE_ENABLE_CEROD
6931/*
6932** Specify the activation key for a CEROD database. Unless
6933** activated, none of the CEROD routines will work.
6934*/
6935SQLITE_API void sqlite3_activate_cerod(
6936 const char *zPassPhrase /* Activation phrase */
6937);
6938#endif
6939
6940/*
6941** CAPI3REF: Suspend Execution For A Short Time
6942**
6943** The sqlite3_sleep() function causes the current thread to suspend execution
6944** for at least a number of milliseconds specified in its parameter.
6945**
6946** If the operating system does not support sleep requests with
6947** millisecond time resolution, then the time will be rounded up to
6948** the nearest second. The number of milliseconds of sleep actually
6949** requested from the operating system is returned.
6950**
6951** ^SQLite implements this interface by calling the xSleep()
6952** method of the default [sqlite3_vfs] object. If the xSleep() method
6953** of the default VFS is not implemented correctly, or not implemented at
6954** all, then the behavior of sqlite3_sleep() may deviate from the description
6955** in the previous paragraphs.
6956**
6957** If a negative argument is passed to sqlite3_sleep() the results vary by
6958** VFS and operating system. Some system treat a negative argument as an
6959** instruction to sleep forever. Others understand it to mean do not sleep
6960** at all. ^In SQLite version 3.42.0 and later, a negative
6961** argument passed into sqlite3_sleep() is changed to zero before it is relayed
6962** down into the xSleep method of the VFS.
6963*/
6964SQLITE_API int sqlite3_sleep(int);
6965
6966/*
6967** CAPI3REF: Name Of The Folder Holding Temporary Files
6968**
6969** ^(If this global variable is made to point to a string which is
6970** the name of a folder (a.k.a. directory), then all temporary files
6971** created by SQLite when using a built-in [sqlite3_vfs | VFS]
6972** will be placed in that directory.)^ ^If this variable
6973** is a NULL pointer, then SQLite performs a search for an appropriate
6974** temporary file directory.
6975**
6976** Applications are strongly discouraged from using this global variable.
6977** It is required to set a temporary folder on Windows Runtime (WinRT).
6978** But for all other platforms, it is highly recommended that applications
6979** neither read nor write this variable. This global variable is a relic
6980** that exists for backwards compatibility of legacy applications and should
6981** be avoided in new projects.
6982**
6983** It is not safe to read or modify this variable in more than one
6984** thread at a time. It is not safe to read or modify this variable
6985** if a [database connection] is being used at the same time in a separate
6986** thread.
6987** It is intended that this variable be set once
6988** as part of process initialization and before any SQLite interface
6989** routines have been called and that this variable remain unchanged
6990** thereafter.
6991**
6992** ^The [temp_store_directory pragma] may modify this variable and cause
6993** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
6994** the [temp_store_directory pragma] always assumes that any string
6995** that this variable points to is held in memory obtained from
6996** [sqlite3_malloc] and the pragma may attempt to free that memory
6997** using [sqlite3_free].
6998** Hence, if this variable is modified directly, either it should be
6999** made NULL or made to point to memory obtained from [sqlite3_malloc]
7000** or else the use of the [temp_store_directory pragma] should be avoided.
7001** Except when requested by the [temp_store_directory pragma], SQLite
7002** does not free the memory that sqlite3_temp_directory points to. If
7003** the application wants that memory to be freed, it must do
7004** so itself, taking care to only do so after all [database connection]
7005** objects have been destroyed.
7006**
7007** <b>Note to Windows Runtime users:</b> The temporary directory must be set
7008** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
7009** features that require the use of temporary files may fail. Here is an
7010** example of how to do this using C++ with the Windows Runtime:
7011**
7012** <blockquote><pre>
7013** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
7014** &nbsp; TemporaryFolder->Path->Data();
7015** char zPathBuf&#91;MAX_PATH + 1&#93;;
7016** memset(zPathBuf, 0, sizeof(zPathBuf));
7017** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
7018** &nbsp; NULL, NULL);
7019** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
7020** </pre></blockquote>
7021*/
7022SQLITE_API char *sqlite3_temp_directory;
7023
7024/*
7025** CAPI3REF: Name Of The Folder Holding Database Files
7026**
7027** ^(If this global variable is made to point to a string which is
7028** the name of a folder (a.k.a. directory), then all database files
7029** specified with a relative pathname and created or accessed by
7030** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
7031** to be relative to that directory.)^ ^If this variable is a NULL
7032** pointer, then SQLite assumes that all database files specified
7033** with a relative pathname are relative to the current directory
7034** for the process. Only the windows VFS makes use of this global
7035** variable; it is ignored by the unix VFS.
7036**
7037** Changing the value of this variable while a database connection is
7038** open can result in a corrupt database.
7039**
7040** It is not safe to read or modify this variable in more than one
7041** thread at a time. It is not safe to read or modify this variable
7042** if a [database connection] is being used at the same time in a separate
7043** thread.
7044** It is intended that this variable be set once
7045** as part of process initialization and before any SQLite interface
7046** routines have been called and that this variable remain unchanged
7047** thereafter.
7048**
7049** ^The [data_store_directory pragma] may modify this variable and cause
7050** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
7051** the [data_store_directory pragma] always assumes that any string
7052** that this variable points to is held in memory obtained from
7053** [sqlite3_malloc] and the pragma may attempt to free that memory
7054** using [sqlite3_free].
7055** Hence, if this variable is modified directly, either it should be
7056** made NULL or made to point to memory obtained from [sqlite3_malloc]
7057** or else the use of the [data_store_directory pragma] should be avoided.
7058*/
7059SQLITE_API char *sqlite3_data_directory;
7060
7061/*
7062** CAPI3REF: Win32 Specific Interface
7063**
7064** These interfaces are available only on Windows. The
7065** [sqlite3_win32_set_directory] interface is used to set the value associated
7066** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
7067** zValue, depending on the value of the type parameter. The zValue parameter
7068** should be NULL to cause the previous value to be freed via [sqlite3_free];
7069** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
7070** prior to being used. The [sqlite3_win32_set_directory] interface returns
7071** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
7072** or [SQLITE_NOMEM] if memory could not be allocated. The value of the
7073** [sqlite3_data_directory] variable is intended to act as a replacement for
7074** the current directory on the sub-platforms of Win32 where that concept is
7075** not present, e.g. WinRT and UWP. The [sqlite3_win32_set_directory8] and
7076** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
7077** sqlite3_win32_set_directory interface except the string parameter must be
7078** UTF-8 or UTF-16, respectively.
7079*/
7080SQLITE_API int sqlite3_win32_set_directory(
7081 unsigned long type, /* Identifier for directory being set or reset */
7082 void *zValue /* New value for directory being set or reset */
7083);
7084SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
7085SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
7086
7087/*
7088** CAPI3REF: Win32 Directory Types
7089**
7090** These macros are only available on Windows. They define the allowed values
7091** for the type argument to the [sqlite3_win32_set_directory] interface.
7092*/
7093#define SQLITE_WIN32_DATA_DIRECTORY_TYPE1 1
7094#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE2 2
7095
7096/*
7097** CAPI3REF: Test For Auto-Commit Mode
7098** KEYWORDS: {autocommit mode}
7099** METHOD: sqlite3
7100**
7101** ^The sqlite3_get_autocommit() interface returns non-zero or
7102** zero if the given database connection is or is not in autocommit mode,
7103** respectively. ^Autocommit mode is on by default.
7104** ^Autocommit mode is disabled by a [BEGIN] statement.
7105** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
7106**
7107** If certain kinds of errors occur on a statement within a multi-statement
7108** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
7109** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
7110** transaction might be rolled back automatically. The only way to
7111** find out whether SQLite automatically rolled back the transaction after
7112** an error is to use this function.
7113**
7114** If another thread changes the autocommit status of the database
7115** connection while this routine is running, then the return value
7116** is undefined.
7117*/
7118SQLITE_API int sqlite3_get_autocommit(sqlite3*);
7119
7120/*
7121** CAPI3REF: Find The Database Handle Of A Prepared Statement
7122** METHOD: sqlite3_stmt
7123**
7124** ^The sqlite3_db_handle interface returns the [database connection] handle
7125** to which a [prepared statement] belongs. ^The [database connection]
7126** returned by sqlite3_db_handle is the same [database connection]
7127** that was the first argument
7128** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
7129** create the statement in the first place.
7130*/
7131SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
7132
7133/*
7134** CAPI3REF: Return The Schema Name For A Database Connection
7135** METHOD: sqlite3
7136**
7137** ^The sqlite3_db_name(D,N) interface returns a pointer to the schema name
7138** for the N-th database on database connection D, or a NULL pointer if N is
7139** out of range. An N value of 0 means the main database file. An N of 1 is
7140** the "temp" schema. Larger values of N correspond to various ATTACH-ed
7141** databases.
7142**
7143** Space to hold the string that is returned by sqlite3_db_name() is managed
7144** by SQLite itself. The string might be deallocated by any operation that
7145** changes the schema, including [ATTACH] or [DETACH] or calls to
7146** [sqlite3_serialize()] or [sqlite3_deserialize()], even operations that
7147** occur on a different thread. Applications that need to
7148** remember the string long-term should make their own copy. Applications that
7149** are accessing the same database connection simultaneously on multiple
7150** threads should mutex-protect calls to this API and should make their own
7151** private copy of the result prior to releasing the mutex.
7152*/
7153SQLITE_API const char *sqlite3_db_name(sqlite3 *db, int N);
7154
7155/*
7156** CAPI3REF: Return The Filename For A Database Connection
7157** METHOD: sqlite3
7158**
7159** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename
7160** associated with database N of connection D.
7161** ^If there is no attached database N on the database
7162** connection D, or if database N is a temporary or in-memory database, then
7163** this function will return either a NULL pointer or an empty string.
7164**
7165** ^The string value returned by this routine is owned and managed by
7166** the database connection. ^The value will be valid until the database N
7167** is [DETACH]-ed or until the database connection closes.
7168**
7169** ^The filename returned by this function is the output of the
7170** xFullPathname method of the [VFS]. ^In other words, the filename
7171** will be an absolute pathname, even if the filename used
7172** to open the database originally was a URI or relative pathname.
7173**
7174** If the filename pointer returned by this routine is not NULL, then it
7175** can be used as the filename input parameter to these routines:
7176** <ul>
7177** <li> [sqlite3_uri_parameter()]
7178** <li> [sqlite3_uri_boolean()]
7179** <li> [sqlite3_uri_int64()]
7180** <li> [sqlite3_filename_database()]
7181** <li> [sqlite3_filename_journal()]
7182** <li> [sqlite3_filename_wal()]
7183** </ul>
7184*/
7185SQLITE_API sqlite3_filename sqlite3_db_filename(sqlite3 *db, const char *zDbName);
7186
7187/*
7188** CAPI3REF: Determine if a database is read-only
7189** METHOD: sqlite3
7190**
7191** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
7192** of connection D is read-only, 0 if it is read/write, or -1 if N is not
7193** the name of a database on connection D.
7194*/
7195SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
7196
7197/*
7198** CAPI3REF: Determine the transaction state of a database
7199** METHOD: sqlite3
7200**
7201** ^The sqlite3_txn_state(D,S) interface returns the current
7202** [transaction state] of schema S in database connection D. ^If S is NULL,
7203** then the highest transaction state of any schema on database connection D
7204** is returned. Transaction states are (in order of lowest to highest):
7205** <ol>
7206** <li value="0"> SQLITE_TXN_NONE
7207** <li value="1"> SQLITE_TXN_READ
7208** <li value="2"> SQLITE_TXN_WRITE
7209** </ol>
7210** ^If the S argument to sqlite3_txn_state(D,S) is not the name of
7211** a valid schema, then -1 is returned.
7212*/
7213SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);
7214
7215/*
7216** CAPI3REF: Allowed return values from sqlite3_txn_state()
7217** KEYWORDS: {transaction state}
7218**
7219** These constants define the current transaction state of a database file.
7220** ^The [sqlite3_txn_state(D,S)] interface returns one of these
7221** constants in order to describe the transaction state of schema S
7222** in [database connection] D.
7223**
7224** <dl>
7225** [[SQLITE_TXN_NONE]] <dt>SQLITE_TXN_NONE</dt>
7226** <dd>The SQLITE_TXN_NONE state means that no transaction is currently
7227** pending.</dd>
7228**
7229** [[SQLITE_TXN_READ]] <dt>SQLITE_TXN_READ</dt>
7230** <dd>The SQLITE_TXN_READ state means that the database is currently
7231** in a read transaction. Content has been read from the database file
7232** but nothing in the database file has changed. The transaction state
7233** will be advanced to SQLITE_TXN_WRITE if any changes occur and there are
7234** no other conflicting concurrent write transactions. The transaction
7235** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or
7236** [COMMIT].</dd>
7237**
7238** [[SQLITE_TXN_WRITE]] <dt>SQLITE_TXN_WRITE</dt>
7239** <dd>The SQLITE_TXN_WRITE state means that the database is currently
7240** in a write transaction. Content has been written to the database file
7241** but has not yet committed. The transaction state will change to
7242** SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd>
7243*/
7244#define SQLITE_TXN_NONE0 0
7245#define SQLITE_TXN_READ1 1
7246#define SQLITE_TXN_WRITE2 2
7247
7248/*
7249** CAPI3REF: Find the next prepared statement
7250** METHOD: sqlite3
7251**
7252** ^This interface returns a pointer to the next [prepared statement] after
7253** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
7254** then this interface returns a pointer to the first prepared statement
7255** associated with the database connection pDb. ^If no prepared statement
7256** satisfies the conditions of this routine, it returns NULL.
7257**
7258** The [database connection] pointer D in a call to
7259** [sqlite3_next_stmt(D,S)] must refer to an open database
7260** connection and in particular must not be a NULL pointer.
7261*/
7262SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
7263
7264/*
7265** CAPI3REF: Commit And Rollback Notification Callbacks
7266** METHOD: sqlite3
7267**
7268** ^The sqlite3_commit_hook() interface registers a callback
7269** function to be invoked whenever a transaction is [COMMIT | committed].
7270** ^Any callback set by a previous call to sqlite3_commit_hook()
7271** for the same database connection is overridden.
7272** ^The sqlite3_rollback_hook() interface registers a callback
7273** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
7274** ^Any callback set by a previous call to sqlite3_rollback_hook()
7275** for the same database connection is overridden.
7276** ^The pArg argument is passed through to the callback.
7277** ^If the callback on a commit hook function returns non-zero,
7278** then the commit is converted into a rollback.
7279**
7280** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
7281** return the P argument from the previous call of the same function
7282** on the same [database connection] D, or NULL for
7283** the first call for each function on D.
7284**
7285** The commit and rollback hook callbacks are not reentrant.
7286** The callback implementation must not do anything that will modify
7287** the database connection that invoked the callback. Any actions
7288** to modify the database connection must be deferred until after the
7289** completion of the [sqlite3_step()] call that triggered the commit
7290** or rollback hook in the first place.
7291** Note that running any other SQL statements, including SELECT statements,
7292** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
7293** the database connections for the meaning of "modify" in this paragraph.
7294**
7295** ^Registering a NULL function disables the callback.
7296**
7297** ^When the commit hook callback routine returns zero, the [COMMIT]
7298** operation is allowed to continue normally. ^If the commit hook
7299** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
7300** ^The rollback hook is invoked on a rollback that results from a commit
7301** hook returning non-zero, just as it would be with any other rollback.
7302**
7303** ^For the purposes of this API, a transaction is said to have been
7304** rolled back if an explicit "ROLLBACK" statement is executed, or
7305** an error or constraint causes an implicit rollback to occur.
7306** ^The rollback callback is not invoked if a transaction is
7307** automatically rolled back because the database connection is closed.
7308**
7309** See also the [sqlite3_update_hook()] interface.
7310*/
7311SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
7312SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
7313
7314/*
7315** CAPI3REF: Autovacuum Compaction Amount Callback
7316** METHOD: sqlite3
7317**
7318** ^The sqlite3_autovacuum_pages(D,C,P,X) interface registers a callback
7319** function C that is invoked prior to each autovacuum of the database
7320** file. ^The callback is passed a copy of the generic data pointer (P),
7321** the schema-name of the attached database that is being autovacuumed,
7322** the size of the database file in pages, the number of free pages,
7323** and the number of bytes per page, respectively. The callback should
7324** return the number of free pages that should be removed by the
7325** autovacuum. ^If the callback returns zero, then no autovacuum happens.
7326** ^If the value returned is greater than or equal to the number of
7327** free pages, then a complete autovacuum happens.
7328**
7329** <p>^If there are multiple ATTACH-ed database files that are being
7330** modified as part of a transaction commit, then the autovacuum pages
7331** callback is invoked separately for each file.
7332**
7333** <p><b>The callback is not reentrant.</b> The callback function should
7334** not attempt to invoke any other SQLite interface. If it does, bad
7335** things may happen, including segmentation faults and corrupt database
7336** files. The callback function should be a simple function that
7337** does some arithmetic on its input parameters and returns a result.
7338**
7339** ^The X parameter to sqlite3_autovacuum_pages(D,C,P,X) is an optional
7340** destructor for the P parameter. ^If X is not NULL, then X(P) is
7341** invoked whenever the database connection closes or when the callback
7342** is overwritten by another invocation of sqlite3_autovacuum_pages().
7343**
7344** <p>^There is only one autovacuum pages callback per database connection.
7345** ^Each call to the sqlite3_autovacuum_pages() interface overrides all
7346** previous invocations for that database connection. ^If the callback
7347** argument (C) to sqlite3_autovacuum_pages(D,C,P,X) is a NULL pointer,
7348** then the autovacuum steps callback is canceled. The return value
7349** from sqlite3_autovacuum_pages() is normally SQLITE_OK, but might
7350** be some other error code if something goes wrong. The current
7351** implementation will only return SQLITE_OK or SQLITE_MISUSE, but other
7352** return codes might be added in future releases.
7353**
7354** <p>If no autovacuum pages callback is specified (the usual case) or
7355** a NULL pointer is provided for the callback,
7356** then the default behavior is to vacuum all free pages. So, in other
7357** words, the default behavior is the same as if the callback function
7358** were something like this:
7359**
7360** <blockquote><pre>
7361** &nbsp; unsigned int demonstration_autovac_pages_callback(
7362** &nbsp; void *pClientData,
7363** &nbsp; const char *zSchema,
7364** &nbsp; unsigned int nDbPage,
7365** &nbsp; unsigned int nFreePage,
7366** &nbsp; unsigned int nBytePerPage
7367** &nbsp; ){
7368** &nbsp; return nFreePage;
7369** &nbsp; }
7370** </pre></blockquote>
7371*/
7372SQLITE_API int sqlite3_autovacuum_pages(
7373 sqlite3 *db,
7374 unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),
7375 void*,
7376 void(*)(void*)
7377);
7378
7379
7380/*
7381** CAPI3REF: Data Change Notification Callbacks
7382** METHOD: sqlite3
7383**
7384** ^The sqlite3_update_hook() interface registers a callback function
7385** with the [database connection] identified by the first argument
7386** to be invoked whenever a row is updated, inserted or deleted in
7387** a [rowid table].
7388** ^Any callback set by a previous call to this function
7389** for the same database connection is overridden.
7390**
7391** ^The second argument is a pointer to the function to invoke when a
7392** row is updated, inserted or deleted in a rowid table.
7393** ^The update hook is disabled by invoking sqlite3_update_hook()
7394** with a NULL pointer as the second parameter.
7395** ^The first argument to the callback is a copy of the third argument
7396** to sqlite3_update_hook().
7397** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
7398** or [SQLITE_UPDATE], depending on the operation that caused the callback
7399** to be invoked.
7400** ^The third and fourth arguments to the callback contain pointers to the
7401** database and table name containing the affected row.
7402** ^The final callback parameter is the [rowid] of the row.
7403** ^In the case of an update, this is the [rowid] after the update takes place.
7404**
7405** ^(The update hook is not invoked when internal system tables are
7406** modified (i.e. sqlite_sequence).)^
7407** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
7408**
7409** ^In the current implementation, the update hook
7410** is not invoked when conflicting rows are deleted because of an
7411** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
7412** invoked when rows are deleted using the [truncate optimization].
7413** The exceptions defined in this paragraph might change in a future
7414** release of SQLite.
7415**
7416** Whether the update hook is invoked before or after the
7417** corresponding change is currently unspecified and may differ
7418** depending on the type of change. Do not rely on the order of the
7419** hook call with regards to the final result of the operation which
7420** triggers the hook.
7421**
7422** The update hook implementation must not do anything that will modify
7423** the database connection that invoked the update hook. Any actions
7424** to modify the database connection must be deferred until after the
7425** completion of the [sqlite3_step()] call that triggered the update hook.
7426** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
7427** database connections for the meaning of "modify" in this paragraph.
7428**
7429** ^The sqlite3_update_hook(D,C,P) function
7430** returns the P argument from the previous call
7431** on the same [database connection] D, or NULL for
7432** the first call on D.
7433**
7434** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
7435** and [sqlite3_preupdate_hook()] interfaces.
7436*/
7437SQLITE_API void *sqlite3_update_hook(
7438 sqlite3*,
7439 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
7440 void*
7441);
7442
7443/*
7444** CAPI3REF: Enable Or Disable Shared Pager Cache
7445**
7446** ^(This routine enables or disables the sharing of the database cache
7447** and schema data structures between [database connection | connections]
7448** to the same database. Sharing is enabled if the argument is true
7449** and disabled if the argument is false.)^
7450**
7451** This interface is omitted if SQLite is compiled with
7452** [-DSQLITE_OMIT_SHARED_CACHE]. The [-DSQLITE_OMIT_SHARED_CACHE]
7453** compile-time option is recommended because the
7454** [use of shared cache mode is discouraged].
7455**
7456** ^Cache sharing is enabled and disabled for an entire process.
7457** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
7458** In prior versions of SQLite,
7459** sharing was enabled or disabled for each thread separately.
7460**
7461** ^(The cache sharing mode set by this interface effects all subsequent
7462** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
7463** Existing database connections continue to use the sharing mode
7464** that was in effect at the time they were opened.)^
7465**
7466** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
7467** successfully. An [error code] is returned otherwise.)^
7468**
7469** ^Shared cache is disabled by default. It is recommended that it stay
7470** that way. In other words, do not use this routine. This interface
7471** continues to be provided for historical compatibility, but its use is
7472** discouraged. Any use of shared cache is discouraged. If shared cache
7473** must be used, it is recommended that shared cache only be enabled for
7474** individual database connections using the [sqlite3_open_v2()] interface
7475** with the [SQLITE_OPEN_SHAREDCACHE] flag.
7476**
7477** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
7478** and will always return SQLITE_MISUSE. On those systems,
7479** shared cache mode should be enabled per-database connection via
7480** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
7481**
7482** This interface is threadsafe on processors where writing a
7483** 32-bit integer is atomic.
7484**
7485** See Also: [SQLite Shared-Cache Mode]
7486*/
7487SQLITE_API int sqlite3_enable_shared_cache(int);
7488
7489/*
7490** CAPI3REF: Attempt To Free Heap Memory
7491**
7492** ^The sqlite3_release_memory() interface attempts to free N bytes
7493** of heap memory by deallocating non-essential memory allocations
7494** held by the database library. Memory used to cache database
7495** pages to improve performance is an example of non-essential memory.
7496** ^sqlite3_release_memory() returns the number of bytes actually freed,
7497** which might be more or less than the amount requested.
7498** ^The sqlite3_release_memory() routine is a no-op returning zero
7499** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
7500**
7501** See also: [sqlite3_db_release_memory()]
7502*/
7503SQLITE_API int sqlite3_release_memory(int);
7504
7505/*
7506** CAPI3REF: Free Memory Used By A Database Connection
7507** METHOD: sqlite3
7508**
7509** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
7510** memory as possible from database connection D. Unlike the
7511** [sqlite3_release_memory()] interface, this interface is in effect even
7512** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
7513** omitted.
7514**
7515** See also: [sqlite3_release_memory()]
7516*/
7517SQLITE_API int sqlite3_db_release_memory(sqlite3*);
7518
7519/*
7520** CAPI3REF: Impose A Limit On Heap Size
7521**
7522** These interfaces impose limits on the amount of heap memory that will be
7523** used by all database connections within a single process.
7524**
7525** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
7526** soft limit on the amount of heap memory that may be allocated by SQLite.
7527** ^SQLite strives to keep heap memory utilization below the soft heap
7528** limit by reducing the number of pages held in the page cache
7529** as heap memory usages approaches the limit.
7530** ^The soft heap limit is "soft" because even though SQLite strives to stay
7531** below the limit, it will exceed the limit rather than generate
7532** an [SQLITE_NOMEM] error. In other words, the soft heap limit
7533** is advisory only.
7534**
7535** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of
7536** N bytes on the amount of memory that will be allocated. ^The
7537** sqlite3_hard_heap_limit64(N) interface is similar to
7538** sqlite3_soft_heap_limit64(N) except that memory allocations will fail
7539** when the hard heap limit is reached.
7540**
7541** ^The return value from both sqlite3_soft_heap_limit64() and
7542** sqlite3_hard_heap_limit64() is the size of
7543** the heap limit prior to the call, or negative in the case of an
7544** error. ^If the argument N is negative
7545** then no change is made to the heap limit. Hence, the current
7546** size of heap limits can be determined by invoking
7547** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).
7548**
7549** ^Setting the heap limits to zero disables the heap limiter mechanism.
7550**
7551** ^The soft heap limit may not be greater than the hard heap limit.
7552** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N)
7553** is invoked with a value of N that is greater than the hard heap limit,
7554** the soft heap limit is set to the value of the hard heap limit.
7555** ^The soft heap limit is automatically enabled whenever the hard heap
7556** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and
7557** the soft heap limit is outside the range of 1..N, then the soft heap
7558** limit is set to N. ^Invoking sqlite3_soft_heap_limit64(0) when the
7559** hard heap limit is enabled makes the soft heap limit equal to the
7560** hard heap limit.
7561**
7562** The memory allocation limits can also be adjusted using
7563** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit].
7564**
7565** ^(The heap limits are not enforced in the current implementation
7566** if one or more of following conditions are true:
7567**
7568** <ul>
7569** <li> The limit value is set to zero.
7570** <li> Memory accounting is disabled using a combination of the
7571** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
7572** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
7573** <li> An alternative page cache implementation is specified using
7574** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
7575** <li> The page cache allocates from its own memory pool supplied
7576** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
7577** from the heap.
7578** </ul>)^
7579**
7580** The circumstances under which SQLite will enforce the heap limits may
7581** change in future releases of SQLite.
7582*/
7583SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
7584SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);
7585
7586/*
7587** CAPI3REF: Deprecated Soft Heap Limit Interface
7588** DEPRECATED
7589**
7590** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
7591** interface. This routine is provided for historical compatibility
7592** only. All new applications should use the
7593** [sqlite3_soft_heap_limit64()] interface rather than this one.
7594*/
7595SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
7596
7597
7598/*
7599** CAPI3REF: Extract Metadata About A Column Of A Table
7600** METHOD: sqlite3
7601**
7602** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
7603** information about column C of table T in database D
7604** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
7605** interface returns SQLITE_OK and fills in the non-NULL pointers in
7606** the final five arguments with appropriate values if the specified
7607** column exists. ^The sqlite3_table_column_metadata() interface returns
7608** SQLITE_ERROR if the specified column does not exist.
7609** ^If the column-name parameter to sqlite3_table_column_metadata() is a
7610** NULL pointer, then this routine simply checks for the existence of the
7611** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
7612** does not. If the table name parameter T in a call to
7613** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
7614** undefined behavior.
7615**
7616** ^The column is identified by the second, third and fourth parameters to
7617** this function. ^(The second parameter is either the name of the database
7618** (i.e. "main", "temp", or an attached database) containing the specified
7619** table or NULL.)^ ^If it is NULL, then all attached databases are searched
7620** for the table using the same algorithm used by the database engine to
7621** resolve unqualified table references.
7622**
7623** ^The third and fourth parameters to this function are the table and column
7624** name of the desired column, respectively.
7625**
7626** ^Metadata is returned by writing to the memory locations passed as the 5th
7627** and subsequent parameters to this function. ^Any of these arguments may be
7628** NULL, in which case the corresponding element of metadata is omitted.
7629**
7630** ^(<blockquote>
7631** <table border="1">
7632** <tr><th> Parameter <th> Output<br>Type <th> Description
7633**
7634** <tr><td> 5th <td> const char* <td> Data type
7635** <tr><td> 6th <td> const char* <td> Name of default collation sequence
7636** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
7637** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
7638** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
7639** </table>
7640** </blockquote>)^
7641**
7642** ^The memory pointed to by the character pointers returned for the
7643** declaration type and collation sequence is valid until the next
7644** call to any SQLite API function.
7645**
7646** ^If the specified table is actually a view, an [error code] is returned.
7647**
7648** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
7649** is not a [WITHOUT ROWID] table and an
7650** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
7651** parameters are set for the explicitly declared column. ^(If there is no
7652** [INTEGER PRIMARY KEY] column, then the outputs
7653** for the [rowid] are set as follows:
7654**
7655** <pre>
7656** data type: "INTEGER"
7657** collation sequence: "BINARY"
7658** not null: 0
7659** primary key: 1
7660** auto increment: 0
7661** </pre>)^
7662**
7663** ^This function causes all database schemas to be read from disk and
7664** parsed, if that has not already been done, and returns an error if
7665** any errors are encountered while loading the schema.
7666*/
7667SQLITE_API int sqlite3_table_column_metadata(
7668 sqlite3 *db, /* Connection handle */
7669 const char *zDbName, /* Database name or NULL */
7670 const char *zTableName, /* Table name */
7671 const char *zColumnName, /* Column name */
7672 char const **pzDataType, /* OUTPUT: Declared data type */
7673 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
7674 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
7675 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
7676 int *pAutoinc /* OUTPUT: True if column is auto-increment */
7677);
7678
7679/*
7680** CAPI3REF: Load An Extension
7681** METHOD: sqlite3
7682**
7683** ^This interface loads an SQLite extension library from the named file.
7684**
7685** ^The sqlite3_load_extension() interface attempts to load an
7686** [SQLite extension] library contained in the file zFile. If
7687** the file cannot be loaded directly, attempts are made to load
7688** with various operating-system specific extensions added.
7689** So for example, if "samplelib" cannot be loaded, then names like
7690** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
7691** be tried also.
7692**
7693** ^The entry point is zProc.
7694** ^(zProc may be 0, in which case SQLite will try to come up with an
7695** entry point name on its own. It first tries "sqlite3_extension_init".
7696** If that does not work, it constructs a name "sqlite3_X_init" where
7697** X consists of the lower-case equivalent of all ASCII alphabetic
7698** characters in the filename from the last "/" to the first following
7699** "." and omitting any initial "lib".)^
7700** ^The sqlite3_load_extension() interface returns
7701** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
7702** ^If an error occurs and pzErrMsg is not 0, then the
7703** [sqlite3_load_extension()] interface shall attempt to
7704** fill *pzErrMsg with error message text stored in memory
7705** obtained from [sqlite3_malloc()]. The calling function
7706** should free this memory by calling [sqlite3_free()].
7707**
7708** ^Extension loading must be enabled using
7709** [sqlite3_enable_load_extension()] or
7710** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
7711** prior to calling this API,
7712** otherwise an error will be returned.
7713**
7714** <b>Security warning:</b> It is recommended that the
7715** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
7716** interface. The use of the [sqlite3_enable_load_extension()] interface
7717** should be avoided. This will keep the SQL function [load_extension()]
7718** disabled and prevent SQL injections from giving attackers
7719** access to extension loading capabilities.
7720**
7721** See also the [load_extension() SQL function].
7722*/
7723SQLITE_API int sqlite3_load_extension(
7724 sqlite3 *db, /* Load the extension into this database connection */
7725 const char *zFile, /* Name of the shared library containing extension */
7726 const char *zProc, /* Entry point. Derived from zFile if 0 */
7727 char **pzErrMsg /* Put error message here if not 0 */
7728);
7729
7730/*
7731** CAPI3REF: Enable Or Disable Extension Loading
7732** METHOD: sqlite3
7733**
7734** ^So as not to open security holes in older applications that are
7735** unprepared to deal with [extension loading], and as a means of disabling
7736** [extension loading] while evaluating user-entered SQL, the following API
7737** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
7738**
7739** ^Extension loading is off by default.
7740** ^Call the sqlite3_enable_load_extension() routine with onoff==1
7741** to turn extension loading on and call it with onoff==0 to turn
7742** it back off again.
7743**
7744** ^This interface enables or disables both the C-API
7745** [sqlite3_load_extension()] and the SQL function [load_extension()].
7746** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
7747** to enable or disable only the C-API.)^
7748**
7749** <b>Security warning:</b> It is recommended that extension loading
7750** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
7751** rather than this interface, so the [load_extension()] SQL function
7752** remains disabled. This will prevent SQL injections from giving attackers
7753** access to extension loading capabilities.
7754*/
7755SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
7756
7757/*
7758** CAPI3REF: Automatically Load Statically Linked Extensions
7759**
7760** ^This interface causes the xEntryPoint() function to be invoked for
7761** each new [database connection] that is created. The idea here is that
7762** xEntryPoint() is the entry point for a statically linked [SQLite extension]
7763** that is to be automatically loaded into all new database connections.
7764**
7765** ^(Even though the function prototype shows that xEntryPoint() takes
7766** no arguments and returns void, SQLite invokes xEntryPoint() with three
7767** arguments and expects an integer result as if the signature of the
7768** entry point were as follows:
7769**
7770** <blockquote><pre>
7771** &nbsp; int xEntryPoint(
7772** &nbsp; sqlite3 *db,
7773** &nbsp; const char **pzErrMsg,
7774** &nbsp; const struct sqlite3_api_routines *pThunk
7775** &nbsp; );
7776** </pre></blockquote>)^
7777**
7778** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
7779** point to an appropriate error message (obtained from [sqlite3_mprintf()])
7780** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
7781** is NULL before calling the xEntryPoint(). ^SQLite will invoke
7782** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
7783** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
7784** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
7785**
7786** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
7787** on the list of automatic extensions is a harmless no-op. ^No entry point
7788** will be called more than once for each database connection that is opened.
7789**
7790** See also: [sqlite3_reset_auto_extension()]
7791** and [sqlite3_cancel_auto_extension()]
7792*/
7793SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
7794
7795/*
7796** CAPI3REF: Cancel Automatic Extension Loading
7797**
7798** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
7799** initialization routine X that was registered using a prior call to
7800** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
7801** routine returns 1 if initialization routine X was successfully
7802** unregistered and it returns 0 if X was not on the list of initialization
7803** routines.
7804*/
7805SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
7806
7807/*
7808** CAPI3REF: Reset Automatic Extension Loading
7809**
7810** ^This interface disables all automatic extensions previously
7811** registered using [sqlite3_auto_extension()].
7812*/
7813SQLITE_API void sqlite3_reset_auto_extension(void);
7814
7815/*
7816** Structures used by the virtual table interface
7817*/
7818typedef struct sqlite3_vtab sqlite3_vtab;
7819typedef struct sqlite3_index_info sqlite3_index_info;
7820typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
7821typedef struct sqlite3_module sqlite3_module;
7822
7823/*
7824** CAPI3REF: Virtual Table Object
7825** KEYWORDS: sqlite3_module {virtual table module}
7826**
7827** This structure, sometimes called a "virtual table module",
7828** defines the implementation of a [virtual table].
7829** This structure consists mostly of methods for the module.
7830**
7831** ^A virtual table module is created by filling in a persistent
7832** instance of this structure and passing a pointer to that instance
7833** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
7834** ^The registration remains valid until it is replaced by a different
7835** module or until the [database connection] closes. The content
7836** of this structure must not change while it is registered with
7837** any database connection.
7838*/
7839struct sqlite3_module {
7840 int iVersion;
7841 int (*xCreate)(sqlite3*, void *pAux,
7842 int argc, const char *const*argv,
7843 sqlite3_vtab **ppVTab, char**);
7844 int (*xConnect)(sqlite3*, void *pAux,
7845 int argc, const char *const*argv,
7846 sqlite3_vtab **ppVTab, char**);
7847 int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
7848 int (*xDisconnect)(sqlite3_vtab *pVTab);
7849 int (*xDestroy)(sqlite3_vtab *pVTab);
7850 int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
7851 int (*xClose)(sqlite3_vtab_cursor*);
7852 int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
7853 int argc, sqlite3_value **argv);
7854 int (*xNext)(sqlite3_vtab_cursor*);
7855 int (*xEof)(sqlite3_vtab_cursor*);
7856 int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
7857 int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
7858 int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
7859 int (*xBegin)(sqlite3_vtab *pVTab);
7860 int (*xSync)(sqlite3_vtab *pVTab);
7861 int (*xCommit)(sqlite3_vtab *pVTab);
7862 int (*xRollback)(sqlite3_vtab *pVTab);
7863 int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
7864 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
7865 void **ppArg);
7866 int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
7867 /* The methods above are in version 1 of the sqlite_module object. Those
7868 ** below are for version 2 and greater. */
7869 int (*xSavepoint)(sqlite3_vtab *pVTab, int);
7870 int (*xRelease)(sqlite3_vtab *pVTab, int);
7871 int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
7872 /* The methods above are in versions 1 and 2 of the sqlite_module object.
7873 ** Those below are for version 3 and greater. */
7874 int (*xShadowName)(const char*);
7875 /* The methods above are in versions 1 through 3 of the sqlite_module object.
7876 ** Those below are for version 4 and greater. */
7877 int (*xIntegrity)(sqlite3_vtab *pVTab, const char *zSchema,
7878 const char *zTabName, int mFlags, char **pzErr);
7879};
7880
7881/*
7882** CAPI3REF: Virtual Table Indexing Information
7883** KEYWORDS: sqlite3_index_info
7884**
7885** The sqlite3_index_info structure and its substructures is used as part
7886** of the [virtual table] interface to
7887** pass information into and receive the reply from the [xBestIndex]
7888** method of a [virtual table module]. The fields under **Inputs** are the
7889** inputs to xBestIndex and are read-only. xBestIndex inserts its
7890** results into the **Outputs** fields.
7891**
7892** ^(The aConstraint[] array records WHERE clause constraints of the form:
7893**
7894** <blockquote>column OP expr</blockquote>
7895**
7896** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
7897** stored in aConstraint[].op using one of the
7898** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
7899** ^(The index of the column is stored in
7900** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
7901** expr on the right-hand side can be evaluated (and thus the constraint
7902** is usable) and false if it cannot.)^
7903**
7904** ^The optimizer automatically inverts terms of the form "expr OP column"
7905** and makes other simplifications to the WHERE clause in an attempt to
7906** get as many WHERE clause terms into the form shown above as possible.
7907** ^The aConstraint[] array only reports WHERE clause terms that are
7908** relevant to the particular virtual table being queried.
7909**
7910** ^Information about the ORDER BY clause is stored in aOrderBy[].
7911** ^Each term of aOrderBy records a column of the ORDER BY clause.
7912**
7913** The colUsed field indicates which columns of the virtual table may be
7914** required by the current scan. Virtual table columns are numbered from
7915** zero in the order in which they appear within the CREATE TABLE statement
7916** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
7917** the corresponding bit is set within the colUsed mask if the column may be
7918** required by SQLite. If the table has at least 64 columns and any column
7919** to the right of the first 63 is required, then bit 63 of colUsed is also
7920** set. In other words, column iCol may be required if the expression
7921** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
7922** non-zero.
7923**
7924** The [xBestIndex] method must fill aConstraintUsage[] with information
7925** about what parameters to pass to xFilter. ^If argvIndex>0 then
7926** the right-hand side of the corresponding aConstraint[] is evaluated
7927** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
7928** is true, then the constraint is assumed to be fully handled by the
7929** virtual table and might not be checked again by the byte code.)^ ^(The
7930** aConstraintUsage[].omit flag is an optimization hint. When the omit flag
7931** is left in its default setting of false, the constraint will always be
7932** checked separately in byte code. If the omit flag is changed to true, then
7933** the constraint may or may not be checked in byte code. In other words,
7934** when the omit flag is true there is no guarantee that the constraint will
7935** not be checked again using byte code.)^
7936**
7937** ^The idxNum and idxStr values are recorded and passed into the
7938** [xFilter] method.
7939** ^[sqlite3_free()] is used to free idxStr if and only if
7940** needToFreeIdxStr is true.
7941**
7942** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
7943** the correct order to satisfy the ORDER BY clause so that no separate
7944** sorting step is required.
7945**
7946** ^The estimatedCost value is an estimate of the cost of a particular
7947** strategy. A cost of N indicates that the cost of the strategy is similar
7948** to a linear scan of an SQLite table with N rows. A cost of log(N)
7949** indicates that the expense of the operation is similar to that of a
7950** binary search on a unique indexed field of an SQLite table with N rows.
7951**
7952** ^The estimatedRows value is an estimate of the number of rows that
7953** will be returned by the strategy.
7954**
7955** The xBestIndex method may optionally populate the idxFlags field with a
7956** mask of SQLITE_INDEX_SCAN_* flags. One such flag is
7957** [SQLITE_INDEX_SCAN_HEX], which if set causes the [EXPLAIN QUERY PLAN]
7958** output to show the idxNum as hex instead of as decimal. Another flag is
7959** SQLITE_INDEX_SCAN_UNIQUE, which if set indicates that the query plan will
7960** return at most one row.
7961**
7962** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
7963** SQLite also assumes that if a call to the xUpdate() method is made as
7964** part of the same statement to delete or update a virtual table row and the
7965** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
7966** any database changes. In other words, if the xUpdate() returns
7967** SQLITE_CONSTRAINT, the database contents must be exactly as they were
7968** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
7969** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
7970** the xUpdate method are automatically rolled back by SQLite.
7971**
7972** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
7973** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
7974** If a virtual table extension is
7975** used with an SQLite version earlier than 3.8.2, the results of attempting
7976** to read or write the estimatedRows field are undefined (but are likely
7977** to include crashing the application). The estimatedRows field should
7978** therefore only be used if [sqlite3_libversion_number()] returns a
7979** value greater than or equal to 3008002. Similarly, the idxFlags field
7980** was added for [version 3.9.0] ([dateof:3.9.0]).
7981** It may therefore only be used if
7982** sqlite3_libversion_number() returns a value greater than or equal to
7983** 3009000.
7984*/
7985struct sqlite3_index_info {
7986 /* Inputs */
7987 int nConstraint; /* Number of entries in aConstraint */
7988 struct sqlite3_index_constraint {
7989 int iColumn; /* Column constrained. -1 for ROWID */
7990 unsigned char op; /* Constraint operator */
7991 unsigned char usable; /* True if this constraint is usable */
7992 int iTermOffset; /* Used internally - xBestIndex should ignore */
7993 } *aConstraint; /* Table of WHERE clause constraints */
7994 int nOrderBy; /* Number of terms in the ORDER BY clause */
7995 struct sqlite3_index_orderby {
7996 int iColumn; /* Column number */
7997 unsigned char desc; /* True for DESC. False for ASC. */
7998 } *aOrderBy; /* The ORDER BY clause */
7999 /* Outputs */
8000 struct sqlite3_index_constraint_usage {
8001 int argvIndex; /* if >0, constraint is part of argv to xFilter */
8002 unsigned char omit; /* Do not code a test for this constraint */
8003 } *aConstraintUsage;
8004 int idxNum; /* Number used to identify the index */
8005 char *idxStr; /* String, possibly obtained from sqlite3_malloc */
8006 int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
8007 int orderByConsumed; /* True if output is already ordered */
8008 double estimatedCost; /* Estimated cost of using this index */
8009 /* Fields below are only available in SQLite 3.8.2 and later */
8010 sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
8011 /* Fields below are only available in SQLite 3.9.0 and later */
8012 int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
8013 /* Fields below are only available in SQLite 3.10.0 and later */
8014 sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
8015};
8016
8017/*
8018** CAPI3REF: Virtual Table Scan Flags
8019**
8020** Virtual table implementations are allowed to set the
8021** [sqlite3_index_info].idxFlags field to some combination of
8022** these bits.
8023*/
8024#define SQLITE_INDEX_SCAN_UNIQUE0x00000001 0x00000001 /* Scan visits at most 1 row */
8025#define SQLITE_INDEX_SCAN_HEX0x00000002 0x00000002 /* Display idxNum as hex */
8026 /* in EXPLAIN QUERY PLAN */
8027
8028/*
8029** CAPI3REF: Virtual Table Constraint Operator Codes
8030**
8031** These macros define the allowed values for the
8032** [sqlite3_index_info].aConstraint[].op field. Each value represents
8033** an operator that is part of a constraint term in the WHERE clause of
8034** a query that uses a [virtual table].
8035**
8036** ^The left-hand operand of the operator is given by the corresponding
8037** aConstraint[].iColumn field. ^An iColumn of -1 indicates the left-hand
8038** operand is the rowid.
8039** The SQLITE_INDEX_CONSTRAINT_LIMIT and SQLITE_INDEX_CONSTRAINT_OFFSET
8040** operators have no left-hand operand, and so for those operators the
8041** corresponding aConstraint[].iColumn is meaningless and should not be
8042** used.
8043**
8044** All operator values from SQLITE_INDEX_CONSTRAINT_FUNCTION through
8045** value 255 are reserved to represent functions that are overloaded
8046** by the [xFindFunction|xFindFunction method] of the virtual table
8047** implementation.
8048**
8049** The right-hand operands for each constraint might be accessible using
8050** the [sqlite3_vtab_rhs_value()] interface. Usually the right-hand
8051** operand is only available if it appears as a single constant literal
8052** in the input SQL. If the right-hand operand is another column or an
8053** expression (even a constant expression) or a parameter, then the
8054** sqlite3_vtab_rhs_value() probably will not be able to extract it.
8055** ^The SQLITE_INDEX_CONSTRAINT_ISNULL and
8056** SQLITE_INDEX_CONSTRAINT_ISNOTNULL operators have no right-hand operand
8057** and hence calls to sqlite3_vtab_rhs_value() for those operators will
8058** always return SQLITE_NOTFOUND.
8059**
8060** The collating sequence to be used for comparison can be found using
8061** the [sqlite3_vtab_collation()] interface. For most real-world virtual
8062** tables, the collating sequence of constraints does not matter (for example
8063** because the constraints are numeric) and so the sqlite3_vtab_collation()
8064** interface is not commonly needed.
8065*/
8066#define SQLITE_INDEX_CONSTRAINT_EQ2 2
8067#define SQLITE_INDEX_CONSTRAINT_GT4 4
8068#define SQLITE_INDEX_CONSTRAINT_LE8 8
8069#define SQLITE_INDEX_CONSTRAINT_LT16 16
8070#define SQLITE_INDEX_CONSTRAINT_GE32 32
8071#define SQLITE_INDEX_CONSTRAINT_MATCH64 64
8072#define SQLITE_INDEX_CONSTRAINT_LIKE65 65
8073#define SQLITE_INDEX_CONSTRAINT_GLOB66 66
8074#define SQLITE_INDEX_CONSTRAINT_REGEXP67 67
8075#define SQLITE_INDEX_CONSTRAINT_NE68 68
8076#define SQLITE_INDEX_CONSTRAINT_ISNOT69 69
8077#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL70 70
8078#define SQLITE_INDEX_CONSTRAINT_ISNULL71 71
8079#define SQLITE_INDEX_CONSTRAINT_IS72 72
8080#define SQLITE_INDEX_CONSTRAINT_LIMIT73 73
8081#define SQLITE_INDEX_CONSTRAINT_OFFSET74 74
8082#define SQLITE_INDEX_CONSTRAINT_FUNCTION150 150
8083
8084/*
8085** CAPI3REF: Register A Virtual Table Implementation
8086** METHOD: sqlite3
8087**
8088** ^These routines are used to register a new [virtual table module] name.
8089** ^Module names must be registered before
8090** creating a new [virtual table] using the module and before using a
8091** preexisting [virtual table] for the module.
8092**
8093** ^The module name is registered on the [database connection] specified
8094** by the first parameter. ^The name of the module is given by the
8095** second parameter. ^The third parameter is a pointer to
8096** the implementation of the [virtual table module]. ^The fourth
8097** parameter is an arbitrary client data pointer that is passed through
8098** into the [xCreate] and [xConnect] methods of the virtual table module
8099** when a new virtual table is being created or reinitialized.
8100**
8101** ^The sqlite3_create_module_v2() interface has a fifth parameter which
8102** is a pointer to a destructor for the pClientData. ^SQLite will
8103** invoke the destructor function (if it is not NULL) when SQLite
8104** no longer needs the pClientData pointer. ^The destructor will also
8105** be invoked if the call to sqlite3_create_module_v2() fails.
8106** ^The sqlite3_create_module()
8107** interface is equivalent to sqlite3_create_module_v2() with a NULL
8108** destructor.
8109**
8110** ^If the third parameter (the pointer to the sqlite3_module object) is
8111** NULL then no new module is created and any existing modules with the
8112** same name are dropped.
8113**
8114** See also: [sqlite3_drop_modules()]
8115*/
8116SQLITE_API int sqlite3_create_module(
8117 sqlite3 *db, /* SQLite connection to register module with */
8118 const char *zName, /* Name of the module */
8119 const sqlite3_module *p, /* Methods for the module */
8120 void *pClientData /* Client data for xCreate/xConnect */
8121);
8122SQLITE_API int sqlite3_create_module_v2(
8123 sqlite3 *db, /* SQLite connection to register module with */
8124 const char *zName, /* Name of the module */
8125 const sqlite3_module *p, /* Methods for the module */
8126 void *pClientData, /* Client data for xCreate/xConnect */
8127 void(*xDestroy)(void*) /* Module destructor function */
8128);
8129
8130/*
8131** CAPI3REF: Remove Unnecessary Virtual Table Implementations
8132** METHOD: sqlite3
8133**
8134** ^The sqlite3_drop_modules(D,L) interface removes all virtual
8135** table modules from database connection D except those named on list L.
8136** The L parameter must be either NULL or a pointer to an array of pointers
8137** to strings where the array is terminated by a single NULL pointer.
8138** ^If the L parameter is NULL, then all virtual table modules are removed.
8139**
8140** See also: [sqlite3_create_module()]
8141*/
8142SQLITE_API int sqlite3_drop_modules(
8143 sqlite3 *db, /* Remove modules from this connection */
8144 const char **azKeep /* Except, do not remove the ones named here */
8145);
8146
8147/*
8148** CAPI3REF: Virtual Table Instance Object
8149** KEYWORDS: sqlite3_vtab
8150**
8151** Every [virtual table module] implementation uses a subclass
8152** of this object to describe a particular instance
8153** of the [virtual table]. Each subclass will
8154** be tailored to the specific needs of the module implementation.
8155** The purpose of this superclass is to define certain fields that are
8156** common to all module implementations.
8157**
8158** ^Virtual tables methods can set an error message by assigning a
8159** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
8160** take care that any prior string is freed by a call to [sqlite3_free()]
8161** prior to assigning a new string to zErrMsg. ^After the error message
8162** is delivered up to the client application, the string will be automatically
8163** freed by sqlite3_free() and the zErrMsg field will be zeroed.
8164*/
8165struct sqlite3_vtab {
8166 const sqlite3_module *pModule; /* The module for this virtual table */
8167 int nRef; /* Number of open cursors */
8168 char *zErrMsg; /* Error message from sqlite3_mprintf() */
8169 /* Virtual table implementations will typically add additional fields */
8170};
8171
8172/*
8173** CAPI3REF: Virtual Table Cursor Object
8174** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
8175**
8176** Every [virtual table module] implementation uses a subclass of the
8177** following structure to describe cursors that point into the
8178** [virtual table] and are used
8179** to loop through the virtual table. Cursors are created using the
8180** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
8181** by the [sqlite3_module.xClose | xClose] method. Cursors are used
8182** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
8183** of the module. Each module implementation will define
8184** the content of a cursor structure to suit its own needs.
8185**
8186** This superclass exists in order to define fields of the cursor that
8187** are common to all implementations.
8188*/
8189struct sqlite3_vtab_cursor {
8190 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
8191 /* Virtual table implementations will typically add additional fields */
8192};
8193
8194/*
8195** CAPI3REF: Declare The Schema Of A Virtual Table
8196**
8197** ^The [xCreate] and [xConnect] methods of a
8198** [virtual table module] call this interface
8199** to declare the format (the names and datatypes of the columns) of
8200** the virtual tables they implement.
8201*/
8202SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
8203
8204/*
8205** CAPI3REF: Overload A Function For A Virtual Table
8206** METHOD: sqlite3
8207**
8208** ^(Virtual tables can provide alternative implementations of functions
8209** using the [xFindFunction] method of the [virtual table module].
8210** But global versions of those functions
8211** must exist in order to be overloaded.)^
8212**
8213** ^(This API makes sure a global version of a function with a particular
8214** name and number of parameters exists. If no such function exists
8215** before this API is called, a new function is created.)^ ^The implementation
8216** of the new function always causes an exception to be thrown. So
8217** the new function is not good for anything by itself. Its only
8218** purpose is to be a placeholder function that can be overloaded
8219** by a [virtual table].
8220*/
8221SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
8222
8223/*
8224** CAPI3REF: A Handle To An Open BLOB
8225** KEYWORDS: {BLOB handle} {BLOB handles}
8226**
8227** An instance of this object represents an open BLOB on which
8228** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
8229** ^Objects of this type are created by [sqlite3_blob_open()]
8230** and destroyed by [sqlite3_blob_close()].
8231** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
8232** can be used to read or write small subsections of the BLOB.
8233** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
8234*/
8235typedef struct sqlite3_blob sqlite3_blob;
8236
8237/*
8238** CAPI3REF: Open A BLOB For Incremental I/O
8239** METHOD: sqlite3
8240** CONSTRUCTOR: sqlite3_blob
8241**
8242** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
8243** in row iRow, column zColumn, table zTable in database zDb;
8244** in other words, the same BLOB that would be selected by:
8245**
8246** <pre>
8247** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
8248** </pre>)^
8249**
8250** ^(Parameter zDb is not the filename that contains the database, but
8251** rather the symbolic name of the database. For attached databases, this is
8252** the name that appears after the AS keyword in the [ATTACH] statement.
8253** For the main database file, the database name is "main". For TEMP
8254** tables, the database name is "temp".)^
8255**
8256** ^If the flags parameter is non-zero, then the BLOB is opened for read
8257** and write access. ^If the flags parameter is zero, the BLOB is opened for
8258** read-only access.
8259**
8260** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
8261** in *ppBlob. Otherwise an [error code] is returned and, unless the error
8262** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
8263** the API is not misused, it is always safe to call [sqlite3_blob_close()]
8264** on *ppBlob after this function returns.
8265**
8266** This function fails with SQLITE_ERROR if any of the following are true:
8267** <ul>
8268** <li> ^(Database zDb does not exist)^,
8269** <li> ^(Table zTable does not exist within database zDb)^,
8270** <li> ^(Table zTable is a WITHOUT ROWID table)^,
8271** <li> ^(Column zColumn does not exist)^,
8272** <li> ^(Row iRow is not present in the table)^,
8273** <li> ^(The specified column of row iRow contains a value that is not
8274** a TEXT or BLOB value)^,
8275** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
8276** constraint and the blob is being opened for read/write access)^,
8277** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
8278** column zColumn is part of a [child key] definition and the blob is
8279** being opened for read/write access)^.
8280** </ul>
8281**
8282** ^Unless it returns SQLITE_MISUSE, this function sets the
8283** [database connection] error code and message accessible via
8284** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
8285**
8286** A BLOB referenced by sqlite3_blob_open() may be read using the
8287** [sqlite3_blob_read()] interface and modified by using
8288** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
8289** different row of the same table using the [sqlite3_blob_reopen()]
8290** interface. However, the column, table, or database of a [BLOB handle]
8291** cannot be changed after the [BLOB handle] is opened.
8292**
8293** ^(If the row that a BLOB handle points to is modified by an
8294** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
8295** then the BLOB handle is marked as "expired".
8296** This is true if any column of the row is changed, even a column
8297** other than the one the BLOB handle is open on.)^
8298** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
8299** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
8300** ^(Changes written into a BLOB prior to the BLOB expiring are not
8301** rolled back by the expiration of the BLOB. Such changes will eventually
8302** commit if the transaction continues to completion.)^
8303**
8304** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
8305** the opened blob. ^The size of a blob may not be changed by this
8306** interface. Use the [UPDATE] SQL command to change the size of a
8307** blob.
8308**
8309** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
8310** and the built-in [zeroblob] SQL function may be used to create a
8311** zero-filled blob to read or write using the incremental-blob interface.
8312**
8313** To avoid a resource leak, every open [BLOB handle] should eventually
8314** be released by a call to [sqlite3_blob_close()].
8315**
8316** See also: [sqlite3_blob_close()],
8317** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
8318** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
8319*/
8320SQLITE_API int sqlite3_blob_open(
8321 sqlite3*,
8322 const char *zDb,
8323 const char *zTable,
8324 const char *zColumn,
8325 sqlite3_int64 iRow,
8326 int flags,
8327 sqlite3_blob **ppBlob
8328);
8329
8330/*
8331** CAPI3REF: Move a BLOB Handle to a New Row
8332** METHOD: sqlite3_blob
8333**
8334** ^This function is used to move an existing [BLOB handle] so that it points
8335** to a different row of the same database table. ^The new row is identified
8336** by the rowid value passed as the second argument. Only the row can be
8337** changed. ^The database, table and column on which the blob handle is open
8338** remain the same. Moving an existing [BLOB handle] to a new row is
8339** faster than closing the existing handle and opening a new one.
8340**
8341** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
8342** it must exist and there must be either a blob or text value stored in
8343** the nominated column.)^ ^If the new row is not present in the table, or if
8344** it does not contain a blob or text value, or if another error occurs, an
8345** SQLite error code is returned and the blob handle is considered aborted.
8346** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
8347** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
8348** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
8349** always returns zero.
8350**
8351** ^This function sets the database handle error code and message.
8352*/
8353SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
8354
8355/*
8356** CAPI3REF: Close A BLOB Handle
8357** DESTRUCTOR: sqlite3_blob
8358**
8359** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
8360** unconditionally. Even if this routine returns an error code, the
8361** handle is still closed.)^
8362**
8363** ^If the blob handle being closed was opened for read-write access, and if
8364** the database is in auto-commit mode and there are no other open read-write
8365** blob handles or active write statements, the current transaction is
8366** committed. ^If an error occurs while committing the transaction, an error
8367** code is returned and the transaction rolled back.
8368**
8369** Calling this function with an argument that is not a NULL pointer or an
8370** open blob handle results in undefined behavior. ^Calling this routine
8371** with a null pointer (such as would be returned by a failed call to
8372** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
8373** is passed a valid open blob handle, the values returned by the
8374** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
8375*/
8376SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
8377
8378/*
8379** CAPI3REF: Return The Size Of An Open BLOB
8380** METHOD: sqlite3_blob
8381**
8382** ^Returns the size in bytes of the BLOB accessible via the
8383** successfully opened [BLOB handle] in its only argument. ^The
8384** incremental blob I/O routines can only read or overwrite existing
8385** blob content; they cannot change the size of a blob.
8386**
8387** This routine only works on a [BLOB handle] which has been created
8388** by a prior successful call to [sqlite3_blob_open()] and which has not
8389** been closed by [sqlite3_blob_close()]. Passing any other pointer in
8390** to this routine results in undefined and probably undesirable behavior.
8391*/
8392SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
8393
8394/*
8395** CAPI3REF: Read Data From A BLOB Incrementally
8396** METHOD: sqlite3_blob
8397**
8398** ^(This function is used to read data from an open [BLOB handle] into a
8399** caller-supplied buffer. N bytes of data are copied into buffer Z
8400** from the open BLOB, starting at offset iOffset.)^
8401**
8402** ^If offset iOffset is less than N bytes from the end of the BLOB,
8403** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
8404** less than zero, [SQLITE_ERROR] is returned and no data is read.
8405** ^The size of the blob (and hence the maximum value of N+iOffset)
8406** can be determined using the [sqlite3_blob_bytes()] interface.
8407**
8408** ^An attempt to read from an expired [BLOB handle] fails with an
8409** error code of [SQLITE_ABORT].
8410**
8411** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
8412** Otherwise, an [error code] or an [extended error code] is returned.)^
8413**
8414** This routine only works on a [BLOB handle] which has been created
8415** by a prior successful call to [sqlite3_blob_open()] and which has not
8416** been closed by [sqlite3_blob_close()]. Passing any other pointer in
8417** to this routine results in undefined and probably undesirable behavior.
8418**
8419** See also: [sqlite3_blob_write()].
8420*/
8421SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
8422
8423/*
8424** CAPI3REF: Write Data Into A BLOB Incrementally
8425** METHOD: sqlite3_blob
8426**
8427** ^(This function is used to write data into an open [BLOB handle] from a
8428** caller-supplied buffer. N bytes of data are copied from the buffer Z
8429** into the open BLOB, starting at offset iOffset.)^
8430**
8431** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
8432** Otherwise, an [error code] or an [extended error code] is returned.)^
8433** ^Unless SQLITE_MISUSE is returned, this function sets the
8434** [database connection] error code and message accessible via
8435** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
8436**
8437** ^If the [BLOB handle] passed as the first argument was not opened for
8438** writing (the flags parameter to [sqlite3_blob_open()] was zero),
8439** this function returns [SQLITE_READONLY].
8440**
8441** This function may only modify the contents of the BLOB; it is
8442** not possible to increase the size of a BLOB using this API.
8443** ^If offset iOffset is less than N bytes from the end of the BLOB,
8444** [SQLITE_ERROR] is returned and no data is written. The size of the
8445** BLOB (and hence the maximum value of N+iOffset) can be determined
8446** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
8447** than zero [SQLITE_ERROR] is returned and no data is written.
8448**
8449** ^An attempt to write to an expired [BLOB handle] fails with an
8450** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
8451** before the [BLOB handle] expired are not rolled back by the
8452** expiration of the handle, though of course those changes might
8453** have been overwritten by the statement that expired the BLOB handle
8454** or by other independent statements.
8455**
8456** This routine only works on a [BLOB handle] which has been created
8457** by a prior successful call to [sqlite3_blob_open()] and which has not
8458** been closed by [sqlite3_blob_close()]. Passing any other pointer in
8459** to this routine results in undefined and probably undesirable behavior.
8460**
8461** See also: [sqlite3_blob_read()].
8462*/
8463SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
8464
8465/*
8466** CAPI3REF: Virtual File System Objects
8467**
8468** A virtual filesystem (VFS) is an [sqlite3_vfs] object
8469** that SQLite uses to interact
8470** with the underlying operating system. Most SQLite builds come with a
8471** single default VFS that is appropriate for the host computer.
8472** New VFSes can be registered and existing VFSes can be unregistered.
8473** The following interfaces are provided.
8474**
8475** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
8476** ^Names are case sensitive.
8477** ^Names are zero-terminated UTF-8 strings.
8478** ^If there is no match, a NULL pointer is returned.
8479** ^If zVfsName is NULL then the default VFS is returned.
8480**
8481** ^New VFSes are registered with sqlite3_vfs_register().
8482** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
8483** ^The same VFS can be registered multiple times without injury.
8484** ^To make an existing VFS into the default VFS, register it again
8485** with the makeDflt flag set. If two different VFSes with the
8486** same name are registered, the behavior is undefined. If a
8487** VFS is registered with a name that is NULL or an empty string,
8488** then the behavior is undefined.
8489**
8490** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
8491** ^(If the default VFS is unregistered, another VFS is chosen as
8492** the default. The choice for the new VFS is arbitrary.)^
8493*/
8494SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
8495SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
8496SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
8497
8498/*
8499** CAPI3REF: Mutexes
8500**
8501** The SQLite core uses these routines for thread
8502** synchronization. Though they are intended for internal
8503** use by SQLite, code that links against SQLite is
8504** permitted to use any of these routines.
8505**
8506** The SQLite source code contains multiple implementations
8507** of these mutex routines. An appropriate implementation
8508** is selected automatically at compile-time. The following
8509** implementations are available in the SQLite core:
8510**
8511** <ul>
8512** <li> SQLITE_MUTEX_PTHREADS
8513** <li> SQLITE_MUTEX_W32
8514** <li> SQLITE_MUTEX_NOOP
8515** </ul>
8516**
8517** The SQLITE_MUTEX_NOOP implementation is a set of routines
8518** that does no real locking and is appropriate for use in
8519** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
8520** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
8521** and Windows.
8522**
8523** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
8524** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
8525** implementation is included with the library. In this case the
8526** application must supply a custom mutex implementation using the
8527** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
8528** before calling sqlite3_initialize() or any other public sqlite3_
8529** function that calls sqlite3_initialize().
8530**
8531** ^The sqlite3_mutex_alloc() routine allocates a new
8532** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
8533** routine returns NULL if it is unable to allocate the requested
8534** mutex. The argument to sqlite3_mutex_alloc() must be one of these
8535** integer constants:
8536**
8537** <ul>
8538** <li> SQLITE_MUTEX_FAST
8539** <li> SQLITE_MUTEX_RECURSIVE
8540** <li> SQLITE_MUTEX_STATIC_MAIN
8541** <li> SQLITE_MUTEX_STATIC_MEM
8542** <li> SQLITE_MUTEX_STATIC_OPEN
8543** <li> SQLITE_MUTEX_STATIC_PRNG
8544** <li> SQLITE_MUTEX_STATIC_LRU
8545** <li> SQLITE_MUTEX_STATIC_PMEM
8546** <li> SQLITE_MUTEX_STATIC_APP1
8547** <li> SQLITE_MUTEX_STATIC_APP2
8548** <li> SQLITE_MUTEX_STATIC_APP3
8549** <li> SQLITE_MUTEX_STATIC_VFS1
8550** <li> SQLITE_MUTEX_STATIC_VFS2
8551** <li> SQLITE_MUTEX_STATIC_VFS3
8552** </ul>
8553**
8554** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
8555** cause sqlite3_mutex_alloc() to create
8556** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
8557** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
8558** The mutex implementation does not need to make a distinction
8559** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
8560** not want to. SQLite will only request a recursive mutex in
8561** cases where it really needs one. If a faster non-recursive mutex
8562** implementation is available on the host platform, the mutex subsystem
8563** might return such a mutex in response to SQLITE_MUTEX_FAST.
8564**
8565** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
8566** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
8567** a pointer to a static preexisting mutex. ^Nine static mutexes are
8568** used by the current version of SQLite. Future versions of SQLite
8569** may add additional static mutexes. Static mutexes are for internal
8570** use by SQLite only. Applications that use SQLite mutexes should
8571** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
8572** SQLITE_MUTEX_RECURSIVE.
8573**
8574** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
8575** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
8576** returns a different mutex on every call. ^For the static
8577** mutex types, the same mutex is returned on every call that has
8578** the same type number.
8579**
8580** ^The sqlite3_mutex_free() routine deallocates a previously
8581** allocated dynamic mutex. Attempting to deallocate a static
8582** mutex results in undefined behavior.
8583**
8584** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
8585** to enter a mutex. ^If another thread is already within the mutex,
8586** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
8587** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
8588** upon successful entry. ^(Mutexes created using
8589** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
8590** In such cases, the
8591** mutex must be exited an equal number of times before another thread
8592** can enter.)^ If the same thread tries to enter any mutex other
8593** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
8594**
8595** ^(Some systems (for example, Windows 95) do not support the operation
8596** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
8597** will always return SQLITE_BUSY. In most cases the SQLite core only uses
8598** sqlite3_mutex_try() as an optimization, so this is acceptable
8599** behavior. The exceptions are unix builds that set the
8600** SQLITE_ENABLE_SETLK_TIMEOUT build option. In that case a working
8601** sqlite3_mutex_try() is required.)^
8602**
8603** ^The sqlite3_mutex_leave() routine exits a mutex that was
8604** previously entered by the same thread. The behavior
8605** is undefined if the mutex is not currently entered by the
8606** calling thread or is not currently allocated.
8607**
8608** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(),
8609** sqlite3_mutex_leave(), or sqlite3_mutex_free() is a NULL pointer,
8610** then any of the four routines behaves as a no-op.
8611**
8612** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
8613*/
8614SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
8615SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
8616SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
8617SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
8618SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
8619
8620/*
8621** CAPI3REF: Mutex Methods Object
8622**
8623** An instance of this structure defines the low-level routines
8624** used to allocate and use mutexes.
8625**
8626** Usually, the default mutex implementations provided by SQLite are
8627** sufficient, however the application has the option of substituting a custom
8628** implementation for specialized deployments or systems for which SQLite
8629** does not provide a suitable implementation. In this case, the application
8630** creates and populates an instance of this structure to pass
8631** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
8632** Additionally, an instance of this structure can be used as an
8633** output variable when querying the system for the current mutex
8634** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
8635**
8636** ^The xMutexInit method defined by this structure is invoked as
8637** part of system initialization by the sqlite3_initialize() function.
8638** ^The xMutexInit routine is called by SQLite exactly once for each
8639** effective call to [sqlite3_initialize()].
8640**
8641** ^The xMutexEnd method defined by this structure is invoked as
8642** part of system shutdown by the sqlite3_shutdown() function. The
8643** implementation of this method is expected to release all outstanding
8644** resources obtained by the mutex methods implementation, especially
8645** those obtained by the xMutexInit method. ^The xMutexEnd()
8646** interface is invoked exactly once for each call to [sqlite3_shutdown()].
8647**
8648** ^(The remaining seven methods defined by this structure (xMutexAlloc,
8649** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
8650** xMutexNotheld) implement the following interfaces (respectively):
8651**
8652** <ul>
8653** <li> [sqlite3_mutex_alloc()] </li>
8654** <li> [sqlite3_mutex_free()] </li>
8655** <li> [sqlite3_mutex_enter()] </li>
8656** <li> [sqlite3_mutex_try()] </li>
8657** <li> [sqlite3_mutex_leave()] </li>
8658** <li> [sqlite3_mutex_held()] </li>
8659** <li> [sqlite3_mutex_notheld()] </li>
8660** </ul>)^
8661**
8662** The only difference is that the public sqlite3_XXX functions enumerated
8663** above silently ignore any invocations that pass a NULL pointer instead
8664** of a valid mutex handle. The implementations of the methods defined
8665** by this structure are not required to handle this case. The results
8666** of passing a NULL pointer instead of a valid mutex handle are undefined
8667** (i.e. it is acceptable to provide an implementation that segfaults if
8668** it is passed a NULL pointer).
8669**
8670** The xMutexInit() method must be threadsafe. It must be harmless to
8671** invoke xMutexInit() multiple times within the same process and without
8672** intervening calls to xMutexEnd(). Second and subsequent calls to
8673** xMutexInit() must be no-ops.
8674**
8675** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
8676** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
8677** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
8678** memory allocation for a fast or recursive mutex.
8679**
8680** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
8681** called, but only if the prior call to xMutexInit returned SQLITE_OK.
8682** If xMutexInit fails in any way, it is expected to clean up after itself
8683** prior to returning.
8684*/
8685typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
8686struct sqlite3_mutex_methods {
8687 int (*xMutexInit)(void);
8688 int (*xMutexEnd)(void);
8689 sqlite3_mutex *(*xMutexAlloc)(int);
8690 void (*xMutexFree)(sqlite3_mutex *);
8691 void (*xMutexEnter)(sqlite3_mutex *);
8692 int (*xMutexTry)(sqlite3_mutex *);
8693 void (*xMutexLeave)(sqlite3_mutex *);
8694 int (*xMutexHeld)(sqlite3_mutex *);
8695 int (*xMutexNotheld)(sqlite3_mutex *);
8696};
8697
8698/*
8699** CAPI3REF: Mutex Verification Routines
8700**
8701** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
8702** are intended for use inside assert() statements. The SQLite core
8703** never uses these routines except inside an assert() and applications
8704** are advised to follow the lead of the core. The SQLite core only
8705** provides implementations for these routines when it is compiled
8706** with the SQLITE_DEBUG flag. External mutex implementations
8707** are only required to provide these routines if SQLITE_DEBUG is
8708** defined and if NDEBUG is not defined.
8709**
8710** These routines should return true if the mutex in their argument
8711** is held or not held, respectively, by the calling thread.
8712**
8713** The implementation is not required to provide versions of these
8714** routines that actually work. If the implementation does not provide working
8715** versions of these routines, it should at least provide stubs that always
8716** return true so that one does not get spurious assertion failures.
8717**
8718** If the argument to sqlite3_mutex_held() is a NULL pointer then
8719** the routine should return 1. This seems counter-intuitive since
8720** clearly the mutex cannot be held if it does not exist. But
8721** the reason the mutex does not exist is because the build is not
8722** using mutexes. And we do not want the assert() containing the
8723** call to sqlite3_mutex_held() to fail, so a non-zero return is
8724** the appropriate thing to do. The sqlite3_mutex_notheld()
8725** interface should also return 1 when given a NULL pointer.
8726*/
8727#ifndef NDEBUG1
8728SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
8729SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
8730#endif
8731
8732/*
8733** CAPI3REF: Mutex Types
8734**
8735** The [sqlite3_mutex_alloc()] interface takes a single argument
8736** which is one of these integer constants.
8737**
8738** The set of static mutexes may change from one SQLite release to the
8739** next. Applications that override the built-in mutex logic must be
8740** prepared to accommodate additional static mutexes.
8741*/
8742#define SQLITE_MUTEX_FAST0 0
8743#define SQLITE_MUTEX_RECURSIVE1 1
8744#define SQLITE_MUTEX_STATIC_MAIN2 2
8745#define SQLITE_MUTEX_STATIC_MEM3 3 /* sqlite3_malloc() */
8746#define SQLITE_MUTEX_STATIC_MEM24 4 /* NOT USED */
8747#define SQLITE_MUTEX_STATIC_OPEN4 4 /* sqlite3BtreeOpen() */
8748#define SQLITE_MUTEX_STATIC_PRNG5 5 /* sqlite3_randomness() */
8749#define SQLITE_MUTEX_STATIC_LRU6 6 /* lru page list */
8750#define SQLITE_MUTEX_STATIC_LRU27 7 /* NOT USED */
8751#define SQLITE_MUTEX_STATIC_PMEM7 7 /* sqlite3PageMalloc() */
8752#define SQLITE_MUTEX_STATIC_APP18 8 /* For use by application */
8753#define SQLITE_MUTEX_STATIC_APP29 9 /* For use by application */
8754#define SQLITE_MUTEX_STATIC_APP310 10 /* For use by application */
8755#define SQLITE_MUTEX_STATIC_VFS111 11 /* For use by built-in VFS */
8756#define SQLITE_MUTEX_STATIC_VFS212 12 /* For use by extension VFS */
8757#define SQLITE_MUTEX_STATIC_VFS313 13 /* For use by application VFS */
8758
8759/* Legacy compatibility: */
8760#define SQLITE_MUTEX_STATIC_MASTER2 2
8761
8762
8763/*
8764** CAPI3REF: Retrieve the mutex for a database connection
8765** METHOD: sqlite3
8766**
8767** ^This interface returns a pointer to the [sqlite3_mutex] object that
8768** serializes access to the [database connection] given in the argument
8769** when the [threading mode] is Serialized.
8770** ^If the [threading mode] is Single-thread or Multi-thread then this
8771** routine returns a NULL pointer.
8772*/
8773SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
8774
8775/*
8776** CAPI3REF: Low-Level Control Of Database Files
8777** METHOD: sqlite3
8778** KEYWORDS: {file control}
8779**
8780** ^The [sqlite3_file_control()] interface makes a direct call to the
8781** xFileControl method for the [sqlite3_io_methods] object associated
8782** with a particular database identified by the second argument. ^The
8783** name of the database is "main" for the main database or "temp" for the
8784** TEMP database, or the name that appears after the AS keyword for
8785** databases that are added using the [ATTACH] SQL command.
8786** ^A NULL pointer can be used in place of "main" to refer to the
8787** main database file.
8788** ^The third and fourth parameters to this routine
8789** are passed directly through to the second and third parameters of
8790** the xFileControl method. ^The return value of the xFileControl
8791** method becomes the return value of this routine.
8792**
8793** A few opcodes for [sqlite3_file_control()] are handled directly
8794** by the SQLite core and never invoke the
8795** sqlite3_io_methods.xFileControl method.
8796** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
8797** a pointer to the underlying [sqlite3_file] object to be written into
8798** the space pointed to by the 4th parameter. The
8799** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns
8800** the [sqlite3_file] object associated with the journal file instead of
8801** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns
8802** a pointer to the underlying [sqlite3_vfs] object for the file.
8803** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter
8804** from the pager.
8805**
8806** ^If the second parameter (zDbName) does not match the name of any
8807** open database file, then SQLITE_ERROR is returned. ^This error
8808** code is not remembered and will not be recalled by [sqlite3_errcode()]
8809** or [sqlite3_errmsg()]. The underlying xFileControl method might
8810** also return SQLITE_ERROR. There is no way to distinguish between
8811** an incorrect zDbName and an SQLITE_ERROR return from the underlying
8812** xFileControl method.
8813**
8814** See also: [file control opcodes]
8815*/
8816SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
8817
8818/*
8819** CAPI3REF: Testing Interface
8820**
8821** ^The sqlite3_test_control() interface is used to read out internal
8822** state of SQLite and to inject faults into SQLite for testing
8823** purposes. ^The first parameter is an operation code that determines
8824** the number, meaning, and operation of all subsequent parameters.
8825**
8826** This interface is not for use by applications. It exists solely
8827** for verifying the correct operation of the SQLite library. Depending
8828** on how the SQLite library is compiled, this interface might not exist.
8829**
8830** The details of the operation codes, their meanings, the parameters
8831** they take, and what they do are all subject to change without notice.
8832** Unlike most of the SQLite API, this function is not guaranteed to
8833** operate consistently from one release to the next.
8834*/
8835SQLITE_API int sqlite3_test_control(int op, ...);
8836
8837/*
8838** CAPI3REF: Testing Interface Operation Codes
8839**
8840** These constants are the valid operation code parameters used
8841** as the first argument to [sqlite3_test_control()].
8842**
8843** These parameters and their meanings are subject to change
8844** without notice. These values are for testing purposes only.
8845** Applications should not use any of these parameters or the
8846** [sqlite3_test_control()] interface.
8847*/
8848#define SQLITE_TESTCTRL_FIRST5 5
8849#define SQLITE_TESTCTRL_PRNG_SAVE5 5
8850#define SQLITE_TESTCTRL_PRNG_RESTORE6 6
8851#define SQLITE_TESTCTRL_PRNG_RESET7 7 /* NOT USED */
8852#define SQLITE_TESTCTRL_FK_NO_ACTION7 7
8853#define SQLITE_TESTCTRL_BITVEC_TEST8 8
8854#define SQLITE_TESTCTRL_FAULT_INSTALL9 9
8855#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS10 10
8856#define SQLITE_TESTCTRL_PENDING_BYTE11 11
8857#define SQLITE_TESTCTRL_ASSERT12 12
8858#define SQLITE_TESTCTRL_ALWAYS13 13
8859#define SQLITE_TESTCTRL_RESERVE14 14 /* NOT USED */
8860#define SQLITE_TESTCTRL_JSON_SELFCHECK14 14
8861#define SQLITE_TESTCTRL_OPTIMIZATIONS15 15
8862#define SQLITE_TESTCTRL_ISKEYWORD16 16 /* NOT USED */
8863#define SQLITE_TESTCTRL_GETOPT16 16
8864#define SQLITE_TESTCTRL_SCRATCHMALLOC17 17 /* NOT USED */
8865#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS17 17
8866#define SQLITE_TESTCTRL_LOCALTIME_FAULT18 18
8867#define SQLITE_TESTCTRL_EXPLAIN_STMT19 19 /* NOT USED */
8868#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD19 19
8869#define SQLITE_TESTCTRL_NEVER_CORRUPT20 20
8870#define SQLITE_TESTCTRL_VDBE_COVERAGE21 21
8871#define SQLITE_TESTCTRL_BYTEORDER22 22
8872#define SQLITE_TESTCTRL_ISINIT23 23
8873#define SQLITE_TESTCTRL_SORTER_MMAP24 24
8874#define SQLITE_TESTCTRL_IMPOSTER25 25
8875#define SQLITE_TESTCTRL_PARSER_COVERAGE26 26
8876#define SQLITE_TESTCTRL_RESULT_INTREAL27 27
8877#define SQLITE_TESTCTRL_PRNG_SEED28 28
8878#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS29 29
8879#define SQLITE_TESTCTRL_SEEK_COUNT30 30
8880#define SQLITE_TESTCTRL_TRACEFLAGS31 31
8881#define SQLITE_TESTCTRL_TUNE32 32
8882#define SQLITE_TESTCTRL_LOGEST33 33
8883#define SQLITE_TESTCTRL_USELONGDOUBLE34 34 /* NOT USED */
8884#define SQLITE_TESTCTRL_LAST34 34 /* Largest TESTCTRL */
8885
8886/*
8887** CAPI3REF: SQL Keyword Checking
8888**
8889** These routines provide access to the set of SQL language keywords
8890** recognized by SQLite. Applications can use these routines to determine
8891** whether or not a specific identifier needs to be escaped (for example,
8892** by enclosing in double-quotes) so as not to confuse the parser.
8893**
8894** The sqlite3_keyword_count() interface returns the number of distinct
8895** keywords understood by SQLite.
8896**
8897** The sqlite3_keyword_name(N,Z,L) interface finds the 0-based N-th keyword and
8898** makes *Z point to that keyword expressed as UTF8 and writes the number
8899** of bytes in the keyword into *L. The string that *Z points to is not
8900** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns
8901** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
8902** or L are NULL or invalid pointers then calls to
8903** sqlite3_keyword_name(N,Z,L) result in undefined behavior.
8904**
8905** The sqlite3_keyword_check(Z,L) interface checks to see whether or not
8906** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
8907** if it is and zero if not.
8908**
8909** The parser used by SQLite is forgiving. It is often possible to use
8910** a keyword as an identifier as long as such use does not result in a
8911** parsing ambiguity. For example, the statement
8912** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
8913** creates a new table named "BEGIN" with three columns named
8914** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid
8915** using keywords as identifiers. Common techniques used to avoid keyword
8916** name collisions include:
8917** <ul>
8918** <li> Put all identifier names inside double-quotes. This is the official
8919** SQL way to escape identifier names.
8920** <li> Put identifier names inside &#91;...&#93;. This is not standard SQL,
8921** but it is what SQL Server does and so lots of programmers use this
8922** technique.
8923** <li> Begin every identifier with the letter "Z" as no SQL keywords start
8924** with "Z".
8925** <li> Include a digit somewhere in every identifier name.
8926** </ul>
8927**
8928** Note that the number of keywords understood by SQLite can depend on
8929** compile-time options. For example, "VACUUM" is not a keyword if
8930** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also,
8931** new keywords may be added to future releases of SQLite.
8932*/
8933SQLITE_API int sqlite3_keyword_count(void);
8934SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
8935SQLITE_API int sqlite3_keyword_check(const char*,int);
8936
8937/*
8938** CAPI3REF: Dynamic String Object
8939** KEYWORDS: {dynamic string}
8940**
8941** An instance of the sqlite3_str object contains a dynamically-sized
8942** string under construction.
8943**
8944** The lifecycle of an sqlite3_str object is as follows:
8945** <ol>
8946** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
8947** <li> ^Text is appended to the sqlite3_str object using various
8948** methods, such as [sqlite3_str_appendf()].
8949** <li> ^The sqlite3_str object is destroyed and the string it created
8950** is returned using the [sqlite3_str_finish()] interface.
8951** </ol>
8952*/
8953typedef struct sqlite3_str sqlite3_str;
8954
8955/*
8956** CAPI3REF: Create A New Dynamic String Object
8957** CONSTRUCTOR: sqlite3_str
8958**
8959** ^The [sqlite3_str_new(D)] interface allocates and initializes
8960** a new [sqlite3_str] object. To avoid memory leaks, the object returned by
8961** [sqlite3_str_new()] must be freed by a subsequent call to
8962** [sqlite3_str_finish(X)].
8963**
8964** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
8965** valid [sqlite3_str] object, though in the event of an out-of-memory
8966** error the returned object might be a special singleton that will
8967** silently reject new text, always return SQLITE_NOMEM from
8968** [sqlite3_str_errcode()], always return 0 for
8969** [sqlite3_str_length()], and always return NULL from
8970** [sqlite3_str_finish(X)]. It is always safe to use the value
8971** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
8972** to any of the other [sqlite3_str] methods.
8973**
8974** The D parameter to [sqlite3_str_new(D)] may be NULL. If the
8975** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
8976** length of the string contained in the [sqlite3_str] object will be
8977** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
8978** of [SQLITE_MAX_LENGTH].
8979*/
8980SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
8981
8982/*
8983** CAPI3REF: Finalize A Dynamic String
8984** DESTRUCTOR: sqlite3_str
8985**
8986** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
8987** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
8988** that contains the constructed string. The calling application should
8989** pass the returned value to [sqlite3_free()] to avoid a memory leak.
8990** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
8991** errors were encountered during construction of the string. ^The
8992** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
8993** string in [sqlite3_str] object X is zero bytes long.
8994*/
8995SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
8996
8997/*
8998** CAPI3REF: Add Content To A Dynamic String
8999** METHOD: sqlite3_str
9000**
9001** These interfaces add content to an sqlite3_str object previously obtained
9002** from [sqlite3_str_new()].
9003**
9004** ^The [sqlite3_str_appendf(X,F,...)] and
9005** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
9006** functionality of SQLite to append formatted text onto the end of
9007** [sqlite3_str] object X.
9008**
9009** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
9010** onto the end of the [sqlite3_str] object X. N must be non-negative.
9011** S must contain at least N non-zero bytes of content. To append a
9012** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
9013** method instead.
9014**
9015** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
9016** zero-terminated string S onto the end of [sqlite3_str] object X.
9017**
9018** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
9019** single-byte character C onto the end of [sqlite3_str] object X.
9020** ^This method can be used, for example, to add whitespace indentation.
9021**
9022** ^The [sqlite3_str_reset(X)] method resets the string under construction
9023** inside [sqlite3_str] object X back to zero bytes in length.
9024**
9025** These methods do not return a result code. ^If an error occurs, that fact
9026** is recorded in the [sqlite3_str] object and can be recovered by a
9027** subsequent call to [sqlite3_str_errcode(X)].
9028*/
9029SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
9030SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
9031SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
9032SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
9033SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
9034SQLITE_API void sqlite3_str_reset(sqlite3_str*);
9035
9036/*
9037** CAPI3REF: Status Of A Dynamic String
9038** METHOD: sqlite3_str
9039**
9040** These interfaces return the current status of an [sqlite3_str] object.
9041**
9042** ^If any prior errors have occurred while constructing the dynamic string
9043** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
9044** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns
9045** [SQLITE_NOMEM] following any out-of-memory error, or
9046** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
9047** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
9048**
9049** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
9050** of the dynamic string under construction in [sqlite3_str] object X.
9051** ^The length returned by [sqlite3_str_length(X)] does not include the
9052** zero-termination byte.
9053**
9054** ^The [sqlite3_str_value(X)] method returns a pointer to the current
9055** content of the dynamic string under construction in X. The value
9056** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
9057** and might be freed or altered by any subsequent method on the same
9058** [sqlite3_str] object. Applications must not use the pointer returned by
9059** [sqlite3_str_value(X)] after any subsequent method call on the same
9060** object. ^Applications may change the content of the string returned
9061** by [sqlite3_str_value(X)] as long as they do not write into any bytes
9062** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
9063** write any byte after any subsequent sqlite3_str method call.
9064*/
9065SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
9066SQLITE_API int sqlite3_str_length(sqlite3_str*);
9067SQLITE_API char *sqlite3_str_value(sqlite3_str*);
9068
9069/*
9070** CAPI3REF: SQLite Runtime Status
9071**
9072** ^These interfaces are used to retrieve runtime status information
9073** about the performance of SQLite, and optionally to reset various
9074** highwater marks. ^The first argument is an integer code for
9075** the specific parameter to measure. ^(Recognized integer codes
9076** are of the form [status parameters | SQLITE_STATUS_...].)^
9077** ^The current value of the parameter is returned into *pCurrent.
9078** ^The highest recorded value is returned in *pHighwater. ^If the
9079** resetFlag is true, then the highest record value is reset after
9080** *pHighwater is written. ^(Some parameters do not record the highest
9081** value. For those parameters
9082** nothing is written into *pHighwater and the resetFlag is ignored.)^
9083** ^(Other parameters record only the highwater mark and not the current
9084** value. For these latter parameters nothing is written into *pCurrent.)^
9085**
9086** ^The sqlite3_status() and sqlite3_status64() routines return
9087** SQLITE_OK on success and a non-zero [error code] on failure.
9088**
9089** If either the current value or the highwater mark is too large to
9090** be represented by a 32-bit integer, then the values returned by
9091** sqlite3_status() are undefined.
9092**
9093** See also: [sqlite3_db_status()]
9094*/
9095SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
9096SQLITE_API int sqlite3_status64(
9097 int op,
9098 sqlite3_int64 *pCurrent,
9099 sqlite3_int64 *pHighwater,
9100 int resetFlag
9101);
9102
9103
9104/*
9105** CAPI3REF: Status Parameters
9106** KEYWORDS: {status parameters}
9107**
9108** These integer constants designate various run-time status parameters
9109** that can be returned by [sqlite3_status()].
9110**
9111** <dl>
9112** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
9113** <dd>This parameter is the current amount of memory checked out
9114** using [sqlite3_malloc()], either directly or indirectly. The
9115** figure includes calls made to [sqlite3_malloc()] by the application
9116** and internal memory usage by the SQLite library. Auxiliary page-cache
9117** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
9118** this parameter. The amount returned is the sum of the allocation
9119** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
9120**
9121** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
9122** <dd>This parameter records the largest memory allocation request
9123** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
9124** internal equivalents). Only the value returned in the
9125** *pHighwater parameter to [sqlite3_status()] is of interest.
9126** The value written into the *pCurrent parameter is undefined.</dd>)^
9127**
9128** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
9129** <dd>This parameter records the number of separate memory allocations
9130** currently checked out.</dd>)^
9131**
9132** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
9133** <dd>This parameter returns the number of pages used out of the
9134** [pagecache memory allocator] that was configured using
9135** [SQLITE_CONFIG_PAGECACHE]. The
9136** value returned is in pages, not in bytes.</dd>)^
9137**
9138** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
9139** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
9140** <dd>This parameter returns the number of bytes of page cache
9141** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
9142** buffer and where forced to overflow to [sqlite3_malloc()]. The
9143** returned value includes allocations that overflowed because they
9144** were too large (they were larger than the "sz" parameter to
9145** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
9146** no space was left in the page cache.</dd>)^
9147**
9148** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
9149** <dd>This parameter records the largest memory allocation request
9150** handed to the [pagecache memory allocator]. Only the value returned in the
9151** *pHighwater parameter to [sqlite3_status()] is of interest.
9152** The value written into the *pCurrent parameter is undefined.</dd>)^
9153**
9154** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
9155** <dd>No longer used.</dd>
9156**
9157** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
9158** <dd>No longer used.</dd>
9159**
9160** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
9161** <dd>No longer used.</dd>
9162**
9163** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
9164** <dd>The *pHighwater parameter records the deepest parser stack.
9165** The *pCurrent value is undefined. The *pHighwater value is only
9166** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
9167** </dl>
9168**
9169** New status parameters may be added from time to time.
9170*/
9171#define SQLITE_STATUS_MEMORY_USED0 0
9172#define SQLITE_STATUS_PAGECACHE_USED1 1
9173#define SQLITE_STATUS_PAGECACHE_OVERFLOW2 2
9174#define SQLITE_STATUS_SCRATCH_USED3 3 /* NOT USED */
9175#define SQLITE_STATUS_SCRATCH_OVERFLOW4 4 /* NOT USED */
9176#define SQLITE_STATUS_MALLOC_SIZE5 5
9177#define SQLITE_STATUS_PARSER_STACK6 6
9178#define SQLITE_STATUS_PAGECACHE_SIZE7 7
9179#define SQLITE_STATUS_SCRATCH_SIZE8 8 /* NOT USED */
9180#define SQLITE_STATUS_MALLOC_COUNT9 9
9181
9182/*
9183** CAPI3REF: Database Connection Status
9184** METHOD: sqlite3
9185**
9186** ^This interface is used to retrieve runtime status information
9187** about a single [database connection]. ^The first argument is the
9188** database connection object to be interrogated. ^The second argument
9189** is an integer constant, taken from the set of
9190** [SQLITE_DBSTATUS options], that
9191** determines the parameter to interrogate. The set of
9192** [SQLITE_DBSTATUS options] is likely
9193** to grow in future releases of SQLite.
9194**
9195** ^The current value of the requested parameter is written into *pCur
9196** and the highest instantaneous value is written into *pHiwtr. ^If
9197** the resetFlg is true, then the highest instantaneous value is
9198** reset back down to the current value.
9199**
9200** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
9201** non-zero [error code] on failure.
9202**
9203** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
9204*/
9205SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
9206
9207/*
9208** CAPI3REF: Status Parameters for database connections
9209** KEYWORDS: {SQLITE_DBSTATUS options}
9210**
9211** These constants are the available integer "verbs" that can be passed as
9212** the second argument to the [sqlite3_db_status()] interface.
9213**
9214** New verbs may be added in future releases of SQLite. Existing verbs
9215** might be discontinued. Applications should check the return code from
9216** [sqlite3_db_status()] to make sure that the call worked.
9217** The [sqlite3_db_status()] interface will return a non-zero error code
9218** if a discontinued or unsupported verb is invoked.
9219**
9220** <dl>
9221** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
9222** <dd>This parameter returns the number of lookaside memory slots currently
9223** checked out.</dd>)^
9224**
9225** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
9226** <dd>This parameter returns the number of malloc attempts that were
9227** satisfied using lookaside memory. Only the high-water value is meaningful;
9228** the current value is always zero.</dd>)^
9229**
9230** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
9231** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
9232** <dd>This parameter returns the number of malloc attempts that might have
9233** been satisfied using lookaside memory but failed due to the amount of
9234** memory requested being larger than the lookaside slot size.
9235** Only the high-water value is meaningful;
9236** the current value is always zero.</dd>)^
9237**
9238** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
9239** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
9240** <dd>This parameter returns the number of malloc attempts that might have
9241** been satisfied using lookaside memory but failed due to all lookaside
9242** memory already being in use.
9243** Only the high-water value is meaningful;
9244** the current value is always zero.</dd>)^
9245**
9246** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
9247** <dd>This parameter returns the approximate number of bytes of heap
9248** memory used by all pager caches associated with the database connection.)^
9249** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
9250** </dd>
9251**
9252** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
9253** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
9254** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
9255** pager cache is shared between two or more connections the bytes of heap
9256** memory used by that pager cache is divided evenly between the attached
9257** connections.)^ In other words, if none of the pager caches associated
9258** with the database connection are shared, this request returns the same
9259** value as DBSTATUS_CACHE_USED. Or, if one or more of the pager caches are
9260** shared, the value returned by this call will be smaller than that returned
9261** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
9262** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.</dd>
9263**
9264** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
9265** <dd>This parameter returns the approximate number of bytes of heap
9266** memory used to store the schema for all databases associated
9267** with the connection - main, temp, and any [ATTACH]-ed databases.)^
9268** ^The full amount of memory used by the schemas is reported, even if the
9269** schema memory is shared with other database connections due to
9270** [shared cache mode] being enabled.
9271** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
9272** </dd>
9273**
9274** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
9275** <dd>This parameter returns the approximate number of bytes of heap
9276** and lookaside memory used by all prepared statements associated with
9277** the database connection.)^
9278** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
9279** </dd>
9280**
9281** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
9282** <dd>This parameter returns the number of pager cache hits that have
9283** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
9284** is always 0.
9285** </dd>
9286**
9287** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
9288** <dd>This parameter returns the number of pager cache misses that have
9289** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
9290** is always 0.
9291** </dd>
9292**
9293** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
9294** <dd>This parameter returns the number of dirty cache entries that have
9295** been written to disk. Specifically, the number of pages written to the
9296** wal file in wal mode databases, or the number of pages written to the
9297** database file in rollback mode databases. Any pages written as part of
9298** transaction rollback or database recovery operations are not included.
9299** If an IO or other error occurs while writing a page to disk, the effect
9300** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
9301** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
9302** </dd>
9303**
9304** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>
9305** <dd>This parameter returns the number of dirty cache entries that have
9306** been written to disk in the middle of a transaction due to the page
9307** cache overflowing. Transactions are more efficient if they are written
9308** to disk all at once. When pages spill mid-transaction, that introduces
9309** additional overhead. This parameter can be used to help identify
9310** inefficiencies that can be resolved by increasing the cache size.
9311** </dd>
9312**
9313** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
9314** <dd>This parameter returns zero for the current value if and only if
9315** all foreign key constraints (deferred or immediate) have been
9316** resolved.)^ ^The highwater mark is always 0.
9317** </dd>
9318** </dl>
9319*/
9320#define SQLITE_DBSTATUS_LOOKASIDE_USED0 0
9321#define SQLITE_DBSTATUS_CACHE_USED1 1
9322#define SQLITE_DBSTATUS_SCHEMA_USED2 2
9323#define SQLITE_DBSTATUS_STMT_USED3 3
9324#define SQLITE_DBSTATUS_LOOKASIDE_HIT4 4
9325#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE5 5
9326#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL6 6
9327#define SQLITE_DBSTATUS_CACHE_HIT7 7
9328#define SQLITE_DBSTATUS_CACHE_MISS8 8
9329#define SQLITE_DBSTATUS_CACHE_WRITE9 9
9330#define SQLITE_DBSTATUS_DEFERRED_FKS10 10
9331#define SQLITE_DBSTATUS_CACHE_USED_SHARED11 11
9332#define SQLITE_DBSTATUS_CACHE_SPILL12 12
9333#define SQLITE_DBSTATUS_MAX12 12 /* Largest defined DBSTATUS */
9334
9335
9336/*
9337** CAPI3REF: Prepared Statement Status
9338** METHOD: sqlite3_stmt
9339**
9340** ^(Each prepared statement maintains various
9341** [SQLITE_STMTSTATUS counters] that measure the number
9342** of times it has performed specific operations.)^ These counters can
9343** be used to monitor the performance characteristics of the prepared
9344** statements. For example, if the number of table steps greatly exceeds
9345** the number of table searches or result rows, that would tend to indicate
9346** that the prepared statement is using a full table scan rather than
9347** an index.
9348**
9349** ^(This interface is used to retrieve and reset counter values from
9350** a [prepared statement]. The first argument is the prepared statement
9351** object to be interrogated. The second argument
9352** is an integer code for a specific [SQLITE_STMTSTATUS counter]
9353** to be interrogated.)^
9354** ^The current value of the requested counter is returned.
9355** ^If the resetFlg is true, then the counter is reset to zero after this
9356** interface call returns.
9357**
9358** See also: [sqlite3_status()] and [sqlite3_db_status()].
9359*/
9360SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
9361
9362/*
9363** CAPI3REF: Status Parameters for prepared statements
9364** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
9365**
9366** These preprocessor macros define integer codes that name counter
9367** values associated with the [sqlite3_stmt_status()] interface.
9368** The meanings of the various counters are as follows:
9369**
9370** <dl>
9371** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
9372** <dd>^This is the number of times that SQLite has stepped forward in
9373** a table as part of a full table scan. Large numbers for this counter
9374** may indicate opportunities for performance improvement through
9375** careful use of indices.</dd>
9376**
9377** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
9378** <dd>^This is the number of sort operations that have occurred.
9379** A non-zero value in this counter may indicate an opportunity to
9380** improve performance through careful use of indices.</dd>
9381**
9382** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
9383** <dd>^This is the number of rows inserted into transient indices that
9384** were created automatically in order to help joins run faster.
9385** A non-zero value in this counter may indicate an opportunity to
9386** improve performance by adding permanent indices that do not
9387** need to be reinitialized each time the statement is run.</dd>
9388**
9389** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
9390** <dd>^This is the number of virtual machine operations executed
9391** by the prepared statement if that number is less than or equal
9392** to 2147483647. The number of virtual machine operations can be
9393** used as a proxy for the total work done by the prepared statement.
9394** If the number of virtual machine operations exceeds 2147483647
9395** then the value returned by this statement status code is undefined.</dd>
9396**
9397** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
9398** <dd>^This is the number of times that the prepare statement has been
9399** automatically regenerated due to schema changes or changes to
9400** [bound parameters] that might affect the query plan.</dd>
9401**
9402** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
9403** <dd>^This is the number of times that the prepared statement has
9404** been run. A single "run" for the purposes of this counter is one
9405** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
9406** The counter is incremented on the first [sqlite3_step()] call of each
9407** cycle.</dd>
9408**
9409** [[SQLITE_STMTSTATUS_FILTER_MISS]]
9410** [[SQLITE_STMTSTATUS_FILTER HIT]]
9411** <dt>SQLITE_STMTSTATUS_FILTER_HIT<br>
9412** SQLITE_STMTSTATUS_FILTER_MISS</dt>
9413** <dd>^SQLITE_STMTSTATUS_FILTER_HIT is the number of times that a join
9414** step was bypassed because a Bloom filter returned not-found. The
9415** corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of
9416** times that the Bloom filter returned a find, and thus the join step
9417** had to be processed as normal.</dd>
9418**
9419** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
9420** <dd>^This is the approximate number of bytes of heap memory
9421** used to store the prepared statement. ^This value is not actually
9422** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
9423** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
9424** </dd>
9425** </dl>
9426*/
9427#define SQLITE_STMTSTATUS_FULLSCAN_STEP1 1
9428#define SQLITE_STMTSTATUS_SORT2 2
9429#define SQLITE_STMTSTATUS_AUTOINDEX3 3
9430#define SQLITE_STMTSTATUS_VM_STEP4 4
9431#define SQLITE_STMTSTATUS_REPREPARE5 5
9432#define SQLITE_STMTSTATUS_RUN6 6
9433#define SQLITE_STMTSTATUS_FILTER_MISS7 7
9434#define SQLITE_STMTSTATUS_FILTER_HIT8 8
9435#define SQLITE_STMTSTATUS_MEMUSED99 99
9436
9437/*
9438** CAPI3REF: Custom Page Cache Object
9439**
9440** The sqlite3_pcache type is opaque. It is implemented by
9441** the pluggable module. The SQLite core has no knowledge of
9442** its size or internal structure and never deals with the
9443** sqlite3_pcache object except by holding and passing pointers
9444** to the object.
9445**
9446** See [sqlite3_pcache_methods2] for additional information.
9447*/
9448typedef struct sqlite3_pcache sqlite3_pcache;
9449
9450/*
9451** CAPI3REF: Custom Page Cache Object
9452**
9453** The sqlite3_pcache_page object represents a single page in the
9454** page cache. The page cache will allocate instances of this
9455** object. Various methods of the page cache use pointers to instances
9456** of this object as parameters or as their return value.
9457**
9458** See [sqlite3_pcache_methods2] for additional information.
9459*/
9460typedef struct sqlite3_pcache_page sqlite3_pcache_page;
9461struct sqlite3_pcache_page {
9462 void *pBuf; /* The content of the page */
9463 void *pExtra; /* Extra information associated with the page */
9464};
9465
9466/*
9467** CAPI3REF: Application Defined Page Cache.
9468** KEYWORDS: {page cache}
9469**
9470** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
9471** register an alternative page cache implementation by passing in an
9472** instance of the sqlite3_pcache_methods2 structure.)^
9473** In many applications, most of the heap memory allocated by
9474** SQLite is used for the page cache.
9475** By implementing a
9476** custom page cache using this API, an application can better control
9477** the amount of memory consumed by SQLite, the way in which
9478** that memory is allocated and released, and the policies used to
9479** determine exactly which parts of a database file are cached and for
9480** how long.
9481**
9482** The alternative page cache mechanism is an
9483** extreme measure that is only needed by the most demanding applications.
9484** The built-in page cache is recommended for most uses.
9485**
9486** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
9487** internal buffer by SQLite within the call to [sqlite3_config]. Hence
9488** the application may discard the parameter after the call to
9489** [sqlite3_config()] returns.)^
9490**
9491** [[the xInit() page cache method]]
9492** ^(The xInit() method is called once for each effective
9493** call to [sqlite3_initialize()])^
9494** (usually only once during the lifetime of the process). ^(The xInit()
9495** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
9496** The intent of the xInit() method is to set up global data structures
9497** required by the custom page cache implementation.
9498** ^(If the xInit() method is NULL, then the
9499** built-in default page cache is used instead of the application defined
9500** page cache.)^
9501**
9502** [[the xShutdown() page cache method]]
9503** ^The xShutdown() method is called by [sqlite3_shutdown()].
9504** It can be used to clean up
9505** any outstanding resources before process shutdown, if required.
9506** ^The xShutdown() method may be NULL.
9507**
9508** ^SQLite automatically serializes calls to the xInit method,
9509** so the xInit method need not be threadsafe. ^The
9510** xShutdown method is only called from [sqlite3_shutdown()] so it does
9511** not need to be threadsafe either. All other methods must be threadsafe
9512** in multithreaded applications.
9513**
9514** ^SQLite will never invoke xInit() more than once without an intervening
9515** call to xShutdown().
9516**
9517** [[the xCreate() page cache methods]]
9518** ^SQLite invokes the xCreate() method to construct a new cache instance.
9519** SQLite will typically create one cache instance for each open database file,
9520** though this is not guaranteed. ^The
9521** first parameter, szPage, is the size in bytes of the pages that must
9522** be allocated by the cache. ^szPage will always be a power of two. ^The
9523** second parameter szExtra is a number of bytes of extra storage
9524** associated with each page cache entry. ^The szExtra parameter will be
9525** a number less than 250. SQLite will use the
9526** extra szExtra bytes on each page to store metadata about the underlying
9527** database page on disk. The value passed into szExtra depends
9528** on the SQLite version, the target platform, and how SQLite was compiled.
9529** ^The third argument to xCreate(), bPurgeable, is true if the cache being
9530** created will be used to cache database pages of a file stored on disk, or
9531** false if it is used for an in-memory database. The cache implementation
9532** does not have to do anything special based upon the value of bPurgeable;
9533** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
9534** never invoke xUnpin() except to deliberately delete a page.
9535** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
9536** false will always have the "discard" flag set to true.
9537** ^Hence, a cache created with bPurgeable set to false will
9538** never contain any unpinned pages.
9539**
9540** [[the xCachesize() page cache method]]
9541** ^(The xCachesize() method may be called at any time by SQLite to set the
9542** suggested maximum cache-size (number of pages stored) for the cache
9543** instance passed as the first argument. This is the value configured using
9544** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
9545** parameter, the implementation is not required to do anything with this
9546** value; it is advisory only.
9547**
9548** [[the xPagecount() page cache methods]]
9549** The xPagecount() method must return the number of pages currently
9550** stored in the cache, both pinned and unpinned.
9551**
9552** [[the xFetch() page cache methods]]
9553** The xFetch() method locates a page in the cache and returns a pointer to
9554** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
9555** The pBuf element of the returned sqlite3_pcache_page object will be a
9556** pointer to a buffer of szPage bytes used to store the content of a
9557** single database page. The pExtra element of sqlite3_pcache_page will be
9558** a pointer to the szExtra bytes of extra storage that SQLite has requested
9559** for each entry in the page cache.
9560**
9561** The page to be fetched is determined by the key. ^The minimum key value
9562** is 1. After it has been retrieved using xFetch, the page is considered
9563** to be "pinned".
9564**
9565** If the requested page is already in the page cache, then the page cache
9566** implementation must return a pointer to the page buffer with its content
9567** intact. If the requested page is not already in the cache, then the
9568** cache implementation should use the value of the createFlag
9569** parameter to help it determine what action to take:
9570**
9571** <table border=1 width=85% align=center>
9572** <tr><th> createFlag <th> Behavior when page is not already in cache
9573** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
9574** <tr><td> 1 <td> Allocate a new page if it is easy and convenient to do so.
9575** Otherwise return NULL.
9576** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
9577** NULL if allocating a new page is effectively impossible.
9578** </table>
9579**
9580** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
9581** will only use a createFlag of 2 after a prior call with a createFlag of 1
9582** failed.)^ In between the xFetch() calls, SQLite may
9583** attempt to unpin one or more cache pages by spilling the content of
9584** pinned pages to disk and synching the operating system disk cache.
9585**
9586** [[the xUnpin() page cache method]]
9587** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
9588** as its second argument. If the third parameter, discard, is non-zero,
9589** then the page must be evicted from the cache.
9590** ^If the discard parameter is
9591** zero, then the page may be discarded or retained at the discretion of the
9592** page cache implementation. ^The page cache implementation
9593** may choose to evict unpinned pages at any time.
9594**
9595** The cache must not perform any reference counting. A single
9596** call to xUnpin() unpins the page regardless of the number of prior calls
9597** to xFetch().
9598**
9599** [[the xRekey() page cache methods]]
9600** The xRekey() method is used to change the key value associated with the
9601** page passed as the second argument. If the cache
9602** previously contains an entry associated with newKey, it must be
9603** discarded. ^Any prior cache entry associated with newKey is guaranteed not
9604** to be pinned.
9605**
9606** When SQLite calls the xTruncate() method, the cache must discard all
9607** existing cache entries with page numbers (keys) greater than or equal
9608** to the value of the iLimit parameter passed to xTruncate(). If any
9609** of these pages are pinned, they become implicitly unpinned, meaning that
9610** they can be safely discarded.
9611**
9612** [[the xDestroy() page cache method]]
9613** ^The xDestroy() method is used to delete a cache allocated by xCreate().
9614** All resources associated with the specified cache should be freed. ^After
9615** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
9616** handle invalid, and will not use it with any other sqlite3_pcache_methods2
9617** functions.
9618**
9619** [[the xShrink() page cache method]]
9620** ^SQLite invokes the xShrink() method when it wants the page cache to
9621** free up as much of heap memory as possible. The page cache implementation
9622** is not obligated to free any memory, but well-behaved implementations should
9623** do their best.
9624*/
9625typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
9626struct sqlite3_pcache_methods2 {
9627 int iVersion;
9628 void *pArg;
9629 int (*xInit)(void*);
9630 void (*xShutdown)(void*);
9631 sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
9632 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
9633 int (*xPagecount)(sqlite3_pcache*);
9634 sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
9635 void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
9636 void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
9637 unsigned oldKey, unsigned newKey);
9638 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
9639 void (*xDestroy)(sqlite3_pcache*);
9640 void (*xShrink)(sqlite3_pcache*);
9641};
9642
9643/*
9644** This is the obsolete pcache_methods object that has now been replaced
9645** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
9646** retained in the header file for backwards compatibility only.
9647*/
9648typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
9649struct sqlite3_pcache_methods {
9650 void *pArg;
9651 int (*xInit)(void*);
9652 void (*xShutdown)(void*);
9653 sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
9654 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
9655 int (*xPagecount)(sqlite3_pcache*);
9656 void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
9657 void (*xUnpin)(sqlite3_pcache*, void*, int discard);
9658 void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
9659 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
9660 void (*xDestroy)(sqlite3_pcache*);
9661};
9662
9663
9664/*
9665** CAPI3REF: Online Backup Object
9666**
9667** The sqlite3_backup object records state information about an ongoing
9668** online backup operation. ^The sqlite3_backup object is created by
9669** a call to [sqlite3_backup_init()] and is destroyed by a call to
9670** [sqlite3_backup_finish()].
9671**
9672** See Also: [Using the SQLite Online Backup API]
9673*/
9674typedef struct sqlite3_backup sqlite3_backup;
9675
9676/*
9677** CAPI3REF: Online Backup API.
9678**
9679** The backup API copies the content of one database into another.
9680** It is useful either for creating backups of databases or
9681** for copying in-memory databases to or from persistent files.
9682**
9683** See Also: [Using the SQLite Online Backup API]
9684**
9685** ^SQLite holds a write transaction open on the destination database file
9686** for the duration of the backup operation.
9687** ^The source database is read-locked only while it is being read;
9688** it is not locked continuously for the entire backup operation.
9689** ^Thus, the backup may be performed on a live source database without
9690** preventing other database connections from
9691** reading or writing to the source database while the backup is underway.
9692**
9693** ^(To perform a backup operation:
9694** <ol>
9695** <li><b>sqlite3_backup_init()</b> is called once to initialize the
9696** backup,
9697** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
9698** the data between the two databases, and finally
9699** <li><b>sqlite3_backup_finish()</b> is called to release all resources
9700** associated with the backup operation.
9701** </ol>)^
9702** There should be exactly one call to sqlite3_backup_finish() for each
9703** successful call to sqlite3_backup_init().
9704**
9705** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
9706**
9707** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
9708** [database connection] associated with the destination database
9709** and the database name, respectively.
9710** ^The database name is "main" for the main database, "temp" for the
9711** temporary database, or the name specified after the AS keyword in
9712** an [ATTACH] statement for an attached database.
9713** ^The S and M arguments passed to
9714** sqlite3_backup_init(D,N,S,M) identify the [database connection]
9715** and database name of the source database, respectively.
9716** ^The source and destination [database connections] (parameters S and D)
9717** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
9718** an error.
9719**
9720** ^A call to sqlite3_backup_init() will fail, returning NULL, if
9721** there is already a read or read-write transaction open on the
9722** destination database.
9723**
9724** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
9725** returned and an error code and error message are stored in the
9726** destination [database connection] D.
9727** ^The error code and message for the failed call to sqlite3_backup_init()
9728** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
9729** [sqlite3_errmsg16()] functions.
9730** ^A successful call to sqlite3_backup_init() returns a pointer to an
9731** [sqlite3_backup] object.
9732** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
9733** sqlite3_backup_finish() functions to perform the specified backup
9734** operation.
9735**
9736** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
9737**
9738** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
9739** the source and destination databases specified by [sqlite3_backup] object B.
9740** ^If N is negative, all remaining source pages are copied.
9741** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
9742** are still more pages to be copied, then the function returns [SQLITE_OK].
9743** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
9744** from source to destination, then it returns [SQLITE_DONE].
9745** ^If an error occurs while running sqlite3_backup_step(B,N),
9746** then an [error code] is returned. ^As well as [SQLITE_OK] and
9747** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
9748** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
9749** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
9750**
9751** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
9752** <ol>
9753** <li> the destination database was opened read-only, or
9754** <li> the destination database is using write-ahead-log journaling
9755** and the destination and source page sizes differ, or
9756** <li> the destination database is an in-memory database and the
9757** destination and source page sizes differ.
9758** </ol>)^
9759**
9760** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
9761** the [sqlite3_busy_handler | busy-handler function]
9762** is invoked (if one is specified). ^If the
9763** busy-handler returns non-zero before the lock is available, then
9764** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
9765** sqlite3_backup_step() can be retried later. ^If the source
9766** [database connection]
9767** is being used to write to the source database when sqlite3_backup_step()
9768** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
9769** case the call to sqlite3_backup_step() can be retried later on. ^(If
9770** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
9771** [SQLITE_READONLY] is returned, then
9772** there is no point in retrying the call to sqlite3_backup_step(). These
9773** errors are considered fatal.)^ The application must accept
9774** that the backup operation has failed and pass the backup operation handle
9775** to the sqlite3_backup_finish() to release associated resources.
9776**
9777** ^The first call to sqlite3_backup_step() obtains an exclusive lock
9778** on the destination file. ^The exclusive lock is not released until either
9779** sqlite3_backup_finish() is called or the backup operation is complete
9780** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
9781** sqlite3_backup_step() obtains a [shared lock] on the source database that
9782** lasts for the duration of the sqlite3_backup_step() call.
9783** ^Because the source database is not locked between calls to
9784** sqlite3_backup_step(), the source database may be modified mid-way
9785** through the backup process. ^If the source database is modified by an
9786** external process or via a database connection other than the one being
9787** used by the backup operation, then the backup will be automatically
9788** restarted by the next call to sqlite3_backup_step(). ^If the source
9789** database is modified by using the same database connection as is used
9790** by the backup operation, then the backup database is automatically
9791** updated at the same time.
9792**
9793** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
9794**
9795** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
9796** application wishes to abandon the backup operation, the application
9797** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
9798** ^The sqlite3_backup_finish() interfaces releases all
9799** resources associated with the [sqlite3_backup] object.
9800** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
9801** active write-transaction on the destination database is rolled back.
9802** The [sqlite3_backup] object is invalid
9803** and may not be used following a call to sqlite3_backup_finish().
9804**
9805** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
9806** sqlite3_backup_step() errors occurred, regardless of whether or not
9807** sqlite3_backup_step() completed.
9808** ^If an out-of-memory condition or IO error occurred during any prior
9809** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
9810** sqlite3_backup_finish() returns the corresponding [error code].
9811**
9812** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
9813** is not a permanent error and does not affect the return value of
9814** sqlite3_backup_finish().
9815**
9816** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
9817** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
9818**
9819** ^The sqlite3_backup_remaining() routine returns the number of pages still
9820** to be backed up at the conclusion of the most recent sqlite3_backup_step().
9821** ^The sqlite3_backup_pagecount() routine returns the total number of pages
9822** in the source database at the conclusion of the most recent
9823** sqlite3_backup_step().
9824** ^(The values returned by these functions are only updated by
9825** sqlite3_backup_step(). If the source database is modified in a way that
9826** changes the size of the source database or the number of pages remaining,
9827** those changes are not reflected in the output of sqlite3_backup_pagecount()
9828** and sqlite3_backup_remaining() until after the next
9829** sqlite3_backup_step().)^
9830**
9831** <b>Concurrent Usage of Database Handles</b>
9832**
9833** ^The source [database connection] may be used by the application for other
9834** purposes while a backup operation is underway or being initialized.
9835** ^If SQLite is compiled and configured to support threadsafe database
9836** connections, then the source database connection may be used concurrently
9837** from within other threads.
9838**
9839** However, the application must guarantee that the destination
9840** [database connection] is not passed to any other API (by any thread) after
9841** sqlite3_backup_init() is called and before the corresponding call to
9842** sqlite3_backup_finish(). SQLite does not currently check to see
9843** if the application incorrectly accesses the destination [database connection]
9844** and so no error code is reported, but the operations may malfunction
9845** nevertheless. Use of the destination database connection while a
9846** backup is in progress might also cause a mutex deadlock.
9847**
9848** If running in [shared cache mode], the application must
9849** guarantee that the shared cache used by the destination database
9850** is not accessed while the backup is running. In practice this means
9851** that the application must guarantee that the disk file being
9852** backed up to is not accessed by any connection within the process,
9853** not just the specific connection that was passed to sqlite3_backup_init().
9854**
9855** The [sqlite3_backup] object itself is partially threadsafe. Multiple
9856** threads may safely make multiple concurrent calls to sqlite3_backup_step().
9857** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
9858** APIs are not strictly speaking threadsafe. If they are invoked at the
9859** same time as another thread is invoking sqlite3_backup_step() it is
9860** possible that they return invalid values.
9861**
9862** <b>Alternatives To Using The Backup API</b>
9863**
9864** Other techniques for safely creating a consistent backup of an SQLite
9865** database include:
9866**
9867** <ul>
9868** <li> The [VACUUM INTO] command.
9869** <li> The [sqlite3_rsync] utility program.
9870** </ul>
9871*/
9872SQLITE_API sqlite3_backup *sqlite3_backup_init(
9873 sqlite3 *pDest, /* Destination database handle */
9874 const char *zDestName, /* Destination database name */
9875 sqlite3 *pSource, /* Source database handle */
9876 const char *zSourceName /* Source database name */
9877);
9878SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
9879SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
9880SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
9881SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
9882
9883/*
9884** CAPI3REF: Unlock Notification
9885** METHOD: sqlite3
9886**
9887** ^When running in shared-cache mode, a database operation may fail with
9888** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
9889** individual tables within the shared-cache cannot be obtained. See
9890** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
9891** ^This API may be used to register a callback that SQLite will invoke
9892** when the connection currently holding the required lock relinquishes it.
9893** ^This API is only available if the library was compiled with the
9894** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
9895**
9896** See Also: [Using the SQLite Unlock Notification Feature].
9897**
9898** ^Shared-cache locks are released when a database connection concludes
9899** its current transaction, either by committing it or rolling it back.
9900**
9901** ^When a connection (known as the blocked connection) fails to obtain a
9902** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
9903** identity of the database connection (the blocking connection) that
9904** has locked the required resource is stored internally. ^After an
9905** application receives an SQLITE_LOCKED error, it may call the
9906** sqlite3_unlock_notify() method with the blocked connection handle as
9907** the first argument to register for a callback that will be invoked
9908** when the blocking connection's current transaction is concluded. ^The
9909** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
9910** call that concludes the blocking connection's transaction.
9911**
9912** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
9913** there is a chance that the blocking connection will have already
9914** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
9915** If this happens, then the specified callback is invoked immediately,
9916** from within the call to sqlite3_unlock_notify().)^
9917**
9918** ^If the blocked connection is attempting to obtain a write-lock on a
9919** shared-cache table, and more than one other connection currently holds
9920** a read-lock on the same table, then SQLite arbitrarily selects one of
9921** the other connections to use as the blocking connection.
9922**
9923** ^(There may be at most one unlock-notify callback registered by a
9924** blocked connection. If sqlite3_unlock_notify() is called when the
9925** blocked connection already has a registered unlock-notify callback,
9926** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
9927** called with a NULL pointer as its second argument, then any existing
9928** unlock-notify callback is canceled. ^The blocked connection's
9929** unlock-notify callback may also be canceled by closing the blocked
9930** connection using [sqlite3_close()].
9931**
9932** The unlock-notify callback is not reentrant. If an application invokes
9933** any sqlite3_xxx API functions from within an unlock-notify callback, a
9934** crash or deadlock may be the result.
9935**
9936** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
9937** returns SQLITE_OK.
9938**
9939** <b>Callback Invocation Details</b>
9940**
9941** When an unlock-notify callback is registered, the application provides a
9942** single void* pointer that is passed to the callback when it is invoked.
9943** However, the signature of the callback function allows SQLite to pass
9944** it an array of void* context pointers. The first argument passed to
9945** an unlock-notify callback is a pointer to an array of void* pointers,
9946** and the second is the number of entries in the array.
9947**
9948** When a blocking connection's transaction is concluded, there may be
9949** more than one blocked connection that has registered for an unlock-notify
9950** callback. ^If two or more such blocked connections have specified the
9951** same callback function, then instead of invoking the callback function
9952** multiple times, it is invoked once with the set of void* context pointers
9953** specified by the blocked connections bundled together into an array.
9954** This gives the application an opportunity to prioritize any actions
9955** related to the set of unblocked database connections.
9956**
9957** <b>Deadlock Detection</b>
9958**
9959** Assuming that after registering for an unlock-notify callback a
9960** database waits for the callback to be issued before taking any further
9961** action (a reasonable assumption), then using this API may cause the
9962** application to deadlock. For example, if connection X is waiting for
9963** connection Y's transaction to be concluded, and similarly connection
9964** Y is waiting on connection X's transaction, then neither connection
9965** will proceed and the system may remain deadlocked indefinitely.
9966**
9967** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
9968** detection. ^If a given call to sqlite3_unlock_notify() would put the
9969** system in a deadlocked state, then SQLITE_LOCKED is returned and no
9970** unlock-notify callback is registered. The system is said to be in
9971** a deadlocked state if connection A has registered for an unlock-notify
9972** callback on the conclusion of connection B's transaction, and connection
9973** B has itself registered for an unlock-notify callback when connection
9974** A's transaction is concluded. ^Indirect deadlock is also detected, so
9975** the system is also considered to be deadlocked if connection B has
9976** registered for an unlock-notify callback on the conclusion of connection
9977** C's transaction, where connection C is waiting on connection A. ^Any
9978** number of levels of indirection are allowed.
9979**
9980** <b>The "DROP TABLE" Exception</b>
9981**
9982** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
9983** always appropriate to call sqlite3_unlock_notify(). There is however,
9984** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
9985** SQLite checks if there are any currently executing SELECT statements
9986** that belong to the same connection. If there are, SQLITE_LOCKED is
9987** returned. In this case there is no "blocking connection", so invoking
9988** sqlite3_unlock_notify() results in the unlock-notify callback being
9989** invoked immediately. If the application then re-attempts the "DROP TABLE"
9990** or "DROP INDEX" query, an infinite loop might be the result.
9991**
9992** One way around this problem is to check the extended error code returned
9993** by an sqlite3_step() call. ^(If there is a blocking connection, then the
9994** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
9995** the special "DROP TABLE/INDEX" case, the extended error code is just
9996** SQLITE_LOCKED.)^
9997*/
9998SQLITE_API int sqlite3_unlock_notify(
9999 sqlite3 *pBlocked, /* Waiting connection */
10000 void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
10001 void *pNotifyArg /* Argument to pass to xNotify */
10002);
10003
10004
10005/*
10006** CAPI3REF: String Comparison
10007**
10008** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
10009** and extensions to compare the contents of two buffers containing UTF-8
10010** strings in a case-independent fashion, using the same definition of "case
10011** independence" that SQLite uses internally when comparing identifiers.
10012*/
10013SQLITE_API int sqlite3_stricmp(const char *, const char *);
10014SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
10015
10016/*
10017** CAPI3REF: String Globbing
10018*
10019** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
10020** string X matches the [GLOB] pattern P.
10021** ^The definition of [GLOB] pattern matching used in
10022** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
10023** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
10024** is case sensitive.
10025**
10026** Note that this routine returns zero on a match and non-zero if the strings
10027** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
10028**
10029** See also: [sqlite3_strlike()].
10030*/
10031SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
10032
10033/*
10034** CAPI3REF: String LIKE Matching
10035*
10036** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
10037** string X matches the [LIKE] pattern P with escape character E.
10038** ^The definition of [LIKE] pattern matching used in
10039** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
10040** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
10041** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
10042** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
10043** insensitive - equivalent upper and lower case ASCII characters match
10044** one another.
10045**
10046** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
10047** only ASCII characters are case folded.
10048**
10049** Note that this routine returns zero on a match and non-zero if the strings
10050** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
10051**
10052** See also: [sqlite3_strglob()].
10053*/
10054SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
10055
10056/*
10057** CAPI3REF: Error Logging Interface
10058**
10059** ^The [sqlite3_log()] interface writes a message into the [error log]
10060** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
10061** ^If logging is enabled, the zFormat string and subsequent arguments are
10062** used with [sqlite3_snprintf()] to generate the final output string.
10063**
10064** The sqlite3_log() interface is intended for use by extensions such as
10065** virtual tables, collating functions, and SQL functions. While there is
10066** nothing to prevent an application from calling sqlite3_log(), doing so
10067** is considered bad form.
10068**
10069** The zFormat string must not be NULL.
10070**
10071** To avoid deadlocks and other threading problems, the sqlite3_log() routine
10072** will not use dynamically allocated memory. The log message is stored in
10073** a fixed-length buffer on the stack. If the log message is longer than
10074** a few hundred characters, it will be truncated to the length of the
10075** buffer.
10076*/
10077SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
10078
10079/*
10080** CAPI3REF: Write-Ahead Log Commit Hook
10081** METHOD: sqlite3
10082**
10083** ^The [sqlite3_wal_hook()] function is used to register a callback that
10084** is invoked each time data is committed to a database in wal mode.
10085**
10086** ^(The callback is invoked by SQLite after the commit has taken place and
10087** the associated write-lock on the database released)^, so the implementation
10088** may read, write or [checkpoint] the database as required.
10089**
10090** ^The first parameter passed to the callback function when it is invoked
10091** is a copy of the third parameter passed to sqlite3_wal_hook() when
10092** registering the callback. ^The second is a copy of the database handle.
10093** ^The third parameter is the name of the database that was written to -
10094** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
10095** is the number of pages currently in the write-ahead log file,
10096** including those that were just committed.
10097**
10098** The callback function should normally return [SQLITE_OK]. ^If an error
10099** code is returned, that error will propagate back up through the
10100** SQLite code base to cause the statement that provoked the callback
10101** to report an error, though the commit will have still occurred. If the
10102** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
10103** that does not correspond to any valid SQLite error code, the results
10104** are undefined.
10105**
10106** A single database handle may have at most a single write-ahead log callback
10107** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
10108** previously registered write-ahead log callback. ^The return value is
10109** a copy of the third parameter from the previous call, if any, or 0.
10110** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the
10111** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
10112** overwrite any prior [sqlite3_wal_hook()] settings.
10113*/
10114SQLITE_API void *sqlite3_wal_hook(
10115 sqlite3*,
10116 int(*)(void *,sqlite3*,const char*,int),
10117 void*
10118);
10119
10120/*
10121** CAPI3REF: Configure an auto-checkpoint
10122** METHOD: sqlite3
10123**
10124** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
10125** [sqlite3_wal_hook()] that causes any database on [database connection] D
10126** to automatically [checkpoint]
10127** after committing a transaction if there are N or
10128** more frames in the [write-ahead log] file. ^Passing zero or
10129** a negative value as the nFrame parameter disables automatic
10130** checkpoints entirely.
10131**
10132** ^The callback registered by this function replaces any existing callback
10133** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
10134** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
10135** configured by this function.
10136**
10137** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
10138** from SQL.
10139**
10140** ^Checkpoints initiated by this mechanism are
10141** [sqlite3_wal_checkpoint_v2|PASSIVE].
10142**
10143** ^Every new [database connection] defaults to having the auto-checkpoint
10144** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
10145** pages. The use of this interface
10146** is only necessary if the default setting is found to be suboptimal
10147** for a particular application.
10148*/
10149SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
10150
10151/*
10152** CAPI3REF: Checkpoint a database
10153** METHOD: sqlite3
10154**
10155** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
10156** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
10157**
10158** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
10159** [write-ahead log] for database X on [database connection] D to be
10160** transferred into the database file and for the write-ahead log to
10161** be reset. See the [checkpointing] documentation for addition
10162** information.
10163**
10164** This interface used to be the only way to cause a checkpoint to
10165** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
10166** interface was added. This interface is retained for backwards
10167** compatibility and as a convenience for applications that need to manually
10168** start a callback but which do not need the full power (and corresponding
10169** complication) of [sqlite3_wal_checkpoint_v2()].
10170*/
10171SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
10172
10173/*
10174** CAPI3REF: Checkpoint a database
10175** METHOD: sqlite3
10176**
10177** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
10178** operation on database X of [database connection] D in mode M. Status
10179** information is written back into integers pointed to by L and C.)^
10180** ^(The M parameter must be a valid [checkpoint mode]:)^
10181**
10182** <dl>
10183** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
10184** ^Checkpoint as many frames as possible without waiting for any database
10185** readers or writers to finish, then sync the database file if all frames
10186** in the log were checkpointed. ^The [busy-handler callback]
10187** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
10188** ^On the other hand, passive mode might leave the checkpoint unfinished
10189** if there are concurrent readers or writers.
10190**
10191** <dt>SQLITE_CHECKPOINT_FULL<dd>
10192** ^This mode blocks (it invokes the
10193** [sqlite3_busy_handler|busy-handler callback]) until there is no
10194** database writer and all readers are reading from the most recent database
10195** snapshot. ^It then checkpoints all frames in the log file and syncs the
10196** database file. ^This mode blocks new database writers while it is pending,
10197** but new database readers are allowed to continue unimpeded.
10198**
10199** <dt>SQLITE_CHECKPOINT_RESTART<dd>
10200** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
10201** that after checkpointing the log file it blocks (calls the
10202** [busy-handler callback])
10203** until all readers are reading from the database file only. ^This ensures
10204** that the next writer will restart the log file from the beginning.
10205** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
10206** database writer attempts while it is pending, but does not impede readers.
10207**
10208** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
10209** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
10210** addition that it also truncates the log file to zero bytes just prior
10211** to a successful return.
10212** </dl>
10213**
10214** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
10215** the log file or to -1 if the checkpoint could not run because
10216** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
10217** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
10218** log file (including any that were already checkpointed before the function
10219** was called) or to -1 if the checkpoint could not run due to an error or
10220** because the database is not in WAL mode. ^Note that upon successful
10221** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
10222** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
10223**
10224** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
10225** any other process is running a checkpoint operation at the same time, the
10226** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
10227** busy-handler configured, it will not be invoked in this case.
10228**
10229** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
10230** exclusive "writer" lock on the database file. ^If the writer lock cannot be
10231** obtained immediately, and a busy-handler is configured, it is invoked and
10232** the writer lock retried until either the busy-handler returns 0 or the lock
10233** is successfully obtained. ^The busy-handler is also invoked while waiting for
10234** database readers as described above. ^If the busy-handler returns 0 before
10235** the writer lock is obtained or while waiting for database readers, the
10236** checkpoint operation proceeds from that point in the same way as
10237** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
10238** without blocking any further. ^SQLITE_BUSY is returned in this case.
10239**
10240** ^If parameter zDb is NULL or points to a zero length string, then the
10241** specified operation is attempted on all WAL databases [attached] to
10242** [database connection] db. In this case the
10243** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
10244** an SQLITE_BUSY error is encountered when processing one or more of the
10245** attached WAL databases, the operation is still attempted on any remaining
10246** attached databases and SQLITE_BUSY is returned at the end. ^If any other
10247** error occurs while processing an attached database, processing is abandoned
10248** and the error code is returned to the caller immediately. ^If no error
10249** (SQLITE_BUSY or otherwise) is encountered while processing the attached
10250** databases, SQLITE_OK is returned.
10251**
10252** ^If database zDb is the name of an attached database that is not in WAL
10253** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
10254** zDb is not NULL (or a zero length string) and is not the name of any
10255** attached database, SQLITE_ERROR is returned to the caller.
10256**
10257** ^Unless it returns SQLITE_MISUSE,
10258** the sqlite3_wal_checkpoint_v2() interface
10259** sets the error information that is queried by
10260** [sqlite3_errcode()] and [sqlite3_errmsg()].
10261**
10262** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
10263** from SQL.
10264*/
10265SQLITE_API int sqlite3_wal_checkpoint_v2(
10266 sqlite3 *db, /* Database handle */
10267 const char *zDb, /* Name of attached database (or NULL) */
10268 int eMode, /* SQLITE_CHECKPOINT_* value */
10269 int *pnLog, /* OUT: Size of WAL log in frames */
10270 int *pnCkpt /* OUT: Total number of frames checkpointed */
10271);
10272
10273/*
10274** CAPI3REF: Checkpoint Mode Values
10275** KEYWORDS: {checkpoint mode}
10276**
10277** These constants define all valid values for the "checkpoint mode" passed
10278** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
10279** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
10280** meaning of each of these checkpoint modes.
10281*/
10282#define SQLITE_CHECKPOINT_PASSIVE0 0 /* Do as much as possible w/o blocking */
10283#define SQLITE_CHECKPOINT_FULL1 1 /* Wait for writers, then checkpoint */
10284#define SQLITE_CHECKPOINT_RESTART2 2 /* Like FULL but wait for readers */
10285#define SQLITE_CHECKPOINT_TRUNCATE3 3 /* Like RESTART but also truncate WAL */
10286
10287/*
10288** CAPI3REF: Virtual Table Interface Configuration
10289**
10290** This function may be called by either the [xConnect] or [xCreate] method
10291** of a [virtual table] implementation to configure
10292** various facets of the virtual table interface.
10293**
10294** If this interface is invoked outside the context of an xConnect or
10295** xCreate virtual table method then the behavior is undefined.
10296**
10297** In the call sqlite3_vtab_config(D,C,...) the D parameter is the
10298** [database connection] in which the virtual table is being created and
10299** which is passed in as the first argument to the [xConnect] or [xCreate]
10300** method that is invoking sqlite3_vtab_config(). The C parameter is one
10301** of the [virtual table configuration options]. The presence and meaning
10302** of parameters after C depend on which [virtual table configuration option]
10303** is used.
10304*/
10305SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
10306
10307/*
10308** CAPI3REF: Virtual Table Configuration Options
10309** KEYWORDS: {virtual table configuration options}
10310** KEYWORDS: {virtual table configuration option}
10311**
10312** These macros define the various options to the
10313** [sqlite3_vtab_config()] interface that [virtual table] implementations
10314** can use to customize and optimize their behavior.
10315**
10316** <dl>
10317** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
10318** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt>
10319** <dd>Calls of the form
10320** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
10321** where X is an integer. If X is zero, then the [virtual table] whose
10322** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
10323** support constraints. In this configuration (which is the default) if
10324** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
10325** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
10326** specified as part of the user's SQL statement, regardless of the actual
10327** ON CONFLICT mode specified.
10328**
10329** If X is non-zero, then the virtual table implementation guarantees
10330** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
10331** any modifications to internal or persistent data structures have been made.
10332** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
10333** is able to roll back a statement or database transaction, and abandon
10334** or continue processing the current SQL statement as appropriate.
10335** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
10336** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
10337** had been ABORT.
10338**
10339** Virtual table implementations that are required to handle OR REPLACE
10340** must do so within the [xUpdate] method. If a call to the
10341** [sqlite3_vtab_on_conflict()] function indicates that the current ON
10342** CONFLICT policy is REPLACE, the virtual table implementation should
10343** silently replace the appropriate rows within the xUpdate callback and
10344** return SQLITE_OK. Or, if this is not possible, it may return
10345** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
10346** constraint handling.
10347** </dd>
10348**
10349** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt>
10350** <dd>Calls of the form
10351** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the
10352** the [xConnect] or [xCreate] methods of a [virtual table] implementation
10353** prohibits that virtual table from being used from within triggers and
10354** views.
10355** </dd>
10356**
10357** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>
10358** <dd>Calls of the form
10359** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the
10360** [xConnect] or [xCreate] methods of a [virtual table] implementation
10361** identify that virtual table as being safe to use from within triggers
10362** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
10363** virtual table can do no serious harm even if it is controlled by a
10364** malicious hacker. Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
10365** flag unless absolutely necessary.
10366** </dd>
10367**
10368** [[SQLITE_VTAB_USES_ALL_SCHEMAS]]<dt>SQLITE_VTAB_USES_ALL_SCHEMAS</dt>
10369** <dd>Calls of the form
10370** [sqlite3_vtab_config](db,SQLITE_VTAB_USES_ALL_SCHEMA) from within the
10371** the [xConnect] or [xCreate] methods of a [virtual table] implementation
10372** instruct the query planner to begin at least a read transaction on
10373** all schemas ("main", "temp", and any ATTACH-ed databases) whenever the
10374** virtual table is used.
10375** </dd>
10376** </dl>
10377*/
10378#define SQLITE_VTAB_CONSTRAINT_SUPPORT1 1
10379#define SQLITE_VTAB_INNOCUOUS2 2
10380#define SQLITE_VTAB_DIRECTONLY3 3
10381#define SQLITE_VTAB_USES_ALL_SCHEMAS4 4
10382
10383/*
10384** CAPI3REF: Determine The Virtual Table Conflict Policy
10385**
10386** This function may only be called from within a call to the [xUpdate] method
10387** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
10388** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
10389** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
10390** of the SQL statement that triggered the call to the [xUpdate] method of the
10391** [virtual table].
10392*/
10393SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
10394
10395/*
10396** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
10397**
10398** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
10399** method of a [virtual table], then it might return true if the
10400** column is being fetched as part of an UPDATE operation during which the
10401** column value will not change. The virtual table implementation can use
10402** this hint as permission to substitute a return value that is less
10403** expensive to compute and that the corresponding
10404** [xUpdate] method understands as a "no-change" value.
10405**
10406** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
10407** the column is not changed by the UPDATE statement, then the xColumn
10408** method can optionally return without setting a result, without calling
10409** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
10410** In that case, [sqlite3_value_nochange(X)] will return true for the
10411** same column in the [xUpdate] method.
10412**
10413** The sqlite3_vtab_nochange() routine is an optimization. Virtual table
10414** implementations should continue to give a correct answer even if the
10415** sqlite3_vtab_nochange() interface were to always return false. In the
10416** current implementation, the sqlite3_vtab_nochange() interface does always
10417** returns false for the enhanced [UPDATE FROM] statement.
10418*/
10419SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
10420
10421/*
10422** CAPI3REF: Determine The Collation For a Virtual Table Constraint
10423** METHOD: sqlite3_index_info
10424**
10425** This function may only be called from within a call to the [xBestIndex]
10426** method of a [virtual table]. This function returns a pointer to a string
10427** that is the name of the appropriate collation sequence to use for text
10428** comparisons on the constraint identified by its arguments.
10429**
10430** The first argument must be the pointer to the [sqlite3_index_info] object
10431** that is the first parameter to the xBestIndex() method. The second argument
10432** must be an index into the aConstraint[] array belonging to the
10433** sqlite3_index_info structure passed to xBestIndex.
10434**
10435** Important:
10436** The first parameter must be the same pointer that is passed into the
10437** xBestMethod() method. The first parameter may not be a pointer to a
10438** different [sqlite3_index_info] object, even an exact copy.
10439**
10440** The return value is computed as follows:
10441**
10442** <ol>
10443** <li><p> If the constraint comes from a WHERE clause expression that contains
10444** a [COLLATE operator], then the name of the collation specified by
10445** that COLLATE operator is returned.
10446** <li><p> If there is no COLLATE operator, but the column that is the subject
10447** of the constraint specifies an alternative collating sequence via
10448** a [COLLATE clause] on the column definition within the CREATE TABLE
10449** statement that was passed into [sqlite3_declare_vtab()], then the
10450** name of that alternative collating sequence is returned.
10451** <li><p> Otherwise, "BINARY" is returned.
10452** </ol>
10453*/
10454SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
10455
10456/*
10457** CAPI3REF: Determine if a virtual table query is DISTINCT
10458** METHOD: sqlite3_index_info
10459**
10460** This API may only be used from within an [xBestIndex|xBestIndex method]
10461** of a [virtual table] implementation. The result of calling this
10462** interface from outside of xBestIndex() is undefined and probably harmful.
10463**
10464** ^The sqlite3_vtab_distinct() interface returns an integer between 0 and
10465** 3. The integer returned by sqlite3_vtab_distinct()
10466** gives the virtual table additional information about how the query
10467** planner wants the output to be ordered. As long as the virtual table
10468** can meet the ordering requirements of the query planner, it may set
10469** the "orderByConsumed" flag.
10470**
10471** <ol><li value="0"><p>
10472** ^If the sqlite3_vtab_distinct() interface returns 0, that means
10473** that the query planner needs the virtual table to return all rows in the
10474** sort order defined by the "nOrderBy" and "aOrderBy" fields of the
10475** [sqlite3_index_info] object. This is the default expectation. If the
10476** virtual table outputs all rows in sorted order, then it is always safe for
10477** the xBestIndex method to set the "orderByConsumed" flag, regardless of
10478** the return value from sqlite3_vtab_distinct().
10479** <li value="1"><p>
10480** ^(If the sqlite3_vtab_distinct() interface returns 1, that means
10481** that the query planner does not need the rows to be returned in sorted order
10482** as long as all rows with the same values in all columns identified by the
10483** "aOrderBy" field are adjacent.)^ This mode is used when the query planner
10484** is doing a GROUP BY.
10485** <li value="2"><p>
10486** ^(If the sqlite3_vtab_distinct() interface returns 2, that means
10487** that the query planner does not need the rows returned in any particular
10488** order, as long as rows with the same values in all columns identified
10489** by "aOrderBy" are adjacent.)^ ^(Furthermore, when two or more rows
10490** contain the same values for all columns identified by "colUsed", all but
10491** one such row may optionally be omitted from the result.)^
10492** The virtual table is not required to omit rows that are duplicates
10493** over the "colUsed" columns, but if the virtual table can do that without
10494** too much extra effort, it could potentially help the query to run faster.
10495** This mode is used for a DISTINCT query.
10496** <li value="3"><p>
10497** ^(If the sqlite3_vtab_distinct() interface returns 3, that means the
10498** virtual table must return rows in the order defined by "aOrderBy" as
10499** if the sqlite3_vtab_distinct() interface had returned 0. However if
10500** two or more rows in the result have the same values for all columns
10501** identified by "colUsed", then all but one such row may optionally be
10502** omitted.)^ Like when the return value is 2, the virtual table
10503** is not required to omit rows that are duplicates over the "colUsed"
10504** columns, but if the virtual table can do that without
10505** too much extra effort, it could potentially help the query to run faster.
10506** This mode is used for queries
10507** that have both DISTINCT and ORDER BY clauses.
10508** </ol>
10509**
10510** <p>The following table summarizes the conditions under which the
10511** virtual table is allowed to set the "orderByConsumed" flag based on
10512** the value returned by sqlite3_vtab_distinct(). This table is a
10513** restatement of the previous four paragraphs:
10514**
10515** <table border=1 cellspacing=0 cellpadding=10 width="90%">
10516** <tr>
10517** <td valign="top">sqlite3_vtab_distinct() return value
10518** <td valign="top">Rows are returned in aOrderBy order
10519** <td valign="top">Rows with the same value in all aOrderBy columns are adjacent
10520** <td valign="top">Duplicates over all colUsed columns may be omitted
10521** <tr><td>0<td>yes<td>yes<td>no
10522** <tr><td>1<td>no<td>yes<td>no
10523** <tr><td>2<td>no<td>yes<td>yes
10524** <tr><td>3<td>yes<td>yes<td>yes
10525** </table>
10526**
10527** ^For the purposes of comparing virtual table output values to see if the
10528** values are the same value for sorting purposes, two NULL values are considered
10529** to be the same. In other words, the comparison operator is "IS"
10530** (or "IS NOT DISTINCT FROM") and not "==".
10531**
10532** If a virtual table implementation is unable to meet the requirements
10533** specified above, then it must not set the "orderByConsumed" flag in the
10534** [sqlite3_index_info] object or an incorrect answer may result.
10535**
10536** ^A virtual table implementation is always free to return rows in any order
10537** it wants, as long as the "orderByConsumed" flag is not set. ^When the
10538** "orderByConsumed" flag is unset, the query planner will add extra
10539** [bytecode] to ensure that the final results returned by the SQL query are
10540** ordered correctly. The use of the "orderByConsumed" flag and the
10541** sqlite3_vtab_distinct() interface is merely an optimization. ^Careful
10542** use of the sqlite3_vtab_distinct() interface and the "orderByConsumed"
10543** flag might help queries against a virtual table to run faster. Being
10544** overly aggressive and setting the "orderByConsumed" flag when it is not
10545** valid to do so, on the other hand, might cause SQLite to return incorrect
10546** results.
10547*/
10548SQLITE_API int sqlite3_vtab_distinct(sqlite3_index_info*);
10549
10550/*
10551** CAPI3REF: Identify and handle IN constraints in xBestIndex
10552**
10553** This interface may only be used from within an
10554** [xBestIndex|xBestIndex() method] of a [virtual table] implementation.
10555** The result of invoking this interface from any other context is
10556** undefined and probably harmful.
10557**
10558** ^(A constraint on a virtual table of the form
10559** "[IN operator|column IN (...)]" is
10560** communicated to the xBestIndex method as a
10561** [SQLITE_INDEX_CONSTRAINT_EQ] constraint.)^ If xBestIndex wants to use
10562** this constraint, it must set the corresponding
10563** aConstraintUsage[].argvIndex to a positive integer. ^(Then, under
10564** the usual mode of handling IN operators, SQLite generates [bytecode]
10565** that invokes the [xFilter|xFilter() method] once for each value
10566** on the right-hand side of the IN operator.)^ Thus the virtual table
10567** only sees a single value from the right-hand side of the IN operator
10568** at a time.
10569**
10570** In some cases, however, it would be advantageous for the virtual
10571** table to see all values on the right-hand of the IN operator all at
10572** once. The sqlite3_vtab_in() interfaces facilitates this in two ways:
10573**
10574** <ol>
10575** <li><p>
10576** ^A call to sqlite3_vtab_in(P,N,-1) will return true (non-zero)
10577** if and only if the [sqlite3_index_info|P->aConstraint][N] constraint
10578** is an [IN operator] that can be processed all at once. ^In other words,
10579** sqlite3_vtab_in() with -1 in the third argument is a mechanism
10580** by which the virtual table can ask SQLite if all-at-once processing
10581** of the IN operator is even possible.
10582**
10583** <li><p>
10584** ^A call to sqlite3_vtab_in(P,N,F) with F==1 or F==0 indicates
10585** to SQLite that the virtual table does or does not want to process
10586** the IN operator all-at-once, respectively. ^Thus when the third
10587** parameter (F) is non-negative, this interface is the mechanism by
10588** which the virtual table tells SQLite how it wants to process the
10589** IN operator.
10590** </ol>
10591**
10592** ^The sqlite3_vtab_in(P,N,F) interface can be invoked multiple times
10593** within the same xBestIndex method call. ^For any given P,N pair,
10594** the return value from sqlite3_vtab_in(P,N,F) will always be the same
10595** within the same xBestIndex call. ^If the interface returns true
10596** (non-zero), that means that the constraint is an IN operator
10597** that can be processed all-at-once. ^If the constraint is not an IN
10598** operator or cannot be processed all-at-once, then the interface returns
10599** false.
10600**
10601** ^(All-at-once processing of the IN operator is selected if both of the
10602** following conditions are met:
10603**
10604** <ol>
10605** <li><p> The P->aConstraintUsage[N].argvIndex value is set to a positive
10606** integer. This is how the virtual table tells SQLite that it wants to
10607** use the N-th constraint.
10608**
10609** <li><p> The last call to sqlite3_vtab_in(P,N,F) for which F was
10610** non-negative had F>=1.
10611** </ol>)^
10612**
10613** ^If either or both of the conditions above are false, then SQLite uses
10614** the traditional one-at-a-time processing strategy for the IN constraint.
10615** ^If both conditions are true, then the argvIndex-th parameter to the
10616** xFilter method will be an [sqlite3_value] that appears to be NULL,
10617** but which can be passed to [sqlite3_vtab_in_first()] and
10618** [sqlite3_vtab_in_next()] to find all values on the right-hand side
10619** of the IN constraint.
10620*/
10621SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle);
10622
10623/*
10624** CAPI3REF: Find all elements on the right-hand side of an IN constraint.
10625**
10626** These interfaces are only useful from within the
10627** [xFilter|xFilter() method] of a [virtual table] implementation.
10628** The result of invoking these interfaces from any other context
10629** is undefined and probably harmful.
10630**
10631** The X parameter in a call to sqlite3_vtab_in_first(X,P) or
10632** sqlite3_vtab_in_next(X,P) should be one of the parameters to the
10633** xFilter method which invokes these routines, and specifically
10634** a parameter that was previously selected for all-at-once IN constraint
10635** processing using the [sqlite3_vtab_in()] interface in the
10636** [xBestIndex|xBestIndex method]. ^(If the X parameter is not
10637** an xFilter argument that was selected for all-at-once IN constraint
10638** processing, then these routines return [SQLITE_ERROR].)^
10639**
10640** ^(Use these routines to access all values on the right-hand side
10641** of the IN constraint using code like the following:
10642**
10643** <blockquote><pre>
10644** &nbsp; for(rc=sqlite3_vtab_in_first(pList, &pVal);
10645** &nbsp; rc==SQLITE_OK && pVal;
10646** &nbsp; rc=sqlite3_vtab_in_next(pList, &pVal)
10647** &nbsp; ){
10648** &nbsp; // do something with pVal
10649** &nbsp; }
10650** &nbsp; if( rc!=SQLITE_OK ){
10651** &nbsp; // an error has occurred
10652** &nbsp; }
10653** </pre></blockquote>)^
10654**
10655** ^On success, the sqlite3_vtab_in_first(X,P) and sqlite3_vtab_in_next(X,P)
10656** routines return SQLITE_OK and set *P to point to the first or next value
10657** on the RHS of the IN constraint. ^If there are no more values on the
10658** right hand side of the IN constraint, then *P is set to NULL and these
10659** routines return [SQLITE_DONE]. ^The return value might be
10660** some other value, such as SQLITE_NOMEM, in the event of a malfunction.
10661**
10662** The *ppOut values returned by these routines are only valid until the
10663** next call to either of these routines or until the end of the xFilter
10664** method from which these routines were called. If the virtual table
10665** implementation needs to retain the *ppOut values for longer, it must make
10666** copies. The *ppOut values are [protected sqlite3_value|protected].
10667*/
10668SQLITE_API int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut);
10669SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut);
10670
10671/*
10672** CAPI3REF: Constraint values in xBestIndex()
10673** METHOD: sqlite3_index_info
10674**
10675** This API may only be used from within the [xBestIndex|xBestIndex method]
10676** of a [virtual table] implementation. The result of calling this interface
10677** from outside of an xBestIndex method are undefined and probably harmful.
10678**
10679** ^When the sqlite3_vtab_rhs_value(P,J,V) interface is invoked from within
10680** the [xBestIndex] method of a [virtual table] implementation, with P being
10681** a copy of the [sqlite3_index_info] object pointer passed into xBestIndex and
10682** J being a 0-based index into P->aConstraint[], then this routine
10683** attempts to set *V to the value of the right-hand operand of
10684** that constraint if the right-hand operand is known. ^If the
10685** right-hand operand is not known, then *V is set to a NULL pointer.
10686** ^The sqlite3_vtab_rhs_value(P,J,V) interface returns SQLITE_OK if
10687** and only if *V is set to a value. ^The sqlite3_vtab_rhs_value(P,J,V)
10688** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th
10689** constraint is not available. ^The sqlite3_vtab_rhs_value() interface
10690** can return a result code other than SQLITE_OK or SQLITE_NOTFOUND if
10691** something goes wrong.
10692**
10693** The sqlite3_vtab_rhs_value() interface is usually only successful if
10694** the right-hand operand of a constraint is a literal value in the original
10695** SQL statement. If the right-hand operand is an expression or a reference
10696** to some other column or a [host parameter], then sqlite3_vtab_rhs_value()
10697** will probably return [SQLITE_NOTFOUND].
10698**
10699** ^(Some constraints, such as [SQLITE_INDEX_CONSTRAINT_ISNULL] and
10700** [SQLITE_INDEX_CONSTRAINT_ISNOTNULL], have no right-hand operand. For such
10701** constraints, sqlite3_vtab_rhs_value() always returns SQLITE_NOTFOUND.)^
10702**
10703** ^The [sqlite3_value] object returned in *V is a protected sqlite3_value
10704** and remains valid for the duration of the xBestIndex method call.
10705** ^When xBestIndex returns, the sqlite3_value object returned by
10706** sqlite3_vtab_rhs_value() is automatically deallocated.
10707**
10708** The "_rhs_" in the name of this routine is an abbreviation for
10709** "Right-Hand Side".
10710*/
10711SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **ppVal);
10712
10713/*
10714** CAPI3REF: Conflict resolution modes
10715** KEYWORDS: {conflict resolution mode}
10716**
10717** These constants are returned by [sqlite3_vtab_on_conflict()] to
10718** inform a [virtual table] implementation of the [ON CONFLICT] mode
10719** for the SQL statement being evaluated.
10720**
10721** Note that the [SQLITE_IGNORE] constant is also used as a potential
10722** return value from the [sqlite3_set_authorizer()] callback and that
10723** [SQLITE_ABORT] is also a [result code].
10724*/
10725#define SQLITE_ROLLBACK1 1
10726/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
10727#define SQLITE_FAIL3 3
10728/* #define SQLITE_ABORT 4 // Also an error code */
10729#define SQLITE_REPLACE5 5
10730
10731/*
10732** CAPI3REF: Prepared Statement Scan Status Opcodes
10733** KEYWORDS: {scanstatus options}
10734**
10735** The following constants can be used for the T parameter to the
10736** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
10737** different metric for sqlite3_stmt_scanstatus() to return.
10738**
10739** When the value returned to V is a string, space to hold that string is
10740** managed by the prepared statement S and will be automatically freed when
10741** S is finalized.
10742**
10743** Not all values are available for all query elements. When a value is
10744** not available, the output variable is set to -1 if the value is numeric,
10745** or to NULL if it is a string (SQLITE_SCANSTAT_NAME).
10746**
10747** <dl>
10748** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
10749** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be
10750** set to the total number of times that the X-th loop has run.</dd>
10751**
10752** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
10753** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be set
10754** to the total number of rows examined by all iterations of the X-th loop.</dd>
10755**
10756** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
10757** <dd>^The "double" variable pointed to by the V parameter will be set to the
10758** query planner's estimate for the average number of rows output from each
10759** iteration of the X-th loop. If the query planner's estimate was accurate,
10760** then this value will approximate the quotient NVISIT/NLOOP and the
10761** product of this value for all prior loops with the same SELECTID will
10762** be the NLOOP value for the current loop.</dd>
10763**
10764** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
10765** <dd>^The "const char *" variable pointed to by the V parameter will be set
10766** to a zero-terminated UTF-8 string containing the name of the index or table
10767** used for the X-th loop.</dd>
10768**
10769** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
10770** <dd>^The "const char *" variable pointed to by the V parameter will be set
10771** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
10772** description for the X-th loop.</dd>
10773**
10774** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECTID</dt>
10775** <dd>^The "int" variable pointed to by the V parameter will be set to the
10776** id for the X-th query plan element. The id value is unique within the
10777** statement. The select-id is the same value as is output in the first
10778** column of an [EXPLAIN QUERY PLAN] query.</dd>
10779**
10780** [[SQLITE_SCANSTAT_PARENTID]] <dt>SQLITE_SCANSTAT_PARENTID</dt>
10781** <dd>The "int" variable pointed to by the V parameter will be set to the
10782** id of the parent of the current query element, if applicable, or
10783** to zero if the query element has no parent. This is the same value as
10784** returned in the second column of an [EXPLAIN QUERY PLAN] query.</dd>
10785**
10786** [[SQLITE_SCANSTAT_NCYCLE]] <dt>SQLITE_SCANSTAT_NCYCLE</dt>
10787** <dd>The sqlite3_int64 output value is set to the number of cycles,
10788** according to the processor time-stamp counter, that elapsed while the
10789** query element was being processed. This value is not available for
10790** all query elements - if it is unavailable the output variable is
10791** set to -1.</dd>
10792** </dl>
10793*/
10794#define SQLITE_SCANSTAT_NLOOP0 0
10795#define SQLITE_SCANSTAT_NVISIT1 1
10796#define SQLITE_SCANSTAT_EST2 2
10797#define SQLITE_SCANSTAT_NAME3 3
10798#define SQLITE_SCANSTAT_EXPLAIN4 4
10799#define SQLITE_SCANSTAT_SELECTID5 5
10800#define SQLITE_SCANSTAT_PARENTID6 6
10801#define SQLITE_SCANSTAT_NCYCLE7 7
10802
10803/*
10804** CAPI3REF: Prepared Statement Scan Status
10805** METHOD: sqlite3_stmt
10806**
10807** These interfaces return information about the predicted and measured
10808** performance for pStmt. Advanced applications can use this
10809** interface to compare the predicted and the measured performance and
10810** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
10811**
10812** Since this interface is expected to be rarely used, it is only
10813** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
10814** compile-time option.
10815**
10816** The "iScanStatusOp" parameter determines which status information to return.
10817** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
10818** of this interface is undefined. ^The requested measurement is written into
10819** a variable pointed to by the "pOut" parameter.
10820**
10821** The "flags" parameter must be passed a mask of flags. At present only
10822** one flag is defined - SQLITE_SCANSTAT_COMPLEX. If SQLITE_SCANSTAT_COMPLEX
10823** is specified, then status information is available for all elements
10824** of a query plan that are reported by "EXPLAIN QUERY PLAN" output. If
10825** SQLITE_SCANSTAT_COMPLEX is not specified, then only query plan elements
10826** that correspond to query loops (the "SCAN..." and "SEARCH..." elements of
10827** the EXPLAIN QUERY PLAN output) are available. Invoking API
10828** sqlite3_stmt_scanstatus() is equivalent to calling
10829** sqlite3_stmt_scanstatus_v2() with a zeroed flags parameter.
10830**
10831** Parameter "idx" identifies the specific query element to retrieve statistics
10832** for. Query elements are numbered starting from zero. A value of -1 may
10833** retrieve statistics for the entire query. ^If idx is out of range
10834** - less than -1 or greater than or equal to the total number of query
10835** elements used to implement the statement - a non-zero value is returned and
10836** the variable that pOut points to is unchanged.
10837**
10838** See also: [sqlite3_stmt_scanstatus_reset()]
10839*/
10840SQLITE_API int sqlite3_stmt_scanstatus(
10841 sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
10842 int idx, /* Index of loop to report on */
10843 int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
10844 void *pOut /* Result written here */
10845);
10846SQLITE_API int sqlite3_stmt_scanstatus_v2(
10847 sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
10848 int idx, /* Index of loop to report on */
10849 int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
10850 int flags, /* Mask of flags defined below */
10851 void *pOut /* Result written here */
10852);
10853
10854/*
10855** CAPI3REF: Prepared Statement Scan Status
10856** KEYWORDS: {scan status flags}
10857*/
10858#define SQLITE_SCANSTAT_COMPLEX0x0001 0x0001
10859
10860/*
10861** CAPI3REF: Zero Scan-Status Counters
10862** METHOD: sqlite3_stmt
10863**
10864** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
10865**
10866** This API is only available if the library is built with pre-processor
10867** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
10868*/
10869SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
10870
10871/*
10872** CAPI3REF: Flush caches to disk mid-transaction
10873** METHOD: sqlite3
10874**
10875** ^If a write-transaction is open on [database connection] D when the
10876** [sqlite3_db_cacheflush(D)] interface is invoked, any dirty
10877** pages in the pager-cache that are not currently in use are written out
10878** to disk. A dirty page may be in use if a database cursor created by an
10879** active SQL statement is reading from it, or if it is page 1 of a database
10880** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
10881** interface flushes caches for all schemas - "main", "temp", and
10882** any [attached] databases.
10883**
10884** ^If this function needs to obtain extra database locks before dirty pages
10885** can be flushed to disk, it does so. ^If those locks cannot be obtained
10886** immediately and there is a busy-handler callback configured, it is invoked
10887** in the usual manner. ^If the required lock still cannot be obtained, then
10888** the database is skipped and an attempt made to flush any dirty pages
10889** belonging to the next (if any) database. ^If any databases are skipped
10890** because locks cannot be obtained, but no other error occurs, this
10891** function returns SQLITE_BUSY.
10892**
10893** ^If any other error occurs while flushing dirty pages to disk (for
10894** example an IO error or out-of-memory condition), then processing is
10895** abandoned and an SQLite [error code] is returned to the caller immediately.
10896**
10897** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
10898**
10899** ^This function does not set the database handle error code or message
10900** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
10901*/
10902SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
10903
10904/*
10905** CAPI3REF: The pre-update hook.
10906** METHOD: sqlite3
10907**
10908** ^These interfaces are only available if SQLite is compiled using the
10909** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
10910**
10911** ^The [sqlite3_preupdate_hook()] interface registers a callback function
10912** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
10913** on a database table.
10914** ^At most one preupdate hook may be registered at a time on a single
10915** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
10916** the previous setting.
10917** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
10918** with a NULL pointer as the second parameter.
10919** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
10920** the first parameter to callbacks.
10921**
10922** ^The preupdate hook only fires for changes to real database tables; the
10923** preupdate hook is not invoked for changes to [virtual tables] or to
10924** system tables like sqlite_sequence or sqlite_stat1.
10925**
10926** ^The second parameter to the preupdate callback is a pointer to
10927** the [database connection] that registered the preupdate hook.
10928** ^The third parameter to the preupdate callback is one of the constants
10929** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
10930** kind of update operation that is about to occur.
10931** ^(The fourth parameter to the preupdate callback is the name of the
10932** database within the database connection that is being modified. This
10933** will be "main" for the main database or "temp" for TEMP tables or
10934** the name given after the AS keyword in the [ATTACH] statement for attached
10935** databases.)^
10936** ^The fifth parameter to the preupdate callback is the name of the
10937** table that is being modified.
10938**
10939** For an UPDATE or DELETE operation on a [rowid table], the sixth
10940** parameter passed to the preupdate callback is the initial [rowid] of the
10941** row being modified or deleted. For an INSERT operation on a rowid table,
10942** or any operation on a WITHOUT ROWID table, the value of the sixth
10943** parameter is undefined. For an INSERT or UPDATE on a rowid table the
10944** seventh parameter is the final rowid value of the row being inserted
10945** or updated. The value of the seventh parameter passed to the callback
10946** function is not defined for operations on WITHOUT ROWID tables, or for
10947** DELETE operations on rowid tables.
10948**
10949** ^The sqlite3_preupdate_hook(D,C,P) function returns the P argument from
10950** the previous call on the same [database connection] D, or NULL for
10951** the first call on D.
10952**
10953** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
10954** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
10955** provide additional information about a preupdate event. These routines
10956** may only be called from within a preupdate callback. Invoking any of
10957** these routines from outside of a preupdate callback or with a
10958** [database connection] pointer that is different from the one supplied
10959** to the preupdate callback results in undefined and probably undesirable
10960** behavior.
10961**
10962** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
10963** in the row that is being inserted, updated, or deleted.
10964**
10965** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
10966** a [protected sqlite3_value] that contains the value of the Nth column of
10967** the table row before it is updated. The N parameter must be between 0
10968** and one less than the number of columns or the behavior will be
10969** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
10970** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
10971** behavior is undefined. The [sqlite3_value] that P points to
10972** will be destroyed when the preupdate callback returns.
10973**
10974** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
10975** a [protected sqlite3_value] that contains the value of the Nth column of
10976** the table row after it is updated. The N parameter must be between 0
10977** and one less than the number of columns or the behavior will be
10978** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
10979** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
10980** behavior is undefined. The [sqlite3_value] that P points to
10981** will be destroyed when the preupdate callback returns.
10982**
10983** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
10984** callback was invoked as a result of a direct insert, update, or delete
10985** operation; or 1 for inserts, updates, or deletes invoked by top-level
10986** triggers; or 2 for changes resulting from triggers called by top-level
10987** triggers; and so forth.
10988**
10989** When the [sqlite3_blob_write()] API is used to update a blob column,
10990** the pre-update hook is invoked with SQLITE_DELETE, because
10991** the new values are not yet available. In this case, when a
10992** callback made with op==SQLITE_DELETE is actually a write using the
10993** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns
10994** the index of the column being written. In other cases, where the
10995** pre-update hook is being invoked for some other reason, including a
10996** regular DELETE, sqlite3_preupdate_blobwrite() returns -1.
10997**
10998** See also: [sqlite3_update_hook()]
10999*/
11000#if defined(SQLITE_ENABLE_PREUPDATE_HOOK1)
11001SQLITE_API void *sqlite3_preupdate_hook(
11002 sqlite3 *db,
11003 void(*xPreUpdate)(
11004 void *pCtx, /* Copy of third arg to preupdate_hook() */
11005 sqlite3 *db, /* Database handle */
11006 int op, /* SQLITE_UPDATE, DELETE or INSERT */
11007 char const *zDb, /* Database name */
11008 char const *zName, /* Table name */
11009 sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
11010 sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
11011 ),
11012 void*
11013);
11014SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
11015SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
11016SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
11017SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
11018SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *);
11019#endif
11020
11021/*
11022** CAPI3REF: Low-level system error code
11023** METHOD: sqlite3
11024**
11025** ^Attempt to return the underlying operating system error code or error
11026** number that caused the most recent I/O error or failure to open a file.
11027** The return value is OS-dependent. For example, on unix systems, after
11028** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
11029** called to get back the underlying "errno" that caused the problem, such
11030** as ENOSPC, EAUTH, EISDIR, and so forth.
11031*/
11032SQLITE_API int sqlite3_system_errno(sqlite3*);
11033
11034/*
11035** CAPI3REF: Database Snapshot
11036** KEYWORDS: {snapshot} {sqlite3_snapshot}
11037**
11038** An instance of the snapshot object records the state of a [WAL mode]
11039** database for some specific point in history.
11040**
11041** In [WAL mode], multiple [database connections] that are open on the
11042** same database file can each be reading a different historical version
11043** of the database file. When a [database connection] begins a read
11044** transaction, that connection sees an unchanging copy of the database
11045** as it existed for the point in time when the transaction first started.
11046** Subsequent changes to the database from other connections are not seen
11047** by the reader until a new read transaction is started.
11048**
11049** The sqlite3_snapshot object records state information about an historical
11050** version of the database file so that it is possible to later open a new read
11051** transaction that sees that historical version of the database rather than
11052** the most recent version.
11053*/
11054typedef struct sqlite3_snapshot {
11055 unsigned char hidden[48];
11056} sqlite3_snapshot;
11057
11058/*
11059** CAPI3REF: Record A Database Snapshot
11060** CONSTRUCTOR: sqlite3_snapshot
11061**
11062** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
11063** new [sqlite3_snapshot] object that records the current state of
11064** schema S in database connection D. ^On success, the
11065** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
11066** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
11067** If there is not already a read-transaction open on schema S when
11068** this function is called, one is opened automatically.
11069**
11070** If a read-transaction is opened by this function, then it is guaranteed
11071** that the returned snapshot object may not be invalidated by a database
11072** writer or checkpointer until after the read-transaction is closed. This
11073** is not guaranteed if a read-transaction is already open when this
11074** function is called. In that case, any subsequent write or checkpoint
11075** operation on the database may invalidate the returned snapshot handle,
11076** even while the read-transaction remains open.
11077**
11078** The following must be true for this function to succeed. If any of
11079** the following statements are false when sqlite3_snapshot_get() is
11080** called, SQLITE_ERROR is returned. The final value of *P is undefined
11081** in this case.
11082**
11083** <ul>
11084** <li> The database handle must not be in [autocommit mode].
11085**
11086** <li> Schema S of [database connection] D must be a [WAL mode] database.
11087**
11088** <li> There must not be a write transaction open on schema S of database
11089** connection D.
11090**
11091** <li> One or more transactions must have been written to the current wal
11092** file since it was created on disk (by any connection). This means
11093** that a snapshot cannot be taken on a wal mode database with no wal
11094** file immediately after it is first opened. At least one transaction
11095** must be written to it first.
11096** </ul>
11097**
11098** This function may also return SQLITE_NOMEM. If it is called with the
11099** database handle in autocommit mode but fails for some other reason,
11100** whether or not a read transaction is opened on schema S is undefined.
11101**
11102** The [sqlite3_snapshot] object returned from a successful call to
11103** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
11104** to avoid a memory leak.
11105**
11106** The [sqlite3_snapshot_get()] interface is only available when the
11107** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
11108*/
11109SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
11110 sqlite3 *db,
11111 const char *zSchema,
11112 sqlite3_snapshot **ppSnapshot
11113);
11114
11115/*
11116** CAPI3REF: Start a read transaction on an historical snapshot
11117** METHOD: sqlite3_snapshot
11118**
11119** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read
11120** transaction or upgrades an existing one for schema S of
11121** [database connection] D such that the read transaction refers to
11122** historical [snapshot] P, rather than the most recent change to the
11123** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK
11124** on success or an appropriate [error code] if it fails.
11125**
11126** ^In order to succeed, the database connection must not be in
11127** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
11128** is already a read transaction open on schema S, then the database handle
11129** must have no active statements (SELECT statements that have been passed
11130** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).
11131** SQLITE_ERROR is returned if either of these conditions is violated, or
11132** if schema S does not exist, or if the snapshot object is invalid.
11133**
11134** ^A call to sqlite3_snapshot_open() will fail to open if the specified
11135** snapshot has been overwritten by a [checkpoint]. In this case
11136** SQLITE_ERROR_SNAPSHOT is returned.
11137**
11138** If there is already a read transaction open when this function is
11139** invoked, then the same read transaction remains open (on the same
11140** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
11141** is returned. If another error code - for example SQLITE_PROTOCOL or an
11142** SQLITE_IOERR error code - is returned, then the final state of the
11143** read transaction is undefined. If SQLITE_OK is returned, then the
11144** read transaction is now open on database snapshot P.
11145**
11146** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
11147** database connection D does not know that the database file for
11148** schema S is in [WAL mode]. A database connection might not know
11149** that the database file is in [WAL mode] if there has been no prior
11150** I/O on that database connection, or if the database entered [WAL mode]
11151** after the most recent I/O on the database connection.)^
11152** (Hint: Run "[PRAGMA application_id]" against a newly opened
11153** database connection in order to make it ready to use snapshots.)
11154**
11155** The [sqlite3_snapshot_open()] interface is only available when the
11156** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
11157*/
11158SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
11159 sqlite3 *db,
11160 const char *zSchema,
11161 sqlite3_snapshot *pSnapshot
11162);
11163
11164/*
11165** CAPI3REF: Destroy a snapshot
11166** DESTRUCTOR: sqlite3_snapshot
11167**
11168** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
11169** The application must eventually free every [sqlite3_snapshot] object
11170** using this routine to avoid a memory leak.
11171**
11172** The [sqlite3_snapshot_free()] interface is only available when the
11173** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
11174*/
11175SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
11176
11177/*
11178** CAPI3REF: Compare the ages of two snapshot handles.
11179** METHOD: sqlite3_snapshot
11180**
11181** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
11182** of two valid snapshot handles.
11183**
11184** If the two snapshot handles are not associated with the same database
11185** file, the result of the comparison is undefined.
11186**
11187** Additionally, the result of the comparison is only valid if both of the
11188** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
11189** last time the wal file was deleted. The wal file is deleted when the
11190** database is changed back to rollback mode or when the number of database
11191** clients drops to zero. If either snapshot handle was obtained before the
11192** wal file was last deleted, the value returned by this function
11193** is undefined.
11194**
11195** Otherwise, this API returns a negative value if P1 refers to an older
11196** snapshot than P2, zero if the two handles refer to the same database
11197** snapshot, and a positive value if P1 is a newer snapshot than P2.
11198**
11199** This interface is only available if SQLite is compiled with the
11200** [SQLITE_ENABLE_SNAPSHOT] option.
11201*/
11202SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
11203 sqlite3_snapshot *p1,
11204 sqlite3_snapshot *p2
11205);
11206
11207/*
11208** CAPI3REF: Recover snapshots from a wal file
11209** METHOD: sqlite3_snapshot
11210**
11211** If a [WAL file] remains on disk after all database connections close
11212** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]
11213** or because the last process to have the database opened exited without
11214** calling [sqlite3_close()]) and a new connection is subsequently opened
11215** on that database and [WAL file], the [sqlite3_snapshot_open()] interface
11216** will only be able to open the last transaction added to the WAL file
11217** even though the WAL file contains other valid transactions.
11218**
11219** This function attempts to scan the WAL file associated with database zDb
11220** of database handle db and make all valid snapshots available to
11221** sqlite3_snapshot_open(). It is an error if there is already a read
11222** transaction open on the database, or if the database is not a WAL mode
11223** database.
11224**
11225** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
11226**
11227** This interface is only available if SQLite is compiled with the
11228** [SQLITE_ENABLE_SNAPSHOT] option.
11229*/
11230SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
11231
11232/*
11233** CAPI3REF: Serialize a database
11234**
11235** The sqlite3_serialize(D,S,P,F) interface returns a pointer to
11236** memory that is a serialization of the S database on
11237** [database connection] D. If S is a NULL pointer, the main database is used.
11238** If P is not a NULL pointer, then the size of the database in bytes
11239** is written into *P.
11240**
11241** For an ordinary on-disk database file, the serialization is just a
11242** copy of the disk file. For an in-memory database or a "TEMP" database,
11243** the serialization is the same sequence of bytes which would be written
11244** to disk if that database were backed up to disk.
11245**
11246** The usual case is that sqlite3_serialize() copies the serialization of
11247** the database into memory obtained from [sqlite3_malloc64()] and returns
11248** a pointer to that memory. The caller is responsible for freeing the
11249** returned value to avoid a memory leak. However, if the F argument
11250** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
11251** are made, and the sqlite3_serialize() function will return a pointer
11252** to the contiguous memory representation of the database that SQLite
11253** is currently using for that database, or NULL if no such contiguous
11254** memory representation of the database exists. A contiguous memory
11255** representation of the database will usually only exist if there has
11256** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
11257** values of D and S.
11258** The size of the database is written into *P even if the
11259** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
11260** of the database exists.
11261**
11262** After the call, if the SQLITE_SERIALIZE_NOCOPY bit had been set,
11263** the returned buffer content will remain accessible and unchanged
11264** until either the next write operation on the connection or when
11265** the connection is closed, and applications must not modify the
11266** buffer. If the bit had been clear, the returned buffer will not
11267** be accessed by SQLite after the call.
11268**
11269** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
11270** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
11271** allocation error occurs.
11272**
11273** This interface is omitted if SQLite is compiled with the
11274** [SQLITE_OMIT_DESERIALIZE] option.
11275*/
11276SQLITE_API unsigned char *sqlite3_serialize(
11277 sqlite3 *db, /* The database connection */
11278 const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */
11279 sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
11280 unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */
11281);
11282
11283/*
11284** CAPI3REF: Flags for sqlite3_serialize
11285**
11286** Zero or more of the following constants can be OR-ed together for
11287** the F argument to [sqlite3_serialize(D,S,P,F)].
11288**
11289** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
11290** a pointer to contiguous in-memory database that it is currently using,
11291** without making a copy of the database. If SQLite is not currently using
11292** a contiguous in-memory database, then this option causes
11293** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be
11294** using a contiguous in-memory database if it has been initialized by a
11295** prior call to [sqlite3_deserialize()].
11296*/
11297#define SQLITE_SERIALIZE_NOCOPY0x001 0x001 /* Do no memory allocations */
11298
11299/*
11300** CAPI3REF: Deserialize a database
11301**
11302** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
11303** [database connection] D to disconnect from database S and then
11304** reopen S as an in-memory database based on the serialization contained
11305** in P. The serialized database P is N bytes in size. M is the size of
11306** the buffer P, which might be larger than N. If M is larger than N, and
11307** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
11308** permitted to add content to the in-memory database as long as the total
11309** size does not exceed M bytes.
11310**
11311** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
11312** invoke sqlite3_free() on the serialization buffer when the database
11313** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
11314** SQLite will try to increase the buffer size using sqlite3_realloc64()
11315** if writes on the database cause it to grow larger than M bytes.
11316**
11317** Applications must not modify the buffer P or invalidate it before
11318** the database connection D is closed.
11319**
11320** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
11321** database is currently in a read transaction or is involved in a backup
11322** operation.
11323**
11324** It is not possible to deserialize into the TEMP database. If the
11325** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the
11326** function returns SQLITE_ERROR.
11327**
11328** The deserialized database should not be in [WAL mode]. If the database
11329** is in WAL mode, then any attempt to use the database file will result
11330** in an [SQLITE_CANTOPEN] error. The application can set the
11331** [file format version numbers] (bytes 18 and 19) of the input database P
11332** to 0x01 prior to invoking sqlite3_deserialize(D,S,P,N,M,F) to force the
11333** database file into rollback mode and work around this limitation.
11334**
11335** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
11336** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
11337** [sqlite3_free()] is invoked on argument P prior to returning.
11338**
11339** This interface is omitted if SQLite is compiled with the
11340** [SQLITE_OMIT_DESERIALIZE] option.
11341*/
11342SQLITE_API int sqlite3_deserialize(
11343 sqlite3 *db, /* The database connection */
11344 const char *zSchema, /* Which DB to reopen with the deserialization */
11345 unsigned char *pData, /* The serialized database content */
11346 sqlite3_int64 szDb, /* Number of bytes in the deserialization */
11347 sqlite3_int64 szBuf, /* Total size of buffer pData[] */
11348 unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
11349);
11350
11351/*
11352** CAPI3REF: Flags for sqlite3_deserialize()
11353**
11354** The following are allowed values for the 6th argument (the F argument) to
11355** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
11356**
11357** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
11358** in the P argument is held in memory obtained from [sqlite3_malloc64()]
11359** and that SQLite should take ownership of this memory and automatically
11360** free it when it has finished using it. Without this flag, the caller
11361** is responsible for freeing any dynamically allocated memory.
11362**
11363** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
11364** grow the size of the database using calls to [sqlite3_realloc64()]. This
11365** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
11366** Without this flag, the deserialized database cannot increase in size beyond
11367** the number of bytes specified by the M parameter.
11368**
11369** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
11370** should be treated as read-only.
11371*/
11372#define SQLITE_DESERIALIZE_FREEONCLOSE1 1 /* Call sqlite3_free() on close */
11373#define SQLITE_DESERIALIZE_RESIZEABLE2 2 /* Resize using sqlite3_realloc64() */
11374#define SQLITE_DESERIALIZE_READONLY4 4 /* Database is read-only */
11375
11376/*
11377** Undo the hack that converts floating point types to integer for
11378** builds on processors without floating point support.
11379*/
11380#ifdef SQLITE_OMIT_FLOATING_POINT
11381# undef double
11382#endif
11383
11384#if defined(__wasi__)
11385# undef SQLITE_WASI
11386# define SQLITE_WASI 1
11387# ifndef SQLITE_OMIT_LOAD_EXTENSION1
11388# define SQLITE_OMIT_LOAD_EXTENSION1
11389# endif
11390# ifndef SQLITE_THREADSAFE2
11391# define SQLITE_THREADSAFE2 0
11392# endif
11393#endif
11394
11395#if 0
11396} /* End of the 'extern "C"' block */
11397#endif
11398/* #endif for SQLITE3_H will be added by mksqlite3.tcl */
11399
11400/******** Begin file sqlite3rtree.h *********/
11401/*
11402** 2010 August 30
11403**
11404** The author disclaims copyright to this source code. In place of
11405** a legal notice, here is a blessing:
11406**
11407** May you do good and not evil.
11408** May you find forgiveness for yourself and forgive others.
11409** May you share freely, never taking more than you give.
11410**
11411*************************************************************************
11412*/
11413
11414#ifndef _SQLITE3RTREE_H_
11415#define _SQLITE3RTREE_H_
11416
11417
11418#if 0
11419extern "C" {
11420#endif
11421
11422typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
11423typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
11424
11425/* The double-precision datatype used by RTree depends on the
11426** SQLITE_RTREE_INT_ONLY compile-time option.
11427*/
11428#ifdef SQLITE_RTREE_INT_ONLY
11429 typedef sqlite3_int64 sqlite3_rtree_dbl;
11430#else
11431 typedef double sqlite3_rtree_dbl;
11432#endif
11433
11434/*
11435** Register a geometry callback named zGeom that can be used as part of an
11436** R-Tree geometry query as follows:
11437**
11438** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
11439*/
11440SQLITE_API int sqlite3_rtree_geometry_callback(
11441 sqlite3 *db,
11442 const char *zGeom,
11443 int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
11444 void *pContext
11445);
11446
11447
11448/*
11449** A pointer to a structure of the following type is passed as the first
11450** argument to callbacks registered using rtree_geometry_callback().
11451*/
11452struct sqlite3_rtree_geometry {
11453 void *pContext; /* Copy of pContext passed to s_r_g_c() */
11454 int nParam; /* Size of array aParam[] */
11455 sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
11456 void *pUser; /* Callback implementation user data */
11457 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
11458};
11459
11460/*
11461** Register a 2nd-generation geometry callback named zScore that can be
11462** used as part of an R-Tree geometry query as follows:
11463**
11464** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
11465*/
11466SQLITE_API int sqlite3_rtree_query_callback(
11467 sqlite3 *db,
11468 const char *zQueryFunc,
11469 int (*xQueryFunc)(sqlite3_rtree_query_info*),
11470 void *pContext,
11471 void (*xDestructor)(void*)
11472);
11473
11474
11475/*
11476** A pointer to a structure of the following type is passed as the
11477** argument to scored geometry callback registered using
11478** sqlite3_rtree_query_callback().
11479**
11480** Note that the first 5 fields of this structure are identical to
11481** sqlite3_rtree_geometry. This structure is a subclass of
11482** sqlite3_rtree_geometry.
11483*/
11484struct sqlite3_rtree_query_info {
11485 void *pContext; /* pContext from when function registered */
11486 int nParam; /* Number of function parameters */
11487 sqlite3_rtree_dbl *aParam; /* value of function parameters */
11488 void *pUser; /* callback can use this, if desired */
11489 void (*xDelUser)(void*); /* function to free pUser */
11490 sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
11491 unsigned int *anQueue; /* Number of pending entries in the queue */
11492 int nCoord; /* Number of coordinates */
11493 int iLevel; /* Level of current node or entry */
11494 int mxLevel; /* The largest iLevel value in the tree */
11495 sqlite3_int64 iRowid; /* Rowid for current entry */
11496 sqlite3_rtree_dbl rParentScore; /* Score of parent node */
11497 int eParentWithin; /* Visibility of parent node */
11498 int eWithin; /* OUT: Visibility */
11499 sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
11500 /* The following fields are only available in 3.8.11 and later */
11501 sqlite3_value **apSqlParam; /* Original SQL values of parameters */
11502};
11503
11504/*
11505** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
11506*/
11507#define NOT_WITHIN0 0 /* Object completely outside of query region */
11508#define PARTLY_WITHIN1 1 /* Object partially overlaps query region */
11509#define FULLY_WITHIN2 2 /* Object fully contained within query region */
11510
11511
11512#if 0
11513} /* end of the 'extern "C"' block */
11514#endif
11515
11516#endif /* ifndef _SQLITE3RTREE_H_ */
11517
11518/******** End of sqlite3rtree.h *********/
11519/******** Begin file sqlite3session.h *********/
11520
11521#if !defined(__SQLITESESSION_H_1) && defined(SQLITE_ENABLE_SESSION1)
11522#define __SQLITESESSION_H_1 1
11523
11524/*
11525** Make sure we can call this stuff from C++.
11526*/
11527#if 0
11528extern "C" {
11529#endif
11530
11531
11532/*
11533** CAPI3REF: Session Object Handle
11534**
11535** An instance of this object is a [session] that can be used to
11536** record changes to a database.
11537*/
11538typedef struct sqlite3_session sqlite3_session;
11539
11540/*
11541** CAPI3REF: Changeset Iterator Handle
11542**
11543** An instance of this object acts as a cursor for iterating
11544** over the elements of a [changeset] or [patchset].
11545*/
11546typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
11547
11548/*
11549** CAPI3REF: Create A New Session Object
11550** CONSTRUCTOR: sqlite3_session
11551**
11552** Create a new session object attached to database handle db. If successful,
11553** a pointer to the new object is written to *ppSession and SQLITE_OK is
11554** returned. If an error occurs, *ppSession is set to NULL and an SQLite
11555** error code (e.g. SQLITE_NOMEM) is returned.
11556**
11557** It is possible to create multiple session objects attached to a single
11558** database handle.
11559**
11560** Session objects created using this function should be deleted using the
11561** [sqlite3session_delete()] function before the database handle that they
11562** are attached to is itself closed. If the database handle is closed before
11563** the session object is deleted, then the results of calling any session
11564** module function, including [sqlite3session_delete()] on the session object
11565** are undefined.
11566**
11567** Because the session module uses the [sqlite3_preupdate_hook()] API, it
11568** is not possible for an application to register a pre-update hook on a
11569** database handle that has one or more session objects attached. Nor is
11570** it possible to create a session object attached to a database handle for
11571** which a pre-update hook is already defined. The results of attempting
11572** either of these things are undefined.
11573**
11574** The session object will be used to create changesets for tables in
11575** database zDb, where zDb is either "main", or "temp", or the name of an
11576** attached database. It is not an error if database zDb is not attached
11577** to the database when the session object is created.
11578*/
11579SQLITE_API int sqlite3session_create(
11580 sqlite3 *db, /* Database handle */
11581 const char *zDb, /* Name of db (e.g. "main") */
11582 sqlite3_session **ppSession /* OUT: New session object */
11583);
11584
11585/*
11586** CAPI3REF: Delete A Session Object
11587** DESTRUCTOR: sqlite3_session
11588**
11589** Delete a session object previously allocated using
11590** [sqlite3session_create()]. Once a session object has been deleted, the
11591** results of attempting to use pSession with any other session module
11592** function are undefined.
11593**
11594** Session objects must be deleted before the database handle to which they
11595** are attached is closed. Refer to the documentation for
11596** [sqlite3session_create()] for details.
11597*/
11598SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
11599
11600/*
11601** CAPI3REF: Configure a Session Object
11602** METHOD: sqlite3_session
11603**
11604** This method is used to configure a session object after it has been
11605** created. At present the only valid values for the second parameter are
11606** [SQLITE_SESSION_OBJCONFIG_SIZE] and [SQLITE_SESSION_OBJCONFIG_ROWID].
11607**
11608*/
11609SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg);
11610
11611/*
11612** CAPI3REF: Options for sqlite3session_object_config
11613**
11614** The following values may passed as the the 2nd parameter to
11615** sqlite3session_object_config().
11616**
11617** <dt>SQLITE_SESSION_OBJCONFIG_SIZE <dd>
11618** This option is used to set, clear or query the flag that enables
11619** the [sqlite3session_changeset_size()] API. Because it imposes some
11620** computational overhead, this API is disabled by default. Argument
11621** pArg must point to a value of type (int). If the value is initially
11622** 0, then the sqlite3session_changeset_size() API is disabled. If it
11623** is greater than 0, then the same API is enabled. Or, if the initial
11624** value is less than zero, no change is made. In all cases the (int)
11625** variable is set to 1 if the sqlite3session_changeset_size() API is
11626** enabled following the current call, or 0 otherwise.
11627**
11628** It is an error (SQLITE_MISUSE) to attempt to modify this setting after
11629** the first table has been attached to the session object.
11630**
11631** <dt>SQLITE_SESSION_OBJCONFIG_ROWID <dd>
11632** This option is used to set, clear or query the flag that enables
11633** collection of data for tables with no explicit PRIMARY KEY.
11634**
11635** Normally, tables with no explicit PRIMARY KEY are simply ignored
11636** by the sessions module. However, if this flag is set, it behaves
11637** as if such tables have a column "_rowid_ INTEGER PRIMARY KEY" inserted
11638** as their leftmost columns.
11639**
11640** It is an error (SQLITE_MISUSE) to attempt to modify this setting after
11641** the first table has been attached to the session object.
11642*/
11643#define SQLITE_SESSION_OBJCONFIG_SIZE1 1
11644#define SQLITE_SESSION_OBJCONFIG_ROWID2 2
11645
11646/*
11647** CAPI3REF: Enable Or Disable A Session Object
11648** METHOD: sqlite3_session
11649**
11650** Enable or disable the recording of changes by a session object. When
11651** enabled, a session object records changes made to the database. When
11652** disabled - it does not. A newly created session object is enabled.
11653** Refer to the documentation for [sqlite3session_changeset()] for further
11654** details regarding how enabling and disabling a session object affects
11655** the eventual changesets.
11656**
11657** Passing zero to this function disables the session. Passing a value
11658** greater than zero enables it. Passing a value less than zero is a
11659** no-op, and may be used to query the current state of the session.
11660**
11661** The return value indicates the final state of the session object: 0 if
11662** the session is disabled, or 1 if it is enabled.
11663*/
11664SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
11665
11666/*
11667** CAPI3REF: Set Or Clear the Indirect Change Flag
11668** METHOD: sqlite3_session
11669**
11670** Each change recorded by a session object is marked as either direct or
11671** indirect. A change is marked as indirect if either:
11672**
11673** <ul>
11674** <li> The session object "indirect" flag is set when the change is
11675** made, or
11676** <li> The change is made by an SQL trigger or foreign key action
11677** instead of directly as a result of a users SQL statement.
11678** </ul>
11679**
11680** If a single row is affected by more than one operation within a session,
11681** then the change is considered indirect if all operations meet the criteria
11682** for an indirect change above, or direct otherwise.
11683**
11684** This function is used to set, clear or query the session object indirect
11685** flag. If the second argument passed to this function is zero, then the
11686** indirect flag is cleared. If it is greater than zero, the indirect flag
11687** is set. Passing a value less than zero does not modify the current value
11688** of the indirect flag, and may be used to query the current state of the
11689** indirect flag for the specified session object.
11690**
11691** The return value indicates the final state of the indirect flag: 0 if
11692** it is clear, or 1 if it is set.
11693*/
11694SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
11695
11696/*
11697** CAPI3REF: Attach A Table To A Session Object
11698** METHOD: sqlite3_session
11699**
11700** If argument zTab is not NULL, then it is the name of a table to attach
11701** to the session object passed as the first argument. All subsequent changes
11702** made to the table while the session object is enabled will be recorded. See
11703** documentation for [sqlite3session_changeset()] for further details.
11704**
11705** Or, if argument zTab is NULL, then changes are recorded for all tables
11706** in the database. If additional tables are added to the database (by
11707** executing "CREATE TABLE" statements) after this call is made, changes for
11708** the new tables are also recorded.
11709**
11710** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
11711** defined as part of their CREATE TABLE statement. It does not matter if the
11712** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
11713** KEY may consist of a single column, or may be a composite key.
11714**
11715** It is not an error if the named table does not exist in the database. Nor
11716** is it an error if the named table does not have a PRIMARY KEY. However,
11717** no changes will be recorded in either of these scenarios.
11718**
11719** Changes are not recorded for individual rows that have NULL values stored
11720** in one or more of their PRIMARY KEY columns.
11721**
11722** SQLITE_OK is returned if the call completes without error. Or, if an error
11723** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
11724**
11725** <h3>Special sqlite_stat1 Handling</h3>
11726**
11727** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
11728** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
11729** <pre>
11730** &nbsp; CREATE TABLE sqlite_stat1(tbl,idx,stat)
11731** </pre>
11732**
11733** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
11734** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
11735** are recorded for rows for which (idx IS NULL) is true. However, for such
11736** rows a zero-length blob (SQL value X'') is stored in the changeset or
11737** patchset instead of a NULL value. This allows such changesets to be
11738** manipulated by legacy implementations of sqlite3changeset_invert(),
11739** concat() and similar.
11740**
11741** The sqlite3changeset_apply() function automatically converts the
11742** zero-length blob back to a NULL value when updating the sqlite_stat1
11743** table. However, if the application calls sqlite3changeset_new(),
11744** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
11745** iterator directly (including on a changeset iterator passed to a
11746** conflict-handler callback) then the X'' value is returned. The application
11747** must translate X'' to NULL itself if required.
11748**
11749** Legacy (older than 3.22.0) versions of the sessions module cannot capture
11750** changes made to the sqlite_stat1 table. Legacy versions of the
11751** sqlite3changeset_apply() function silently ignore any modifications to the
11752** sqlite_stat1 table that are part of a changeset or patchset.
11753*/
11754SQLITE_API int sqlite3session_attach(
11755 sqlite3_session *pSession, /* Session object */
11756 const char *zTab /* Table name */
11757);
11758
11759/*
11760** CAPI3REF: Set a table filter on a Session Object.
11761** METHOD: sqlite3_session
11762**
11763** The second argument (xFilter) is the "filter callback". For changes to rows
11764** in tables that are not attached to the Session object, the filter is called
11765** to determine whether changes to the table's rows should be tracked or not.
11766** If xFilter returns 0, changes are not tracked. Note that once a table is
11767** attached, xFilter will not be called again.
11768*/
11769SQLITE_API void sqlite3session_table_filter(
11770 sqlite3_session *pSession, /* Session object */
11771 int(*xFilter)(
11772 void *pCtx, /* Copy of third arg to _filter_table() */
11773 const char *zTab /* Table name */
11774 ),
11775 void *pCtx /* First argument passed to xFilter */
11776);
11777
11778/*
11779** CAPI3REF: Generate A Changeset From A Session Object
11780** METHOD: sqlite3_session
11781**
11782** Obtain a changeset containing changes to the tables attached to the
11783** session object passed as the first argument. If successful,
11784** set *ppChangeset to point to a buffer containing the changeset
11785** and *pnChangeset to the size of the changeset in bytes before returning
11786** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
11787** zero and return an SQLite error code.
11788**
11789** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
11790** each representing a change to a single row of an attached table. An INSERT
11791** change contains the values of each field of a new database row. A DELETE
11792** contains the original values of each field of a deleted database row. An
11793** UPDATE change contains the original values of each field of an updated
11794** database row along with the updated values for each updated non-primary-key
11795** column. It is not possible for an UPDATE change to represent a change that
11796** modifies the values of primary key columns. If such a change is made, it
11797** is represented in a changeset as a DELETE followed by an INSERT.
11798**
11799** Changes are not recorded for rows that have NULL values stored in one or
11800** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
11801** no corresponding change is present in the changesets returned by this
11802** function. If an existing row with one or more NULL values stored in
11803** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
11804** only an INSERT is appears in the changeset. Similarly, if an existing row
11805** with non-NULL PRIMARY KEY values is updated so that one or more of its
11806** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
11807** DELETE change only.
11808**
11809** The contents of a changeset may be traversed using an iterator created
11810** using the [sqlite3changeset_start()] API. A changeset may be applied to
11811** a database with a compatible schema using the [sqlite3changeset_apply()]
11812** API.
11813**
11814** Within a changeset generated by this function, all changes related to a
11815** single table are grouped together. In other words, when iterating through
11816** a changeset or when applying a changeset to a database, all changes related
11817** to a single table are processed before moving on to the next table. Tables
11818** are sorted in the same order in which they were attached (or auto-attached)
11819** to the sqlite3_session object. The order in which the changes related to
11820** a single table are stored is undefined.
11821**
11822** Following a successful call to this function, it is the responsibility of
11823** the caller to eventually free the buffer that *ppChangeset points to using
11824** [sqlite3_free()].
11825**
11826** <h3>Changeset Generation</h3>
11827**
11828** Once a table has been attached to a session object, the session object
11829** records the primary key values of all new rows inserted into the table.
11830** It also records the original primary key and other column values of any
11831** deleted or updated rows. For each unique primary key value, data is only
11832** recorded once - the first time a row with said primary key is inserted,
11833** updated or deleted in the lifetime of the session.
11834**
11835** There is one exception to the previous paragraph: when a row is inserted,
11836** updated or deleted, if one or more of its primary key columns contain a
11837** NULL value, no record of the change is made.
11838**
11839** The session object therefore accumulates two types of records - those
11840** that consist of primary key values only (created when the user inserts
11841** a new record) and those that consist of the primary key values and the
11842** original values of other table columns (created when the users deletes
11843** or updates a record).
11844**
11845** When this function is called, the requested changeset is created using
11846** both the accumulated records and the current contents of the database
11847** file. Specifically:
11848**
11849** <ul>
11850** <li> For each record generated by an insert, the database is queried
11851** for a row with a matching primary key. If one is found, an INSERT
11852** change is added to the changeset. If no such row is found, no change
11853** is added to the changeset.
11854**
11855** <li> For each record generated by an update or delete, the database is
11856** queried for a row with a matching primary key. If such a row is
11857** found and one or more of the non-primary key fields have been
11858** modified from their original values, an UPDATE change is added to
11859** the changeset. Or, if no such row is found in the table, a DELETE
11860** change is added to the changeset. If there is a row with a matching
11861** primary key in the database, but all fields contain their original
11862** values, no change is added to the changeset.
11863** </ul>
11864**
11865** This means, amongst other things, that if a row is inserted and then later
11866** deleted while a session object is active, neither the insert nor the delete
11867** will be present in the changeset. Or if a row is deleted and then later a
11868** row with the same primary key values inserted while a session object is
11869** active, the resulting changeset will contain an UPDATE change instead of
11870** a DELETE and an INSERT.
11871**
11872** When a session object is disabled (see the [sqlite3session_enable()] API),
11873** it does not accumulate records when rows are inserted, updated or deleted.
11874** This may appear to have some counter-intuitive effects if a single row
11875** is written to more than once during a session. For example, if a row
11876** is inserted while a session object is enabled, then later deleted while
11877** the same session object is disabled, no INSERT record will appear in the
11878** changeset, even though the delete took place while the session was disabled.
11879** Or, if one field of a row is updated while a session is enabled, and
11880** then another field of the same row is updated while the session is disabled,
11881** the resulting changeset will contain an UPDATE change that updates both
11882** fields.
11883*/
11884SQLITE_API int sqlite3session_changeset(
11885 sqlite3_session *pSession, /* Session object */
11886 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
11887 void **ppChangeset /* OUT: Buffer containing changeset */
11888);
11889
11890/*
11891** CAPI3REF: Return An Upper-limit For The Size Of The Changeset
11892** METHOD: sqlite3_session
11893**
11894** By default, this function always returns 0. For it to return
11895** a useful result, the sqlite3_session object must have been configured
11896** to enable this API using sqlite3session_object_config() with the
11897** SQLITE_SESSION_OBJCONFIG_SIZE verb.
11898**
11899** When enabled, this function returns an upper limit, in bytes, for the size
11900** of the changeset that might be produced if sqlite3session_changeset() were
11901** called. The final changeset size might be equal to or smaller than the
11902** size in bytes returned by this function.
11903*/
11904SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession);
11905
11906/*
11907** CAPI3REF: Load The Difference Between Tables Into A Session
11908** METHOD: sqlite3_session
11909**
11910** If it is not already attached to the session object passed as the first
11911** argument, this function attaches table zTbl in the same manner as the
11912** [sqlite3session_attach()] function. If zTbl does not exist, or if it
11913** does not have a primary key, this function is a no-op (but does not return
11914** an error).
11915**
11916** Argument zFromDb must be the name of a database ("main", "temp" etc.)
11917** attached to the same database handle as the session object that contains
11918** a table compatible with the table attached to the session by this function.
11919** A table is considered compatible if it:
11920**
11921** <ul>
11922** <li> Has the same name,
11923** <li> Has the same set of columns declared in the same order, and
11924** <li> Has the same PRIMARY KEY definition.
11925** </ul>
11926**
11927** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
11928** are compatible but do not have any PRIMARY KEY columns, it is not an error
11929** but no changes are added to the session object. As with other session
11930** APIs, tables without PRIMARY KEYs are simply ignored.
11931**
11932** This function adds a set of changes to the session object that could be
11933** used to update the table in database zFrom (call this the "from-table")
11934** so that its content is the same as the table attached to the session
11935** object (call this the "to-table"). Specifically:
11936**
11937** <ul>
11938** <li> For each row (primary key) that exists in the to-table but not in
11939** the from-table, an INSERT record is added to the session object.
11940**
11941** <li> For each row (primary key) that exists in the to-table but not in
11942** the from-table, a DELETE record is added to the session object.
11943**
11944** <li> For each row (primary key) that exists in both tables, but features
11945** different non-PK values in each, an UPDATE record is added to the
11946** session.
11947** </ul>
11948**
11949** To clarify, if this function is called and then a changeset constructed
11950** using [sqlite3session_changeset()], then after applying that changeset to
11951** database zFrom the contents of the two compatible tables would be
11952** identical.
11953**
11954** Unless the call to this function is a no-op as described above, it is an
11955** error if database zFrom does not exist or does not contain the required
11956** compatible table.
11957**
11958** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite
11959** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
11960** may be set to point to a buffer containing an English language error
11961** message. It is the responsibility of the caller to free this buffer using
11962** sqlite3_free().
11963*/
11964SQLITE_API int sqlite3session_diff(
11965 sqlite3_session *pSession,
11966 const char *zFromDb,
11967 const char *zTbl,
11968 char **pzErrMsg
11969);
11970
11971
11972/*
11973** CAPI3REF: Generate A Patchset From A Session Object
11974** METHOD: sqlite3_session
11975**
11976** The differences between a patchset and a changeset are that:
11977**
11978** <ul>
11979** <li> DELETE records consist of the primary key fields only. The
11980** original values of other fields are omitted.
11981** <li> The original values of any modified fields are omitted from
11982** UPDATE records.
11983** </ul>
11984**
11985** A patchset blob may be used with up to date versions of all
11986** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
11987** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
11988** attempting to use a patchset blob with old versions of the
11989** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
11990**
11991** Because the non-primary key "old.*" fields are omitted, no
11992** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
11993** is passed to the sqlite3changeset_apply() API. Other conflict types work
11994** in the same way as for changesets.
11995**
11996** Changes within a patchset are ordered in the same way as for changesets
11997** generated by the sqlite3session_changeset() function (i.e. all changes for
11998** a single table are grouped together, tables appear in the order in which
11999** they were attached to the session object).
12000*/
12001SQLITE_API int sqlite3session_patchset(
12002 sqlite3_session *pSession, /* Session object */
12003 int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
12004 void **ppPatchset /* OUT: Buffer containing patchset */
12005);
12006
12007/*
12008** CAPI3REF: Test if a changeset has recorded any changes.
12009**
12010** Return non-zero if no changes to attached tables have been recorded by
12011** the session object passed as the first argument. Otherwise, if one or
12012** more changes have been recorded, return zero.
12013**
12014** Even if this function returns zero, it is possible that calling
12015** [sqlite3session_changeset()] on the session handle may still return a
12016** changeset that contains no changes. This can happen when a row in
12017** an attached table is modified and then later on the original values
12018** are restored. However, if this function returns non-zero, then it is
12019** guaranteed that a call to sqlite3session_changeset() will return a
12020** changeset containing zero changes.
12021*/
12022SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
12023
12024/*
12025** CAPI3REF: Query for the amount of heap memory used by a session object.
12026**
12027** This API returns the total amount of heap memory in bytes currently
12028** used by the session object passed as the only argument.
12029*/
12030SQLITE_API sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession);
12031
12032/*
12033** CAPI3REF: Create An Iterator To Traverse A Changeset
12034** CONSTRUCTOR: sqlite3_changeset_iter
12035**
12036** Create an iterator used to iterate through the contents of a changeset.
12037** If successful, *pp is set to point to the iterator handle and SQLITE_OK
12038** is returned. Otherwise, if an error occurs, *pp is set to zero and an
12039** SQLite error code is returned.
12040**
12041** The following functions can be used to advance and query a changeset
12042** iterator created by this function:
12043**
12044** <ul>
12045** <li> [sqlite3changeset_next()]
12046** <li> [sqlite3changeset_op()]
12047** <li> [sqlite3changeset_new()]
12048** <li> [sqlite3changeset_old()]
12049** </ul>
12050**
12051** It is the responsibility of the caller to eventually destroy the iterator
12052** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
12053** changeset (pChangeset) must remain valid until after the iterator is
12054** destroyed.
12055**
12056** Assuming the changeset blob was created by one of the
12057** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
12058** [sqlite3changeset_invert()] functions, all changes within the changeset
12059** that apply to a single table are grouped together. This means that when
12060** an application iterates through a changeset using an iterator created by
12061** this function, all changes that relate to a single table are visited
12062** consecutively. There is no chance that the iterator will visit a change
12063** the applies to table X, then one for table Y, and then later on visit
12064** another change for table X.
12065**
12066** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
12067** may be modified by passing a combination of
12068** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.
12069**
12070** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>
12071** and therefore subject to change.
12072*/
12073SQLITE_API int sqlite3changeset_start(
12074 sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
12075 int nChangeset, /* Size of changeset blob in bytes */
12076 void *pChangeset /* Pointer to blob containing changeset */
12077);
12078SQLITE_API int sqlite3changeset_start_v2(
12079 sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
12080 int nChangeset, /* Size of changeset blob in bytes */
12081 void *pChangeset, /* Pointer to blob containing changeset */
12082 int flags /* SESSION_CHANGESETSTART_* flags */
12083);
12084
12085/*
12086** CAPI3REF: Flags for sqlite3changeset_start_v2
12087**
12088** The following flags may passed via the 4th parameter to
12089** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:
12090**
12091** <dt>SQLITE_CHANGESETSTART_INVERT <dd>
12092** Invert the changeset while iterating through it. This is equivalent to
12093** inverting a changeset using sqlite3changeset_invert() before applying it.
12094** It is an error to specify this flag with a patchset.
12095*/
12096#define SQLITE_CHANGESETSTART_INVERT0x0002 0x0002
12097
12098
12099/*
12100** CAPI3REF: Advance A Changeset Iterator
12101** METHOD: sqlite3_changeset_iter
12102**
12103** This function may only be used with iterators created by the function
12104** [sqlite3changeset_start()]. If it is called on an iterator passed to
12105** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
12106** is returned and the call has no effect.
12107**
12108** Immediately after an iterator is created by sqlite3changeset_start(), it
12109** does not point to any change in the changeset. Assuming the changeset
12110** is not empty, the first call to this function advances the iterator to
12111** point to the first change in the changeset. Each subsequent call advances
12112** the iterator to point to the next change in the changeset (if any). If
12113** no error occurs and the iterator points to a valid change after a call
12114** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
12115** Otherwise, if all changes in the changeset have already been visited,
12116** SQLITE_DONE is returned.
12117**
12118** If an error occurs, an SQLite error code is returned. Possible error
12119** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
12120** SQLITE_NOMEM.
12121*/
12122SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
12123
12124/*
12125** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
12126** METHOD: sqlite3_changeset_iter
12127**
12128** The pIter argument passed to this function may either be an iterator
12129** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
12130** created by [sqlite3changeset_start()]. In the latter case, the most recent
12131** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
12132** is not the case, this function returns [SQLITE_MISUSE].
12133**
12134** Arguments pOp, pnCol and pzTab may not be NULL. Upon return, three
12135** outputs are set through these pointers:
12136**
12137** *pOp is set to one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
12138** depending on the type of change that the iterator currently points to;
12139**
12140** *pnCol is set to the number of columns in the table affected by the change; and
12141**
12142** *pzTab is set to point to a nul-terminated utf-8 encoded string containing
12143** the name of the table affected by the current change. The buffer remains
12144** valid until either sqlite3changeset_next() is called on the iterator
12145** or until the conflict-handler function returns.
12146**
12147** If pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
12148** is an indirect change, or false (0) otherwise. See the documentation for
12149** [sqlite3session_indirect()] for a description of direct and indirect
12150** changes.
12151**
12152** If no error occurs, SQLITE_OK is returned. If an error does occur, an
12153** SQLite error code is returned. The values of the output variables may not
12154** be trusted in this case.
12155*/
12156SQLITE_API int sqlite3changeset_op(
12157 sqlite3_changeset_iter *pIter, /* Iterator object */
12158 const char **pzTab, /* OUT: Pointer to table name */
12159 int *pnCol, /* OUT: Number of columns in table */
12160 int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
12161 int *pbIndirect /* OUT: True for an 'indirect' change */
12162);
12163
12164/*
12165** CAPI3REF: Obtain The Primary Key Definition Of A Table
12166** METHOD: sqlite3_changeset_iter
12167**
12168** For each modified table, a changeset includes the following:
12169**
12170** <ul>
12171** <li> The number of columns in the table, and
12172** <li> Which of those columns make up the tables PRIMARY KEY.
12173** </ul>
12174**
12175** This function is used to find which columns comprise the PRIMARY KEY of
12176** the table modified by the change that iterator pIter currently points to.
12177** If successful, *pabPK is set to point to an array of nCol entries, where
12178** nCol is the number of columns in the table. Elements of *pabPK are set to
12179** 0x01 if the corresponding column is part of the tables primary key, or
12180** 0x00 if it is not.
12181**
12182** If argument pnCol is not NULL, then *pnCol is set to the number of columns
12183** in the table.
12184**
12185** If this function is called when the iterator does not point to a valid
12186** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
12187** SQLITE_OK is returned and the output variables populated as described
12188** above.
12189*/
12190SQLITE_API int sqlite3changeset_pk(
12191 sqlite3_changeset_iter *pIter, /* Iterator object */
12192 unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
12193 int *pnCol /* OUT: Number of entries in output array */
12194);
12195
12196/*
12197** CAPI3REF: Obtain old.* Values From A Changeset Iterator
12198** METHOD: sqlite3_changeset_iter
12199**
12200** The pIter argument passed to this function may either be an iterator
12201** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
12202** created by [sqlite3changeset_start()]. In the latter case, the most recent
12203** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
12204** Furthermore, it may only be called if the type of change that the iterator
12205** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
12206** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
12207**
12208** Argument iVal must be greater than or equal to 0, and less than the number
12209** of columns in the table affected by the current change. Otherwise,
12210** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
12211**
12212** If successful, this function sets *ppValue to point to a protected
12213** sqlite3_value object containing the iVal'th value from the vector of
12214** original row values stored as part of the UPDATE or DELETE change and
12215** returns SQLITE_OK. The name of the function comes from the fact that this
12216** is similar to the "old.*" columns available to update or delete triggers.
12217**
12218** If some other error occurs (e.g. an OOM condition), an SQLite error code
12219** is returned and *ppValue is set to NULL.
12220*/
12221SQLITE_API int sqlite3changeset_old(
12222 sqlite3_changeset_iter *pIter, /* Changeset iterator */
12223 int iVal, /* Column number */
12224 sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
12225);
12226
12227/*
12228** CAPI3REF: Obtain new.* Values From A Changeset Iterator
12229** METHOD: sqlite3_changeset_iter
12230**
12231** The pIter argument passed to this function may either be an iterator
12232** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
12233** created by [sqlite3changeset_start()]. In the latter case, the most recent
12234** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
12235** Furthermore, it may only be called if the type of change that the iterator
12236** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
12237** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
12238**
12239** Argument iVal must be greater than or equal to 0, and less than the number
12240** of columns in the table affected by the current change. Otherwise,
12241** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
12242**
12243** If successful, this function sets *ppValue to point to a protected
12244** sqlite3_value object containing the iVal'th value from the vector of
12245** new row values stored as part of the UPDATE or INSERT change and
12246** returns SQLITE_OK. If the change is an UPDATE and does not include
12247** a new value for the requested column, *ppValue is set to NULL and
12248** SQLITE_OK returned. The name of the function comes from the fact that
12249** this is similar to the "new.*" columns available to update or delete
12250** triggers.
12251**
12252** If some other error occurs (e.g. an OOM condition), an SQLite error code
12253** is returned and *ppValue is set to NULL.
12254*/
12255SQLITE_API int sqlite3changeset_new(
12256 sqlite3_changeset_iter *pIter, /* Changeset iterator */
12257 int iVal, /* Column number */
12258 sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
12259);
12260
12261/*
12262** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
12263** METHOD: sqlite3_changeset_iter
12264**
12265** This function should only be used with iterator objects passed to a
12266** conflict-handler callback by [sqlite3changeset_apply()] with either
12267** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
12268** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
12269** is set to NULL.
12270**
12271** Argument iVal must be greater than or equal to 0, and less than the number
12272** of columns in the table affected by the current change. Otherwise,
12273** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
12274**
12275** If successful, this function sets *ppValue to point to a protected
12276** sqlite3_value object containing the iVal'th value from the
12277** "conflicting row" associated with the current conflict-handler callback
12278** and returns SQLITE_OK.
12279**
12280** If some other error occurs (e.g. an OOM condition), an SQLite error code
12281** is returned and *ppValue is set to NULL.
12282*/
12283SQLITE_API int sqlite3changeset_conflict(
12284 sqlite3_changeset_iter *pIter, /* Changeset iterator */
12285 int iVal, /* Column number */
12286 sqlite3_value **ppValue /* OUT: Value from conflicting row */
12287);
12288
12289/*
12290** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
12291** METHOD: sqlite3_changeset_iter
12292**
12293** This function may only be called with an iterator passed to an
12294** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
12295** it sets the output variable to the total number of known foreign key
12296** violations in the destination database and returns SQLITE_OK.
12297**
12298** In all other cases this function returns SQLITE_MISUSE.
12299*/
12300SQLITE_API int sqlite3changeset_fk_conflicts(
12301 sqlite3_changeset_iter *pIter, /* Changeset iterator */
12302 int *pnOut /* OUT: Number of FK violations */
12303);
12304
12305
12306/*
12307** CAPI3REF: Finalize A Changeset Iterator
12308** METHOD: sqlite3_changeset_iter
12309**
12310** This function is used to finalize an iterator allocated with
12311** [sqlite3changeset_start()].
12312**
12313** This function should only be called on iterators created using the
12314** [sqlite3changeset_start()] function. If an application calls this
12315** function with an iterator passed to a conflict-handler by
12316** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
12317** call has no effect.
12318**
12319** If an error was encountered within a call to an sqlite3changeset_xxx()
12320** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
12321** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
12322** to that error is returned by this function. Otherwise, SQLITE_OK is
12323** returned. This is to allow the following pattern (pseudo-code):
12324**
12325** <pre>
12326** sqlite3changeset_start();
12327** while( SQLITE_ROW==sqlite3changeset_next() ){
12328** // Do something with change.
12329** }
12330** rc = sqlite3changeset_finalize();
12331** if( rc!=SQLITE_OK ){
12332** // An error has occurred
12333** }
12334** </pre>
12335*/
12336SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
12337
12338/*
12339** CAPI3REF: Invert A Changeset
12340**
12341** This function is used to "invert" a changeset object. Applying an inverted
12342** changeset to a database reverses the effects of applying the uninverted
12343** changeset. Specifically:
12344**
12345** <ul>
12346** <li> Each DELETE change is changed to an INSERT, and
12347** <li> Each INSERT change is changed to a DELETE, and
12348** <li> For each UPDATE change, the old.* and new.* values are exchanged.
12349** </ul>
12350**
12351** This function does not change the order in which changes appear within
12352** the changeset. It merely reverses the sense of each individual change.
12353**
12354** If successful, a pointer to a buffer containing the inverted changeset
12355** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
12356** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
12357** zeroed and an SQLite error code returned.
12358**
12359** It is the responsibility of the caller to eventually call sqlite3_free()
12360** on the *ppOut pointer to free the buffer allocation following a successful
12361** call to this function.
12362**
12363** WARNING/TODO: This function currently assumes that the input is a valid
12364** changeset. If it is not, the results are undefined.
12365*/
12366SQLITE_API int sqlite3changeset_invert(
12367 int nIn, const void *pIn, /* Input changeset */
12368 int *pnOut, void **ppOut /* OUT: Inverse of input */
12369);
12370
12371/*
12372** CAPI3REF: Concatenate Two Changeset Objects
12373**
12374** This function is used to concatenate two changesets, A and B, into a
12375** single changeset. The result is a changeset equivalent to applying
12376** changeset A followed by changeset B.
12377**
12378** This function combines the two input changesets using an
12379** sqlite3_changegroup object. Calling it produces similar results as the
12380** following code fragment:
12381**
12382** <pre>
12383** sqlite3_changegroup *pGrp;
12384** rc = sqlite3_changegroup_new(&pGrp);
12385** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
12386** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
12387** if( rc==SQLITE_OK ){
12388** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
12389** }else{
12390** *ppOut = 0;
12391** *pnOut = 0;
12392** }
12393** </pre>
12394**
12395** Refer to the sqlite3_changegroup documentation below for details.
12396*/
12397SQLITE_API int sqlite3changeset_concat(
12398 int nA, /* Number of bytes in buffer pA */
12399 void *pA, /* Pointer to buffer containing changeset A */
12400 int nB, /* Number of bytes in buffer pB */
12401 void *pB, /* Pointer to buffer containing changeset B */
12402 int *pnOut, /* OUT: Number of bytes in output changeset */
12403 void **ppOut /* OUT: Buffer containing output changeset */
12404);
12405
12406/*
12407** CAPI3REF: Changegroup Handle
12408**
12409** A changegroup is an object used to combine two or more
12410** [changesets] or [patchsets]
12411*/
12412typedef struct sqlite3_changegroup sqlite3_changegroup;
12413
12414/*
12415** CAPI3REF: Create A New Changegroup Object
12416** CONSTRUCTOR: sqlite3_changegroup
12417**
12418** An sqlite3_changegroup object is used to combine two or more changesets
12419** (or patchsets) into a single changeset (or patchset). A single changegroup
12420** object may combine changesets or patchsets, but not both. The output is
12421** always in the same format as the input.
12422**
12423** If successful, this function returns SQLITE_OK and populates (*pp) with
12424** a pointer to a new sqlite3_changegroup object before returning. The caller
12425** should eventually free the returned object using a call to
12426** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
12427** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
12428**
12429** The usual usage pattern for an sqlite3_changegroup object is as follows:
12430**
12431** <ul>
12432** <li> It is created using a call to sqlite3changegroup_new().
12433**
12434** <li> Zero or more changesets (or patchsets) are added to the object
12435** by calling sqlite3changegroup_add().
12436**
12437** <li> The result of combining all input changesets together is obtained
12438** by the application via a call to sqlite3changegroup_output().
12439**
12440** <li> The object is deleted using a call to sqlite3changegroup_delete().
12441** </ul>
12442**
12443** Any number of calls to add() and output() may be made between the calls to
12444** new() and delete(), and in any order.
12445**
12446** As well as the regular sqlite3changegroup_add() and
12447** sqlite3changegroup_output() functions, also available are the streaming
12448** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
12449*/
12450SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
12451
12452/*
12453** CAPI3REF: Add a Schema to a Changegroup
12454** METHOD: sqlite3_changegroup_schema
12455**
12456** This method may be used to optionally enforce the rule that the changesets
12457** added to the changegroup handle must match the schema of database zDb
12458** ("main", "temp", or the name of an attached database). If
12459** sqlite3changegroup_add() is called to add a changeset that is not compatible
12460** with the configured schema, SQLITE_SCHEMA is returned and the changegroup
12461** object is left in an undefined state.
12462**
12463** A changeset schema is considered compatible with the database schema in
12464** the same way as for sqlite3changeset_apply(). Specifically, for each
12465** table in the changeset, there exists a database table with:
12466**
12467** <ul>
12468** <li> The name identified by the changeset, and
12469** <li> at least as many columns as recorded in the changeset, and
12470** <li> the primary key columns in the same position as recorded in
12471** the changeset.
12472** </ul>
12473**
12474** The output of the changegroup object always has the same schema as the
12475** database nominated using this function. In cases where changesets passed
12476** to sqlite3changegroup_add() have fewer columns than the corresponding table
12477** in the database schema, these are filled in using the default column
12478** values from the database schema. This makes it possible to combined
12479** changesets that have different numbers of columns for a single table
12480** within a changegroup, provided that they are otherwise compatible.
12481*/
12482SQLITE_API int sqlite3changegroup_schema(sqlite3_changegroup*, sqlite3*, const char *zDb);
12483
12484/*
12485** CAPI3REF: Add A Changeset To A Changegroup
12486** METHOD: sqlite3_changegroup
12487**
12488** Add all changes within the changeset (or patchset) in buffer pData (size
12489** nData bytes) to the changegroup.
12490**
12491** If the buffer contains a patchset, then all prior calls to this function
12492** on the same changegroup object must also have specified patchsets. Or, if
12493** the buffer contains a changeset, so must have the earlier calls to this
12494** function. Otherwise, SQLITE_ERROR is returned and no changes are added
12495** to the changegroup.
12496**
12497** Rows within the changeset and changegroup are identified by the values in
12498** their PRIMARY KEY columns. A change in the changeset is considered to
12499** apply to the same row as a change already present in the changegroup if
12500** the two rows have the same primary key.
12501**
12502** Changes to rows that do not already appear in the changegroup are
12503** simply copied into it. Or, if both the new changeset and the changegroup
12504** contain changes that apply to a single row, the final contents of the
12505** changegroup depends on the type of each change, as follows:
12506**
12507** <table border=1 style="margin-left:8ex;margin-right:8ex">
12508** <tr><th style="white-space:pre">Existing Change </th>
12509** <th style="white-space:pre">New Change </th>
12510** <th>Output Change
12511** <tr><td>INSERT <td>INSERT <td>
12512** The new change is ignored. This case does not occur if the new
12513** changeset was recorded immediately after the changesets already
12514** added to the changegroup.
12515** <tr><td>INSERT <td>UPDATE <td>
12516** The INSERT change remains in the changegroup. The values in the
12517** INSERT change are modified as if the row was inserted by the
12518** existing change and then updated according to the new change.
12519** <tr><td>INSERT <td>DELETE <td>
12520** The existing INSERT is removed from the changegroup. The DELETE is
12521** not added.
12522** <tr><td>UPDATE <td>INSERT <td>
12523** The new change is ignored. This case does not occur if the new
12524** changeset was recorded immediately after the changesets already
12525** added to the changegroup.
12526** <tr><td>UPDATE <td>UPDATE <td>
12527** The existing UPDATE remains within the changegroup. It is amended
12528** so that the accompanying values are as if the row was updated once
12529** by the existing change and then again by the new change.
12530** <tr><td>UPDATE <td>DELETE <td>
12531** The existing UPDATE is replaced by the new DELETE within the
12532** changegroup.
12533** <tr><td>DELETE <td>INSERT <td>
12534** If one or more of the column values in the row inserted by the
12535** new change differ from those in the row deleted by the existing
12536** change, the existing DELETE is replaced by an UPDATE within the
12537** changegroup. Otherwise, if the inserted row is exactly the same
12538** as the deleted row, the existing DELETE is simply discarded.
12539** <tr><td>DELETE <td>UPDATE <td>
12540** The new change is ignored. This case does not occur if the new
12541** changeset was recorded immediately after the changesets already
12542** added to the changegroup.
12543** <tr><td>DELETE <td>DELETE <td>
12544** The new change is ignored. This case does not occur if the new
12545** changeset was recorded immediately after the changesets already
12546** added to the changegroup.
12547** </table>
12548**
12549** If the new changeset contains changes to a table that is already present
12550** in the changegroup, then the number of columns and the position of the
12551** primary key columns for the table must be consistent. If this is not the
12552** case, this function fails with SQLITE_SCHEMA. Except, if the changegroup
12553** object has been configured with a database schema using the
12554** sqlite3changegroup_schema() API, then it is possible to combine changesets
12555** with different numbers of columns for a single table, provided that
12556** they are otherwise compatible.
12557**
12558** If the input changeset appears to be corrupt and the corruption is
12559** detected, SQLITE_CORRUPT is returned. Or, if an out-of-memory condition
12560** occurs during processing, this function returns SQLITE_NOMEM.
12561**
12562** In all cases, if an error occurs the state of the final contents of the
12563** changegroup is undefined. If no error occurs, SQLITE_OK is returned.
12564*/
12565SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
12566
12567/*
12568** CAPI3REF: Add A Single Change To A Changegroup
12569** METHOD: sqlite3_changegroup
12570**
12571** This function adds the single change currently indicated by the iterator
12572** passed as the second argument to the changegroup object. The rules for
12573** adding the change are just as described for [sqlite3changegroup_add()].
12574**
12575** If the change is successfully added to the changegroup, SQLITE_OK is
12576** returned. Otherwise, an SQLite error code is returned.
12577**
12578** The iterator must point to a valid entry when this function is called.
12579** If it does not, SQLITE_ERROR is returned and no change is added to the
12580** changegroup. Additionally, the iterator must not have been opened with
12581** the SQLITE_CHANGESETAPPLY_INVERT flag. In this case SQLITE_ERROR is also
12582** returned.
12583*/
12584SQLITE_API int sqlite3changegroup_add_change(
12585 sqlite3_changegroup*,
12586 sqlite3_changeset_iter*
12587);
12588
12589
12590
12591/*
12592** CAPI3REF: Obtain A Composite Changeset From A Changegroup
12593** METHOD: sqlite3_changegroup
12594**
12595** Obtain a buffer containing a changeset (or patchset) representing the
12596** current contents of the changegroup. If the inputs to the changegroup
12597** were themselves changesets, the output is a changeset. Or, if the
12598** inputs were patchsets, the output is also a patchset.
12599**
12600** As with the output of the sqlite3session_changeset() and
12601** sqlite3session_patchset() functions, all changes related to a single
12602** table are grouped together in the output of this function. Tables appear
12603** in the same order as for the very first changeset added to the changegroup.
12604** If the second or subsequent changesets added to the changegroup contain
12605** changes for tables that do not appear in the first changeset, they are
12606** appended onto the end of the output changeset, again in the order in
12607** which they are first encountered.
12608**
12609** If an error occurs, an SQLite error code is returned and the output
12610** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
12611** is returned and the output variables are set to the size of and a
12612** pointer to the output buffer, respectively. In this case it is the
12613** responsibility of the caller to eventually free the buffer using a
12614** call to sqlite3_free().
12615*/
12616SQLITE_API int sqlite3changegroup_output(
12617 sqlite3_changegroup*,
12618 int *pnData, /* OUT: Size of output buffer in bytes */
12619 void **ppData /* OUT: Pointer to output buffer */
12620);
12621
12622/*
12623** CAPI3REF: Delete A Changegroup Object
12624** DESTRUCTOR: sqlite3_changegroup
12625*/
12626SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
12627
12628/*
12629** CAPI3REF: Apply A Changeset To A Database
12630**
12631** Apply a changeset or patchset to a database. These functions attempt to
12632** update the "main" database attached to handle db with the changes found in
12633** the changeset passed via the second and third arguments.
12634**
12635** The fourth argument (xFilter) passed to these functions is the "filter
12636** callback". If it is not NULL, then for each table affected by at least one
12637** change in the changeset, the filter callback is invoked with
12638** the table name as the second argument, and a copy of the context pointer
12639** passed as the sixth argument as the first. If the "filter callback"
12640** returns zero, then no attempt is made to apply any changes to the table.
12641** Otherwise, if the return value is non-zero or the xFilter argument to
12642** is NULL, all changes related to the table are attempted.
12643**
12644** For each table that is not excluded by the filter callback, this function
12645** tests that the target database contains a compatible table. A table is
12646** considered compatible if all of the following are true:
12647**
12648** <ul>
12649** <li> The table has the same name as the name recorded in the
12650** changeset, and
12651** <li> The table has at least as many columns as recorded in the
12652** changeset, and
12653** <li> The table has primary key columns in the same position as
12654** recorded in the changeset.
12655** </ul>
12656**
12657** If there is no compatible table, it is not an error, but none of the
12658** changes associated with the table are applied. A warning message is issued
12659** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
12660** one such warning is issued for each table in the changeset.
12661**
12662** For each change for which there is a compatible table, an attempt is made
12663** to modify the table contents according to the UPDATE, INSERT or DELETE
12664** change. If a change cannot be applied cleanly, the conflict handler
12665** function passed as the fifth argument to sqlite3changeset_apply() may be
12666** invoked. A description of exactly when the conflict handler is invoked for
12667** each type of change is below.
12668**
12669** Unlike the xFilter argument, xConflict may not be passed NULL. The results
12670** of passing anything other than a valid function pointer as the xConflict
12671** argument are undefined.
12672**
12673** Each time the conflict handler function is invoked, it must return one
12674** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
12675** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
12676** if the second argument passed to the conflict handler is either
12677** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
12678** returns an illegal value, any changes already made are rolled back and
12679** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
12680** actions are taken by sqlite3changeset_apply() depending on the value
12681** returned by each invocation of the conflict-handler function. Refer to
12682** the documentation for the three
12683** [SQLITE_CHANGESET_OMIT|available return values] for details.
12684**
12685** <dl>
12686** <dt>DELETE Changes<dd>
12687** For each DELETE change, the function checks if the target database
12688** contains a row with the same primary key value (or values) as the
12689** original row values stored in the changeset. If it does, and the values
12690** stored in all non-primary key columns also match the values stored in
12691** the changeset the row is deleted from the target database.
12692**
12693** If a row with matching primary key values is found, but one or more of
12694** the non-primary key fields contains a value different from the original
12695** row value stored in the changeset, the conflict-handler function is
12696** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
12697** database table has more columns than are recorded in the changeset,
12698** only the values of those non-primary key fields are compared against
12699** the current database contents - any trailing database table columns
12700** are ignored.
12701**
12702** If no row with matching primary key values is found in the database,
12703** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
12704** passed as the second argument.
12705**
12706** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
12707** (which can only happen if a foreign key constraint is violated), the
12708** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
12709** passed as the second argument. This includes the case where the DELETE
12710** operation is attempted because an earlier call to the conflict handler
12711** function returned [SQLITE_CHANGESET_REPLACE].
12712**
12713** <dt>INSERT Changes<dd>
12714** For each INSERT change, an attempt is made to insert the new row into
12715** the database. If the changeset row contains fewer fields than the
12716** database table, the trailing fields are populated with their default
12717** values.
12718**
12719** If the attempt to insert the row fails because the database already
12720** contains a row with the same primary key values, the conflict handler
12721** function is invoked with the second argument set to
12722** [SQLITE_CHANGESET_CONFLICT].
12723**
12724** If the attempt to insert the row fails because of some other constraint
12725** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
12726** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
12727** This includes the case where the INSERT operation is re-attempted because
12728** an earlier call to the conflict handler function returned
12729** [SQLITE_CHANGESET_REPLACE].
12730**
12731** <dt>UPDATE Changes<dd>
12732** For each UPDATE change, the function checks if the target database
12733** contains a row with the same primary key value (or values) as the
12734** original row values stored in the changeset. If it does, and the values
12735** stored in all modified non-primary key columns also match the values
12736** stored in the changeset the row is updated within the target database.
12737**
12738** If a row with matching primary key values is found, but one or more of
12739** the modified non-primary key fields contains a value different from an
12740** original row value stored in the changeset, the conflict-handler function
12741** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
12742** UPDATE changes only contain values for non-primary key fields that are
12743** to be modified, only those fields need to match the original values to
12744** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
12745**
12746** If no row with matching primary key values is found in the database,
12747** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
12748** passed as the second argument.
12749**
12750** If the UPDATE operation is attempted, but SQLite returns
12751** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
12752** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
12753** This includes the case where the UPDATE operation is attempted after
12754** an earlier call to the conflict handler function returned
12755** [SQLITE_CHANGESET_REPLACE].
12756** </dl>
12757**
12758** It is safe to execute SQL statements, including those that write to the
12759** table that the callback related to, from within the xConflict callback.
12760** This can be used to further customize the application's conflict
12761** resolution strategy.
12762**
12763** All changes made by these functions are enclosed in a savepoint transaction.
12764** If any other error (aside from a constraint failure when attempting to
12765** write to the target database) occurs, then the savepoint transaction is
12766** rolled back, restoring the target database to its original state, and an
12767** SQLite error code returned.
12768**
12769** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
12770** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
12771** may set (*ppRebase) to point to a "rebase" that may be used with the
12772** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
12773** is set to the size of the buffer in bytes. It is the responsibility of the
12774** caller to eventually free any such buffer using sqlite3_free(). The buffer
12775** is only allocated and populated if one or more conflicts were encountered
12776** while applying the patchset. See comments surrounding the sqlite3_rebaser
12777** APIs for further details.
12778**
12779** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
12780** may be modified by passing a combination of
12781** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
12782**
12783** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>
12784** and therefore subject to change.
12785*/
12786SQLITE_API int sqlite3changeset_apply(
12787 sqlite3 *db, /* Apply change to "main" db of this handle */
12788 int nChangeset, /* Size of changeset in bytes */
12789 void *pChangeset, /* Changeset blob */
12790 int(*xFilter)(
12791 void *pCtx, /* Copy of sixth arg to _apply() */
12792 const char *zTab /* Table name */
12793 ),
12794 int(*xConflict)(
12795 void *pCtx, /* Copy of sixth arg to _apply() */
12796 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
12797 sqlite3_changeset_iter *p /* Handle describing change and conflict */
12798 ),
12799 void *pCtx /* First argument passed to xConflict */
12800);
12801SQLITE_API int sqlite3changeset_apply_v2(
12802 sqlite3 *db, /* Apply change to "main" db of this handle */
12803 int nChangeset, /* Size of changeset in bytes */
12804 void *pChangeset, /* Changeset blob */
12805 int(*xFilter)(
12806 void *pCtx, /* Copy of sixth arg to _apply() */
12807 const char *zTab /* Table name */
12808 ),
12809 int(*xConflict)(
12810 void *pCtx, /* Copy of sixth arg to _apply() */
12811 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
12812 sqlite3_changeset_iter *p /* Handle describing change and conflict */
12813 ),
12814 void *pCtx, /* First argument passed to xConflict */
12815 void **ppRebase, int *pnRebase, /* OUT: Rebase data */
12816 int flags /* SESSION_CHANGESETAPPLY_* flags */
12817);
12818
12819/*
12820** CAPI3REF: Flags for sqlite3changeset_apply_v2
12821**
12822** The following flags may passed via the 9th parameter to
12823** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
12824**
12825** <dl>
12826** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>
12827** Usually, the sessions module encloses all operations performed by
12828** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
12829** SAVEPOINT is committed if the changeset or patchset is successfully
12830** applied, or rolled back if an error occurs. Specifying this flag
12831** causes the sessions module to omit this savepoint. In this case, if the
12832** caller has an open transaction or savepoint when apply_v2() is called,
12833** it may revert the partially applied changeset by rolling it back.
12834**
12835** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
12836** Invert the changeset before applying it. This is equivalent to inverting
12837** a changeset using sqlite3changeset_invert() before applying it. It is
12838** an error to specify this flag with a patchset.
12839**
12840** <dt>SQLITE_CHANGESETAPPLY_IGNORENOOP <dd>
12841** Do not invoke the conflict handler callback for any changes that
12842** would not actually modify the database even if they were applied.
12843** Specifically, this means that the conflict handler is not invoked
12844** for:
12845** <ul>
12846** <li>a delete change if the row being deleted cannot be found,
12847** <li>an update change if the modified fields are already set to
12848** their new values in the conflicting row, or
12849** <li>an insert change if all fields of the conflicting row match
12850** the row being inserted.
12851** </ul>
12852**
12853** <dt>SQLITE_CHANGESETAPPLY_FKNOACTION <dd>
12854** If this flag it set, then all foreign key constraints in the target
12855** database behave as if they were declared with "ON UPDATE NO ACTION ON
12856** DELETE NO ACTION", even if they are actually CASCADE, RESTRICT, SET NULL
12857** or SET DEFAULT.
12858*/
12859#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT0x0001 0x0001
12860#define SQLITE_CHANGESETAPPLY_INVERT0x0002 0x0002
12861#define SQLITE_CHANGESETAPPLY_IGNORENOOP0x0004 0x0004
12862#define SQLITE_CHANGESETAPPLY_FKNOACTION0x0008 0x0008
12863
12864/*
12865** CAPI3REF: Constants Passed To The Conflict Handler
12866**
12867** Values that may be passed as the second argument to a conflict-handler.
12868**
12869** <dl>
12870** <dt>SQLITE_CHANGESET_DATA<dd>
12871** The conflict handler is invoked with CHANGESET_DATA as the second argument
12872** when processing a DELETE or UPDATE change if a row with the required
12873** PRIMARY KEY fields is present in the database, but one or more other
12874** (non primary-key) fields modified by the update do not contain the
12875** expected "before" values.
12876**
12877** The conflicting row, in this case, is the database row with the matching
12878** primary key.
12879**
12880** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
12881** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
12882** argument when processing a DELETE or UPDATE change if a row with the
12883** required PRIMARY KEY fields is not present in the database.
12884**
12885** There is no conflicting row in this case. The results of invoking the
12886** sqlite3changeset_conflict() API are undefined.
12887**
12888** <dt>SQLITE_CHANGESET_CONFLICT<dd>
12889** CHANGESET_CONFLICT is passed as the second argument to the conflict
12890** handler while processing an INSERT change if the operation would result
12891** in duplicate primary key values.
12892**
12893** The conflicting row in this case is the database row with the matching
12894** primary key.
12895**
12896** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
12897** If foreign key handling is enabled, and applying a changeset leaves the
12898** database in a state containing foreign key violations, the conflict
12899** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
12900** exactly once before the changeset is committed. If the conflict handler
12901** returns CHANGESET_OMIT, the changes, including those that caused the
12902** foreign key constraint violation, are committed. Or, if it returns
12903** CHANGESET_ABORT, the changeset is rolled back.
12904**
12905** No current or conflicting row information is provided. The only function
12906** it is possible to call on the supplied sqlite3_changeset_iter handle
12907** is sqlite3changeset_fk_conflicts().
12908**
12909** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
12910** If any other constraint violation occurs while applying a change (i.e.
12911** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
12912** invoked with CHANGESET_CONSTRAINT as the second argument.
12913**
12914** There is no conflicting row in this case. The results of invoking the
12915** sqlite3changeset_conflict() API are undefined.
12916**
12917** </dl>
12918*/
12919#define SQLITE_CHANGESET_DATA1 1
12920#define SQLITE_CHANGESET_NOTFOUND2 2
12921#define SQLITE_CHANGESET_CONFLICT3 3
12922#define SQLITE_CHANGESET_CONSTRAINT4 4
12923#define SQLITE_CHANGESET_FOREIGN_KEY5 5
12924
12925/*
12926** CAPI3REF: Constants Returned By The Conflict Handler
12927**
12928** A conflict handler callback must return one of the following three values.
12929**
12930** <dl>
12931** <dt>SQLITE_CHANGESET_OMIT<dd>
12932** If a conflict handler returns this value no special action is taken. The
12933** change that caused the conflict is not applied. The session module
12934** continues to the next change in the changeset.
12935**
12936** <dt>SQLITE_CHANGESET_REPLACE<dd>
12937** This value may only be returned if the second argument to the conflict
12938** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
12939** is not the case, any changes applied so far are rolled back and the
12940** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
12941**
12942** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
12943** handler, then the conflicting row is either updated or deleted, depending
12944** on the type of change.
12945**
12946** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
12947** handler, then the conflicting row is removed from the database and a
12948** second attempt to apply the change is made. If this second attempt fails,
12949** the original row is restored to the database before continuing.
12950**
12951** <dt>SQLITE_CHANGESET_ABORT<dd>
12952** If this value is returned, any changes applied so far are rolled back
12953** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
12954** </dl>
12955*/
12956#define SQLITE_CHANGESET_OMIT0 0
12957#define SQLITE_CHANGESET_REPLACE1 1
12958#define SQLITE_CHANGESET_ABORT2 2
12959
12960/*
12961** CAPI3REF: Rebasing changesets
12962** EXPERIMENTAL
12963**
12964** Suppose there is a site hosting a database in state S0. And that
12965** modifications are made that move that database to state S1 and a
12966** changeset recorded (the "local" changeset). Then, a changeset based
12967** on S0 is received from another site (the "remote" changeset) and
12968** applied to the database. The database is then in state
12969** (S1+"remote"), where the exact state depends on any conflict
12970** resolution decisions (OMIT or REPLACE) made while applying "remote".
12971** Rebasing a changeset is to update it to take those conflict
12972** resolution decisions into account, so that the same conflicts
12973** do not have to be resolved elsewhere in the network.
12974**
12975** For example, if both the local and remote changesets contain an
12976** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
12977**
12978** local: INSERT INTO t1 VALUES(1, 'v1');
12979** remote: INSERT INTO t1 VALUES(1, 'v2');
12980**
12981** and the conflict resolution is REPLACE, then the INSERT change is
12982** removed from the local changeset (it was overridden). Or, if the
12983** conflict resolution was "OMIT", then the local changeset is modified
12984** to instead contain:
12985**
12986** UPDATE t1 SET b = 'v2' WHERE a=1;
12987**
12988** Changes within the local changeset are rebased as follows:
12989**
12990** <dl>
12991** <dt>Local INSERT<dd>
12992** This may only conflict with a remote INSERT. If the conflict
12993** resolution was OMIT, then add an UPDATE change to the rebased
12994** changeset. Or, if the conflict resolution was REPLACE, add
12995** nothing to the rebased changeset.
12996**
12997** <dt>Local DELETE<dd>
12998** This may conflict with a remote UPDATE or DELETE. In both cases the
12999** only possible resolution is OMIT. If the remote operation was a
13000** DELETE, then add no change to the rebased changeset. If the remote
13001** operation was an UPDATE, then the old.* fields of change are updated
13002** to reflect the new.* values in the UPDATE.
13003**
13004** <dt>Local UPDATE<dd>
13005** This may conflict with a remote UPDATE or DELETE. If it conflicts
13006** with a DELETE, and the conflict resolution was OMIT, then the update
13007** is changed into an INSERT. Any undefined values in the new.* record
13008** from the update change are filled in using the old.* values from
13009** the conflicting DELETE. Or, if the conflict resolution was REPLACE,
13010** the UPDATE change is simply omitted from the rebased changeset.
13011**
13012** If conflict is with a remote UPDATE and the resolution is OMIT, then
13013** the old.* values are rebased using the new.* values in the remote
13014** change. Or, if the resolution is REPLACE, then the change is copied
13015** into the rebased changeset with updates to columns also updated by
13016** the conflicting remote UPDATE removed. If this means no columns would
13017** be updated, the change is omitted.
13018** </dl>
13019**
13020** A local change may be rebased against multiple remote changes
13021** simultaneously. If a single key is modified by multiple remote
13022** changesets, they are combined as follows before the local changeset
13023** is rebased:
13024**
13025** <ul>
13026** <li> If there has been one or more REPLACE resolutions on a
13027** key, it is rebased according to a REPLACE.
13028**
13029** <li> If there have been no REPLACE resolutions on a key, then
13030** the local changeset is rebased according to the most recent
13031** of the OMIT resolutions.
13032** </ul>
13033**
13034** Note that conflict resolutions from multiple remote changesets are
13035** combined on a per-field basis, not per-row. This means that in the
13036** case of multiple remote UPDATE operations, some fields of a single
13037** local change may be rebased for REPLACE while others are rebased for
13038** OMIT.
13039**
13040** In order to rebase a local changeset, the remote changeset must first
13041** be applied to the local database using sqlite3changeset_apply_v2() and
13042** the buffer of rebase information captured. Then:
13043**
13044** <ol>
13045** <li> An sqlite3_rebaser object is created by calling
13046** sqlite3rebaser_create().
13047** <li> The new object is configured with the rebase buffer obtained from
13048** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
13049** If the local changeset is to be rebased against multiple remote
13050** changesets, then sqlite3rebaser_configure() should be called
13051** multiple times, in the same order that the multiple
13052** sqlite3changeset_apply_v2() calls were made.
13053** <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().
13054** <li> The sqlite3_rebaser object is deleted by calling
13055** sqlite3rebaser_delete().
13056** </ol>
13057*/
13058typedef struct sqlite3_rebaser sqlite3_rebaser;
13059
13060/*
13061** CAPI3REF: Create a changeset rebaser object.
13062** EXPERIMENTAL
13063**
13064** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
13065** point to the new object and return SQLITE_OK. Otherwise, if an error
13066** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
13067** to NULL.
13068*/
13069SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
13070
13071/*
13072** CAPI3REF: Configure a changeset rebaser object.
13073** EXPERIMENTAL
13074**
13075** Configure the changeset rebaser object to rebase changesets according
13076** to the conflict resolutions described by buffer pRebase (size nRebase
13077** bytes), which must have been obtained from a previous call to
13078** sqlite3changeset_apply_v2().
13079*/
13080SQLITE_API int sqlite3rebaser_configure(
13081 sqlite3_rebaser*,
13082 int nRebase, const void *pRebase
13083);
13084
13085/*
13086** CAPI3REF: Rebase a changeset
13087** EXPERIMENTAL
13088**
13089** Argument pIn must point to a buffer containing a changeset nIn bytes
13090** in size. This function allocates and populates a buffer with a copy
13091** of the changeset rebased according to the configuration of the
13092** rebaser object passed as the first argument. If successful, (*ppOut)
13093** is set to point to the new buffer containing the rebased changeset and
13094** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
13095** responsibility of the caller to eventually free the new buffer using
13096** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
13097** are set to zero and an SQLite error code returned.
13098*/
13099SQLITE_API int sqlite3rebaser_rebase(
13100 sqlite3_rebaser*,
13101 int nIn, const void *pIn,
13102 int *pnOut, void **ppOut
13103);
13104
13105/*
13106** CAPI3REF: Delete a changeset rebaser object.
13107** EXPERIMENTAL
13108**
13109** Delete the changeset rebaser object and all associated resources. There
13110** should be one call to this function for each successful invocation
13111** of sqlite3rebaser_create().
13112*/
13113SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
13114
13115/*
13116** CAPI3REF: Streaming Versions of API functions.
13117**
13118** The six streaming API xxx_strm() functions serve similar purposes to the
13119** corresponding non-streaming API functions:
13120**
13121** <table border=1 style="margin-left:8ex;margin-right:8ex">
13122** <tr><th>Streaming function<th>Non-streaming equivalent</th>
13123** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
13124** <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
13125** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
13126** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
13127** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
13128** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
13129** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
13130** </table>
13131**
13132** Non-streaming functions that accept changesets (or patchsets) as input
13133** require that the entire changeset be stored in a single buffer in memory.
13134** Similarly, those that return a changeset or patchset do so by returning
13135** a pointer to a single large buffer allocated using sqlite3_malloc().
13136** Normally this is convenient. However, if an application running in a
13137** low-memory environment is required to handle very large changesets, the
13138** large contiguous memory allocations required can become onerous.
13139**
13140** In order to avoid this problem, instead of a single large buffer, input
13141** is passed to a streaming API functions by way of a callback function that
13142** the sessions module invokes to incrementally request input data as it is
13143** required. In all cases, a pair of API function parameters such as
13144**
13145** <pre>
13146** &nbsp; int nChangeset,
13147** &nbsp; void *pChangeset,
13148** </pre>
13149**
13150** Is replaced by:
13151**
13152** <pre>
13153** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
13154** &nbsp; void *pIn,
13155** </pre>
13156**
13157** Each time the xInput callback is invoked by the sessions module, the first
13158** argument passed is a copy of the supplied pIn context pointer. The second
13159** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
13160** error occurs the xInput method should copy up to (*pnData) bytes of data
13161** into the buffer and set (*pnData) to the actual number of bytes copied
13162** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
13163** should be set to zero to indicate this. Or, if an error occurs, an SQLite
13164** error code should be returned. In all cases, if an xInput callback returns
13165** an error, all processing is abandoned and the streaming API function
13166** returns a copy of the error code to the caller.
13167**
13168** In the case of sqlite3changeset_start_strm(), the xInput callback may be
13169** invoked by the sessions module at any point during the lifetime of the
13170** iterator. If such an xInput callback returns an error, the iterator enters
13171** an error state, whereby all subsequent calls to iterator functions
13172** immediately fail with the same error code as returned by xInput.
13173**
13174** Similarly, streaming API functions that return changesets (or patchsets)
13175** return them in chunks by way of a callback function instead of via a
13176** pointer to a single large buffer. In this case, a pair of parameters such
13177** as:
13178**
13179** <pre>
13180** &nbsp; int *pnChangeset,
13181** &nbsp; void **ppChangeset,
13182** </pre>
13183**
13184** Is replaced by:
13185**
13186** <pre>
13187** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
13188** &nbsp; void *pOut
13189** </pre>
13190**
13191** The xOutput callback is invoked zero or more times to return data to
13192** the application. The first parameter passed to each call is a copy of the
13193** pOut pointer supplied by the application. The second parameter, pData,
13194** points to a buffer nData bytes in size containing the chunk of output
13195** data being returned. If the xOutput callback successfully processes the
13196** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
13197** it should return some other SQLite error code. In this case processing
13198** is immediately abandoned and the streaming API function returns a copy
13199** of the xOutput error code to the application.
13200**
13201** The sessions module never invokes an xOutput callback with the third
13202** parameter set to a value less than or equal to zero. Other than this,
13203** no guarantees are made as to the size of the chunks of data returned.
13204*/
13205SQLITE_API int sqlite3changeset_apply_strm(
13206 sqlite3 *db, /* Apply change to "main" db of this handle */
13207 int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
13208 void *pIn, /* First arg for xInput */
13209 int(*xFilter)(
13210 void *pCtx, /* Copy of sixth arg to _apply() */
13211 const char *zTab /* Table name */
13212 ),
13213 int(*xConflict)(
13214 void *pCtx, /* Copy of sixth arg to _apply() */
13215 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
13216 sqlite3_changeset_iter *p /* Handle describing change and conflict */
13217 ),
13218 void *pCtx /* First argument passed to xConflict */
13219);
13220SQLITE_API int sqlite3changeset_apply_v2_strm(
13221 sqlite3 *db, /* Apply change to "main" db of this handle */
13222 int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
13223 void *pIn, /* First arg for xInput */
13224 int(*xFilter)(
13225 void *pCtx, /* Copy of sixth arg to _apply() */
13226 const char *zTab /* Table name */
13227 ),
13228 int(*xConflict)(
13229 void *pCtx, /* Copy of sixth arg to _apply() */
13230 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
13231 sqlite3_changeset_iter *p /* Handle describing change and conflict */
13232 ),
13233 void *pCtx, /* First argument passed to xConflict */
13234 void **ppRebase, int *pnRebase,
13235 int flags
13236);
13237SQLITE_API int sqlite3changeset_concat_strm(
13238 int (*xInputA)(void *pIn, void *pData, int *pnData),
13239 void *pInA,
13240 int (*xInputB)(void *pIn, void *pData, int *pnData),
13241 void *pInB,
13242 int (*xOutput)(void *pOut, const void *pData, int nData),
13243 void *pOut
13244);
13245SQLITE_API int sqlite3changeset_invert_strm(
13246 int (*xInput)(void *pIn, void *pData, int *pnData),
13247 void *pIn,
13248 int (*xOutput)(void *pOut, const void *pData, int nData),
13249 void *pOut
13250);
13251SQLITE_API int sqlite3changeset_start_strm(
13252 sqlite3_changeset_iter **pp,
13253 int (*xInput)(void *pIn, void *pData, int *pnData),
13254 void *pIn
13255);
13256SQLITE_API int sqlite3changeset_start_v2_strm(
13257 sqlite3_changeset_iter **pp,
13258 int (*xInput)(void *pIn, void *pData, int *pnData),
13259 void *pIn,
13260 int flags
13261);
13262SQLITE_API int sqlite3session_changeset_strm(
13263 sqlite3_session *pSession,
13264 int (*xOutput)(void *pOut, const void *pData, int nData),
13265 void *pOut
13266);
13267SQLITE_API int sqlite3session_patchset_strm(
13268 sqlite3_session *pSession,
13269 int (*xOutput)(void *pOut, const void *pData, int nData),
13270 void *pOut
13271);
13272SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
13273 int (*xInput)(void *pIn, void *pData, int *pnData),
13274 void *pIn
13275);
13276SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
13277 int (*xOutput)(void *pOut, const void *pData, int nData),
13278 void *pOut
13279);
13280SQLITE_API int sqlite3rebaser_rebase_strm(
13281 sqlite3_rebaser *pRebaser,
13282 int (*xInput)(void *pIn, void *pData, int *pnData),
13283 void *pIn,
13284 int (*xOutput)(void *pOut, const void *pData, int nData),
13285 void *pOut
13286);
13287
13288/*
13289** CAPI3REF: Configure global parameters
13290**
13291** The sqlite3session_config() interface is used to make global configuration
13292** changes to the sessions module in order to tune it to the specific needs
13293** of the application.
13294**
13295** The sqlite3session_config() interface is not threadsafe. If it is invoked
13296** while any other thread is inside any other sessions method then the
13297** results are undefined. Furthermore, if it is invoked after any sessions
13298** related objects have been created, the results are also undefined.
13299**
13300** The first argument to the sqlite3session_config() function must be one
13301** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The
13302** interpretation of the (void*) value passed as the second parameter and
13303** the effect of calling this function depends on the value of the first
13304** parameter.
13305**
13306** <dl>
13307** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>
13308** By default, the sessions module streaming interfaces attempt to input
13309** and output data in approximately 1 KiB chunks. This operand may be used
13310** to set and query the value of this configuration setting. The pointer
13311** passed as the second argument must point to a value of type (int).
13312** If this value is greater than 0, it is used as the new streaming data
13313** chunk size for both input and output. Before returning, the (int) value
13314** pointed to by pArg is set to the final value of the streaming interface
13315** chunk size.
13316** </dl>
13317**
13318** This function returns SQLITE_OK if successful, or an SQLite error code
13319** otherwise.
13320*/
13321SQLITE_API int sqlite3session_config(int op, void *pArg);
13322
13323/*
13324** CAPI3REF: Values for sqlite3session_config().
13325*/
13326#define SQLITE_SESSION_CONFIG_STRMSIZE1 1
13327
13328/*
13329** Make sure we can call this stuff from C++.
13330*/
13331#if 0
13332}
13333#endif
13334
13335#endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
13336
13337/******** End of sqlite3session.h *********/
13338/******** Begin file fts5.h *********/
13339/*
13340** 2014 May 31
13341**
13342** The author disclaims copyright to this source code. In place of
13343** a legal notice, here is a blessing:
13344**
13345** May you do good and not evil.
13346** May you find forgiveness for yourself and forgive others.
13347** May you share freely, never taking more than you give.
13348**
13349******************************************************************************
13350**
13351** Interfaces to extend FTS5. Using the interfaces defined in this file,
13352** FTS5 may be extended with:
13353**
13354** * custom tokenizers, and
13355** * custom auxiliary functions.
13356*/
13357
13358
13359#ifndef _FTS5_H
13360#define _FTS5_H
13361
13362
13363#if 0
13364extern "C" {
13365#endif
13366
13367/*************************************************************************
13368** CUSTOM AUXILIARY FUNCTIONS
13369**
13370** Virtual table implementations may overload SQL functions by implementing
13371** the sqlite3_module.xFindFunction() method.
13372*/
13373
13374typedef struct Fts5ExtensionApi Fts5ExtensionApi;
13375typedef struct Fts5Context Fts5Context;
13376typedef struct Fts5PhraseIter Fts5PhraseIter;
13377
13378typedef void (*fts5_extension_function)(
13379 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
13380 Fts5Context *pFts, /* First arg to pass to pApi functions */
13381 sqlite3_context *pCtx, /* Context for returning result/error */
13382 int nVal, /* Number of values in apVal[] array */
13383 sqlite3_value **apVal /* Array of trailing arguments */
13384);
13385
13386struct Fts5PhraseIter {
13387 const unsigned char *a;
13388 const unsigned char *b;
13389};
13390
13391/*
13392** EXTENSION API FUNCTIONS
13393**
13394** xUserData(pFts):
13395** Return a copy of the pUserData pointer passed to the xCreateFunction()
13396** API when the extension function was registered.
13397**
13398** xColumnTotalSize(pFts, iCol, pnToken):
13399** If parameter iCol is less than zero, set output variable *pnToken
13400** to the total number of tokens in the FTS5 table. Or, if iCol is
13401** non-negative but less than the number of columns in the table, return
13402** the total number of tokens in column iCol, considering all rows in
13403** the FTS5 table.
13404**
13405** If parameter iCol is greater than or equal to the number of columns
13406** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
13407** an OOM condition or IO error), an appropriate SQLite error code is
13408** returned.
13409**
13410** xColumnCount(pFts):
13411** Return the number of columns in the table.
13412**
13413** xColumnSize(pFts, iCol, pnToken):
13414** If parameter iCol is less than zero, set output variable *pnToken
13415** to the total number of tokens in the current row. Or, if iCol is
13416** non-negative but less than the number of columns in the table, set
13417** *pnToken to the number of tokens in column iCol of the current row.
13418**
13419** If parameter iCol is greater than or equal to the number of columns
13420** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
13421** an OOM condition or IO error), an appropriate SQLite error code is
13422** returned.
13423**
13424** This function may be quite inefficient if used with an FTS5 table
13425** created with the "columnsize=0" option.
13426**
13427** xColumnText:
13428** If parameter iCol is less than zero, or greater than or equal to the
13429** number of columns in the table, SQLITE_RANGE is returned.
13430**
13431** Otherwise, this function attempts to retrieve the text of column iCol of
13432** the current document. If successful, (*pz) is set to point to a buffer
13433** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
13434** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
13435** if an error occurs, an SQLite error code is returned and the final values
13436** of (*pz) and (*pn) are undefined.
13437**
13438** xPhraseCount:
13439** Returns the number of phrases in the current query expression.
13440**
13441** xPhraseSize:
13442** If parameter iCol is less than zero, or greater than or equal to the
13443** number of phrases in the current query, as returned by xPhraseCount,
13444** 0 is returned. Otherwise, this function returns the number of tokens in
13445** phrase iPhrase of the query. Phrases are numbered starting from zero.
13446**
13447** xInstCount:
13448** Set *pnInst to the total number of occurrences of all phrases within
13449** the query within the current row. Return SQLITE_OK if successful, or
13450** an error code (i.e. SQLITE_NOMEM) if an error occurs.
13451**
13452** This API can be quite slow if used with an FTS5 table created with the
13453** "detail=none" or "detail=column" option. If the FTS5 table is created
13454** with either "detail=none" or "detail=column" and "content=" option
13455** (i.e. if it is a contentless table), then this API always returns 0.
13456**
13457** xInst:
13458** Query for the details of phrase match iIdx within the current row.
13459** Phrase matches are numbered starting from zero, so the iIdx argument
13460** should be greater than or equal to zero and smaller than the value
13461** output by xInstCount(). If iIdx is less than zero or greater than
13462** or equal to the value returned by xInstCount(), SQLITE_RANGE is returned.
13463**
13464** Otherwise, output parameter *piPhrase is set to the phrase number, *piCol
13465** to the column in which it occurs and *piOff the token offset of the
13466** first token of the phrase. SQLITE_OK is returned if successful, or an
13467** error code (i.e. SQLITE_NOMEM) if an error occurs.
13468**
13469** This API can be quite slow if used with an FTS5 table created with the
13470** "detail=none" or "detail=column" option.
13471**
13472** xRowid:
13473** Returns the rowid of the current row.
13474**
13475** xTokenize:
13476** Tokenize text using the tokenizer belonging to the FTS5 table.
13477**
13478** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
13479** This API function is used to query the FTS table for phrase iPhrase
13480** of the current query. Specifically, a query equivalent to:
13481**
13482** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
13483**
13484** with $p set to a phrase equivalent to the phrase iPhrase of the
13485** current query is executed. Any column filter that applies to
13486** phrase iPhrase of the current query is included in $p. For each
13487** row visited, the callback function passed as the fourth argument
13488** is invoked. The context and API objects passed to the callback
13489** function may be used to access the properties of each matched row.
13490** Invoking Api.xUserData() returns a copy of the pointer passed as
13491** the third argument to pUserData.
13492**
13493** If parameter iPhrase is less than zero, or greater than or equal to
13494** the number of phrases in the query, as returned by xPhraseCount(),
13495** this function returns SQLITE_RANGE.
13496**
13497** If the callback function returns any value other than SQLITE_OK, the
13498** query is abandoned and the xQueryPhrase function returns immediately.
13499** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
13500** Otherwise, the error code is propagated upwards.
13501**
13502** If the query runs to completion without incident, SQLITE_OK is returned.
13503** Or, if some error occurs before the query completes or is aborted by
13504** the callback, an SQLite error code is returned.
13505**
13506**
13507** xSetAuxdata(pFts5, pAux, xDelete)
13508**
13509** Save the pointer passed as the second argument as the extension function's
13510** "auxiliary data". The pointer may then be retrieved by the current or any
13511** future invocation of the same fts5 extension function made as part of
13512** the same MATCH query using the xGetAuxdata() API.
13513**
13514** Each extension function is allocated a single auxiliary data slot for
13515** each FTS query (MATCH expression). If the extension function is invoked
13516** more than once for a single FTS query, then all invocations share a
13517** single auxiliary data context.
13518**
13519** If there is already an auxiliary data pointer when this function is
13520** invoked, then it is replaced by the new pointer. If an xDelete callback
13521** was specified along with the original pointer, it is invoked at this
13522** point.
13523**
13524** The xDelete callback, if one is specified, is also invoked on the
13525** auxiliary data pointer after the FTS5 query has finished.
13526**
13527** If an error (e.g. an OOM condition) occurs within this function,
13528** the auxiliary data is set to NULL and an error code returned. If the
13529** xDelete parameter was not NULL, it is invoked on the auxiliary data
13530** pointer before returning.
13531**
13532**
13533** xGetAuxdata(pFts5, bClear)
13534**
13535** Returns the current auxiliary data pointer for the fts5 extension
13536** function. See the xSetAuxdata() method for details.
13537**
13538** If the bClear argument is non-zero, then the auxiliary data is cleared
13539** (set to NULL) before this function returns. In this case the xDelete,
13540** if any, is not invoked.
13541**
13542**
13543** xRowCount(pFts5, pnRow)
13544**
13545** This function is used to retrieve the total number of rows in the table.
13546** In other words, the same value that would be returned by:
13547**
13548** SELECT count(*) FROM ftstable;
13549**
13550** xPhraseFirst()
13551** This function is used, along with type Fts5PhraseIter and the xPhraseNext
13552** method, to iterate through all instances of a single query phrase within
13553** the current row. This is the same information as is accessible via the
13554** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
13555** to use, this API may be faster under some circumstances. To iterate
13556** through instances of phrase iPhrase, use the following code:
13557**
13558** Fts5PhraseIter iter;
13559** int iCol, iOff;
13560** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
13561** iCol>=0;
13562** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
13563** ){
13564** // An instance of phrase iPhrase at offset iOff of column iCol
13565** }
13566**
13567** The Fts5PhraseIter structure is defined above. Applications should not
13568** modify this structure directly - it should only be used as shown above
13569** with the xPhraseFirst() and xPhraseNext() API methods (and by
13570** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
13571**
13572** This API can be quite slow if used with an FTS5 table created with the
13573** "detail=none" or "detail=column" option. If the FTS5 table is created
13574** with either "detail=none" or "detail=column" and "content=" option
13575** (i.e. if it is a contentless table), then this API always iterates
13576** through an empty set (all calls to xPhraseFirst() set iCol to -1).
13577**
13578** In all cases, matches are visited in (column ASC, offset ASC) order.
13579** i.e. all those in column 0, sorted by offset, followed by those in
13580** column 1, etc.
13581**
13582** xPhraseNext()
13583** See xPhraseFirst above.
13584**
13585** xPhraseFirstColumn()
13586** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
13587** and xPhraseNext() APIs described above. The difference is that instead
13588** of iterating through all instances of a phrase in the current row, these
13589** APIs are used to iterate through the set of columns in the current row
13590** that contain one or more instances of a specified phrase. For example:
13591**
13592** Fts5PhraseIter iter;
13593** int iCol;
13594** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
13595** iCol>=0;
13596** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
13597** ){
13598** // Column iCol contains at least one instance of phrase iPhrase
13599** }
13600**
13601** This API can be quite slow if used with an FTS5 table created with the
13602** "detail=none" option. If the FTS5 table is created with either
13603** "detail=none" "content=" option (i.e. if it is a contentless table),
13604** then this API always iterates through an empty set (all calls to
13605** xPhraseFirstColumn() set iCol to -1).
13606**
13607** The information accessed using this API and its companion
13608** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
13609** (or xInst/xInstCount). The chief advantage of this API is that it is
13610** significantly more efficient than those alternatives when used with
13611** "detail=column" tables.
13612**
13613** xPhraseNextColumn()
13614** See xPhraseFirstColumn above.
13615**
13616** xQueryToken(pFts5, iPhrase, iToken, ppToken, pnToken)
13617** This is used to access token iToken of phrase iPhrase of the current
13618** query. Before returning, output parameter *ppToken is set to point
13619** to a buffer containing the requested token, and *pnToken to the
13620** size of this buffer in bytes.
13621**
13622** If iPhrase or iToken are less than zero, or if iPhrase is greater than
13623** or equal to the number of phrases in the query as reported by
13624** xPhraseCount(), or if iToken is equal to or greater than the number of
13625** tokens in the phrase, SQLITE_RANGE is returned and *ppToken and *pnToken
13626 are both zeroed.
13627**
13628** The output text is not a copy of the query text that specified the
13629** token. It is the output of the tokenizer module. For tokendata=1
13630** tables, this includes any embedded 0x00 and trailing data.
13631**
13632** xInstToken(pFts5, iIdx, iToken, ppToken, pnToken)
13633** This is used to access token iToken of phrase hit iIdx within the
13634** current row. If iIdx is less than zero or greater than or equal to the
13635** value returned by xInstCount(), SQLITE_RANGE is returned. Otherwise,
13636** output variable (*ppToken) is set to point to a buffer containing the
13637** matching document token, and (*pnToken) to the size of that buffer in
13638** bytes.
13639**
13640** The output text is not a copy of the document text that was tokenized.
13641** It is the output of the tokenizer module. For tokendata=1 tables, this
13642** includes any embedded 0x00 and trailing data.
13643**
13644** This API may be slow in some cases if the token identified by parameters
13645** iIdx and iToken matched a prefix token in the query. In most cases, the
13646** first call to this API for each prefix token in the query is forced
13647** to scan the portion of the full-text index that matches the prefix
13648** token to collect the extra data required by this API. If the prefix
13649** token matches a large number of token instances in the document set,
13650** this may be a performance problem.
13651**
13652** If the user knows in advance that a query may use this API for a
13653** prefix token, FTS5 may be configured to collect all required data as part
13654** of the initial querying of the full-text index, avoiding the second scan
13655** entirely. This also causes prefix queries that do not use this API to
13656** run more slowly and use more memory. FTS5 may be configured in this way
13657** either on a per-table basis using the [FTS5 insttoken | 'insttoken']
13658** option, or on a per-query basis using the
13659** [fts5_insttoken | fts5_insttoken()] user function.
13660**
13661** This API can be quite slow if used with an FTS5 table created with the
13662** "detail=none" or "detail=column" option.
13663**
13664** xColumnLocale(pFts5, iIdx, pzLocale, pnLocale)
13665** If parameter iCol is less than zero, or greater than or equal to the
13666** number of columns in the table, SQLITE_RANGE is returned.
13667**
13668** Otherwise, this function attempts to retrieve the locale associated
13669** with column iCol of the current row. Usually, there is no associated
13670** locale, and output parameters (*pzLocale) and (*pnLocale) are set
13671** to NULL and 0, respectively. However, if the fts5_locale() function
13672** was used to associate a locale with the value when it was inserted
13673** into the fts5 table, then (*pzLocale) is set to point to a nul-terminated
13674** buffer containing the name of the locale in utf-8 encoding. (*pnLocale)
13675** is set to the size in bytes of the buffer, not including the
13676** nul-terminator.
13677**
13678** If successful, SQLITE_OK is returned. Or, if an error occurs, an
13679** SQLite error code is returned. The final value of the output parameters
13680** is undefined in this case.
13681**
13682** xTokenize_v2:
13683** Tokenize text using the tokenizer belonging to the FTS5 table. This
13684** API is the same as the xTokenize() API, except that it allows a tokenizer
13685** locale to be specified.
13686*/
13687struct Fts5ExtensionApi {
13688 int iVersion; /* Currently always set to 4 */
13689
13690 void *(*xUserData)(Fts5Context*);
13691
13692 int (*xColumnCount)(Fts5Context*);
13693 int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
13694 int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
13695
13696 int (*xTokenize)(Fts5Context*,
13697 const char *pText, int nText, /* Text to tokenize */
13698 void *pCtx, /* Context passed to xToken() */
13699 int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
13700 );
13701
13702 int (*xPhraseCount)(Fts5Context*);
13703 int (*xPhraseSize)(Fts5Context*, int iPhrase);
13704
13705 int (*xInstCount)(Fts5Context*, int *pnInst);
13706 int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
13707
13708 sqlite3_int64 (*xRowid)(Fts5Context*);
13709 int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
13710 int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
13711
13712 int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
13713 int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
13714 );
13715 int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
13716 void *(*xGetAuxdata)(Fts5Context*, int bClear);
13717
13718 int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
13719 void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
13720
13721 int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
13722 void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
13723
13724 /* Below this point are iVersion>=3 only */
13725 int (*xQueryToken)(Fts5Context*,
13726 int iPhrase, int iToken,
13727 const char **ppToken, int *pnToken
13728 );
13729 int (*xInstToken)(Fts5Context*, int iIdx, int iToken, const char**, int*);
13730
13731 /* Below this point are iVersion>=4 only */
13732 int (*xColumnLocale)(Fts5Context*, int iCol, const char **pz, int *pn);
13733 int (*xTokenize_v2)(Fts5Context*,
13734 const char *pText, int nText, /* Text to tokenize */
13735 const char *pLocale, int nLocale, /* Locale to pass to tokenizer */
13736 void *pCtx, /* Context passed to xToken() */
13737 int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
13738 );
13739};
13740
13741/*
13742** CUSTOM AUXILIARY FUNCTIONS
13743*************************************************************************/
13744
13745/*************************************************************************
13746** CUSTOM TOKENIZERS
13747**
13748** Applications may also register custom tokenizer types. A tokenizer
13749** is registered by providing fts5 with a populated instance of the
13750** following structure. All structure methods must be defined, setting
13751** any member of the fts5_tokenizer struct to NULL leads to undefined
13752** behaviour. The structure methods are expected to function as follows:
13753**
13754** xCreate:
13755** This function is used to allocate and initialize a tokenizer instance.
13756** A tokenizer instance is required to actually tokenize text.
13757**
13758** The first argument passed to this function is a copy of the (void*)
13759** pointer provided by the application when the fts5_tokenizer_v2 object
13760** was registered with FTS5 (the third argument to xCreateTokenizer()).
13761** The second and third arguments are an array of nul-terminated strings
13762** containing the tokenizer arguments, if any, specified following the
13763** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
13764** to create the FTS5 table.
13765**
13766** The final argument is an output variable. If successful, (*ppOut)
13767** should be set to point to the new tokenizer handle and SQLITE_OK
13768** returned. If an error occurs, some value other than SQLITE_OK should
13769** be returned. In this case, fts5 assumes that the final value of *ppOut
13770** is undefined.
13771**
13772** xDelete:
13773** This function is invoked to delete a tokenizer handle previously
13774** allocated using xCreate(). Fts5 guarantees that this function will
13775** be invoked exactly once for each successful call to xCreate().
13776**
13777** xTokenize:
13778** This function is expected to tokenize the nText byte string indicated
13779** by argument pText. pText may or may not be nul-terminated. The first
13780** argument passed to this function is a pointer to an Fts5Tokenizer object
13781** returned by an earlier call to xCreate().
13782**
13783** The third argument indicates the reason that FTS5 is requesting
13784** tokenization of the supplied text. This is always one of the following
13785** four values:
13786**
13787** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
13788** or removed from the FTS table. The tokenizer is being invoked to
13789** determine the set of tokens to add to (or delete from) the
13790** FTS index.
13791**
13792** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
13793** against the FTS index. The tokenizer is being called to tokenize
13794** a bareword or quoted string specified as part of the query.
13795**
13796** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
13797** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
13798** followed by a "*" character, indicating that the last token
13799** returned by the tokenizer will be treated as a token prefix.
13800**
13801** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
13802** satisfy an fts5_api.xTokenize() request made by an auxiliary
13803** function. Or an fts5_api.xColumnSize() request made by the same
13804** on a columnsize=0 database.
13805** </ul>
13806**
13807** The sixth and seventh arguments passed to xTokenize() - pLocale and
13808** nLocale - are a pointer to a buffer containing the locale to use for
13809** tokenization (e.g. "en_US") and its size in bytes, respectively. The
13810** pLocale buffer is not nul-terminated. pLocale may be passed NULL (in
13811** which case nLocale is always 0) to indicate that the tokenizer should
13812** use its default locale.
13813**
13814** For each token in the input string, the supplied callback xToken() must
13815** be invoked. The first argument to it should be a copy of the pointer
13816** passed as the second argument to xTokenize(). The third and fourth
13817** arguments are a pointer to a buffer containing the token text, and the
13818** size of the token in bytes. The 4th and 5th arguments are the byte offsets
13819** of the first byte of and first byte immediately following the text from
13820** which the token is derived within the input.
13821**
13822** The second argument passed to the xToken() callback ("tflags") should
13823** normally be set to 0. The exception is if the tokenizer supports
13824** synonyms. In this case see the discussion below for details.
13825**
13826** FTS5 assumes the xToken() callback is invoked for each token in the
13827** order that they occur within the input text.
13828**
13829** If an xToken() callback returns any value other than SQLITE_OK, then
13830** the tokenization should be abandoned and the xTokenize() method should
13831** immediately return a copy of the xToken() return value. Or, if the
13832** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
13833** if an error occurs with the xTokenize() implementation itself, it
13834** may abandon the tokenization and return any error code other than
13835** SQLITE_OK or SQLITE_DONE.
13836**
13837** If the tokenizer is registered using an fts5_tokenizer_v2 object,
13838** then the xTokenize() method has two additional arguments - pLocale
13839** and nLocale. These specify the locale that the tokenizer should use
13840** for the current request. If pLocale and nLocale are both 0, then the
13841** tokenizer should use its default locale. Otherwise, pLocale points to
13842** an nLocale byte buffer containing the name of the locale to use as utf-8
13843** text. pLocale is not nul-terminated.
13844**
13845** FTS5_TOKENIZER
13846**
13847** There is also an fts5_tokenizer object. This is an older, deprecated,
13848** version of fts5_tokenizer_v2. It is similar except that:
13849**
13850** <ul>
13851** <li> There is no "iVersion" field, and
13852** <li> The xTokenize() method does not take a locale argument.
13853** </ul>
13854**
13855** Legacy fts5_tokenizer tokenizers must be registered using the
13856** legacy xCreateTokenizer() function, instead of xCreateTokenizer_v2().
13857**
13858** Tokenizer implementations registered using either API may be retrieved
13859** using both xFindTokenizer() and xFindTokenizer_v2().
13860**
13861** SYNONYM SUPPORT
13862**
13863** Custom tokenizers may also support synonyms. Consider a case in which a
13864** user wishes to query for a phrase such as "first place". Using the
13865** built-in tokenizers, the FTS5 query 'first + place' will match instances
13866** of "first place" within the document set, but not alternative forms
13867** such as "1st place". In some applications, it would be better to match
13868** all instances of "first place" or "1st place" regardless of which form
13869** the user specified in the MATCH query text.
13870**
13871** There are several ways to approach this in FTS5:
13872**
13873** <ol><li> By mapping all synonyms to a single token. In this case, using
13874** the above example, this means that the tokenizer returns the
13875** same token for inputs "first" and "1st". Say that token is in
13876** fact "first", so that when the user inserts the document "I won
13877** 1st place" entries are added to the index for tokens "i", "won",
13878** "first" and "place". If the user then queries for '1st + place',
13879** the tokenizer substitutes "first" for "1st" and the query works
13880** as expected.
13881**
13882** <li> By querying the index for all synonyms of each query term
13883** separately. In this case, when tokenizing query text, the
13884** tokenizer may provide multiple synonyms for a single term
13885** within the document. FTS5 then queries the index for each
13886** synonym individually. For example, faced with the query:
13887**
13888** <codeblock>
13889** ... MATCH 'first place'</codeblock>
13890**
13891** the tokenizer offers both "1st" and "first" as synonyms for the
13892** first token in the MATCH query and FTS5 effectively runs a query
13893** similar to:
13894**
13895** <codeblock>
13896** ... MATCH '(first OR 1st) place'</codeblock>
13897**
13898** except that, for the purposes of auxiliary functions, the query
13899** still appears to contain just two phrases - "(first OR 1st)"
13900** being treated as a single phrase.
13901**
13902** <li> By adding multiple synonyms for a single term to the FTS index.
13903** Using this method, when tokenizing document text, the tokenizer
13904** provides multiple synonyms for each token. So that when a
13905** document such as "I won first place" is tokenized, entries are
13906** added to the FTS index for "i", "won", "first", "1st" and
13907** "place".
13908**
13909** This way, even if the tokenizer does not provide synonyms
13910** when tokenizing query text (it should not - to do so would be
13911** inefficient), it doesn't matter if the user queries for
13912** 'first + place' or '1st + place', as there are entries in the
13913** FTS index corresponding to both forms of the first token.
13914** </ol>
13915**
13916** Whether it is parsing document or query text, any call to xToken that
13917** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
13918** is considered to supply a synonym for the previous token. For example,
13919** when parsing the document "I won first place", a tokenizer that supports
13920** synonyms would call xToken() 5 times, as follows:
13921**
13922** <codeblock>
13923** xToken(pCtx, 0, "i", 1, 0, 1);
13924** xToken(pCtx, 0, "won", 3, 2, 5);
13925** xToken(pCtx, 0, "first", 5, 6, 11);
13926** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
13927** xToken(pCtx, 0, "place", 5, 12, 17);
13928**</codeblock>
13929**
13930** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
13931** xToken() is called. Multiple synonyms may be specified for a single token
13932** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
13933** There is no limit to the number of synonyms that may be provided for a
13934** single token.
13935**
13936** In many cases, method (1) above is the best approach. It does not add
13937** extra data to the FTS index or require FTS5 to query for multiple terms,
13938** so it is efficient in terms of disk space and query speed. However, it
13939** does not support prefix queries very well. If, as suggested above, the
13940** token "first" is substituted for "1st" by the tokenizer, then the query:
13941**
13942** <codeblock>
13943** ... MATCH '1s*'</codeblock>
13944**
13945** will not match documents that contain the token "1st" (as the tokenizer
13946** will probably not map "1s" to any prefix of "first").
13947**
13948** For full prefix support, method (3) may be preferred. In this case,
13949** because the index contains entries for both "first" and "1st", prefix
13950** queries such as 'fi*' or '1s*' will match correctly. However, because
13951** extra entries are added to the FTS index, this method uses more space
13952** within the database.
13953**
13954** Method (2) offers a midpoint between (1) and (3). Using this method,
13955** a query such as '1s*' will match documents that contain the literal
13956** token "1st", but not "first" (assuming the tokenizer is not able to
13957** provide synonyms for prefixes). However, a non-prefix query like '1st'
13958** will match against "1st" and "first". This method does not require
13959** extra disk space, as no extra entries are added to the FTS index.
13960** On the other hand, it may require more CPU cycles to run MATCH queries,
13961** as separate queries of the FTS index are required for each synonym.
13962**
13963** When using methods (2) or (3), it is important that the tokenizer only
13964** provide synonyms when tokenizing document text (method (3)) or query
13965** text (method (2)), not both. Doing so will not cause any errors, but is
13966** inefficient.
13967*/
13968typedef struct Fts5Tokenizer Fts5Tokenizer;
13969typedef struct fts5_tokenizer_v2 fts5_tokenizer_v2;
13970struct fts5_tokenizer_v2 {
13971 int iVersion; /* Currently always 2 */
13972
13973 int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
13974 void (*xDelete)(Fts5Tokenizer*);
13975 int (*xTokenize)(Fts5Tokenizer*,
13976 void *pCtx,
13977 int flags, /* Mask of FTS5_TOKENIZE_* flags */
13978 const char *pText, int nText,
13979 const char *pLocale, int nLocale,
13980 int (*xToken)(
13981 void *pCtx, /* Copy of 2nd argument to xTokenize() */
13982 int tflags, /* Mask of FTS5_TOKEN_* flags */
13983 const char *pToken, /* Pointer to buffer containing token */
13984 int nToken, /* Size of token in bytes */
13985 int iStart, /* Byte offset of token within input text */
13986 int iEnd /* Byte offset of end of token within input text */
13987 )
13988 );
13989};
13990
13991/*
13992** New code should use the fts5_tokenizer_v2 type to define tokenizer
13993** implementations. The following type is included for legacy applications
13994** that still use it.
13995*/
13996typedef struct fts5_tokenizer fts5_tokenizer;
13997struct fts5_tokenizer {
13998 int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
13999 void (*xDelete)(Fts5Tokenizer*);
14000 int (*xTokenize)(Fts5Tokenizer*,
14001 void *pCtx,
14002 int flags, /* Mask of FTS5_TOKENIZE_* flags */
14003 const char *pText, int nText,
14004 int (*xToken)(
14005 void *pCtx, /* Copy of 2nd argument to xTokenize() */
14006 int tflags, /* Mask of FTS5_TOKEN_* flags */
14007 const char *pToken, /* Pointer to buffer containing token */
14008 int nToken, /* Size of token in bytes */
14009 int iStart, /* Byte offset of token within input text */
14010 int iEnd /* Byte offset of end of token within input text */
14011 )
14012 );
14013};
14014
14015
14016/* Flags that may be passed as the third argument to xTokenize() */
14017#define FTS5_TOKENIZE_QUERY0x0001 0x0001
14018#define FTS5_TOKENIZE_PREFIX0x0002 0x0002
14019#define FTS5_TOKENIZE_DOCUMENT0x0004 0x0004
14020#define FTS5_TOKENIZE_AUX0x0008 0x0008
14021
14022/* Flags that may be passed by the tokenizer implementation back to FTS5
14023** as the third argument to the supplied xToken callback. */
14024#define FTS5_TOKEN_COLOCATED0x0001 0x0001 /* Same position as prev. token */
14025
14026/*
14027** END OF CUSTOM TOKENIZERS
14028*************************************************************************/
14029
14030/*************************************************************************
14031** FTS5 EXTENSION REGISTRATION API
14032*/
14033typedef struct fts5_api fts5_api;
14034struct fts5_api {
14035 int iVersion; /* Currently always set to 3 */
14036
14037 /* Create a new tokenizer */
14038 int (*xCreateTokenizer)(
14039 fts5_api *pApi,
14040 const char *zName,
14041 void *pUserData,
14042 fts5_tokenizer *pTokenizer,
14043 void (*xDestroy)(void*)
14044 );
14045
14046 /* Find an existing tokenizer */
14047 int (*xFindTokenizer)(
14048 fts5_api *pApi,
14049 const char *zName,
14050 void **ppUserData,
14051 fts5_tokenizer *pTokenizer
14052 );
14053
14054 /* Create a new auxiliary function */
14055 int (*xCreateFunction)(
14056 fts5_api *pApi,
14057 const char *zName,
14058 void *pUserData,
14059 fts5_extension_function xFunction,
14060 void (*xDestroy)(void*)
14061 );
14062
14063 /* APIs below this point are only available if iVersion>=3 */
14064
14065 /* Create a new tokenizer */
14066 int (*xCreateTokenizer_v2)(
14067 fts5_api *pApi,
14068 const char *zName,
14069 void *pUserData,
14070 fts5_tokenizer_v2 *pTokenizer,
14071 void (*xDestroy)(void*)
14072 );
14073
14074 /* Find an existing tokenizer */
14075 int (*xFindTokenizer_v2)(
14076 fts5_api *pApi,
14077 const char *zName,
14078 void **ppUserData,
14079 fts5_tokenizer_v2 **ppTokenizer
14080 );
14081};
14082
14083/*
14084** END OF REGISTRATION API
14085*************************************************************************/
14086
14087#if 0
14088} /* end of the 'extern "C"' block */
14089#endif
14090
14091#endif /* _FTS5_H */
14092
14093/******** End of fts5.h *********/
14094#endif /* SQLITE3_H */
14095
14096/************** End of sqlite3.h *********************************************/
14097/************** Continuing where we left off in sqliteInt.h ******************/
14098
14099/*
14100** Reuse the STATIC_LRU for mutex access to sqlite3_temp_directory.
14101*/
14102#define SQLITE_MUTEX_STATIC_TEMPDIR11 SQLITE_MUTEX_STATIC_VFS111
14103
14104/*
14105** Include the configuration header output by 'configure' if we're using the
14106** autoconf-based build
14107*/
14108#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
14109#include "sqlite_cfg.h"
14110#define SQLITECONFIG_H 1
14111#endif
14112
14113/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
14114/************** Begin file sqliteLimit.h *************************************/
14115/*
14116** 2007 May 7
14117**
14118** The author disclaims copyright to this source code. In place of
14119** a legal notice, here is a blessing:
14120**
14121** May you do good and not evil.
14122** May you find forgiveness for yourself and forgive others.
14123** May you share freely, never taking more than you give.
14124**
14125*************************************************************************
14126**
14127** This file defines various limits of what SQLite can process.
14128*/
14129
14130/*
14131** The maximum length of a TEXT or BLOB in bytes. This also
14132** limits the size of a row in a table or index.
14133**
14134** The hard limit is the ability of a 32-bit signed integer
14135** to count the size: 2^31-1 or 2147483647.
14136*/
14137#ifndef SQLITE_MAX_LENGTH2147483645
14138# define SQLITE_MAX_LENGTH2147483645 1000000000
14139#endif
14140#define SQLITE_MIN_LENGTH30 30 /* Minimum value for the length limit */
14141
14142/*
14143** This is the maximum number of
14144**
14145** * Columns in a table
14146** * Columns in an index
14147** * Columns in a view
14148** * Terms in the SET clause of an UPDATE statement
14149** * Terms in the result set of a SELECT statement
14150** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
14151** * Terms in the VALUES clause of an INSERT statement
14152**
14153** The hard upper limit here is 32767. Most database people will
14154** tell you that in a well-normalized database, you usually should
14155** not have more than a dozen or so columns in any table. And if
14156** that is the case, there is no point in having more than a few
14157** dozen values in any of the other situations described above.
14158**
14159** An index can only have SQLITE_MAX_COLUMN columns from the user
14160** point of view, but the underlying b-tree that implements the index
14161** might have up to twice as many columns in a WITHOUT ROWID table,
14162** since must also store the primary key at the end. Hence the
14163** column count for Index is u16 instead of i16.
14164*/
14165#if !defined(SQLITE_MAX_COLUMN2000)
14166# define SQLITE_MAX_COLUMN2000 2000
14167#elif SQLITE_MAX_COLUMN2000>32767
14168# error SQLITE_MAX_COLUMN2000 may not exceed 32767
14169#endif
14170
14171/*
14172** The maximum length of a single SQL statement in bytes.
14173**
14174** It used to be the case that setting this value to zero would
14175** turn the limit off. That is no longer true. It is not possible
14176** to turn this limit off.
14177*/
14178#ifndef SQLITE_MAX_SQL_LENGTH1000000000
14179# define SQLITE_MAX_SQL_LENGTH1000000000 1000000000
14180#endif
14181
14182/*
14183** The maximum depth of an expression tree. This is limited to
14184** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
14185** want to place more severe limits on the complexity of an
14186** expression. A value of 0 means that there is no limit.
14187*/
14188#ifndef SQLITE_MAX_EXPR_DEPTH1000
14189# define SQLITE_MAX_EXPR_DEPTH1000 1000
14190#endif
14191
14192/*
14193** The maximum number of terms in a compound SELECT statement.
14194** The code generator for compound SELECT statements does one
14195** level of recursion for each term. A stack overflow can result
14196** if the number of terms is too large. In practice, most SQL
14197** never has more than 3 or 4 terms. Use a value of 0 to disable
14198** any limit on the number of terms in a compound SELECT.
14199*/
14200#ifndef SQLITE_MAX_COMPOUND_SELECT500
14201# define SQLITE_MAX_COMPOUND_SELECT500 500
14202#endif
14203
14204/*
14205** The maximum number of opcodes in a VDBE program.
14206** Not currently enforced.
14207*/
14208#ifndef SQLITE_MAX_VDBE_OP250000000
14209# define SQLITE_MAX_VDBE_OP250000000 250000000
14210#endif
14211
14212/*
14213** The maximum number of arguments to an SQL function.
14214**
14215** This value has a hard upper limit of 32767 due to storage
14216** constraints (it needs to fit inside a i16). We keep it
14217** lower than that to prevent abuse.
14218*/
14219#ifndef SQLITE_MAX_FUNCTION_ARG1000
14220# define SQLITE_MAX_FUNCTION_ARG1000 1000
14221#endif
14222
14223/*
14224** The suggested maximum number of in-memory pages to use for
14225** the main database table and for temporary tables.
14226**
14227** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
14228** which means the cache size is limited to 2048000 bytes of memory.
14229** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
14230** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
14231*/
14232#ifndef SQLITE_DEFAULT_CACHE_SIZE128
14233# define SQLITE_DEFAULT_CACHE_SIZE128 -2000
14234#endif
14235
14236/*
14237** The default number of frames to accumulate in the log file before
14238** checkpointing the database in WAL mode.
14239*/
14240#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT1000
14241# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT1000 1000
14242#endif
14243
14244/*
14245** The maximum number of attached databases. This must be between 0
14246** and 125. The upper bound of 125 is because the attached databases are
14247** counted using a signed 8-bit integer which has a maximum value of 127
14248** and we have to allow 2 extra counts for the "main" and "temp" databases.
14249*/
14250#ifndef SQLITE_MAX_ATTACHED10
14251# define SQLITE_MAX_ATTACHED10 10
14252#endif
14253
14254
14255/*
14256** The maximum value of a ?nnn wildcard that the parser will accept.
14257** If the value exceeds 32767 then extra space is required for the Expr
14258** structure. But otherwise, we believe that the number can be as large
14259** as a signed 32-bit integer can hold.
14260*/
14261#ifndef SQLITE_MAX_VARIABLE_NUMBER500000
14262# define SQLITE_MAX_VARIABLE_NUMBER500000 32766
14263#endif
14264
14265/* Maximum page size. The upper bound on this value is 65536. This a limit
14266** imposed by the use of 16-bit offsets within each page.
14267**
14268** Earlier versions of SQLite allowed the user to change this value at
14269** compile time. This is no longer permitted, on the grounds that it creates
14270** a library that is technically incompatible with an SQLite library
14271** compiled with a different limit. If a process operating on a database
14272** with a page-size of 65536 bytes crashes, then an instance of SQLite
14273** compiled with the default page-size limit will not be able to rollback
14274** the aborted transaction. This could lead to database corruption.
14275*/
14276#ifdef SQLITE_MAX_PAGE_SIZE65536
14277# undef SQLITE_MAX_PAGE_SIZE65536
14278#endif
14279#define SQLITE_MAX_PAGE_SIZE65536 65536
14280
14281
14282/*
14283** The default size of a database page.
14284*/
14285#ifndef SQLITE_DEFAULT_PAGE_SIZE4096
14286# define SQLITE_DEFAULT_PAGE_SIZE4096 4096
14287#endif
14288#if SQLITE_DEFAULT_PAGE_SIZE4096>SQLITE_MAX_PAGE_SIZE65536
14289# undef SQLITE_DEFAULT_PAGE_SIZE4096
14290# define SQLITE_DEFAULT_PAGE_SIZE4096 SQLITE_MAX_PAGE_SIZE65536
14291#endif
14292
14293/*
14294** Ordinarily, if no value is explicitly provided, SQLite creates databases
14295** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
14296** device characteristics (sector-size and atomic write() support),
14297** SQLite may choose a larger value. This constant is the maximum value
14298** SQLite will choose on its own.
14299*/
14300#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE8192
14301# define SQLITE_MAX_DEFAULT_PAGE_SIZE8192 8192
14302#endif
14303#if SQLITE_MAX_DEFAULT_PAGE_SIZE8192>SQLITE_MAX_PAGE_SIZE65536
14304# undef SQLITE_MAX_DEFAULT_PAGE_SIZE8192
14305# define SQLITE_MAX_DEFAULT_PAGE_SIZE8192 SQLITE_MAX_PAGE_SIZE65536
14306#endif
14307
14308
14309/*
14310** Maximum number of pages in one database file.
14311**
14312** This is really just the default value for the max_page_count pragma.
14313** This value can be lowered (or raised) at run-time using that the
14314** max_page_count macro.
14315*/
14316#ifndef SQLITE_MAX_PAGE_COUNT0xfffffffe
14317# define SQLITE_MAX_PAGE_COUNT0xfffffffe 0xfffffffe /* 4294967294 */
14318#endif
14319
14320/*
14321** Maximum length (in bytes) of the pattern in a LIKE or GLOB
14322** operator.
14323*/
14324#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH50000
14325# define SQLITE_MAX_LIKE_PATTERN_LENGTH50000 50000
14326#endif
14327
14328/*
14329** Maximum depth of recursion for triggers.
14330**
14331** A value of 1 means that a trigger program will not be able to itself
14332** fire any triggers. A value of 0 means that no trigger programs at all
14333** may be executed.
14334*/
14335#ifndef SQLITE_MAX_TRIGGER_DEPTH1000
14336# define SQLITE_MAX_TRIGGER_DEPTH1000 1000
14337#endif
14338
14339/************** End of sqliteLimit.h *****************************************/
14340/************** Continuing where we left off in sqliteInt.h ******************/
14341
14342/* Disable nuisance warnings on Borland compilers */
14343#if defined(__BORLANDC__)
14344#pragma warn -rch /* unreachable code */
14345#pragma warn -ccc /* Condition is always true or false */
14346#pragma warn -aus /* Assigned value is never used */
14347#pragma warn -csu /* Comparing signed and unsigned */
14348#pragma warn -spa /* Suspicious pointer arithmetic */
14349#endif
14350
14351/*
14352** A few places in the code require atomic load/store of aligned
14353** integer values.
14354*/
14355#ifndef __has_extension
14356# define0 __has_extension(x)0 0 /* compatibility with non-clang compilers */
14357#endif
14358#if GCC_VERSION(4*1000000+2*1000+1)>=4007000 || __has_extension(c_atomic)1
14359# define SQLITE_ATOMIC_INTRINSICS1 1
14360# define AtomicLoad(PTR)__atomic_load_n((PTR),0) __atomic_load_n((PTR),__ATOMIC_RELAXED0)
14361# define AtomicStore(PTR,VAL)__atomic_store_n((PTR),(VAL),0) __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED0)
14362#else
14363# define SQLITE_ATOMIC_INTRINSICS1 0
14364# define AtomicLoad(PTR)__atomic_load_n((PTR),0) (*(PTR))
14365# define AtomicStore(PTR,VAL)__atomic_store_n((PTR),(VAL),0) (*(PTR) = (VAL))
14366#endif
14367
14368/*
14369** Include standard header files as necessary
14370*/
14371#ifdef HAVE_STDINT_H
14372#include <stdint.h>
14373#endif
14374#ifdef HAVE_INTTYPES_H
14375#include <inttypes.h>
14376#endif
14377
14378/*
14379** The following macros are used to cast pointers to integers and
14380** integers to pointers. The way you do this varies from one compiler
14381** to the next, so we have developed the following set of #if statements
14382** to generate appropriate macros for a wide range of compilers.
14383**
14384** The correct "ANSI" way to do this is to use the intptr_t type.
14385** Unfortunately, that typedef is not available on all compilers, or
14386** if it is available, it requires an #include of specific headers
14387** that vary from one machine to the next.
14388**
14389** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
14390** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
14391** So we have to define the macros in different ways depending on the
14392** compiler.
14393*/
14394#if defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
14395# define SQLITE_INT_TO_PTR(X)((void*)(long int)(X)) ((void*)(intptr_t)(X))
14396# define SQLITE_PTR_TO_INT(X)((int)(long int)(X)) ((int)(intptr_t)(X))
14397#elif defined(__PTRDIFF_TYPE__long int) /* This case should work for GCC */
14398# define SQLITE_INT_TO_PTR(X)((void*)(long int)(X)) ((void*)(__PTRDIFF_TYPE__long int)(X))
14399# define SQLITE_PTR_TO_INT(X)((int)(long int)(X)) ((int)(__PTRDIFF_TYPE__long int)(X))
14400#elif !defined(__GNUC__4) /* Works for compilers other than LLVM */
14401# define SQLITE_INT_TO_PTR(X)((void*)(long int)(X)) ((void*)&((char*)0)[X])
14402# define SQLITE_PTR_TO_INT(X)((int)(long int)(X)) ((int)(((char*)X)-(char*)0))
14403#else /* Generates a warning - but it always works */
14404# define SQLITE_INT_TO_PTR(X)((void*)(long int)(X)) ((void*)(X))
14405# define SQLITE_PTR_TO_INT(X)((int)(long int)(X)) ((int)(X))
14406#endif
14407
14408/*
14409** Macros to hint to the compiler that a function should or should not be
14410** inlined.
14411*/
14412#if defined(__GNUC__4)
14413# define SQLITE_NOINLINE__attribute__((noinline)) __attribute__((noinline))
14414# define SQLITE_INLINE__attribute__((always_inline)) inline __attribute__((always_inline)) inline
14415#elif defined(_MSC_VER) && _MSC_VER>=1310
14416# define SQLITE_NOINLINE__attribute__((noinline)) __declspec(noinline)
14417# define SQLITE_INLINE__attribute__((always_inline)) inline __forceinline
14418#else
14419# define SQLITE_NOINLINE__attribute__((noinline))
14420# define SQLITE_INLINE__attribute__((always_inline)) inline
14421#endif
14422#if defined(SQLITE_COVERAGE_TEST) || defined(__STRICT_ANSI__)
14423# undef SQLITE_INLINE__attribute__((always_inline)) inline
14424# define SQLITE_INLINE__attribute__((always_inline)) inline
14425#endif
14426
14427/*
14428** Make sure that the compiler intrinsics we desire are enabled when
14429** compiling with an appropriate version of MSVC unless prevented by
14430** the SQLITE_DISABLE_INTRINSIC define.
14431*/
14432#if !defined(SQLITE_DISABLE_INTRINSIC)
14433# if defined(_MSC_VER) && _MSC_VER>=1400
14434# if !defined(_WIN32_WCE)
14435# include <intrin.h>
14436# pragma intrinsic(_byteswap_ushort)
14437# pragma intrinsic(_byteswap_ulong)
14438# pragma intrinsic(_byteswap_uint64)
14439# pragma intrinsic(_ReadWriteBarrier)
14440# else
14441# include <cmnintrin.h>
14442# endif
14443# endif
14444#endif
14445
14446/*
14447** Enable SQLITE_USE_SEH by default on MSVC builds. Only omit
14448** SEH support if the -DSQLITE_OMIT_SEH option is given.
14449*/
14450#if defined(_MSC_VER) && !defined(SQLITE_OMIT_SEH)
14451# define SQLITE_USE_SEH 1
14452#else
14453# undef SQLITE_USE_SEH
14454#endif
14455
14456/*
14457** Enable SQLITE_DIRECT_OVERFLOW_READ, unless the build explicitly
14458** disables it using -DSQLITE_DIRECT_OVERFLOW_READ=0
14459*/
14460#if defined(SQLITE_DIRECT_OVERFLOW_READ1) && SQLITE_DIRECT_OVERFLOW_READ1+1==1
14461 /* Disable if -DSQLITE_DIRECT_OVERFLOW_READ=0 */
14462# undef SQLITE_DIRECT_OVERFLOW_READ1
14463#else
14464 /* In all other cases, enable */
14465# define SQLITE_DIRECT_OVERFLOW_READ1 1
14466#endif
14467
14468
14469/*
14470** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
14471** 0 means mutexes are permanently disable and the library is never
14472** threadsafe. 1 means the library is serialized which is the highest
14473** level of threadsafety. 2 means the library is multithreaded - multiple
14474** threads can use SQLite as long as no two threads try to use the same
14475** database connection at the same time.
14476**
14477** Older versions of SQLite used an optional THREADSAFE macro.
14478** We support that for legacy.
14479**
14480** To ensure that the correct value of "THREADSAFE" is reported when querying
14481** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
14482** logic is partially replicated in ctime.c. If it is updated here, it should
14483** also be updated there.
14484*/
14485#if !defined(SQLITE_THREADSAFE2)
14486# if defined(THREADSAFE)
14487# define SQLITE_THREADSAFE2 THREADSAFE
14488# else
14489# define SQLITE_THREADSAFE2 1 /* IMP: R-07272-22309 */
14490# endif
14491#endif
14492
14493/*
14494** Powersafe overwrite is on by default. But can be turned off using
14495** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
14496*/
14497#ifndef SQLITE_POWERSAFE_OVERWRITE1
14498# define SQLITE_POWERSAFE_OVERWRITE1 1
14499#endif
14500
14501/*
14502** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
14503** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
14504** which case memory allocation statistics are disabled by default.
14505*/
14506#if !defined(SQLITE_DEFAULT_MEMSTATUS1)
14507# define SQLITE_DEFAULT_MEMSTATUS1 1
14508#endif
14509
14510/*
14511** Exactly one of the following macros must be defined in order to
14512** specify which memory allocation subsystem to use.
14513**
14514** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
14515** SQLITE_WIN32_MALLOC // Use Win32 native heap API
14516** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
14517** SQLITE_MEMDEBUG // Debugging version of system malloc()
14518**
14519** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
14520** assert() macro is enabled, each call into the Win32 native heap subsystem
14521** will cause HeapValidate to be called. If heap validation should fail, an
14522** assertion will be triggered.
14523**
14524** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
14525** the default.
14526*/
14527#if defined(SQLITE_SYSTEM_MALLOC1) \
14528 + defined(SQLITE_WIN32_MALLOC) \
14529 + defined(SQLITE_ZERO_MALLOC) \
14530 + defined(SQLITE_MEMDEBUG)>1
14531# error "Two or more of the following compile-time configuration options\
14532 are defined but at most one is allowed:\
14533 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
14534 SQLITE_ZERO_MALLOC"
14535#endif
14536#if defined(SQLITE_SYSTEM_MALLOC1) \
14537 + defined(SQLITE_WIN32_MALLOC) \
14538 + defined(SQLITE_ZERO_MALLOC) \
14539 + defined(SQLITE_MEMDEBUG)==0
14540# define SQLITE_SYSTEM_MALLOC1 1
14541#endif
14542
14543/*
14544** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
14545** sizes of memory allocations below this value where possible.
14546*/
14547#if !defined(SQLITE_MALLOC_SOFT_LIMIT1024)
14548# define SQLITE_MALLOC_SOFT_LIMIT1024 1024
14549#endif
14550
14551/*
14552** We need to define _XOPEN_SOURCE as follows in order to enable
14553** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
14554** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
14555** it.
14556*/
14557#if !defined(_XOPEN_SOURCE700) && !defined(__DARWIN__) && !defined(__APPLE__)
14558# define _XOPEN_SOURCE700 600
14559#endif
14560
14561/*
14562** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
14563** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
14564** make it true by defining or undefining NDEBUG.
14565**
14566** Setting NDEBUG makes the code smaller and faster by disabling the
14567** assert() statements in the code. So we want the default action
14568** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
14569** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
14570** feature.
14571*/
14572#if !defined(NDEBUG1) && !defined(SQLITE_DEBUG)
14573# define NDEBUG1 1
14574#endif
14575#if defined(NDEBUG1) && defined(SQLITE_DEBUG)
14576# undef NDEBUG1
14577#endif
14578
14579/*
14580** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
14581*/
14582#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
14583# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
14584#endif
14585
14586/*
14587** The testcase() macro is used to aid in coverage testing. When
14588** doing coverage testing, the condition inside the argument to
14589** testcase() must be evaluated both true and false in order to
14590** get full branch coverage. The testcase() macro is inserted
14591** to help ensure adequate test coverage in places where simple
14592** condition/decision coverage is inadequate. For example, testcase()
14593** can be used to make sure boundary values are tested. For
14594** bitmask tests, testcase() can be used to make sure each bit
14595** is significant and used at least once. On switch statements
14596** where multiple cases go to the same block of code, testcase()
14597** can insure that all cases are evaluated.
14598*/
14599#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
14600# ifndef SQLITE_AMALGAMATION1
14601 extern unsigned int sqlite3CoverageCounter;
14602# endif
14603# define testcase(X) if( X ){ sqlite3CoverageCounter += (unsigned)__LINE__14603; }
14604#else
14605# define testcase(X)
14606#endif
14607
14608/*
14609** The TESTONLY macro is used to enclose variable declarations or
14610** other bits of code that are needed to support the arguments
14611** within testcase() and assert() macros.
14612*/
14613#if !defined(NDEBUG1) || defined(SQLITE_COVERAGE_TEST)
14614# define TESTONLY(X) X
14615#else
14616# define TESTONLY(X)
14617#endif
14618
14619/*
14620** Sometimes we need a small amount of code such as a variable initialization
14621** to setup for a later assert() statement. We do not want this code to
14622** appear when assert() is disabled. The following macro is therefore
14623** used to contain that setup code. The "VVA" acronym stands for
14624** "Verification, Validation, and Accreditation". In other words, the
14625** code within VVA_ONLY() will only run during verification processes.
14626*/
14627#ifndef NDEBUG1
14628# define VVA_ONLY(X) X
14629#else
14630# define VVA_ONLY(X)
14631#endif
14632
14633/*
14634** Disable ALWAYS() and NEVER() (make them pass-throughs) for coverage
14635** and mutation testing
14636*/
14637#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
14638# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
14639#endif
14640
14641/*
14642** The ALWAYS and NEVER macros surround boolean expressions which
14643** are intended to always be true or false, respectively. Such
14644** expressions could be omitted from the code completely. But they
14645** are included in a few cases in order to enhance the resilience
14646** of SQLite to unexpected behavior - to make the code "self-healing"
14647** or "ductile" rather than being "brittle" and crashing at the first
14648** hint of unplanned behavior.
14649**
14650** In other words, ALWAYS and NEVER are added for defensive code.
14651**
14652** When doing coverage testing ALWAYS and NEVER are hard-coded to
14653** be true and false so that the unreachable code they specify will
14654** not be counted as untested code.
14655*/
14656#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
14657# define ALWAYS(X)(X) (1)
14658# define NEVER(X)(X) (0)
14659#elif !defined(NDEBUG1)
14660# define ALWAYS(X)(X) ((X)?1:(assert(0)((void) (0)),0))
14661# define NEVER(X)(X) ((X)?(assert(0)((void) (0)),1):0)
14662#else
14663# define ALWAYS(X)(X) (X)
14664# define NEVER(X)(X) (X)
14665#endif
14666
14667/*
14668** Some conditionals are optimizations only. In other words, if the
14669** conditionals are replaced with a constant 1 (true) or 0 (false) then
14670** the correct answer is still obtained, though perhaps not as quickly.
14671**
14672** The following macros mark these optimizations conditionals.
14673*/
14674#if defined(SQLITE_MUTATION_TEST)
14675# define OK_IF_ALWAYS_TRUE(X)(X) (1)
14676# define OK_IF_ALWAYS_FALSE(X)(X) (0)
14677#else
14678# define OK_IF_ALWAYS_TRUE(X)(X) (X)
14679# define OK_IF_ALWAYS_FALSE(X)(X) (X)
14680#endif
14681
14682/*
14683** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
14684** defined. We need to defend against those failures when testing with
14685** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
14686** during a normal build. The following macro can be used to disable tests
14687** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
14688*/
14689#if defined(SQLITE_TEST_REALLOC_STRESS)
14690# define ONLY_IF_REALLOC_STRESS(X)(0) (X)
14691#elif !defined(NDEBUG1)
14692# define ONLY_IF_REALLOC_STRESS(X)(0) ((X)?(assert(0)((void) (0)),1):0)
14693#else
14694# define ONLY_IF_REALLOC_STRESS(X)(0) (0)
14695#endif
14696
14697/*
14698** Declarations used for tracing the operating system interfaces.
14699*/
14700#if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
14701 (defined(SQLITE_DEBUG) && SQLITE_OS_WIN0)
14702 extern int sqlite3OSTrace;
14703# define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
14704# define SQLITE_HAVE_OS_TRACE
14705#else
14706# define OSTRACE(X)
14707# undef SQLITE_HAVE_OS_TRACE
14708#endif
14709
14710/*
14711** Is the sqlite3ErrName() function needed in the build? Currently,
14712** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
14713** OSTRACE is enabled), and by several "test*.c" files (which are
14714** compiled using SQLITE_TEST).
14715*/
14716#if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
14717 (defined(SQLITE_DEBUG) && SQLITE_OS_WIN0)
14718# define SQLITE_NEED_ERR_NAME
14719#else
14720# undef SQLITE_NEED_ERR_NAME
14721#endif
14722
14723/*
14724** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
14725*/
14726#ifdef SQLITE_OMIT_EXPLAIN
14727# undef SQLITE_ENABLE_EXPLAIN_COMMENTS
14728#endif
14729
14730/*
14731** SQLITE_OMIT_VIRTUALTABLE implies SQLITE_OMIT_ALTERTABLE
14732*/
14733#if defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_ALTERTABLE)
14734# define SQLITE_OMIT_ALTERTABLE
14735#endif
14736
14737#define SQLITE_DIGIT_SEPARATOR'_' '_'
14738
14739/*
14740** Return true (non-zero) if the input is an integer that is too large
14741** to fit in 32-bits. This macro is used inside of various testcase()
14742** macros to verify that we have tested SQLite for large-file support.
14743*/
14744#define IS_BIG_INT(X)(((X)&~(i64)0xffffffff)!=0) (((X)&~(i64)0xffffffff)!=0)
14745
14746/*
14747** The macro unlikely() is a hint that surrounds a boolean
14748** expression that is usually false. Macro likely() surrounds
14749** a boolean expression that is usually true. These hints could,
14750** in theory, be used by the compiler to generate better code, but
14751** currently they are just comments for human readers.
14752*/
14753#define likely(X)(X) (X)
14754#define unlikely(X)(X) (X)
14755
14756/************** Include hash.h in the middle of sqliteInt.h ******************/
14757/************** Begin file hash.h ********************************************/
14758/*
14759** 2001 September 22
14760**
14761** The author disclaims copyright to this source code. In place of
14762** a legal notice, here is a blessing:
14763**
14764** May you do good and not evil.
14765** May you find forgiveness for yourself and forgive others.
14766** May you share freely, never taking more than you give.
14767**
14768*************************************************************************
14769** This is the header file for the generic hash-table implementation
14770** used in SQLite.
14771*/
14772#ifndef SQLITE_HASH_H
14773#define SQLITE_HASH_H
14774
14775/* Forward declarations of structures. */
14776typedef struct Hash Hash;
14777typedef struct HashElem HashElem;
14778
14779/* A complete hash table is an instance of the following structure.
14780** The internals of this structure are intended to be opaque -- client
14781** code should not attempt to access or modify the fields of this structure
14782** directly. Change this structure only by using the routines below.
14783** However, some of the "procedures" and "functions" for modifying and
14784** accessing this structure are really macros, so we can't really make
14785** this structure opaque.
14786**
14787** All elements of the hash table are on a single doubly-linked list.
14788** Hash.first points to the head of this list.
14789**
14790** There are Hash.htsize buckets. Each bucket points to a spot in
14791** the global doubly-linked list. The contents of the bucket are the
14792** element pointed to plus the next _ht.count-1 elements in the list.
14793**
14794** Hash.htsize and Hash.ht may be zero. In that case lookup is done
14795** by a linear search of the global list. For small tables, the
14796** Hash.ht table is never allocated because if there are few elements
14797** in the table, it is faster to do a linear search than to manage
14798** the hash table.
14799*/
14800struct Hash {
14801 unsigned int htsize; /* Number of buckets in the hash table */
14802 unsigned int count; /* Number of entries in this table */
14803 HashElem *first; /* The first element of the array */
14804 struct _ht { /* the hash table */
14805 unsigned int count; /* Number of entries with this hash */
14806 HashElem *chain; /* Pointer to first entry with this hash */
14807 } *ht;
14808};
14809
14810/* Each element in the hash table is an instance of the following
14811** structure. All elements are stored on a single doubly-linked list.
14812**
14813** Again, this structure is intended to be opaque, but it can't really
14814** be opaque because it is used by macros.
14815*/
14816struct HashElem {
14817 HashElem *next, *prev; /* Next and previous elements in the table */
14818 void *data; /* Data associated with this element */
14819 const char *pKey; /* Key associated with this element */
14820 unsigned int h; /* hash for pKey */
14821};
14822
14823/*
14824** Access routines. To delete, insert a NULL pointer.
14825*/
14826SQLITE_PRIVATEstatic void sqlite3HashInit(Hash*);
14827SQLITE_PRIVATEstatic void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
14828SQLITE_PRIVATEstatic void *sqlite3HashFind(const Hash*, const char *pKey);
14829SQLITE_PRIVATEstatic void sqlite3HashClear(Hash*);
14830
14831/*
14832** Macros for looping over all elements of a hash table. The idiom is
14833** like this:
14834**
14835** Hash h;
14836** HashElem *p;
14837** ...
14838** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
14839** SomeStructure *pData = sqliteHashData(p);
14840** // do something with pData
14841** }
14842*/
14843#define sqliteHashFirst(H)((H)->first) ((H)->first)
14844#define sqliteHashNext(E)((E)->next) ((E)->next)
14845#define sqliteHashData(E)((E)->data) ((E)->data)
14846/* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
14847/* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
14848
14849/*
14850** Number of entries in a hash table
14851*/
14852#define sqliteHashCount(H)((H)->count) ((H)->count)
14853
14854#endif /* SQLITE_HASH_H */
14855
14856/************** End of hash.h ************************************************/
14857/************** Continuing where we left off in sqliteInt.h ******************/
14858/************** Include parse.h in the middle of sqliteInt.h *****************/
14859/************** Begin file parse.h *******************************************/
14860#define TK_SEMI1 1
14861#define TK_EXPLAIN2 2
14862#define TK_QUERY3 3
14863#define TK_PLAN4 4
14864#define TK_BEGIN5 5
14865#define TK_TRANSACTION6 6
14866#define TK_DEFERRED7 7
14867#define TK_IMMEDIATE8 8
14868#define TK_EXCLUSIVE9 9
14869#define TK_COMMIT10 10
14870#define TK_END11 11
14871#define TK_ROLLBACK12 12
14872#define TK_SAVEPOINT13 13
14873#define TK_RELEASE14 14
14874#define TK_TO15 15
14875#define TK_TABLE16 16
14876#define TK_CREATE17 17
14877#define TK_IF18 18
14878#define TK_NOT19 19
14879#define TK_EXISTS20 20
14880#define TK_TEMP21 21
14881#define TK_LP22 22
14882#define TK_RP23 23
14883#define TK_AS24 24
14884#define TK_COMMA25 25
14885#define TK_WITHOUT26 26
14886#define TK_ABORT27 27
14887#define TK_ACTION28 28
14888#define TK_AFTER29 29
14889#define TK_ANALYZE30 30
14890#define TK_ASC31 31
14891#define TK_ATTACH32 32
14892#define TK_BEFORE33 33
14893#define TK_BY34 34
14894#define TK_CASCADE35 35
14895#define TK_CAST36 36
14896#define TK_CONFLICT37 37
14897#define TK_DATABASE38 38
14898#define TK_DESC39 39
14899#define TK_DETACH40 40
14900#define TK_EACH41 41
14901#define TK_FAIL42 42
14902#define TK_OR43 43
14903#define TK_AND44 44
14904#define TK_IS45 45
14905#define TK_ISNOT46 46
14906#define TK_MATCH47 47
14907#define TK_LIKE_KW48 48
14908#define TK_BETWEEN49 49
14909#define TK_IN50 50
14910#define TK_ISNULL51 51
14911#define TK_NOTNULL52 52
14912#define TK_NE53 53
14913#define TK_EQ54 54
14914#define TK_GT55 55
14915#define TK_LE56 56
14916#define TK_LT57 57
14917#define TK_GE58 58
14918#define TK_ESCAPE59 59
14919#define TK_ID60 60
14920#define TK_COLUMNKW61 61
14921#define TK_DO62 62
14922#define TK_FOR63 63
14923#define TK_IGNORE64 64
14924#define TK_INITIALLY65 65
14925#define TK_INSTEAD66 66
14926#define TK_NO67 67
14927#define TK_KEY68 68
14928#define TK_OF69 69
14929#define TK_OFFSET70 70
14930#define TK_PRAGMA71 71
14931#define TK_RAISE72 72
14932#define TK_RECURSIVE73 73
14933#define TK_REPLACE74 74
14934#define TK_RESTRICT75 75
14935#define TK_ROW76 76
14936#define TK_ROWS77 77
14937#define TK_TRIGGER78 78
14938#define TK_VACUUM79 79
14939#define TK_VIEW80 80
14940#define TK_VIRTUAL81 81
14941#define TK_WITH82 82
14942#define TK_NULLS83 83
14943#define TK_FIRST84 84
14944#define TK_LAST85 85
14945#define TK_CURRENT86 86
14946#define TK_FOLLOWING87 87
14947#define TK_PARTITION88 88
14948#define TK_PRECEDING89 89
14949#define TK_RANGE90 90
14950#define TK_UNBOUNDED91 91
14951#define TK_EXCLUDE92 92
14952#define TK_GROUPS93 93
14953#define TK_OTHERS94 94
14954#define TK_TIES95 95
14955#define TK_GENERATED96 96
14956#define TK_ALWAYS97 97
14957#define TK_MATERIALIZED98 98
14958#define TK_REINDEX99 99
14959#define TK_RENAME100 100
14960#define TK_CTIME_KW101 101
14961#define TK_ANY102 102
14962#define TK_BITAND103 103
14963#define TK_BITOR104 104
14964#define TK_LSHIFT105 105
14965#define TK_RSHIFT106 106
14966#define TK_PLUS107 107
14967#define TK_MINUS108 108
14968#define TK_STAR109 109
14969#define TK_SLASH110 110
14970#define TK_REM111 111
14971#define TK_CONCAT112 112
14972#define TK_PTR113 113
14973#define TK_COLLATE114 114
14974#define TK_BITNOT115 115
14975#define TK_ON116 116
14976#define TK_INDEXED117 117
14977#define TK_STRING118 118
14978#define TK_JOIN_KW119 119
14979#define TK_CONSTRAINT120 120
14980#define TK_DEFAULT121 121
14981#define TK_NULL122 122
14982#define TK_PRIMARY123 123
14983#define TK_UNIQUE124 124
14984#define TK_CHECK125 125
14985#define TK_REFERENCES126 126
14986#define TK_AUTOINCR127 127
14987#define TK_INSERT128 128
14988#define TK_DELETE129 129
14989#define TK_UPDATE130 130
14990#define TK_SET131 131
14991#define TK_DEFERRABLE132 132
14992#define TK_FOREIGN133 133
14993#define TK_DROP134 134
14994#define TK_UNION135 135
14995#define TK_ALL136 136
14996#define TK_EXCEPT137 137
14997#define TK_INTERSECT138 138
14998#define TK_SELECT139 139
14999#define TK_VALUES140 140
15000#define TK_DISTINCT141 141
15001#define TK_DOT142 142
15002#define TK_FROM143 143
15003#define TK_JOIN144 144
15004#define TK_USING145 145
15005#define TK_ORDER146 146
15006#define TK_GROUP147 147
15007#define TK_HAVING148 148
15008#define TK_LIMIT149 149
15009#define TK_WHERE150 150
15010#define TK_RETURNING151 151
15011#define TK_INTO152 152
15012#define TK_NOTHING153 153
15013#define TK_FLOAT154 154
15014#define TK_BLOB155 155
15015#define TK_INTEGER156 156
15016#define TK_VARIABLE157 157
15017#define TK_CASE158 158
15018#define TK_WHEN159 159
15019#define TK_THEN160 160
15020#define TK_ELSE161 161
15021#define TK_INDEX162 162
15022#define TK_ALTER163 163
15023#define TK_ADD164 164
15024#define TK_WINDOW165 165
15025#define TK_OVER166 166
15026#define TK_FILTER167 167
15027#define TK_COLUMN168 168
15028#define TK_AGG_FUNCTION169 169
15029#define TK_AGG_COLUMN170 170
15030#define TK_TRUEFALSE171 171
15031#define TK_FUNCTION172 172
15032#define TK_UPLUS173 173
15033#define TK_UMINUS174 174
15034#define TK_TRUTH175 175
15035#define TK_REGISTER176 176
15036#define TK_VECTOR177 177
15037#define TK_SELECT_COLUMN178 178
15038#define TK_IF_NULL_ROW179 179
15039#define TK_ASTERISK180 180
15040#define TK_SPAN181 181
15041#define TK_ERROR182 182
15042#define TK_QNUMBER183 183
15043#define TK_SPACE184 184
15044#define TK_COMMENT185 185
15045#define TK_ILLEGAL186 186
15046
15047/************** End of parse.h ***********************************************/
15048/************** Continuing where we left off in sqliteInt.h ******************/
15049#include <stdio.h>
15050#include <stdlib.h>
15051#include <string.h>
15052#include <assert.h>
15053#include <stddef.h>
15054#include <ctype.h>
15055
15056/*
15057** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
15058** This allows better measurements of where memcpy() is used when running
15059** cachegrind. But this macro version of memcpy() is very slow so it
15060** should not be used in production. This is a performance measurement
15061** hack only.
15062*/
15063#ifdef SQLITE_INLINE_MEMCPY
15064# define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
15065 int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
15066#endif
15067
15068/*
15069** If compiling for a processor that lacks floating point support,
15070** substitute integer for floating-point
15071*/
15072#ifdef SQLITE_OMIT_FLOATING_POINT
15073# define double sqlite_int64
15074# define float sqlite_int64
15075# define fabs(X) ((X)<0?-(X):(X))
15076# define sqlite3IsOverflow(X) 0
15077# ifndef SQLITE_BIG_DBL(1e99)
15078# define SQLITE_BIG_DBL(1e99) (((sqlite3_int64)1)<<50)
15079# endif
15080# define SQLITE_OMIT_DATETIME_FUNCS 1
15081# define SQLITE_OMIT_TRACE 1
15082# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
15083# undef SQLITE_HAVE_ISNAN1
15084#endif
15085#ifndef SQLITE_BIG_DBL(1e99)
15086# define SQLITE_BIG_DBL(1e99) (1e99)
15087#endif
15088
15089/*
15090** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
15091** afterward. Having this macro allows us to cause the C compiler
15092** to omit code used by TEMP tables without messy #ifndef statements.
15093*/
15094#ifdef SQLITE_OMIT_TEMPDB
15095#define OMIT_TEMPDB0 1
15096#else
15097#define OMIT_TEMPDB0 0
15098#endif
15099
15100/*
15101** The "file format" number is an integer that is incremented whenever
15102** the VDBE-level file format changes. The following macros define the
15103** the default file format for new databases and the maximum file format
15104** that the library can read.
15105*/
15106#define SQLITE_MAX_FILE_FORMAT4 4
15107#ifndef SQLITE_DEFAULT_FILE_FORMAT4
15108# define SQLITE_DEFAULT_FILE_FORMAT4 4
15109#endif
15110
15111/*
15112** Determine whether triggers are recursive by default. This can be
15113** changed at run-time using a pragma.
15114*/
15115#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS0
15116# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS0 0
15117#endif
15118
15119/*
15120** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
15121** on the command-line
15122*/
15123#ifndef SQLITE_TEMP_STORE1
15124# define SQLITE_TEMP_STORE1 1
15125#endif
15126
15127/*
15128** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
15129** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
15130** to zero.
15131*/
15132#if SQLITE_TEMP_STORE1==3 || SQLITE_THREADSAFE2==0
15133# undef SQLITE_MAX_WORKER_THREADS8
15134# define SQLITE_MAX_WORKER_THREADS8 0
15135#endif
15136#ifndef SQLITE_MAX_WORKER_THREADS8
15137# define SQLITE_MAX_WORKER_THREADS8 8
15138#endif
15139#ifndef SQLITE_DEFAULT_WORKER_THREADS0
15140# define SQLITE_DEFAULT_WORKER_THREADS0 0
15141#endif
15142#if SQLITE_DEFAULT_WORKER_THREADS0>SQLITE_MAX_WORKER_THREADS8
15143# undef SQLITE_MAX_WORKER_THREADS8
15144# define SQLITE_MAX_WORKER_THREADS8 SQLITE_DEFAULT_WORKER_THREADS0
15145#endif
15146
15147/*
15148** The default initial allocation for the pagecache when using separate
15149** pagecaches for each database connection. A positive number is the
15150** number of pages. A negative number N translations means that a buffer
15151** of -1024*N bytes is allocated and used for as many pages as it will hold.
15152**
15153** The default value of "20" was chosen to minimize the run-time of the
15154** speedtest1 test program with options: --shrink-memory --reprepare
15155*/
15156#ifndef SQLITE_DEFAULT_PCACHE_INITSZ20
15157# define SQLITE_DEFAULT_PCACHE_INITSZ20 20
15158#endif
15159
15160/*
15161** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
15162*/
15163#ifndef SQLITE_DEFAULT_SORTERREF_SIZE0x7fffffff
15164# define SQLITE_DEFAULT_SORTERREF_SIZE0x7fffffff 0x7fffffff
15165#endif
15166
15167/*
15168** The compile-time options SQLITE_MMAP_READWRITE and
15169** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
15170** You must choose one or the other (or neither) but not both.
15171*/
15172#if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
15173#error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
15174#endif
15175
15176/*
15177** GCC does not define the offsetof() macro so we'll have to do it
15178** ourselves.
15179*/
15180#ifndef offsetof
15181#define offsetof(STRUCTURE,FIELD)__builtin_offsetof(STRUCTURE, FIELD) ((size_t)((char*)&((STRUCTURE*)0)->FIELD))
15182#endif
15183
15184/*
15185** Work around C99 "flex-array" syntax for pre-C99 compilers, so as
15186** to avoid complaints from -fsanitize=strict-bounds.
15187*/
15188#if defined(__STDC_VERSION__201710L) && (__STDC_VERSION__201710L >= 199901L)
15189# define FLEXARRAY
15190#else
15191# define FLEXARRAY 1
15192#endif
15193
15194/*
15195** Macros to compute minimum and maximum of two numbers.
15196*/
15197#ifndef MIN
15198# define MIN(A,B)((A)<(B)?(A):(B)) ((A)<(B)?(A):(B))
15199#endif
15200#ifndef MAX
15201# define MAX(A,B)((A)>(B)?(A):(B)) ((A)>(B)?(A):(B))
15202#endif
15203
15204/*
15205** Swap two objects of type TYPE.
15206*/
15207#define SWAP(TYPE,A,B){TYPE t=A; A=B; B=t;} {TYPE t=A; A=B; B=t;}
15208
15209/*
15210** Check to see if this machine uses EBCDIC. (Yes, believe it or
15211** not, there are still machines out there that use EBCDIC.)
15212*/
15213#if 'A' == '\301'
15214# define SQLITE_EBCDIC 1
15215#else
15216# define SQLITE_ASCII1 1
15217#endif
15218
15219/*
15220** Integers of known sizes. These typedefs might change for architectures
15221** where the sizes very. Preprocessor macros are available so that the
15222** types can be conveniently redefined at compile-type. Like this:
15223**
15224** cc '-DUINTPTR_TYPE=long long int' ...
15225*/
15226#ifndef UINT32_TYPEunsigned int
15227# ifdef HAVE_UINT32_T
15228# define UINT32_TYPEunsigned int uint32_t
15229# else
15230# define UINT32_TYPEunsigned int unsigned int
15231# endif
15232#endif
15233#ifndef UINT16_TYPEunsigned short int
15234# ifdef HAVE_UINT16_T
15235# define UINT16_TYPEunsigned short int uint16_t
15236# else
15237# define UINT16_TYPEunsigned short int unsigned short int
15238# endif
15239#endif
15240#ifndef INT16_TYPEshort int
15241# ifdef HAVE_INT16_T
15242# define INT16_TYPEshort int int16_t
15243# else
15244# define INT16_TYPEshort int short int
15245# endif
15246#endif
15247#ifndef UINT8_TYPEunsigned char
15248# ifdef HAVE_UINT8_T
15249# define UINT8_TYPEunsigned char uint8_t
15250# else
15251# define UINT8_TYPEunsigned char unsigned char
15252# endif
15253#endif
15254#ifndef INT8_TYPEsigned char
15255# ifdef HAVE_INT8_T
15256# define INT8_TYPEsigned char int8_t
15257# else
15258# define INT8_TYPEsigned char signed char
15259# endif
15260#endif
15261typedef sqlite_int64 i64; /* 8-byte signed integer */
15262typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
15263typedef UINT32_TYPEunsigned int u32; /* 4-byte unsigned integer */
15264typedef UINT16_TYPEunsigned short int u16; /* 2-byte unsigned integer */
15265typedef INT16_TYPEshort int i16; /* 2-byte signed integer */
15266typedef UINT8_TYPEunsigned char u8; /* 1-byte unsigned integer */
15267typedef INT8_TYPEsigned char i8; /* 1-byte signed integer */
15268
15269/* A bitfield type for use inside of structures. Always follow with :N where
15270** N is the number of bits.
15271*/
15272typedef unsigned bft; /* Bit Field Type */
15273
15274/*
15275** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
15276** that can be stored in a u32 without loss of data. The value
15277** is 0x00000000ffffffff. But because of quirks of some compilers, we
15278** have to specify the value in the less intuitive manner shown:
15279*/
15280#define SQLITE_MAX_U32((((u64)1)<<32)-1) ((((u64)1)<<32)-1)
15281
15282/*
15283** The datatype used to store estimates of the number of rows in a
15284** table or index.
15285*/
15286typedef u64 tRowcnt;
15287
15288/*
15289** Estimated quantities used for query planning are stored as 16-bit
15290** logarithms. For quantity X, the value stored is 10*log2(X). This
15291** gives a possible range of values of approximately 1.0e986 to 1e-986.
15292** But the allowed values are "grainy". Not every value is representable.
15293** For example, quantities 16 and 17 are both represented by a LogEst
15294** of 40. However, since LogEst quantities are suppose to be estimates,
15295** not exact values, this imprecision is not a problem.
15296**
15297** "LogEst" is short for "Logarithmic Estimate".
15298**
15299** Examples:
15300** 1 -> 0 20 -> 43 10000 -> 132
15301** 2 -> 10 25 -> 46 25000 -> 146
15302** 3 -> 16 100 -> 66 1000000 -> 199
15303** 4 -> 20 1000 -> 99 1048576 -> 200
15304** 10 -> 33 1024 -> 100 4294967296 -> 320
15305**
15306** The LogEst can be negative to indicate fractional values.
15307** Examples:
15308**
15309** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
15310*/
15311typedef INT16_TYPEshort int LogEst;
15312#define LOGEST_MIN(-32768) (-32768)
15313#define LOGEST_MAX(32767) (32767)
15314
15315/*
15316** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
15317*/
15318#ifndef SQLITE_PTRSIZE8
15319# if defined(__SIZEOF_POINTER__8)
15320# define SQLITE_PTRSIZE8 __SIZEOF_POINTER__8
15321# elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
15322 defined(_M_ARM) || defined(__arm__) || defined(__x86) || \
15323 (defined(__APPLE__) && defined(__ppc__)) || \
15324 (defined(__TOS_AIX__) && !defined(__64BIT__))
15325# define SQLITE_PTRSIZE8 4
15326# else
15327# define SQLITE_PTRSIZE8 8
15328# endif
15329#endif
15330
15331/* The uptr type is an unsigned integer large enough to hold a pointer
15332*/
15333#if defined(HAVE_STDINT_H)
15334 typedef uintptr_t uptr;
15335#elif SQLITE_PTRSIZE8==4
15336 typedef u32 uptr;
15337#else
15338 typedef u64 uptr;
15339#endif
15340
15341/*
15342** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
15343** something between S (inclusive) and E (exclusive).
15344**
15345** In other words, S is a buffer and E is a pointer to the first byte after
15346** the end of buffer S. This macro returns true if P points to something
15347** contained within the buffer S.
15348*/
15349#define SQLITE_WITHIN(P,S,E)(((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E))) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
15350
15351/*
15352** P is one byte past the end of a large buffer. Return true if a span of bytes
15353** between S..E crosses the end of that buffer. In other words, return true
15354** if the sub-buffer S..E-1 overflows the buffer whose last byte is P-1.
15355**
15356** S is the start of the span. E is one byte past the end of end of span.
15357**
15358** P
15359** |-----------------| FALSE
15360** |-------|
15361** S E
15362**
15363** P
15364** |-----------------|
15365** |-------| TRUE
15366** S E
15367**
15368** P
15369** |-----------------|
15370** |-------| FALSE
15371** S E
15372*/
15373#define SQLITE_OVERFLOW(P,S,E)(((uptr)(S)<(uptr)(P))&&((uptr)(E)>(uptr)(P))) (((uptr)(S)<(uptr)(P))&&((uptr)(E)>(uptr)(P)))
15374
15375/*
15376** Macros to determine whether the machine is big or little endian,
15377** and whether or not that determination is run-time or compile-time.
15378**
15379** For best performance, an attempt is made to guess at the byte-order
15380** using C-preprocessor macros. If that is unsuccessful, or if
15381** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
15382** at run-time.
15383**
15384** If you are building SQLite on some obscure platform for which the
15385** following ifdef magic does not work, you can always include either:
15386**
15387** -DSQLITE_BYTEORDER=1234
15388**
15389** or
15390**
15391** -DSQLITE_BYTEORDER=4321
15392**
15393** to cause the build to work for little-endian or big-endian processors,
15394** respectively.
15395*/
15396#ifndef SQLITE_BYTEORDER1234 /* Replicate changes at tag-20230904a */
15397# if defined(__BYTE_ORDER__1234) && __BYTE_ORDER__1234==__ORDER_BIG_ENDIAN__4321
15398# define SQLITE_BYTEORDER1234 4321
15399# elif defined(__BYTE_ORDER__1234) && __BYTE_ORDER__1234==__ORDER_LITTLE_ENDIAN__1234
15400# define SQLITE_BYTEORDER1234 1234
15401# elif defined(__BIG_ENDIAN__) && __BIG_ENDIAN__==1
15402# define SQLITE_BYTEORDER1234 4321
15403# elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
15404 defined(__x86_641) || defined(__x86_64__1) || defined(_M_X64) || \
15405 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
15406 defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
15407# define SQLITE_BYTEORDER1234 1234
15408# elif defined(sparc) || defined(__ARMEB__) || defined(__AARCH64EB__)
15409# define SQLITE_BYTEORDER1234 4321
15410# else
15411# define SQLITE_BYTEORDER1234 0
15412# endif
15413#endif
15414#if SQLITE_BYTEORDER1234==4321
15415# define SQLITE_BIGENDIAN0 1
15416# define SQLITE_LITTLEENDIAN1 0
15417# define SQLITE_UTF16NATIVE2 SQLITE_UTF16BE3
15418#elif SQLITE_BYTEORDER1234==1234
15419# define SQLITE_BIGENDIAN0 0
15420# define SQLITE_LITTLEENDIAN1 1
15421# define SQLITE_UTF16NATIVE2 SQLITE_UTF16LE2
15422#else
15423# ifdef SQLITE_AMALGAMATION1
15424 const int sqlite3one = 1;
15425# else
15426 extern const int sqlite3one;
15427# endif
15428# define SQLITE_BIGENDIAN0 (*(char *)(&sqlite3one)==0)
15429# define SQLITE_LITTLEENDIAN1 (*(char *)(&sqlite3one)==1)
15430# define SQLITE_UTF16NATIVE2 (SQLITE_BIGENDIAN0?SQLITE_UTF16BE3:SQLITE_UTF16LE2)
15431#endif
15432
15433/*
15434** Constants for the largest and smallest possible 64-bit signed integers.
15435** These macros are designed to work correctly on both 32-bit and 64-bit
15436** compilers.
15437*/
15438#define LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32)) (0xffffffff|(((i64)0x7fffffff)<<32))
15439#define LARGEST_UINT64(0xffffffff|(((u64)0xffffffff)<<32)) (0xffffffff|(((u64)0xffffffff)<<32))
15440#define SMALLEST_INT64(((i64)-1) - (0xffffffff|(((i64)0x7fffffff)<<32))) (((i64)-1) - LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32)))
15441
15442/*
15443** Macro SMXV(n) return the maximum value that can be held in variable n,
15444** assuming n is a signed integer type. UMXV(n) is similar for unsigned
15445** integer types.
15446*/
15447#define SMXV(n)((((i64)1)<<(sizeof(n)*8-1))-1) ((((i64)1)<<(sizeof(n)*8-1))-1)
15448#define UMXV(n)((((i64)1)<<(sizeof(n)*8))-1) ((((i64)1)<<(sizeof(n)*8))-1)
15449
15450/*
15451** Round up a number to the next larger multiple of 8. This is used
15452** to force 8-byte alignment on 64-bit architectures.
15453**
15454** ROUND8() always does the rounding, for any argument.
15455**
15456** ROUND8P() assumes that the argument is already an integer number of
15457** pointers in size, and so it is a no-op on systems where the pointer
15458** size is 8.
15459*/
15460#define ROUND8(x)(((x)+7)&~7) (((x)+7)&~7)
15461#if SQLITE_PTRSIZE8==8
15462# define ROUND8P(x)(x) (x)
15463#else
15464# define ROUND8P(x)(x) (((x)+7)&~7)
15465#endif
15466
15467/*
15468** Round down to the nearest multiple of 8
15469*/
15470#define ROUNDDOWN8(x)((x)&~7) ((x)&~7)
15471
15472/*
15473** Assert that the pointer X is aligned to an 8-byte boundary. This
15474** macro is used only within assert() to verify that the code gets
15475** all alignment restrictions correct.
15476**
15477** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
15478** underlying malloc() implementation might return us 4-byte aligned
15479** pointers. In that case, only verify 4-byte alignment.
15480*/
15481#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
15482# define EIGHT_BYTE_ALIGNMENT(X)((((uptr)(X) - (uptr)0)&7)==0) ((((uptr)(X) - (uptr)0)&3)==0)
15483#else
15484# define EIGHT_BYTE_ALIGNMENT(X)((((uptr)(X) - (uptr)0)&7)==0) ((((uptr)(X) - (uptr)0)&7)==0)
15485#endif
15486
15487/*
15488** Disable MMAP on platforms where it is known to not work
15489*/
15490#if defined(__OpenBSD__) || defined(__QNXNTO__)
15491# undef SQLITE_MAX_MMAP_SIZE20971520
15492# define SQLITE_MAX_MMAP_SIZE20971520 0
15493#endif
15494
15495/*
15496** Default maximum size of memory used by memory-mapped I/O in the VFS
15497*/
15498#ifdef __APPLE__
15499# include <TargetConditionals.h>
15500#endif
15501#ifndef SQLITE_MAX_MMAP_SIZE20971520
15502# if defined(__linux__1) \
15503 || defined(_WIN32) \
15504 || (defined(__APPLE__) && defined(__MACH__)) \
15505 || defined(__sun) \
15506 || defined(__FreeBSD__) \
15507 || defined(__DragonFly__)
15508# define SQLITE_MAX_MMAP_SIZE20971520 0x7fff0000 /* 2147418112 */
15509# else
15510# define SQLITE_MAX_MMAP_SIZE20971520 0
15511# endif
15512#endif
15513
15514/*
15515** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
15516** default MMAP_SIZE is specified at compile-time, make sure that it does
15517** not exceed the maximum mmap size.
15518*/
15519#ifndef SQLITE_DEFAULT_MMAP_SIZE0
15520# define SQLITE_DEFAULT_MMAP_SIZE0 0
15521#endif
15522#if SQLITE_DEFAULT_MMAP_SIZE0>SQLITE_MAX_MMAP_SIZE20971520
15523# undef SQLITE_DEFAULT_MMAP_SIZE0
15524# define SQLITE_DEFAULT_MMAP_SIZE0 SQLITE_MAX_MMAP_SIZE20971520
15525#endif
15526
15527/*
15528** TREETRACE_ENABLED will be either 1 or 0 depending on whether or not
15529** the Abstract Syntax Tree tracing logic is turned on.
15530*/
15531#if !defined(SQLITE_AMALGAMATION1)
15532SQLITE_PRIVATEstatic u32 sqlite3TreeTrace;
15533#endif
15534#if defined(SQLITE_DEBUG) \
15535 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_SELECTTRACE) \
15536 || defined(SQLITE_ENABLE_TREETRACE))
15537# define TREETRACE_ENABLED0 1
15538# define TREETRACE(K,P,S,X) \
15539 if(sqlite3TreeTrace&(K)) \
15540 sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
15541 sqlite3DebugPrintf X
15542#else
15543# define TREETRACE(K,P,S,X)
15544# define TREETRACE_ENABLED0 0
15545#endif
15546
15547/* TREETRACE flag meanings:
15548**
15549** 0x00000001 Beginning and end of SELECT processing
15550** 0x00000002 WHERE clause processing
15551** 0x00000004 Query flattener
15552** 0x00000008 Result-set wildcard expansion
15553** 0x00000010 Query name resolution
15554** 0x00000020 Aggregate analysis
15555** 0x00000040 Window functions
15556** 0x00000080 Generated column names
15557** 0x00000100 Move HAVING terms into WHERE
15558** 0x00000200 Count-of-view optimization
15559** 0x00000400 Compound SELECT processing
15560** 0x00000800 Drop superfluous ORDER BY
15561** 0x00001000 LEFT JOIN simplifies to JOIN
15562** 0x00002000 Constant propagation
15563** 0x00004000 Push-down optimization
15564** 0x00008000 After all FROM-clause analysis
15565** 0x00010000 Beginning of DELETE/INSERT/UPDATE processing
15566** 0x00020000 Transform DISTINCT into GROUP BY
15567** 0x00040000 SELECT tree dump after all code has been generated
15568** 0x00080000 NOT NULL strength reduction
15569*/
15570
15571/*
15572** Macros for "wheretrace"
15573*/
15574SQLITE_PRIVATEstatic u32 sqlite3WhereTrace;
15575#if defined(SQLITE_DEBUG) \
15576 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
15577# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
15578# define WHERETRACE_ENABLED 1
15579#else
15580# define WHERETRACE(K,X)
15581#endif
15582
15583/*
15584** Bits for the sqlite3WhereTrace mask:
15585**
15586** (---any--) Top-level block structure
15587** 0x-------F High-level debug messages
15588** 0x----FFF- More detail
15589** 0xFFFF---- Low-level debug messages
15590**
15591** 0x00000001 Code generation
15592** 0x00000002 Solver (Use 0x40000 for less detail)
15593** 0x00000004 Solver costs
15594** 0x00000008 WhereLoop inserts
15595**
15596** 0x00000010 Display sqlite3_index_info xBestIndex calls
15597** 0x00000020 Range an equality scan metrics
15598** 0x00000040 IN operator decisions
15599** 0x00000080 WhereLoop cost adjustments
15600** 0x00000100
15601** 0x00000200 Covering index decisions
15602** 0x00000400 OR optimization
15603** 0x00000800 Index scanner
15604** 0x00001000 More details associated with code generation
15605** 0x00002000
15606** 0x00004000 Show all WHERE terms at key points
15607** 0x00008000 Show the full SELECT statement at key places
15608**
15609** 0x00010000 Show more detail when printing WHERE terms
15610** 0x00020000 Show WHERE terms returned from whereScanNext()
15611** 0x00040000 Solver overview messages
15612** 0x00080000 Star-query heuristic
15613*/
15614
15615
15616/*
15617** An instance of the following structure is used to store the busy-handler
15618** callback for a given sqlite handle.
15619**
15620** The sqlite.busyHandler member of the sqlite struct contains the busy
15621** callback for the database handle. Each pager opened via the sqlite
15622** handle is passed a pointer to sqlite.busyHandler. The busy-handler
15623** callback is currently invoked only from within pager.c.
15624*/
15625typedef struct BusyHandler BusyHandler;
15626struct BusyHandler {
15627 int (*xBusyHandler)(void *,int); /* The busy callback */
15628 void *pBusyArg; /* First arg to busy callback */
15629 int nBusy; /* Incremented with each busy call */
15630};
15631
15632/*
15633** Name of table that holds the database schema.
15634**
15635** The PREFERRED names are used wherever possible. But LEGACY is also
15636** used for backwards compatibility.
15637**
15638** 1. Queries can use either the PREFERRED or the LEGACY names
15639** 2. The sqlite3_set_authorizer() callback uses the LEGACY name
15640** 3. The PRAGMA table_list statement uses the PREFERRED name
15641**
15642** The LEGACY names are stored in the internal symbol hash table
15643** in support of (2). Names are translated using sqlite3PreferredTableName()
15644** for (3). The sqlite3FindTable() function takes care of translating
15645** names for (1).
15646**
15647** Note that "sqlite_temp_schema" can also be called "temp.sqlite_schema".
15648*/
15649#define LEGACY_SCHEMA_TABLE"sqlite_master" "sqlite_master"
15650#define LEGACY_TEMP_SCHEMA_TABLE"sqlite_temp_master" "sqlite_temp_master"
15651#define PREFERRED_SCHEMA_TABLE"sqlite_schema" "sqlite_schema"
15652#define PREFERRED_TEMP_SCHEMA_TABLE"sqlite_temp_schema" "sqlite_temp_schema"
15653
15654
15655/*
15656** The root-page of the schema table.
15657*/
15658#define SCHEMA_ROOT1 1
15659
15660/*
15661** The name of the schema table. The name is different for TEMP.
15662*/
15663#define SCHEMA_TABLE(x)((!0)&&(x==1)?"sqlite_temp_master":"sqlite_master") \
15664 ((!OMIT_TEMPDB0)&&(x==1)?LEGACY_TEMP_SCHEMA_TABLE"sqlite_temp_master":LEGACY_SCHEMA_TABLE"sqlite_master")
15665
15666/*
15667** A convenience macro that returns the number of elements in
15668** an array.
15669*/
15670#define ArraySize(X)((int)(sizeof(X)/sizeof(X[0]))) ((int)(sizeof(X)/sizeof(X[0])))
15671
15672/*
15673** Determine if the argument is a power of two
15674*/
15675#define IsPowerOfTwo(X)(((X)&((X)-1))==0) (((X)&((X)-1))==0)
15676
15677/*
15678** The following value as a destructor means to use sqlite3DbFree().
15679** The sqlite3DbFree() routine requires two parameters instead of the
15680** one parameter that destructors normally want. So we have to introduce
15681** this magic value that the code knows to handle differently. Any
15682** pointer will work here as long as it is distinct from SQLITE_STATIC
15683** and SQLITE_TRANSIENT.
15684*/
15685#define SQLITE_DYNAMIC((sqlite3_destructor_type)sqlite3OomClear) ((sqlite3_destructor_type)sqlite3OomClear)
15686
15687/*
15688** When SQLITE_OMIT_WSD is defined, it means that the target platform does
15689** not support Writable Static Data (WSD) such as global and static variables.
15690** All variables must either be on the stack or dynamically allocated from
15691** the heap. When WSD is unsupported, the variable declarations scattered
15692** throughout the SQLite code must become constants instead. The SQLITE_WSD
15693** macro is used for this purpose. And instead of referencing the variable
15694** directly, we use its constant as a key to lookup the run-time allocated
15695** buffer that holds real variable. The constant is also the initializer
15696** for the run-time allocated buffer.
15697**
15698** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
15699** macros become no-ops and have zero performance impact.
15700*/
15701#ifdef SQLITE_OMIT_WSD
15702 #define SQLITE_WSD const
15703 #define GLOBAL(t,v)v (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
15704 #define sqlite3GlobalConfigsqlite3Config GLOBAL(struct Sqlite3Config, sqlite3Config)sqlite3Config
15705SQLITE_API int sqlite3_wsd_init(int N, int J);
15706SQLITE_API void *sqlite3_wsd_find(void *K, int L);
15707#else
15708 #define SQLITE_WSD
15709 #define GLOBAL(t,v)v v
15710 #define sqlite3GlobalConfigsqlite3Config sqlite3Config
15711#endif
15712
15713/*
15714** The following macros are used to suppress compiler warnings and to
15715** make it clear to human readers when a function parameter is deliberately
15716** left unused within the body of a function. This usually happens when
15717** a function is called via a function pointer. For example the
15718** implementation of an SQL aggregate step callback may not use the
15719** parameter indicating the number of arguments passed to the aggregate,
15720** if it knows that this is enforced elsewhere.
15721**
15722** When a function parameter is not used at all within the body of a function,
15723** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
15724** However, these macros may also be used to suppress warnings related to
15725** parameters that may or may not be used depending on compilation options.
15726** For example those parameters only used in assert() statements. In these
15727** cases the parameters are named as per the usual conventions.
15728*/
15729#define UNUSED_PARAMETER(x)(void)(x) (void)(x)
15730#define UNUSED_PARAMETER2(x,y)(void)(x),(void)(y) UNUSED_PARAMETER(x)(void)(x),UNUSED_PARAMETER(y)(void)(y)
15731
15732/*
15733** Forward references to structures
15734*/
15735typedef struct AggInfo AggInfo;
15736typedef struct AuthContext AuthContext;
15737typedef struct AutoincInfo AutoincInfo;
15738typedef struct Bitvec Bitvec;
15739typedef struct CollSeq CollSeq;
15740typedef struct Column Column;
15741typedef struct Cte Cte;
15742typedef struct CteUse CteUse;
15743typedef struct Db Db;
15744typedef struct DbClientData DbClientData;
15745typedef struct DbFixer DbFixer;
15746typedef struct Schema Schema;
15747typedef struct Expr Expr;
15748typedef struct ExprList ExprList;
15749typedef struct FKey FKey;
15750typedef struct FpDecode FpDecode;
15751typedef struct FuncDestructor FuncDestructor;
15752typedef struct FuncDef FuncDef;
15753typedef struct FuncDefHash FuncDefHash;
15754typedef struct IdList IdList;
15755typedef struct Index Index;
15756typedef struct IndexedExpr IndexedExpr;
15757typedef struct IndexSample IndexSample;
15758typedef struct KeyClass KeyClass;
15759typedef struct KeyInfo KeyInfo;
15760typedef struct Lookaside Lookaside;
15761typedef struct LookasideSlot LookasideSlot;
15762typedef struct Module Module;
15763typedef struct NameContext NameContext;
15764typedef struct OnOrUsing OnOrUsing;
15765typedef struct Parse Parse;
15766typedef struct ParseCleanup ParseCleanup;
15767typedef struct PreUpdate PreUpdate;
15768typedef struct PrintfArguments PrintfArguments;
15769typedef struct RCStr RCStr;
15770typedef struct RenameToken RenameToken;
15771typedef struct Returning Returning;
15772typedef struct RowSet RowSet;
15773typedef struct Savepoint Savepoint;
15774typedef struct Select Select;
15775typedef struct SQLiteThread SQLiteThread;
15776typedef struct SelectDest SelectDest;
15777typedef struct Subquery Subquery;
15778typedef struct SrcItem SrcItem;
15779typedef struct SrcList SrcList;
15780typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
15781typedef struct Table Table;
15782typedef struct TableLock TableLock;
15783typedef struct Token Token;
15784typedef struct TreeView TreeView;
15785typedef struct Trigger Trigger;
15786typedef struct TriggerPrg TriggerPrg;
15787typedef struct TriggerStep TriggerStep;
15788typedef struct UnpackedRecord UnpackedRecord;
15789typedef struct Upsert Upsert;
15790typedef struct VTable VTable;
15791typedef struct VtabCtx VtabCtx;
15792typedef struct Walker Walker;
15793typedef struct WhereInfo WhereInfo;
15794typedef struct Window Window;
15795typedef struct With With;
15796
15797
15798/*
15799** The bitmask datatype defined below is used for various optimizations.
15800**
15801** Changing this from a 64-bit to a 32-bit type limits the number of
15802** tables in a join to 32 instead of 64. But it also reduces the size
15803** of the library by 738 bytes on ix86.
15804*/
15805#ifdef SQLITE_BITMASK_TYPE
15806 typedef SQLITE_BITMASK_TYPE Bitmask;
15807#else
15808 typedef u64 Bitmask;
15809#endif
15810
15811/*
15812** The number of bits in a Bitmask. "BMS" means "BitMask Size".
15813*/
15814#define BMS((int)(sizeof(Bitmask)*8)) ((int)(sizeof(Bitmask)*8))
15815
15816/*
15817** A bit in a Bitmask
15818*/
15819#define MASKBIT(n)(((Bitmask)1)<<(n)) (((Bitmask)1)<<(n))
15820#define MASKBIT64(n)(((u64)1)<<(n)) (((u64)1)<<(n))
15821#define MASKBIT32(n)(((unsigned int)1)<<(n)) (((unsigned int)1)<<(n))
15822#define SMASKBIT32(n)((n)<=31?((unsigned int)1)<<(n):0) ((n)<=31?((unsigned int)1)<<(n):0)
15823#define ALLBITS((Bitmask)-1) ((Bitmask)-1)
15824#define TOPBIT(((Bitmask)1)<<(((int)(sizeof(Bitmask)*8))-1)) (((Bitmask)1)<<(BMS((int)(sizeof(Bitmask)*8))-1))
15825
15826/* A VList object records a mapping between parameters/variables/wildcards
15827** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
15828** variable number associated with that parameter. See the format description
15829** on the sqlite3VListAdd() routine for more information. A VList is really
15830** just an array of integers.
15831*/
15832typedef int VList;
15833
15834/*
15835** Defer sourcing vdbe.h and btree.h until after the "u8" and
15836** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
15837** pointer types (i.e. FuncDef) defined above.
15838*/
15839/************** Include os.h in the middle of sqliteInt.h ********************/
15840/************** Begin file os.h **********************************************/
15841/*
15842** 2001 September 16
15843**
15844** The author disclaims copyright to this source code. In place of
15845** a legal notice, here is a blessing:
15846**
15847** May you do good and not evil.
15848** May you find forgiveness for yourself and forgive others.
15849** May you share freely, never taking more than you give.
15850**
15851******************************************************************************
15852**
15853** This header file (together with is companion C source-code file
15854** "os.c") attempt to abstract the underlying operating system so that
15855** the SQLite library will work on both POSIX and windows systems.
15856**
15857** This header file is #include-ed by sqliteInt.h and thus ends up
15858** being included by every source file.
15859*/
15860#ifndef _SQLITE_OS_H_
15861#define _SQLITE_OS_H_
15862
15863/*
15864** Attempt to automatically detect the operating system and setup the
15865** necessary pre-processor macros for it.
15866*/
15867/************** Include os_setup.h in the middle of os.h *********************/
15868/************** Begin file os_setup.h ****************************************/
15869/*
15870** 2013 November 25
15871**
15872** The author disclaims copyright to this source code. In place of
15873** a legal notice, here is a blessing:
15874**
15875** May you do good and not evil.
15876** May you find forgiveness for yourself and forgive others.
15877** May you share freely, never taking more than you give.
15878**
15879******************************************************************************
15880**
15881** This file contains pre-processor directives related to operating system
15882** detection and/or setup.
15883*/
15884#ifndef SQLITE_OS_SETUP_H
15885#define SQLITE_OS_SETUP_H
15886
15887/*
15888** Figure out if we are dealing with Unix, Windows, or some other operating
15889** system.
15890**
15891** After the following block of preprocess macros, all of
15892**
15893** SQLITE_OS_KV
15894** SQLITE_OS_OTHER
15895** SQLITE_OS_UNIX
15896** SQLITE_OS_WIN
15897**
15898** will defined to either 1 or 0. One of them will be 1. The others will be 0.
15899** If none of the macros are initially defined, then select either
15900** SQLITE_OS_UNIX or SQLITE_OS_WIN depending on the target platform.
15901**
15902** If SQLITE_OS_OTHER=1 is specified at compile-time, then the application
15903** must provide its own VFS implementation together with sqlite3_os_init()
15904** and sqlite3_os_end() routines.
15905*/
15906#if !defined(SQLITE_OS_KV0) && !defined(SQLITE_OS_OTHER0) && \
15907 !defined(SQLITE_OS_UNIX1) && !defined(SQLITE_OS_WIN0)
15908# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
15909 defined(__MINGW32__) || defined(__BORLANDC__)
15910# define SQLITE_OS_WIN0 1
15911# define SQLITE_OS_UNIX1 0
15912# else
15913# define SQLITE_OS_WIN0 0
15914# define SQLITE_OS_UNIX1 1
15915# endif
15916#endif
15917#if SQLITE_OS_OTHER0+1>1
15918# undef SQLITE_OS_KV0
15919# define SQLITE_OS_KV0 0
15920# undef SQLITE_OS_UNIX1
15921# define SQLITE_OS_UNIX1 0
15922# undef SQLITE_OS_WIN0
15923# define SQLITE_OS_WIN0 0
15924#endif
15925#if SQLITE_OS_KV0+1>1
15926# undef SQLITE_OS_OTHER0
15927# define SQLITE_OS_OTHER0 0
15928# undef SQLITE_OS_UNIX1
15929# define SQLITE_OS_UNIX1 0
15930# undef SQLITE_OS_WIN0
15931# define SQLITE_OS_WIN0 0
15932# define SQLITE_OMIT_LOAD_EXTENSION1 1
15933# define SQLITE_OMIT_WAL 1
15934# define SQLITE_OMIT_DEPRECATED1 1
15935# undef SQLITE_TEMP_STORE1
15936# define SQLITE_TEMP_STORE1 3 /* Always use memory for temporary storage */
15937# define SQLITE_DQS0 0
15938# define SQLITE_OMIT_SHARED_CACHE 1
15939# define SQLITE_OMIT_AUTOINIT 1
15940#endif
15941#if SQLITE_OS_UNIX1+1>1
15942# undef SQLITE_OS_KV0
15943# define SQLITE_OS_KV0 0
15944# undef SQLITE_OS_OTHER0
15945# define SQLITE_OS_OTHER0 0
15946# undef SQLITE_OS_WIN0
15947# define SQLITE_OS_WIN0 0
15948#endif
15949#if SQLITE_OS_WIN0+1>1
15950# undef SQLITE_OS_KV0
15951# define SQLITE_OS_KV0 0
15952# undef SQLITE_OS_OTHER0
15953# define SQLITE_OS_OTHER0 0
15954# undef SQLITE_OS_UNIX1
15955# define SQLITE_OS_UNIX1 0
15956#endif
15957
15958
15959#endif /* SQLITE_OS_SETUP_H */
15960
15961/************** End of os_setup.h ********************************************/
15962/************** Continuing where we left off in os.h *************************/
15963
15964/* If the SET_FULLSYNC macro is not defined above, then make it
15965** a no-op
15966*/
15967#ifndef SET_FULLSYNC
15968# define SET_FULLSYNC(x,y)
15969#endif
15970
15971/* Maximum pathname length. Note: FILENAME_MAX defined by stdio.h
15972*/
15973#ifndef SQLITE_MAX_PATHLEN4096
15974# define SQLITE_MAX_PATHLEN4096 FILENAME_MAX4096
15975#endif
15976
15977/* Maximum number of symlinks that will be resolved while trying to
15978** expand a filename in xFullPathname() in the VFS.
15979*/
15980#ifndef SQLITE_MAX_SYMLINK200
15981# define SQLITE_MAX_SYMLINK200 200
15982#endif
15983
15984/*
15985** The default size of a disk sector
15986*/
15987#ifndef SQLITE_DEFAULT_SECTOR_SIZE4096
15988# define SQLITE_DEFAULT_SECTOR_SIZE4096 4096
15989#endif
15990
15991/*
15992** Temporary files are named starting with this prefix followed by 16 random
15993** alphanumeric characters, and no file extension. They are stored in the
15994** OS's standard temporary file directory, and are deleted prior to exit.
15995** If sqlite is being embedded in another program, you may wish to change the
15996** prefix to reflect your program's name, so that if your program exits
15997** prematurely, old temporary files can be easily identified. This can be done
15998** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
15999**
16000** 2006-10-31: The default prefix used to be "sqlite_". But then
16001** Mcafee started using SQLite in their anti-virus product and it
16002** started putting files with the "sqlite" name in the c:/temp folder.
16003** This annoyed many windows users. Those users would then do a
16004** Google search for "sqlite", find the telephone numbers of the
16005** developers and call to wake them up at night and complain.
16006** For this reason, the default name prefix is changed to be "sqlite"
16007** spelled backwards. So the temp files are still identified, but
16008** anybody smart enough to figure out the code is also likely smart
16009** enough to know that calling the developer will not help get rid
16010** of the file.
16011*/
16012#ifndef SQLITE_TEMP_FILE_PREFIX"etilqs_"
16013# define SQLITE_TEMP_FILE_PREFIX"etilqs_" "etilqs_"
16014#endif
16015
16016/*
16017** The following values may be passed as the second argument to
16018** sqlite3OsLock(). The various locks exhibit the following semantics:
16019**
16020** SHARED: Any number of processes may hold a SHARED lock simultaneously.
16021** RESERVED: A single process may hold a RESERVED lock on a file at
16022** any time. Other processes may hold and obtain new SHARED locks.
16023** PENDING: A single process may hold a PENDING lock on a file at
16024** any one time. Existing SHARED locks may persist, but no new
16025** SHARED locks may be obtained by other processes.
16026** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
16027**
16028** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
16029** process that requests an EXCLUSIVE lock may actually obtain a PENDING
16030** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
16031** sqlite3OsLock().
16032*/
16033#define NO_LOCK0 0
16034#define SHARED_LOCK1 1
16035#define RESERVED_LOCK2 2
16036#define PENDING_LOCK3 3
16037#define EXCLUSIVE_LOCK4 4
16038
16039/*
16040** File Locking Notes: (Mostly about windows but also some info for Unix)
16041**
16042** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
16043** those functions are not available. So we use only LockFile() and
16044** UnlockFile().
16045**
16046** LockFile() prevents not just writing but also reading by other processes.
16047** A SHARED_LOCK is obtained by locking a single randomly-chosen
16048** byte out of a specific range of bytes. The lock byte is obtained at
16049** random so two separate readers can probably access the file at the
16050** same time, unless they are unlucky and choose the same lock byte.
16051** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
16052** There can only be one writer. A RESERVED_LOCK is obtained by locking
16053** a single byte of the file that is designated as the reserved lock byte.
16054** A PENDING_LOCK is obtained by locking a designated byte different from
16055** the RESERVED_LOCK byte.
16056**
16057** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
16058** which means we can use reader/writer locks. When reader/writer locks
16059** are used, the lock is placed on the same range of bytes that is used
16060** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
16061** will support two or more Win95 readers or two or more WinNT readers.
16062** But a single Win95 reader will lock out all WinNT readers and a single
16063** WinNT reader will lock out all other Win95 readers.
16064**
16065** The following #defines specify the range of bytes used for locking.
16066** SHARED_SIZE is the number of bytes available in the pool from which
16067** a random byte is selected for a shared lock. The pool of bytes for
16068** shared locks begins at SHARED_FIRST.
16069**
16070** The same locking strategy and
16071** byte ranges are used for Unix. This leaves open the possibility of having
16072** clients on win95, winNT, and unix all talking to the same shared file
16073** and all locking correctly. To do so would require that samba (or whatever
16074** tool is being used for file sharing) implements locks correctly between
16075** windows and unix. I'm guessing that isn't likely to happen, but by
16076** using the same locking range we are at least open to the possibility.
16077**
16078** Locking in windows is manditory. For this reason, we cannot store
16079** actual data in the bytes used for locking. The pager never allocates
16080** the pages involved in locking therefore. SHARED_SIZE is selected so
16081** that all locks will fit on a single page even at the minimum page size.
16082** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
16083** is set high so that we don't have to allocate an unused page except
16084** for very large databases. But one should test the page skipping logic
16085** by setting PENDING_BYTE low and running the entire regression suite.
16086**
16087** Changing the value of PENDING_BYTE results in a subtly incompatible
16088** file format. Depending on how it is changed, you might not notice
16089** the incompatibility right away, even running a full regression test.
16090** The default location of PENDING_BYTE is the first byte past the
16091** 1GB boundary.
16092**
16093*/
16094#ifdef SQLITE_OMIT_WSD
16095# define PENDING_BYTEsqlite3PendingByte (0x40000000)
16096#else
16097# define PENDING_BYTEsqlite3PendingByte sqlite3PendingByte
16098#endif
16099#define RESERVED_BYTE(sqlite3PendingByte+1) (PENDING_BYTEsqlite3PendingByte+1)
16100#define SHARED_FIRST(sqlite3PendingByte+2) (PENDING_BYTEsqlite3PendingByte+2)
16101#define SHARED_SIZE510 510
16102
16103/*
16104** Wrapper around OS specific sqlite3_os_init() function.
16105*/
16106SQLITE_PRIVATEstatic int sqlite3OsInit(void);
16107
16108/*
16109** Functions for accessing sqlite3_file methods
16110*/
16111SQLITE_PRIVATEstatic void sqlite3OsClose(sqlite3_file*);
16112SQLITE_PRIVATEstatic int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
16113SQLITE_PRIVATEstatic int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
16114SQLITE_PRIVATEstatic int sqlite3OsTruncate(sqlite3_file*, i64 size);
16115SQLITE_PRIVATEstatic int sqlite3OsSync(sqlite3_file*, int);
16116SQLITE_PRIVATEstatic int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
16117SQLITE_PRIVATEstatic int sqlite3OsLock(sqlite3_file*, int);
16118SQLITE_PRIVATEstatic int sqlite3OsUnlock(sqlite3_file*, int);
16119SQLITE_PRIVATEstatic int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
16120SQLITE_PRIVATEstatic int sqlite3OsFileControl(sqlite3_file*,int,void*);
16121SQLITE_PRIVATEstatic void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
16122#define SQLITE_FCNTL_DB_UNCHANGED0xca093fa0 0xca093fa0
16123SQLITE_PRIVATEstatic int sqlite3OsSectorSize(sqlite3_file *id);
16124SQLITE_PRIVATEstatic int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
16125#ifndef SQLITE_OMIT_WAL
16126SQLITE_PRIVATEstatic int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
16127SQLITE_PRIVATEstatic int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
16128SQLITE_PRIVATEstatic void sqlite3OsShmBarrier(sqlite3_file *id);
16129SQLITE_PRIVATEstatic int sqlite3OsShmUnmap(sqlite3_file *id, int);
16130#endif /* SQLITE_OMIT_WAL */
16131SQLITE_PRIVATEstatic int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
16132SQLITE_PRIVATEstatic int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
16133
16134
16135/*
16136** Functions for accessing sqlite3_vfs methods
16137*/
16138SQLITE_PRIVATEstatic int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
16139SQLITE_PRIVATEstatic int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
16140SQLITE_PRIVATEstatic int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
16141SQLITE_PRIVATEstatic int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
16142#ifndef SQLITE_OMIT_LOAD_EXTENSION1
16143SQLITE_PRIVATEstatic void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
16144SQLITE_PRIVATEstatic void sqlite3OsDlError(sqlite3_vfs *, int, char *);
16145SQLITE_PRIVATEstatic void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
16146SQLITE_PRIVATEstatic void sqlite3OsDlClose(sqlite3_vfs *, void *);
16147#endif /* SQLITE_OMIT_LOAD_EXTENSION */
16148SQLITE_PRIVATEstatic int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
16149SQLITE_PRIVATEstatic int sqlite3OsSleep(sqlite3_vfs *, int);
16150SQLITE_PRIVATEstatic int sqlite3OsGetLastError(sqlite3_vfs*);
16151SQLITE_PRIVATEstatic int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
16152
16153/*
16154** Convenience functions for opening and closing files using
16155** sqlite3_malloc() to obtain space for the file-handle structure.
16156*/
16157SQLITE_PRIVATEstatic int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
16158SQLITE_PRIVATEstatic void sqlite3OsCloseFree(sqlite3_file *);
16159
16160#endif /* _SQLITE_OS_H_ */
16161
16162/************** End of os.h **************************************************/
16163/************** Continuing where we left off in sqliteInt.h ******************/
16164/************** Include pager.h in the middle of sqliteInt.h *****************/
16165/************** Begin file pager.h *******************************************/
16166/*
16167** 2001 September 15
16168**
16169** The author disclaims copyright to this source code. In place of
16170** a legal notice, here is a blessing:
16171**
16172** May you do good and not evil.
16173** May you find forgiveness for yourself and forgive others.
16174** May you share freely, never taking more than you give.
16175**
16176*************************************************************************
16177** This header file defines the interface that the sqlite page cache
16178** subsystem. The page cache subsystem reads and writes a file a page
16179** at a time and provides a journal for rollback.
16180*/
16181
16182#ifndef SQLITE_PAGER_H
16183#define SQLITE_PAGER_H
16184
16185/*
16186** Default maximum size for persistent journal files. A negative
16187** value means no limit. This value may be overridden using the
16188** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
16189*/
16190#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT32768
16191 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT32768 -1
16192#endif
16193
16194/*
16195** The type used to represent a page number. The first page in a file
16196** is called page 1. 0 is used to represent "not a page".
16197*/
16198typedef u32 Pgno;
16199
16200/*
16201** Each open file is managed by a separate instance of the "Pager" structure.
16202*/
16203typedef struct Pager Pager;
16204
16205/*
16206** Handle type for pages.
16207*/
16208typedef struct PgHdr DbPage;
16209
16210/*
16211** Page number PAGER_SJ_PGNO is never used in an SQLite database (it is
16212** reserved for working around a windows/posix incompatibility). It is
16213** used in the journal to signify that the remainder of the journal file
16214** is devoted to storing a super-journal name - there are no more pages to
16215** roll back. See comments for function writeSuperJournal() in pager.c
16216** for details.
16217*/
16218#define PAGER_SJ_PGNO_COMPUTED(x)((Pgno)((sqlite3PendingByte/((x)->pageSize))+1)) ((Pgno)((PENDING_BYTEsqlite3PendingByte/((x)->pageSize))+1))
16219#define PAGER_SJ_PGNO(x)((x)->lckPgno) ((x)->lckPgno)
16220
16221/*
16222** Allowed values for the flags parameter to sqlite3PagerOpen().
16223**
16224** NOTE: These values must match the corresponding BTREE_ values in btree.h.
16225*/
16226#define PAGER_OMIT_JOURNAL0x0001 0x0001 /* Do not use a rollback journal */
16227#define PAGER_MEMORY0x0002 0x0002 /* In-memory database */
16228
16229/*
16230** Valid values for the second argument to sqlite3PagerLockingMode().
16231*/
16232#define PAGER_LOCKINGMODE_QUERY-1 -1
16233#define PAGER_LOCKINGMODE_NORMAL0 0
16234#define PAGER_LOCKINGMODE_EXCLUSIVE1 1
16235
16236/*
16237** Numeric constants that encode the journalmode.
16238**
16239** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
16240** are exposed in the API via the "PRAGMA journal_mode" command and
16241** therefore cannot be changed without a compatibility break.
16242*/
16243#define PAGER_JOURNALMODE_QUERY(-1) (-1) /* Query the value of journalmode */
16244#define PAGER_JOURNALMODE_DELETE0 0 /* Commit by deleting journal file */
16245#define PAGER_JOURNALMODE_PERSIST1 1 /* Commit by zeroing journal header */
16246#define PAGER_JOURNALMODE_OFF2 2 /* Journal omitted. */
16247#define PAGER_JOURNALMODE_TRUNCATE3 3 /* Commit by truncating journal */
16248#define PAGER_JOURNALMODE_MEMORY4 4 /* In-memory journal file */
16249#define PAGER_JOURNALMODE_WAL5 5 /* Use write-ahead logging */
16250
16251#define isWalMode(x)((x)==5) ((x)==PAGER_JOURNALMODE_WAL5)
16252
16253/*
16254** The argument to this macro is a file descriptor (type sqlite3_file*).
16255** Return 0 if it is not open, or non-zero (but not 1) if it is.
16256**
16257** This is so that expressions can be written as:
16258**
16259** if( isOpen(pPager->jfd) ){ ...
16260**
16261** instead of
16262**
16263** if( pPager->jfd->pMethods ){ ...
16264*/
16265#define isOpen(pFd)((pFd)->pMethods!=0) ((pFd)->pMethods!=0)
16266
16267/*
16268** Flags that make up the mask passed to sqlite3PagerGet().
16269*/
16270#define PAGER_GET_NOCONTENT0x01 0x01 /* Do not load data from disk */
16271#define PAGER_GET_READONLY0x02 0x02 /* Read-only page is acceptable */
16272
16273/*
16274** Flags for sqlite3PagerSetFlags()
16275**
16276** Value constraints (enforced via assert()):
16277** PAGER_FULLFSYNC == SQLITE_FullFSync
16278** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
16279** PAGER_CACHE_SPILL == SQLITE_CacheSpill
16280*/
16281#define PAGER_SYNCHRONOUS_OFF0x01 0x01 /* PRAGMA synchronous=OFF */
16282#define PAGER_SYNCHRONOUS_NORMAL0x02 0x02 /* PRAGMA synchronous=NORMAL */
16283#define PAGER_SYNCHRONOUS_FULL0x03 0x03 /* PRAGMA synchronous=FULL */
16284#define PAGER_SYNCHRONOUS_EXTRA0x04 0x04 /* PRAGMA synchronous=EXTRA */
16285#define PAGER_SYNCHRONOUS_MASK0x07 0x07 /* Mask for four values above */
16286#define PAGER_FULLFSYNC0x08 0x08 /* PRAGMA fullfsync=ON */
16287#define PAGER_CKPT_FULLFSYNC0x10 0x10 /* PRAGMA checkpoint_fullfsync=ON */
16288#define PAGER_CACHESPILL0x20 0x20 /* PRAGMA cache_spill=ON */
16289#define PAGER_FLAGS_MASK0x38 0x38 /* All above except SYNCHRONOUS */
16290
16291/*
16292** The remainder of this file contains the declarations of the functions
16293** that make up the Pager sub-system API. See source code comments for
16294** a detailed description of each routine.
16295*/
16296
16297/* Open and close a Pager connection. */
16298SQLITE_PRIVATEstatic int sqlite3PagerOpen(
16299 sqlite3_vfs*,
16300 Pager **ppPager,
16301 const char*,
16302 int,
16303 int,
16304 int,
16305 void(*)(DbPage*)
16306);
16307SQLITE_PRIVATEstatic int sqlite3PagerClose(Pager *pPager, sqlite3*);
16308SQLITE_PRIVATEstatic int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
16309
16310/* Functions used to configure a Pager object. */
16311SQLITE_PRIVATEstatic void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
16312SQLITE_PRIVATEstatic int sqlite3PagerSetPagesize(Pager*, u32*, int);
16313SQLITE_PRIVATEstatic Pgno sqlite3PagerMaxPageCount(Pager*, Pgno);
16314SQLITE_PRIVATEstatic void sqlite3PagerSetCachesize(Pager*, int);
16315SQLITE_PRIVATEstatic int sqlite3PagerSetSpillsize(Pager*, int);
16316SQLITE_PRIVATEstatic void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
16317SQLITE_PRIVATEstatic void sqlite3PagerShrink(Pager*);
16318SQLITE_PRIVATEstatic void sqlite3PagerSetFlags(Pager*,unsigned);
16319SQLITE_PRIVATEstatic int sqlite3PagerLockingMode(Pager *, int);
16320SQLITE_PRIVATEstatic int sqlite3PagerSetJournalMode(Pager *, int);
16321SQLITE_PRIVATEstatic int sqlite3PagerGetJournalMode(Pager*);
16322SQLITE_PRIVATEstatic int sqlite3PagerOkToChangeJournalMode(Pager*);
16323SQLITE_PRIVATEstatic i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
16324SQLITE_PRIVATEstatic sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
16325SQLITE_PRIVATEstatic int sqlite3PagerFlush(Pager*);
16326
16327/* Functions used to obtain and release page references. */
16328SQLITE_PRIVATEstatic int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
16329SQLITE_PRIVATEstatic DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
16330SQLITE_PRIVATEstatic void sqlite3PagerRef(DbPage*);
16331SQLITE_PRIVATEstatic void sqlite3PagerUnref(DbPage*);
16332SQLITE_PRIVATEstatic void sqlite3PagerUnrefNotNull(DbPage*);
16333SQLITE_PRIVATEstatic void sqlite3PagerUnrefPageOne(DbPage*);
16334
16335/* Operations on page references. */
16336SQLITE_PRIVATEstatic int sqlite3PagerWrite(DbPage*);
16337SQLITE_PRIVATEstatic void sqlite3PagerDontWrite(DbPage*);
16338SQLITE_PRIVATEstatic int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
16339SQLITE_PRIVATEstatic int sqlite3PagerPageRefcount(DbPage*);
16340SQLITE_PRIVATEstatic void *sqlite3PagerGetData(DbPage *);
16341SQLITE_PRIVATEstatic void *sqlite3PagerGetExtra(DbPage *);
16342
16343/* Functions used to manage pager transactions and savepoints. */
16344SQLITE_PRIVATEstatic void sqlite3PagerPagecount(Pager*, int*);
16345SQLITE_PRIVATEstatic int sqlite3PagerBegin(Pager*, int exFlag, int);
16346SQLITE_PRIVATEstatic int sqlite3PagerCommitPhaseOne(Pager*,const char *zSuper, int);
16347SQLITE_PRIVATEstatic int sqlite3PagerExclusiveLock(Pager*);
16348SQLITE_PRIVATEstatic int sqlite3PagerSync(Pager *pPager, const char *zSuper);
16349SQLITE_PRIVATEstatic int sqlite3PagerCommitPhaseTwo(Pager*);
16350SQLITE_PRIVATEstatic int sqlite3PagerRollback(Pager*);
16351SQLITE_PRIVATEstatic int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
16352SQLITE_PRIVATEstatic int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
16353SQLITE_PRIVATEstatic int sqlite3PagerSharedLock(Pager *pPager);
16354
16355#ifndef SQLITE_OMIT_WAL
16356SQLITE_PRIVATEstatic int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
16357SQLITE_PRIVATEstatic int sqlite3PagerWalSupported(Pager *pPager);
16358SQLITE_PRIVATEstatic int sqlite3PagerWalCallback(Pager *pPager);
16359SQLITE_PRIVATEstatic int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
16360SQLITE_PRIVATEstatic int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
16361# ifdef SQLITE_ENABLE_SNAPSHOT1
16362SQLITE_PRIVATEstatic int sqlite3PagerSnapshotGet(Pager*, sqlite3_snapshot **ppSnapshot);
16363SQLITE_PRIVATEstatic int sqlite3PagerSnapshotOpen(Pager*, sqlite3_snapshot *pSnapshot);
16364SQLITE_PRIVATEstatic int sqlite3PagerSnapshotRecover(Pager *pPager);
16365SQLITE_PRIVATEstatic int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
16366SQLITE_PRIVATEstatic void sqlite3PagerSnapshotUnlock(Pager *pPager);
16367# endif
16368#endif
16369
16370#if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_ENABLE_SETLK_TIMEOUT)
16371SQLITE_PRIVATEstatic int sqlite3PagerWalWriteLock(Pager*, int)0;
16372SQLITE_PRIVATEstatic void sqlite3PagerWalDb(Pager*, sqlite3*);
16373#else
16374# define sqlite3PagerWalWriteLock(y,z)0 SQLITE_OK0
16375# define sqlite3PagerWalDb(x,y)
16376#endif
16377
16378#ifdef SQLITE_DIRECT_OVERFLOW_READ1
16379SQLITE_PRIVATEstatic int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
16380#endif
16381
16382#ifdef SQLITE_ENABLE_ZIPVFS
16383SQLITE_PRIVATEstatic int sqlite3PagerWalFramesize(Pager *pPager);
16384#endif
16385
16386/* Functions used to query pager state and configuration. */
16387SQLITE_PRIVATEstatic u8 sqlite3PagerIsreadonly(Pager*);
16388SQLITE_PRIVATEstatic u32 sqlite3PagerDataVersion(Pager*);
16389#ifdef SQLITE_DEBUG
16390SQLITE_PRIVATEstatic int sqlite3PagerRefcount(Pager*);
16391#endif
16392SQLITE_PRIVATEstatic int sqlite3PagerMemUsed(Pager*);
16393SQLITE_PRIVATEstatic const char *sqlite3PagerFilename(const Pager*, int);
16394SQLITE_PRIVATEstatic sqlite3_vfs *sqlite3PagerVfs(Pager*);
16395SQLITE_PRIVATEstatic sqlite3_file *sqlite3PagerFile(Pager*);
16396SQLITE_PRIVATEstatic sqlite3_file *sqlite3PagerJrnlFile(Pager*);
16397SQLITE_PRIVATEstatic const char *sqlite3PagerJournalname(Pager*);
16398SQLITE_PRIVATEstatic void *sqlite3PagerTempSpace(Pager*);
16399SQLITE_PRIVATEstatic int sqlite3PagerIsMemdb(Pager*);
16400SQLITE_PRIVATEstatic void sqlite3PagerCacheStat(Pager *, int, int, u64*);
16401SQLITE_PRIVATEstatic void sqlite3PagerClearCache(Pager*);
16402SQLITE_PRIVATEstatic int sqlite3SectorSize(sqlite3_file *);
16403
16404/* Functions used to truncate the database file. */
16405SQLITE_PRIVATEstatic void sqlite3PagerTruncateImage(Pager*,Pgno);
16406
16407SQLITE_PRIVATEstatic void sqlite3PagerRekey(DbPage*, Pgno, u16);
16408
16409/* Functions to support testing and debugging. */
16410#if !defined(NDEBUG1) || defined(SQLITE_TEST)
16411SQLITE_PRIVATEstatic Pgno sqlite3PagerPagenumber(DbPage*);
16412SQLITE_PRIVATEstatic int sqlite3PagerIswriteable(DbPage*);
16413#endif
16414#ifdef SQLITE_TEST
16415SQLITE_PRIVATEstatic int *sqlite3PagerStats(Pager*);
16416SQLITE_PRIVATEstatic void sqlite3PagerRefdump(Pager*);
16417 void disable_simulated_io_errors(void);
16418 void enable_simulated_io_errors(void);
16419#else
16420# define disable_simulated_io_errors()
16421# define enable_simulated_io_errors()
16422#endif
16423
16424#if defined(SQLITE_USE_SEH) && !defined(SQLITE_OMIT_WAL)
16425SQLITE_PRIVATEstatic int sqlite3PagerWalSystemErrno(Pager*);
16426#endif
16427
16428#endif /* SQLITE_PAGER_H */
16429
16430/************** End of pager.h ***********************************************/
16431/************** Continuing where we left off in sqliteInt.h ******************/
16432/************** Include btree.h in the middle of sqliteInt.h *****************/
16433/************** Begin file btree.h *******************************************/
16434/*
16435** 2001 September 15
16436**
16437** The author disclaims copyright to this source code. In place of
16438** a legal notice, here is a blessing:
16439**
16440** May you do good and not evil.
16441** May you find forgiveness for yourself and forgive others.
16442** May you share freely, never taking more than you give.
16443**
16444*************************************************************************
16445** This header file defines the interface that the sqlite B-Tree file
16446** subsystem. See comments in the source code for a detailed description
16447** of what each interface routine does.
16448*/
16449#ifndef SQLITE_BTREE_H
16450#define SQLITE_BTREE_H
16451
16452/* TODO: This definition is just included so other modules compile. It
16453** needs to be revisited.
16454*/
16455#define SQLITE_N_BTREE_META16 16
16456
16457/*
16458** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
16459** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
16460*/
16461#ifndef SQLITE_DEFAULT_AUTOVACUUM0
16462 #define SQLITE_DEFAULT_AUTOVACUUM0 0
16463#endif
16464
16465#define BTREE_AUTOVACUUM_NONE0 0 /* Do not do auto-vacuum */
16466#define BTREE_AUTOVACUUM_FULL1 1 /* Do full auto-vacuum */
16467#define BTREE_AUTOVACUUM_INCR2 2 /* Incremental vacuum */
16468
16469/*
16470** Forward declarations of structure
16471*/
16472typedef struct Btree Btree;
16473typedef struct BtCursor BtCursor;
16474typedef struct BtShared BtShared;
16475typedef struct BtreePayload BtreePayload;
16476
16477
16478SQLITE_PRIVATEstatic int sqlite3BtreeOpen(
16479 sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
16480 const char *zFilename, /* Name of database file to open */
16481 sqlite3 *db, /* Associated database connection */
16482 Btree **ppBtree, /* Return open Btree* here */
16483 int flags, /* Flags */
16484 int vfsFlags /* Flags passed through to VFS open */
16485);
16486
16487/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
16488** following values.
16489**
16490** NOTE: These values must match the corresponding PAGER_ values in
16491** pager.h.
16492*/
16493#define BTREE_OMIT_JOURNAL1 1 /* Do not create or use a rollback journal */
16494#define BTREE_MEMORY2 2 /* This is an in-memory DB */
16495#define BTREE_SINGLE4 4 /* The file contains at most 1 b-tree */
16496#define BTREE_UNORDERED8 8 /* Use of a hash implementation is OK */
16497
16498SQLITE_PRIVATEstatic int sqlite3BtreeClose(Btree*);
16499SQLITE_PRIVATEstatic int sqlite3BtreeSetCacheSize(Btree*,int);
16500SQLITE_PRIVATEstatic int sqlite3BtreeSetSpillSize(Btree*,int);
16501#if SQLITE_MAX_MMAP_SIZE20971520>0
16502SQLITE_PRIVATEstatic int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
16503#endif
16504SQLITE_PRIVATEstatic int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
16505SQLITE_PRIVATEstatic int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
16506SQLITE_PRIVATEstatic int sqlite3BtreeGetPageSize(Btree*);
16507SQLITE_PRIVATEstatic Pgno sqlite3BtreeMaxPageCount(Btree*,Pgno);
16508SQLITE_PRIVATEstatic Pgno sqlite3BtreeLastPage(Btree*);
16509SQLITE_PRIVATEstatic int sqlite3BtreeSecureDelete(Btree*,int);
16510SQLITE_PRIVATEstatic int sqlite3BtreeGetRequestedReserve(Btree*);
16511SQLITE_PRIVATEstatic int sqlite3BtreeGetReserveNoMutex(Btree *p);
16512SQLITE_PRIVATEstatic int sqlite3BtreeSetAutoVacuum(Btree *, int);
16513SQLITE_PRIVATEstatic int sqlite3BtreeGetAutoVacuum(Btree *);
16514SQLITE_PRIVATEstatic int sqlite3BtreeBeginTrans(Btree*,int,int*);
16515SQLITE_PRIVATEstatic int sqlite3BtreeCommitPhaseOne(Btree*, const char*);
16516SQLITE_PRIVATEstatic int sqlite3BtreeCommitPhaseTwo(Btree*, int);
16517SQLITE_PRIVATEstatic int sqlite3BtreeCommit(Btree*);
16518SQLITE_PRIVATEstatic int sqlite3BtreeRollback(Btree*,int,int);
16519SQLITE_PRIVATEstatic int sqlite3BtreeBeginStmt(Btree*,int);
16520SQLITE_PRIVATEstatic int sqlite3BtreeCreateTable(Btree*, Pgno*, int flags);
16521SQLITE_PRIVATEstatic int sqlite3BtreeTxnState(Btree*);
16522SQLITE_PRIVATEstatic int sqlite3BtreeIsInBackup(Btree*);
16523
16524SQLITE_PRIVATEstatic void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
16525SQLITE_PRIVATEstatic int sqlite3BtreeSchemaLocked(Btree *pBtree);
16526#ifndef SQLITE_OMIT_SHARED_CACHE
16527SQLITE_PRIVATEstatic int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
16528#endif
16529
16530/* Savepoints are named, nestable SQL transactions mostly implemented */
16531/* in vdbe.c and pager.c See https://sqlite.org/lang_savepoint.html */
16532SQLITE_PRIVATEstatic int sqlite3BtreeSavepoint(Btree *, int, int);
16533
16534/* "Checkpoint" only refers to WAL. See https://sqlite.org/wal.html#ckpt */
16535#ifndef SQLITE_OMIT_WAL
16536SQLITE_PRIVATEstatic int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
16537#endif
16538
16539SQLITE_PRIVATEstatic const char *sqlite3BtreeGetFilename(Btree *);
16540SQLITE_PRIVATEstatic const char *sqlite3BtreeGetJournalname(Btree *);
16541SQLITE_PRIVATEstatic int sqlite3BtreeCopyFile(Btree *, Btree *);
16542
16543SQLITE_PRIVATEstatic int sqlite3BtreeIncrVacuum(Btree *);
16544
16545/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
16546** of the flags shown below.
16547**
16548** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
16549** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
16550** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
16551** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
16552** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
16553** indices.)
16554*/
16555#define BTREE_INTKEY1 1 /* Table has only 64-bit signed integer keys */
16556#define BTREE_BLOBKEY2 2 /* Table has keys only - no data */
16557
16558SQLITE_PRIVATEstatic int sqlite3BtreeDropTable(Btree*, int, int*);
16559SQLITE_PRIVATEstatic int sqlite3BtreeClearTable(Btree*, int, i64*);
16560SQLITE_PRIVATEstatic int sqlite3BtreeClearTableOfCursor(BtCursor*);
16561SQLITE_PRIVATEstatic int sqlite3BtreeTripAllCursors(Btree*, int, int);
16562
16563SQLITE_PRIVATEstatic void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
16564SQLITE_PRIVATEstatic int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
16565
16566SQLITE_PRIVATEstatic int sqlite3BtreeNewDb(Btree *p);
16567
16568/*
16569** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
16570** should be one of the following values. The integer values are assigned
16571** to constants so that the offset of the corresponding field in an
16572** SQLite database header may be found using the following formula:
16573**
16574** offset = 36 + (idx * 4)
16575**
16576** For example, the free-page-count field is located at byte offset 36 of
16577** the database file header. The incr-vacuum-flag field is located at
16578** byte offset 64 (== 36+4*7).
16579**
16580** The BTREE_DATA_VERSION value is not really a value stored in the header.
16581** It is a read-only number computed by the pager. But we merge it with
16582** the header value access routines since its access pattern is the same.
16583** Call it a "virtual meta value".
16584*/
16585#define BTREE_FREE_PAGE_COUNT0 0
16586#define BTREE_SCHEMA_VERSION1 1
16587#define BTREE_FILE_FORMAT2 2
16588#define BTREE_DEFAULT_CACHE_SIZE3 3
16589#define BTREE_LARGEST_ROOT_PAGE4 4
16590#define BTREE_TEXT_ENCODING5 5
16591#define BTREE_USER_VERSION6 6
16592#define BTREE_INCR_VACUUM7 7
16593#define BTREE_APPLICATION_ID8 8
16594#define BTREE_DATA_VERSION15 15 /* A virtual meta-value */
16595
16596/*
16597** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
16598** interface.
16599**
16600** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
16601**
16602** The first argument is an Expr* (which is guaranteed to be constant for
16603** the lifetime of the cursor) that defines constraints on which rows
16604** might be fetched with this cursor. The Expr* tree may contain
16605** TK_REGISTER nodes that refer to values stored in the array of registers
16606** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
16607** then the value of the node is the value in Mem[pExpr.iTable]. Any
16608** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
16609** column of the b-tree of the cursor. The Expr tree will not contain
16610** any function calls nor subqueries nor references to b-trees other than
16611** the cursor being hinted.
16612**
16613** The design of the _RANGE hint is aid b-tree implementations that try
16614** to prefetch content from remote machines - to provide those
16615** implementations with limits on what needs to be prefetched and thereby
16616** reduce network bandwidth.
16617**
16618** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
16619** standard SQLite. The other hints are provided for extensions that use
16620** the SQLite parser and code generator but substitute their own storage
16621** engine.
16622*/
16623#define BTREE_HINT_RANGE0 0 /* Range constraints on queries */
16624
16625/*
16626** Values that may be OR'd together to form the argument to the
16627** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
16628**
16629** The BTREE_BULKLOAD flag is set on index cursors when the index is going
16630** to be filled with content that is already in sorted order.
16631**
16632** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
16633** OP_SeekLE opcodes for a range search, but where the range of entries
16634** selected will all have the same key. In other words, the cursor will
16635** be used only for equality key searches.
16636**
16637*/
16638#define BTREE_BULKLOAD0x00000001 0x00000001 /* Used to full index in sorted order */
16639#define BTREE_SEEK_EQ0x00000002 0x00000002 /* EQ seeks only - no range seeks */
16640
16641/*
16642** Flags passed as the third argument to sqlite3BtreeCursor().
16643**
16644** For read-only cursors the wrFlag argument is always zero. For read-write
16645** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
16646** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
16647** only be used by SQLite for the following:
16648**
16649** * to seek to and then delete specific entries, and/or
16650**
16651** * to read values that will be used to create keys that other
16652** BTREE_FORDELETE cursors will seek to and delete.
16653**
16654** The BTREE_FORDELETE flag is an optimization hint. It is not used by
16655** by this, the native b-tree engine of SQLite, but it is available to
16656** alternative storage engines that might be substituted in place of this
16657** b-tree system. For alternative storage engines in which a delete of
16658** the main table row automatically deletes corresponding index rows,
16659** the FORDELETE flag hint allows those alternative storage engines to
16660** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
16661** and DELETE operations as no-ops, and any READ operation against a
16662** FORDELETE cursor may return a null row: 0x01 0x00.
16663*/
16664#define BTREE_WRCSR0x00000004 0x00000004 /* read-write cursor */
16665#define BTREE_FORDELETE0x00000008 0x00000008 /* Cursor is for seek/delete only */
16666
16667SQLITE_PRIVATEstatic int sqlite3BtreeCursor(
16668 Btree*, /* BTree containing table to open */
16669 Pgno iTable, /* Index of root page */
16670 int wrFlag, /* 1 for writing. 0 for read-only */
16671 struct KeyInfo*, /* First argument to compare function */
16672 BtCursor *pCursor /* Space to write cursor structure */
16673);
16674SQLITE_PRIVATEstatic BtCursor *sqlite3BtreeFakeValidCursor(void);
16675SQLITE_PRIVATEstatic int sqlite3BtreeCursorSize(void);
16676#ifdef SQLITE_DEBUG
16677SQLITE_PRIVATEstatic int sqlite3BtreeClosesWithCursor(Btree*,BtCursor*);
16678#endif
16679SQLITE_PRIVATEstatic void sqlite3BtreeCursorZero(BtCursor*);
16680SQLITE_PRIVATEstatic void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
16681#ifdef SQLITE_ENABLE_CURSOR_HINTS
16682SQLITE_PRIVATEstatic void sqlite3BtreeCursorHint(BtCursor*, int, ...);
16683#endif
16684
16685SQLITE_PRIVATEstatic int sqlite3BtreeCloseCursor(BtCursor*);
16686SQLITE_PRIVATEstatic int sqlite3BtreeTableMoveto(
16687 BtCursor*,
16688 i64 intKey,
16689 int bias,
16690 int *pRes
16691);
16692SQLITE_PRIVATEstatic int sqlite3BtreeIndexMoveto(
16693 BtCursor*,
16694 UnpackedRecord *pUnKey,
16695 int *pRes
16696);
16697SQLITE_PRIVATEstatic int sqlite3BtreeCursorHasMoved(BtCursor*);
16698SQLITE_PRIVATEstatic int sqlite3BtreeCursorRestore(BtCursor*, int*);
16699SQLITE_PRIVATEstatic int sqlite3BtreeDelete(BtCursor*, u8 flags);
16700
16701/* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
16702#define BTREE_SAVEPOSITION0x02 0x02 /* Leave cursor pointing at NEXT or PREV */
16703#define BTREE_AUXDELETE0x04 0x04 /* not the primary delete operation */
16704#define BTREE_APPEND0x08 0x08 /* Insert is likely an append */
16705#define BTREE_PREFORMAT0x80 0x80 /* Inserted data is a preformated cell */
16706
16707/* An instance of the BtreePayload object describes the content of a single
16708** entry in either an index or table btree.
16709**
16710** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
16711** an arbitrary key and no data. These btrees have pKey,nKey set to the
16712** key and the pData,nData,nZero fields are uninitialized. The aMem,nMem
16713** fields give an array of Mem objects that are a decomposition of the key.
16714** The nMem field might be zero, indicating that no decomposition is available.
16715**
16716** Table btrees (used for rowid tables) contain an integer rowid used as
16717** the key and passed in the nKey field. The pKey field is zero.
16718** pData,nData hold the content of the new entry. nZero extra zero bytes
16719** are appended to the end of the content when constructing the entry.
16720** The aMem,nMem fields are uninitialized for table btrees.
16721**
16722** Field usage summary:
16723**
16724** Table BTrees Index Btrees
16725**
16726** pKey always NULL encoded key
16727** nKey the ROWID length of pKey
16728** pData data not used
16729** aMem not used decomposed key value
16730** nMem not used entries in aMem
16731** nData length of pData not used
16732** nZero extra zeros after pData not used
16733**
16734** This object is used to pass information into sqlite3BtreeInsert(). The
16735** same information used to be passed as five separate parameters. But placing
16736** the information into this object helps to keep the interface more
16737** organized and understandable, and it also helps the resulting code to
16738** run a little faster by using fewer registers for parameter passing.
16739*/
16740struct BtreePayload {
16741 const void *pKey; /* Key content for indexes. NULL for tables */
16742 sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
16743 const void *pData; /* Data for tables. */
16744 sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
16745 u16 nMem; /* Number of aMem[] value. Might be zero */
16746 int nData; /* Size of pData. 0 if none. */
16747 int nZero; /* Extra zero data appended after pData,nData */
16748};
16749
16750SQLITE_PRIVATEstatic int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
16751 int flags, int seekResult);
16752SQLITE_PRIVATEstatic int sqlite3BtreeFirst(BtCursor*, int *pRes);
16753SQLITE_PRIVATEstatic int sqlite3BtreeLast(BtCursor*, int *pRes);
16754SQLITE_PRIVATEstatic int sqlite3BtreeNext(BtCursor*, int flags);
16755SQLITE_PRIVATEstatic int sqlite3BtreeEof(BtCursor*);
16756SQLITE_PRIVATEstatic int sqlite3BtreePrevious(BtCursor*, int flags);
16757SQLITE_PRIVATEstatic i64 sqlite3BtreeIntegerKey(BtCursor*);
16758SQLITE_PRIVATEstatic void sqlite3BtreeCursorPin(BtCursor*);
16759SQLITE_PRIVATEstatic void sqlite3BtreeCursorUnpin(BtCursor*);
16760SQLITE_PRIVATEstatic i64 sqlite3BtreeOffset(BtCursor*);
16761SQLITE_PRIVATEstatic int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
16762SQLITE_PRIVATEstatic const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
16763SQLITE_PRIVATEstatic u32 sqlite3BtreePayloadSize(BtCursor*);
16764SQLITE_PRIVATEstatic sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*);
16765
16766SQLITE_PRIVATEstatic int sqlite3BtreeIntegrityCheck(
16767 sqlite3 *db, /* Database connection that is running the check */
16768 Btree *p, /* The btree to be checked */
16769 Pgno *aRoot, /* An array of root pages numbers for individual trees */
16770 sqlite3_value *aCnt, /* OUT: entry counts for each btree in aRoot[] */
16771 int nRoot, /* Number of entries in aRoot[] */
16772 int mxErr, /* Stop reporting errors after this many */
16773 int *pnErr, /* OUT: Write number of errors seen to this variable */
16774 char **pzOut /* OUT: Write the error message string here */
16775);
16776SQLITE_PRIVATEstatic struct Pager *sqlite3BtreePager(Btree*);
16777SQLITE_PRIVATEstatic i64 sqlite3BtreeRowCountEst(BtCursor*);
16778
16779#ifndef SQLITE_OMIT_INCRBLOB
16780SQLITE_PRIVATEstatic int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
16781SQLITE_PRIVATEstatic int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
16782SQLITE_PRIVATEstatic void sqlite3BtreeIncrblobCursor(BtCursor *);
16783#endif
16784SQLITE_PRIVATEstatic void sqlite3BtreeClearCursor(BtCursor *);
16785SQLITE_PRIVATEstatic int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
16786SQLITE_PRIVATEstatic int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
16787SQLITE_PRIVATEstatic int sqlite3BtreeIsReadonly(Btree *pBt);
16788SQLITE_PRIVATEstatic int sqlite3HeaderSizeBtree(void);
16789
16790#ifdef SQLITE_DEBUG
16791SQLITE_PRIVATEstatic sqlite3_uint64 sqlite3BtreeSeekCount(Btree*)0;
16792#else
16793# define sqlite3BtreeSeekCount(X)0 0
16794#endif
16795
16796#ifndef NDEBUG1
16797SQLITE_PRIVATEstatic int sqlite3BtreeCursorIsValid(BtCursor*);
16798#endif
16799SQLITE_PRIVATEstatic int sqlite3BtreeCursorIsValidNN(BtCursor*);
16800
16801SQLITE_PRIVATEstatic int sqlite3BtreeCount(sqlite3*, BtCursor*, i64*);
16802
16803#ifdef SQLITE_TEST
16804SQLITE_PRIVATEstatic int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
16805SQLITE_PRIVATEstatic void sqlite3BtreeCursorList(Btree*);
16806#endif
16807
16808#ifndef SQLITE_OMIT_WAL
16809SQLITE_PRIVATEstatic int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
16810#endif
16811
16812SQLITE_PRIVATEstatic int sqlite3BtreeTransferRow(BtCursor*, BtCursor*, i64);
16813
16814SQLITE_PRIVATEstatic void sqlite3BtreeClearCache(Btree*);
16815
16816/*
16817** If we are not using shared cache, then there is no need to
16818** use mutexes to access the BtShared structures. So make the
16819** Enter and Leave procedures no-ops.
16820*/
16821#ifndef SQLITE_OMIT_SHARED_CACHE
16822SQLITE_PRIVATEstatic void sqlite3BtreeEnter(Btree*);
16823SQLITE_PRIVATEstatic void sqlite3BtreeEnterAll(sqlite3*);
16824SQLITE_PRIVATEstatic int sqlite3BtreeSharable(Btree*);
16825SQLITE_PRIVATEstatic void sqlite3BtreeEnterCursor(BtCursor*);
16826SQLITE_PRIVATEstatic int sqlite3BtreeConnectionCount(Btree*);
16827#else
16828# define sqlite3BtreeEnter(X)
16829# define sqlite3BtreeEnterAll(X)
16830# define sqlite3BtreeSharable(X) 0
16831# define sqlite3BtreeEnterCursor(X)
16832# define sqlite3BtreeConnectionCount(X) 1
16833#endif
16834
16835#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE2
16836SQLITE_PRIVATEstatic void sqlite3BtreeLeave(Btree*);
16837SQLITE_PRIVATEstatic void sqlite3BtreeLeaveCursor(BtCursor*);
16838SQLITE_PRIVATEstatic void sqlite3BtreeLeaveAll(sqlite3*);
16839#ifndef NDEBUG1
16840 /* These routines are used inside assert() statements only. */
16841SQLITE_PRIVATEstatic int sqlite3BtreeHoldsMutex(Btree*);
16842SQLITE_PRIVATEstatic int sqlite3BtreeHoldsAllMutexes(sqlite3*);
16843SQLITE_PRIVATEstatic int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
16844#endif
16845#else
16846
16847# define sqlite3BtreeLeave(X)
16848# define sqlite3BtreeLeaveCursor(X)
16849# define sqlite3BtreeLeaveAll(X)
16850
16851# define sqlite3BtreeHoldsMutex(X) 1
16852# define sqlite3BtreeHoldsAllMutexes(X) 1
16853# define sqlite3SchemaMutexHeld(X,Y,Z) 1
16854#endif
16855
16856
16857#endif /* SQLITE_BTREE_H */
16858
16859/************** End of btree.h ***********************************************/
16860/************** Continuing where we left off in sqliteInt.h ******************/
16861/************** Include vdbe.h in the middle of sqliteInt.h ******************/
16862/************** Begin file vdbe.h ********************************************/
16863/*
16864** 2001 September 15
16865**
16866** The author disclaims copyright to this source code. In place of
16867** a legal notice, here is a blessing:
16868**
16869** May you do good and not evil.
16870** May you find forgiveness for yourself and forgive others.
16871** May you share freely, never taking more than you give.
16872**
16873*************************************************************************
16874** Header file for the Virtual DataBase Engine (VDBE)
16875**
16876** This header defines the interface to the virtual database engine
16877** or VDBE. The VDBE implements an abstract machine that runs a
16878** simple program to access and modify the underlying database.
16879*/
16880#ifndef SQLITE_VDBE_H
16881#define SQLITE_VDBE_H
16882/* #include <stdio.h> */
16883
16884/*
16885** A single VDBE is an opaque structure named "Vdbe". Only routines
16886** in the source file sqliteVdbe.c are allowed to see the insides
16887** of this structure.
16888*/
16889typedef struct Vdbe Vdbe;
16890
16891/*
16892** The names of the following types declared in vdbeInt.h are required
16893** for the VdbeOp definition.
16894*/
16895typedef struct sqlite3_value Mem;
16896typedef struct SubProgram SubProgram;
16897typedef struct SubrtnSig SubrtnSig;
16898
16899/*
16900** A signature for a reusable subroutine that materializes the RHS of
16901** an IN operator.
16902*/
16903struct SubrtnSig {
16904 int selId; /* SELECT-id for the SELECT statement on the RHS */
16905 u8 bComplete; /* True if fully coded and available for reusable */
16906 char *zAff; /* Affinity of the overall IN expression */
16907 int iTable; /* Ephemeral table generated by the subroutine */
16908 int iAddr; /* Subroutine entry address */
16909 int regReturn; /* Register used to hold return address */
16910};
16911
16912/*
16913** A single instruction of the virtual machine has an opcode
16914** and as many as three operands. The instruction is recorded
16915** as an instance of the following structure:
16916*/
16917struct VdbeOp {
16918 u8 opcode; /* What operation to perform */
16919 signed char p4type; /* One of the P4_xxx constants for p4 */
16920 u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
16921 int p1; /* First operand */
16922 int p2; /* Second parameter (often the jump destination) */
16923 int p3; /* The third parameter */
16924 union p4union { /* fourth parameter */
16925 int i; /* Integer value if p4type==P4_INT32 */
16926 void *p; /* Generic pointer */
16927 char *z; /* Pointer to data for string (char array) types */
16928 i64 *pI64; /* Used when p4type is P4_INT64 */
16929 double *pReal; /* Used when p4type is P4_REAL */
16930 FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
16931 sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
16932 CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
16933 Mem *pMem; /* Used when p4type is P4_MEM */
16934 VTable *pVtab; /* Used when p4type is P4_VTAB */
16935 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
16936 u32 *ai; /* Used when p4type is P4_INTARRAY */
16937 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
16938 Table *pTab; /* Used when p4type is P4_TABLE */
16939 SubrtnSig *pSubrtnSig; /* Used when p4type is P4_SUBRTNSIG */
16940#ifdef SQLITE_ENABLE_CURSOR_HINTS
16941 Expr *pExpr; /* Used when p4type is P4_EXPR */
16942#endif
16943 } p4;
16944#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
16945 char *zComment; /* Comment to improve readability */
16946#endif
16947#ifdef SQLITE_VDBE_COVERAGE
16948 u32 iSrcLine; /* Source-code line that generated this opcode
16949 ** with flags in the upper 8 bits */
16950#endif
16951#if defined(SQLITE_ENABLE_STMT_SCANSTATUS1) || defined(VDBE_PROFILE)
16952 u64 nExec;
16953 u64 nCycle;
16954#endif
16955};
16956typedef struct VdbeOp VdbeOp;
16957
16958
16959/*
16960** A sub-routine used to implement a trigger program.
16961*/
16962struct SubProgram {
16963 VdbeOp *aOp; /* Array of opcodes for sub-program */
16964 int nOp; /* Elements in aOp[] */
16965 int nMem; /* Number of memory cells required */
16966 int nCsr; /* Number of cursors required */
16967 u8 *aOnce; /* Array of OP_Once flags */
16968 void *token; /* id that may be used to recursive triggers */
16969 SubProgram *pNext; /* Next sub-program already visited */
16970};
16971
16972/*
16973** A smaller version of VdbeOp used for the VdbeAddOpList() function because
16974** it takes up less space.
16975*/
16976struct VdbeOpList {
16977 u8 opcode; /* What operation to perform */
16978 signed char p1; /* First operand */
16979 signed char p2; /* Second parameter (often the jump destination) */
16980 signed char p3; /* Third parameter */
16981};
16982typedef struct VdbeOpList VdbeOpList;
16983
16984/*
16985** Allowed values of VdbeOp.p4type
16986*/
16987#define P4_NOTUSED0 0 /* The P4 parameter is not used */
16988#define P4_TRANSIENT0 0 /* P4 is a pointer to a transient string */
16989#define P4_STATIC(-1) (-1) /* Pointer to a static string */
16990#define P4_COLLSEQ(-2) (-2) /* P4 is a pointer to a CollSeq structure */
16991#define P4_INT32(-3) (-3) /* P4 is a 32-bit signed integer */
16992#define P4_SUBPROGRAM(-4) (-4) /* P4 is a pointer to a SubProgram structure */
16993#define P4_TABLE(-5) (-5) /* P4 is a pointer to a Table structure */
16994/* Above do not own any resources. Must free those below */
16995#define P4_FREE_IF_LE(-6) (-6)
16996#define P4_DYNAMIC(-6) (-6) /* Pointer to memory from sqliteMalloc() */
16997#define P4_FUNCDEF(-7) (-7) /* P4 is a pointer to a FuncDef structure */
16998#define P4_KEYINFO(-8) (-8) /* P4 is a pointer to a KeyInfo structure */
16999#define P4_EXPR(-9) (-9) /* P4 is a pointer to an Expr tree */
17000#define P4_MEM(-10) (-10) /* P4 is a pointer to a Mem* structure */
17001#define P4_VTAB(-11) (-11) /* P4 is a pointer to an sqlite3_vtab structure */
17002#define P4_REAL(-12) (-12) /* P4 is a 64-bit floating point value */
17003#define P4_INT64(-13) (-13) /* P4 is a 64-bit signed integer */
17004#define P4_INTARRAY(-14) (-14) /* P4 is a vector of 32-bit integers */
17005#define P4_FUNCCTX(-15) (-15) /* P4 is a pointer to an sqlite3_context object */
17006#define P4_TABLEREF(-16) (-16) /* Like P4_TABLE, but reference counted */
17007#define P4_SUBRTNSIG(-17) (-17) /* P4 is a SubrtnSig pointer */
17008
17009/* Error message codes for OP_Halt */
17010#define P5_ConstraintNotNull1 1
17011#define P5_ConstraintUnique2 2
17012#define P5_ConstraintCheck3 3
17013#define P5_ConstraintFK4 4
17014
17015/*
17016** The Vdbe.aColName array contains 5n Mem structures, where n is the
17017** number of columns of data returned by the statement.
17018*/
17019#define COLNAME_NAME0 0
17020#define COLNAME_DECLTYPE1 1
17021#define COLNAME_DATABASE2 2
17022#define COLNAME_TABLE3 3
17023#define COLNAME_COLUMN4 4
17024#ifdef SQLITE_ENABLE_COLUMN_METADATA1
17025# define COLNAME_N5 5 /* Number of COLNAME_xxx symbols */
17026#else
17027# ifdef SQLITE_OMIT_DECLTYPE
17028# define COLNAME_N5 1 /* Store only the name */
17029# else
17030# define COLNAME_N5 2 /* Store the name and decltype */
17031# endif
17032#endif
17033
17034/*
17035** The following macro converts a label returned by sqlite3VdbeMakeLabel()
17036** into an index into the Parse.aLabel[] array that contains the resolved
17037** address of that label.
17038*/
17039#define ADDR(X)(~(X)) (~(X))
17040
17041/*
17042** The makefile scans the vdbe.c source file and creates the "opcodes.h"
17043** header file that defines a number for each opcode used by the VDBE.
17044*/
17045/************** Include opcodes.h in the middle of vdbe.h ********************/
17046/************** Begin file opcodes.h *****************************************/
17047/* Automatically generated. Do not edit */
17048/* See the tool/mkopcodeh.tcl script for details */
17049#define OP_Savepoint0 0
17050#define OP_AutoCommit1 1
17051#define OP_Transaction2 2
17052#define OP_Checkpoint3 3
17053#define OP_JournalMode4 4
17054#define OP_Vacuum5 5
17055#define OP_VFilter6 6 /* jump, synopsis: iplan=r[P3] zplan='P4' */
17056#define OP_VUpdate7 7 /* synopsis: data=r[P3@P2] */
17057#define OP_Init8 8 /* jump0, synopsis: Start at P2 */
17058#define OP_Goto9 9 /* jump */
17059#define OP_Gosub10 10 /* jump */
17060#define OP_InitCoroutine11 11 /* jump0 */
17061#define OP_Yield12 12 /* jump0 */
17062#define OP_MustBeInt13 13 /* jump0 */
17063#define OP_Jump14 14 /* jump */
17064#define OP_Once15 15 /* jump */
17065#define OP_If16 16 /* jump */
17066#define OP_IfNot17 17 /* jump */
17067#define OP_IsType18 18 /* jump, synopsis: if typeof(P1.P3) in P5 goto P2 */
17068#define OP_Not19 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
17069#define OP_IfNullRow20 20 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
17070#define OP_SeekLT21 21 /* jump0, synopsis: key=r[P3@P4] */
17071#define OP_SeekLE22 22 /* jump0, synopsis: key=r[P3@P4] */
17072#define OP_SeekGE23 23 /* jump0, synopsis: key=r[P3@P4] */
17073#define OP_SeekGT24 24 /* jump0, synopsis: key=r[P3@P4] */
17074#define OP_IfNotOpen25 25 /* jump, synopsis: if( !csr[P1] ) goto P2 */
17075#define OP_IfNoHope26 26 /* jump, synopsis: key=r[P3@P4] */
17076#define OP_NoConflict27 27 /* jump, synopsis: key=r[P3@P4] */
17077#define OP_NotFound28 28 /* jump, synopsis: key=r[P3@P4] */
17078#define OP_Found29 29 /* jump, synopsis: key=r[P3@P4] */
17079#define OP_SeekRowid30 30 /* jump0, synopsis: intkey=r[P3] */
17080#define OP_NotExists31 31 /* jump, synopsis: intkey=r[P3] */
17081#define OP_Last32 32 /* jump0 */
17082#define OP_IfSizeBetween33 33 /* jump */
17083#define OP_SorterSort34 34 /* jump */
17084#define OP_Sort35 35 /* jump */
17085#define OP_Rewind36 36 /* jump0 */
17086#define OP_SorterNext37 37 /* jump */
17087#define OP_Prev38 38 /* jump */
17088#define OP_Next39 39 /* jump */
17089#define OP_IdxLE40 40 /* jump, synopsis: key=r[P3@P4] */
17090#define OP_IdxGT41 41 /* jump, synopsis: key=r[P3@P4] */
17091#define OP_IdxLT42 42 /* jump, synopsis: key=r[P3@P4] */
17092#define OP_Or43 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
17093#define OP_And44 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
17094#define OP_IdxGE45 45 /* jump, synopsis: key=r[P3@P4] */
17095#define OP_RowSetRead46 46 /* jump, synopsis: r[P3]=rowset(P1) */
17096#define OP_RowSetTest47 47 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
17097#define OP_Program48 48 /* jump0 */
17098#define OP_FkIfZero49 49 /* jump, synopsis: if fkctr[P1]==0 goto P2 */
17099#define OP_IfPos50 50 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
17100#define OP_IsNull51 51 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
17101#define OP_NotNull52 52 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
17102#define OP_Ne53 53 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
17103#define OP_Eq54 54 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
17104#define OP_Gt55 55 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
17105#define OP_Le56 56 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
17106#define OP_Lt57 57 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
17107#define OP_Ge58 58 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
17108#define OP_ElseEq59 59 /* jump, same as TK_ESCAPE */
17109#define OP_IfNotZero60 60 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
17110#define OP_DecrJumpZero61 61 /* jump, synopsis: if (--r[P1])==0 goto P2 */
17111#define OP_IncrVacuum62 62 /* jump */
17112#define OP_VNext63 63 /* jump */
17113#define OP_Filter64 64 /* jump, synopsis: if key(P3@P4) not in filter(P1) goto P2 */
17114#define OP_PureFunc65 65 /* synopsis: r[P3]=func(r[P2@NP]) */
17115#define OP_Function66 66 /* synopsis: r[P3]=func(r[P2@NP]) */
17116#define OP_Return67 67
17117#define OP_EndCoroutine68 68
17118#define OP_HaltIfNull69 69 /* synopsis: if r[P3]=null halt */
17119#define OP_Halt70 70
17120#define OP_Integer71 71 /* synopsis: r[P2]=P1 */
17121#define OP_Int6472 72 /* synopsis: r[P2]=P4 */
17122#define OP_String73 73 /* synopsis: r[P2]='P4' (len=P1) */
17123#define OP_BeginSubrtn74 74 /* synopsis: r[P2]=NULL */
17124#define OP_Null75 75 /* synopsis: r[P2..P3]=NULL */
17125#define OP_SoftNull76 76 /* synopsis: r[P1]=NULL */
17126#define OP_Blob77 77 /* synopsis: r[P2]=P4 (len=P1) */
17127#define OP_Variable78 78 /* synopsis: r[P2]=parameter(P1) */
17128#define OP_Move79 79 /* synopsis: r[P2@P3]=r[P1@P3] */
17129#define OP_Copy80 80 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
17130#define OP_SCopy81 81 /* synopsis: r[P2]=r[P1] */
17131#define OP_IntCopy82 82 /* synopsis: r[P2]=r[P1] */
17132#define OP_FkCheck83 83
17133#define OP_ResultRow84 84 /* synopsis: output=r[P1@P2] */
17134#define OP_CollSeq85 85
17135#define OP_AddImm86 86 /* synopsis: r[P1]=r[P1]+P2 */
17136#define OP_RealAffinity87 87
17137#define OP_Cast88 88 /* synopsis: affinity(r[P1]) */
17138#define OP_Permutation89 89
17139#define OP_Compare90 90 /* synopsis: r[P1@P3] <-> r[P2@P3] */
17140#define OP_IsTrue91 91 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
17141#define OP_ZeroOrNull92 92 /* synopsis: r[P2] = 0 OR NULL */
17142#define OP_Offset93 93 /* synopsis: r[P3] = sqlite_offset(P1) */
17143#define OP_Column94 94 /* synopsis: r[P3]=PX cursor P1 column P2 */
17144#define OP_TypeCheck95 95 /* synopsis: typecheck(r[P1@P2]) */
17145#define OP_Affinity96 96 /* synopsis: affinity(r[P1@P2]) */
17146#define OP_MakeRecord97 97 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
17147#define OP_Count98 98 /* synopsis: r[P2]=count() */
17148#define OP_ReadCookie99 99
17149#define OP_SetCookie100 100
17150#define OP_ReopenIdx101 101 /* synopsis: root=P2 iDb=P3 */
17151#define OP_OpenRead102 102 /* synopsis: root=P2 iDb=P3 */
17152#define OP_BitAnd103 103 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
17153#define OP_BitOr104 104 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
17154#define OP_ShiftLeft105 105 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
17155#define OP_ShiftRight106 106 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
17156#define OP_Add107 107 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
17157#define OP_Subtract108 108 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
17158#define OP_Multiply109 109 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
17159#define OP_Divide110 110 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
17160#define OP_Remainder111 111 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
17161#define OP_Concat112 112 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
17162#define OP_OpenWrite113 113 /* synopsis: root=P2 iDb=P3 */
17163#define OP_OpenDup114 114
17164#define OP_BitNot115 115 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
17165#define OP_OpenAutoindex116 116 /* synopsis: nColumn=P2 */
17166#define OP_OpenEphemeral117 117 /* synopsis: nColumn=P2 */
17167#define OP_String8118 118 /* same as TK_STRING, synopsis: r[P2]='P4' */
17168#define OP_SorterOpen119 119
17169#define OP_SequenceTest120 120 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
17170#define OP_OpenPseudo121 121 /* synopsis: P3 columns in r[P2] */
17171#define OP_Close122 122
17172#define OP_ColumnsUsed123 123
17173#define OP_SeekScan124 124 /* synopsis: Scan-ahead up to P1 rows */
17174#define OP_SeekHit125 125 /* synopsis: set P2<=seekHit<=P3 */
17175#define OP_Sequence126 126 /* synopsis: r[P2]=cursor[P1].ctr++ */
17176#define OP_NewRowid127 127 /* synopsis: r[P2]=rowid */
17177#define OP_Insert128 128 /* synopsis: intkey=r[P3] data=r[P2] */
17178#define OP_RowCell129 129
17179#define OP_Delete130 130
17180#define OP_ResetCount131 131
17181#define OP_SorterCompare132 132 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
17182#define OP_SorterData133 133 /* synopsis: r[P2]=data */
17183#define OP_RowData134 134 /* synopsis: r[P2]=data */
17184#define OP_Rowid135 135 /* synopsis: r[P2]=PX rowid of P1 */
17185#define OP_NullRow136 136
17186#define OP_SeekEnd137 137
17187#define OP_IdxInsert138 138 /* synopsis: key=r[P2] */
17188#define OP_SorterInsert139 139 /* synopsis: key=r[P2] */
17189#define OP_IdxDelete140 140 /* synopsis: key=r[P2@P3] */
17190#define OP_DeferredSeek141 141 /* synopsis: Move P3 to P1.rowid if needed */
17191#define OP_IdxRowid142 142 /* synopsis: r[P2]=rowid */
17192#define OP_FinishSeek143 143
17193#define OP_Destroy144 144
17194#define OP_Clear145 145
17195#define OP_ResetSorter146 146
17196#define OP_CreateBtree147 147 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
17197#define OP_SqlExec148 148
17198#define OP_ParseSchema149 149
17199#define OP_LoadAnalysis150 150
17200#define OP_DropTable151 151
17201#define OP_DropIndex152 152
17202#define OP_DropTrigger153 153
17203#define OP_Real154 154 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
17204#define OP_IntegrityCk155 155
17205#define OP_RowSetAdd156 156 /* synopsis: rowset(P1)=r[P2] */
17206#define OP_Param157 157
17207#define OP_FkCounter158 158 /* synopsis: fkctr[P1]+=P2 */
17208#define OP_MemMax159 159 /* synopsis: r[P1]=max(r[P1],r[P2]) */
17209#define OP_OffsetLimit160 160 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
17210#define OP_AggInverse161 161 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */
17211#define OP_AggStep162 162 /* synopsis: accum=r[P3] step(r[P2@P5]) */
17212#define OP_AggStep1163 163 /* synopsis: accum=r[P3] step(r[P2@P5]) */
17213#define OP_AggValue164 164 /* synopsis: r[P3]=value N=P2 */
17214#define OP_AggFinal165 165 /* synopsis: accum=r[P1] N=P2 */
17215#define OP_Expire166 166
17216#define OP_CursorLock167 167
17217#define OP_CursorUnlock168 168
17218#define OP_TableLock169 169 /* synopsis: iDb=P1 root=P2 write=P3 */
17219#define OP_VBegin170 170
17220#define OP_VCreate171 171
17221#define OP_VDestroy172 172
17222#define OP_VOpen173 173
17223#define OP_VCheck174 174
17224#define OP_VInitIn175 175 /* synopsis: r[P2]=ValueList(P1,P3) */
17225#define OP_VColumn176 176 /* synopsis: r[P3]=vcolumn(P2) */
17226#define OP_VRename177 177
17227#define OP_Pagecount178 178
17228#define OP_MaxPgcnt179 179
17229#define OP_ClrSubtype180 180 /* synopsis: r[P1].subtype = 0 */
17230#define OP_GetSubtype181 181 /* synopsis: r[P2] = r[P1].subtype */
17231#define OP_SetSubtype182 182 /* synopsis: r[P2].subtype = r[P1] */
17232#define OP_FilterAdd183 183 /* synopsis: filter(P1) += key(P3@P4) */
17233#define OP_Trace184 184
17234#define OP_CursorHint185 185
17235#define OP_ReleaseReg186 186 /* synopsis: release r[P1@P2] mask P3 */
17236#define OP_Noop187 187
17237#define OP_Explain188 188
17238#define OP_Abortable189 189
17239
17240/* Properties such as "out2" or "jump" that are specified in
17241** comments following the "case" for each opcode in the vdbe.c
17242** are encoded into bitvectors as follows:
17243*/
17244#define OPFLG_JUMP0x01 0x01 /* jump: P2 holds jmp target */
17245#define OPFLG_IN10x02 0x02 /* in1: P1 is an input */
17246#define OPFLG_IN20x04 0x04 /* in2: P2 is an input */
17247#define OPFLG_IN30x08 0x08 /* in3: P3 is an input */
17248#define OPFLG_OUT20x10 0x10 /* out2: P2 is an output */
17249#define OPFLG_OUT30x20 0x20 /* out3: P3 is an output */
17250#define OPFLG_NCYCLE0x40 0x40 /* ncycle:Cycles count against P1 */
17251#define OPFLG_JUMP00x80 0x80 /* jump0: P2 might be zero */
17252#define OPFLG_INITIALIZER{ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x41, 0x00, 0x81, 0x01,
0x01, 0x81, 0x83, 0x83, 0x01, 0x01, 0x03, 0x03, 0x01, 0x12, 0x01
, 0xc9, 0xc9, 0xc9, 0xc9, 0x01, 0x49, 0x49, 0x49, 0x49, 0xc9,
0x49, 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x41, 0x41, 0x41, 0x41
, 0x41, 0x26, 0x26, 0x41, 0x23, 0x0b, 0x81, 0x01, 0x03, 0x03,
0x03, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x01
, 0x41, 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10,
0x10, 0x00, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00
, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20,
0x40, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x40, 0x26, 0x26
, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x40,
0x12, 0x40, 0x40, 0x10, 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x40
, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x50,
0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40, 0x10, 0x00, 0x00
, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x06,
0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50, 0x40, 0x00,
0x10, 0x10, 0x02, 0x12, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
, 0x00,}
{\
17253/* 0 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x41, 0x00,\
17254/* 8 */ 0x81, 0x01, 0x01, 0x81, 0x83, 0x83, 0x01, 0x01,\
17255/* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0xc9, 0xc9, 0xc9,\
17256/* 24 */ 0xc9, 0x01, 0x49, 0x49, 0x49, 0x49, 0xc9, 0x49,\
17257/* 32 */ 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x41, 0x41,\
17258/* 40 */ 0x41, 0x41, 0x41, 0x26, 0x26, 0x41, 0x23, 0x0b,\
17259/* 48 */ 0x81, 0x01, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b,\
17260/* 56 */ 0x0b, 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x01, 0x41,\
17261/* 64 */ 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10,\
17262/* 72 */ 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10, 0x00,\
17263/* 80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x02, 0x02,\
17264/* 88 */ 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20, 0x40, 0x00,\
17265/* 96 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x40, 0x26,\
17266/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\
17267/* 112 */ 0x26, 0x00, 0x40, 0x12, 0x40, 0x40, 0x10, 0x00,\
17268/* 120 */ 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10, 0x10,\
17269/* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x50,\
17270/* 136 */ 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40,\
17271/* 144 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
17272/* 152 */ 0x00, 0x00, 0x10, 0x00, 0x06, 0x10, 0x00, 0x04,\
17273/* 160 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
17274/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50,\
17275/* 176 */ 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12, 0x00,\
17276/* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}
17277
17278/* The resolve3P2Values() routine is able to run faster if it knows
17279** the value of the largest JUMP opcode. The smaller the maximum
17280** JUMP opcode the better, so the mkopcodeh.tcl script that
17281** generated this include file strives to group all JUMP opcodes
17282** together near the beginning of the list.
17283*/
17284#define SQLITE_MX_JUMP_OPCODE64 64 /* Maximum JUMP opcode */
17285
17286/************** End of opcodes.h *********************************************/
17287/************** Continuing where we left off in vdbe.h ***********************/
17288
17289/*
17290** Additional non-public SQLITE_PREPARE_* flags
17291*/
17292#define SQLITE_PREPARE_SAVESQL0x80 0x80 /* Preserve SQL text */
17293#define SQLITE_PREPARE_MASK0x1f 0x1f /* Mask of public flags */
17294
17295/*
17296** Prototypes for the VDBE interface. See comments on the implementation
17297** for a description of what each of these routines does.
17298*/
17299SQLITE_PRIVATEstatic Vdbe *sqlite3VdbeCreate(Parse*);
17300SQLITE_PRIVATEstatic Parse *sqlite3VdbeParser(Vdbe*);
17301SQLITE_PRIVATEstatic int sqlite3VdbeAddOp0(Vdbe*,int);
17302SQLITE_PRIVATEstatic int sqlite3VdbeAddOp1(Vdbe*,int,int);
17303SQLITE_PRIVATEstatic int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
17304SQLITE_PRIVATEstatic int sqlite3VdbeGoto(Vdbe*,int);
17305SQLITE_PRIVATEstatic int sqlite3VdbeLoadString(Vdbe*,int,const char*);
17306SQLITE_PRIVATEstatic void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
17307SQLITE_PRIVATEstatic int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
17308SQLITE_PRIVATEstatic int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
17309SQLITE_PRIVATEstatic int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
17310SQLITE_PRIVATEstatic int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
17311SQLITE_PRIVATEstatic int sqlite3VdbeAddFunctionCall(Parse*,int,int,int,int,const FuncDef*,int);
17312SQLITE_PRIVATEstatic void sqlite3VdbeEndCoroutine(Vdbe*,int);
17313#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
17314SQLITE_PRIVATEstatic void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
17315SQLITE_PRIVATEstatic void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
17316#else
17317# define sqlite3VdbeVerifyNoMallocRequired(A,B)
17318# define sqlite3VdbeVerifyNoResultRow(A)
17319#endif
17320#if defined(SQLITE_DEBUG)
17321SQLITE_PRIVATEstatic void sqlite3VdbeVerifyAbortable(Vdbe *p, int);
17322SQLITE_PRIVATEstatic void sqlite3VdbeNoJumpsOutsideSubrtn(Vdbe*,int,int,int);
17323#else
17324# define sqlite3VdbeVerifyAbortable(A,B)
17325# define sqlite3VdbeNoJumpsOutsideSubrtn(A,B,C,D)
17326#endif
17327SQLITE_PRIVATEstatic VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);
17328#ifndef SQLITE_OMIT_EXPLAIN
17329SQLITE_PRIVATEstatic int sqlite3VdbeExplain(Parse*,u8,const char*,...);
17330SQLITE_PRIVATEstatic void sqlite3VdbeExplainPop(Parse*);
17331SQLITE_PRIVATEstatic int sqlite3VdbeExplainParent(Parse*);
17332# define ExplainQueryPlan(P)sqlite3VdbeExplain P sqlite3VdbeExplain P
17333# ifdef SQLITE_ENABLE_STMT_SCANSTATUS1
17334# define ExplainQueryPlan2(V,P)(V = sqlite3VdbeExplain P) (V = sqlite3VdbeExplain P)
17335# else
17336# define ExplainQueryPlan2(V,P)(V = sqlite3VdbeExplain P) ExplainQueryPlan(P)sqlite3VdbeExplain P
17337# endif
17338# define ExplainQueryPlanPop(P)sqlite3VdbeExplainPop(P) sqlite3VdbeExplainPop(P)
17339# define ExplainQueryPlanParent(P)sqlite3VdbeExplainParent(P) sqlite3VdbeExplainParent(P)
17340#else
17341# define ExplainQueryPlan(P)sqlite3VdbeExplain P
17342# define ExplainQueryPlan2(V,P)(V = sqlite3VdbeExplain P)
17343# define ExplainQueryPlanPop(P)sqlite3VdbeExplainPop(P)
17344# define ExplainQueryPlanParent(P)sqlite3VdbeExplainParent(P) 0
17345# define sqlite3ExplainBreakpoint(A,B) /*no-op*/
17346#endif
17347#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)
17348SQLITE_PRIVATEstatic void sqlite3ExplainBreakpoint(const char*,const char*);
17349#else
17350# define sqlite3ExplainBreakpoint(A,B) /*no-op*/
17351#endif
17352SQLITE_PRIVATEstatic void sqlite3VdbeAddParseSchemaOp(Vdbe*, int, char*, u16);
17353SQLITE_PRIVATEstatic void sqlite3VdbeChangeOpcode(Vdbe*, int addr, u8);
17354SQLITE_PRIVATEstatic void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
17355SQLITE_PRIVATEstatic void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
17356SQLITE_PRIVATEstatic void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
17357SQLITE_PRIVATEstatic void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
17358SQLITE_PRIVATEstatic void sqlite3VdbeTypeofColumn(Vdbe*, int);
17359SQLITE_PRIVATEstatic void sqlite3VdbeJumpHere(Vdbe*, int addr);
17360SQLITE_PRIVATEstatic void sqlite3VdbeJumpHereOrPopInst(Vdbe*, int addr);
17361SQLITE_PRIVATEstatic int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
17362SQLITE_PRIVATEstatic int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
17363#ifdef SQLITE_DEBUG
17364SQLITE_PRIVATEstatic void sqlite3VdbeReleaseRegisters(Parse*,int addr, int n, u32 mask, int);
17365#else
17366# define sqlite3VdbeReleaseRegisters(P,A,N,M,F)
17367#endif
17368SQLITE_PRIVATEstatic void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
17369SQLITE_PRIVATEstatic void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
17370SQLITE_PRIVATEstatic void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
17371SQLITE_PRIVATEstatic void sqlite3VdbeUsesBtree(Vdbe*, int);
17372SQLITE_PRIVATEstatic VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
17373SQLITE_PRIVATEstatic VdbeOp *sqlite3VdbeGetLastOp(Vdbe*);
17374SQLITE_PRIVATEstatic int sqlite3VdbeMakeLabel(Parse*);
17375SQLITE_PRIVATEstatic void sqlite3VdbeRunOnlyOnce(Vdbe*);
17376SQLITE_PRIVATEstatic void sqlite3VdbeReusable(Vdbe*);
17377SQLITE_PRIVATEstatic void sqlite3VdbeDelete(Vdbe*);
17378SQLITE_PRIVATEstatic void sqlite3VdbeMakeReady(Vdbe*,Parse*);
17379SQLITE_PRIVATEstatic int sqlite3VdbeFinalize(Vdbe*);
17380SQLITE_PRIVATEstatic void sqlite3VdbeResolveLabel(Vdbe*, int);
17381SQLITE_PRIVATEstatic int sqlite3VdbeCurrentAddr(Vdbe*);
17382#ifdef SQLITE_DEBUG
17383SQLITE_PRIVATEstatic int sqlite3VdbeAssertMayAbort(Vdbe *, int);
17384#endif
17385SQLITE_PRIVATEstatic void sqlite3VdbeResetStepResult(Vdbe*);
17386SQLITE_PRIVATEstatic void sqlite3VdbeRewind(Vdbe*);
17387SQLITE_PRIVATEstatic int sqlite3VdbeReset(Vdbe*);
17388SQLITE_PRIVATEstatic void sqlite3VdbeSetNumCols(Vdbe*,int);
17389SQLITE_PRIVATEstatic int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
17390SQLITE_PRIVATEstatic void sqlite3VdbeCountChanges(Vdbe*);
17391SQLITE_PRIVATEstatic sqlite3 *sqlite3VdbeDb(Vdbe*);
17392SQLITE_PRIVATEstatic u8 sqlite3VdbePrepareFlags(Vdbe*);
17393SQLITE_PRIVATEstatic void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
17394#ifdef SQLITE_ENABLE_NORMALIZE
17395SQLITE_PRIVATEstatic void sqlite3VdbeAddDblquoteStr(sqlite3*,Vdbe*,const char*);
17396SQLITE_PRIVATEstatic int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*);
17397#endif
17398SQLITE_PRIVATEstatic void sqlite3VdbeSwap(Vdbe*,Vdbe*);
17399SQLITE_PRIVATEstatic VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
17400SQLITE_PRIVATEstatic sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
17401SQLITE_PRIVATEstatic void sqlite3VdbeSetVarmask(Vdbe*, int);
17402#ifndef SQLITE_OMIT_TRACE
17403SQLITE_PRIVATEstatic char *sqlite3VdbeExpandSql(Vdbe*, const char*);
17404#endif
17405SQLITE_PRIVATEstatic int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
17406SQLITE_PRIVATEstatic int sqlite3BlobCompare(const Mem*, const Mem*);
17407
17408SQLITE_PRIVATEstatic void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
17409SQLITE_PRIVATEstatic int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
17410SQLITE_PRIVATEstatic int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
17411SQLITE_PRIVATEstatic UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
17412
17413typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
17414SQLITE_PRIVATEstatic RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
17415
17416SQLITE_PRIVATEstatic void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
17417SQLITE_PRIVATEstatic int sqlite3VdbeHasSubProgram(Vdbe*);
17418
17419SQLITE_PRIVATEstatic void sqlite3MemSetArrayInt64(sqlite3_value *aMem, int iIdx, i64 val);
17420
17421SQLITE_PRIVATEstatic int sqlite3NotPureFunc(sqlite3_context*);
17422#ifdef SQLITE_ENABLE_BYTECODE_VTAB
17423SQLITE_PRIVATEstatic int sqlite3VdbeBytecodeVtabInit(sqlite3*);
17424#endif
17425
17426/* Use SQLITE_ENABLE_EXPLAIN_COMMENTS to enable generation of extra
17427** comments on each VDBE opcode.
17428**
17429** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
17430** comments in VDBE programs that show key decision points in the code
17431** generator.
17432*/
17433#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
17434SQLITE_PRIVATEstatic void sqlite3VdbeComment(Vdbe*, const char*, ...);
17435# define VdbeComment(X) sqlite3VdbeComment X
17436SQLITE_PRIVATEstatic void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
17437# define VdbeNoopComment(X) sqlite3VdbeNoopComment X
17438# ifdef SQLITE_ENABLE_MODULE_COMMENTS
17439# define VdbeModuleComment(X) sqlite3VdbeNoopComment X
17440# else
17441# define VdbeModuleComment(X)
17442# endif
17443#else
17444# define VdbeComment(X)
17445# define VdbeNoopComment(X)
17446# define VdbeModuleComment(X)
17447#endif
17448
17449/*
17450** The VdbeCoverage macros are used to set a coverage testing point
17451** for VDBE branch instructions. The coverage testing points are line
17452** numbers in the sqlite3.c source file. VDBE branch coverage testing
17453** only works with an amalgamation build. That's ok since a VDBE branch
17454** coverage build designed for testing the test suite only. No application
17455** should ever ship with VDBE branch coverage measuring turned on.
17456**
17457** VdbeCoverage(v) // Mark the previously coded instruction
17458** // as a branch
17459**
17460** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
17461**
17462** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
17463**
17464** VdbeCoverageNeverTaken(v) // Previous branch is never taken
17465**
17466** VdbeCoverageNeverNull(v) // Previous three-way branch is only
17467** // taken on the first two ways. The
17468** // NULL option is not possible
17469**
17470** VdbeCoverageEqNe(v) // Previous OP_Jump is only interested
17471** // in distinguishing equal and not-equal.
17472**
17473** Every VDBE branch operation must be tagged with one of the macros above.
17474** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
17475** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
17476** routine in vdbe.c, alerting the developer to the missed tag.
17477**
17478** During testing, the test application will invoke
17479** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback
17480** routine that is invoked as each bytecode branch is taken. The callback
17481** contains the sqlite3.c source line number of the VdbeCoverage macro and
17482** flags to indicate whether or not the branch was taken. The test application
17483** is responsible for keeping track of this and reporting byte-code branches
17484** that are never taken.
17485**
17486** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the
17487** vdbe.c source file for additional information.
17488*/
17489#ifdef SQLITE_VDBE_COVERAGE
17490SQLITE_PRIVATEstatic void sqlite3VdbeSetLineNumber(Vdbe*,int);
17491# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__17491)
17492# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__17492)
17493# define VdbeCoverageAlwaysTaken(v) \
17494 sqlite3VdbeSetLineNumber(v,__LINE__17494|0x5000000);
17495# define VdbeCoverageNeverTaken(v) \
17496 sqlite3VdbeSetLineNumber(v,__LINE__17496|0x6000000);
17497# define VdbeCoverageNeverNull(v) \
17498 sqlite3VdbeSetLineNumber(v,__LINE__17498|0x4000000);
17499# define VdbeCoverageNeverNullIf(v,x) \
17500 if(x)sqlite3VdbeSetLineNumber(v,__LINE__17500|0x4000000);
17501# define VdbeCoverageEqNe(v) \
17502 sqlite3VdbeSetLineNumber(v,__LINE__17502|0x8000000);
17503# define VDBE_OFFSET_LINENO(x)0 (__LINE__17503+x)
17504#else
17505# define VdbeCoverage(v)
17506# define VdbeCoverageIf(v,x)
17507# define VdbeCoverageAlwaysTaken(v)
17508# define VdbeCoverageNeverTaken(v)
17509# define VdbeCoverageNeverNull(v)
17510# define VdbeCoverageNeverNullIf(v,x)
17511# define VdbeCoverageEqNe(v)
17512# define VDBE_OFFSET_LINENO(x)0 0
17513#endif
17514
17515#ifdef SQLITE_ENABLE_STMT_SCANSTATUS1
17516SQLITE_PRIVATEstatic void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
17517SQLITE_PRIVATEstatic void sqlite3VdbeScanStatusRange(Vdbe*, int, int, int);
17518SQLITE_PRIVATEstatic void sqlite3VdbeScanStatusCounters(Vdbe*, int, int, int);
17519#else
17520# define sqlite3VdbeScanStatus(a,b,c,d,e,f)
17521# define sqlite3VdbeScanStatusRange(a,b,c,d)
17522# define sqlite3VdbeScanStatusCounters(a,b,c,d)
17523#endif
17524
17525#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
17526SQLITE_PRIVATEstatic void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
17527#endif
17528
17529#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
17530SQLITE_PRIVATEstatic int sqlite3CursorRangeHintExprCheck(Walker *pWalker, Expr *pExpr);
17531#endif
17532
17533#endif /* SQLITE_VDBE_H */
17534
17535/************** End of vdbe.h ************************************************/
17536/************** Continuing where we left off in sqliteInt.h ******************/
17537/************** Include pcache.h in the middle of sqliteInt.h ****************/
17538/************** Begin file pcache.h ******************************************/
17539/*
17540** 2008 August 05
17541**
17542** The author disclaims copyright to this source code. In place of
17543** a legal notice, here is a blessing:
17544**
17545** May you do good and not evil.
17546** May you find forgiveness for yourself and forgive others.
17547** May you share freely, never taking more than you give.
17548**
17549*************************************************************************
17550** This header file defines the interface that the sqlite page cache
17551** subsystem.
17552*/
17553
17554#ifndef _PCACHE_H_
17555
17556typedef struct PgHdr PgHdr;
17557typedef struct PCache PCache;
17558
17559/*
17560** Every page in the cache is controlled by an instance of the following
17561** structure.
17562*/
17563struct PgHdr {
17564 sqlite3_pcache_page *pPage; /* Pcache object page handle */
17565 void *pData; /* Page data */
17566 void *pExtra; /* Extra content */
17567 PCache *pCache; /* PRIVATE: Cache that owns this page */
17568 PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
17569 Pager *pPager; /* The pager this page is part of */
17570 Pgno pgno; /* Page number for this page */
17571#ifdef SQLITE_CHECK_PAGES
17572 u32 pageHash; /* Hash of page content */
17573#endif
17574 u16 flags; /* PGHDR flags defined below */
17575
17576 /**********************************************************************
17577 ** Elements above, except pCache, are public. All that follow are
17578 ** private to pcache.c and should not be accessed by other modules.
17579 ** pCache is grouped with the public elements for efficiency.
17580 */
17581 i64 nRef; /* Number of users of this page */
17582 PgHdr *pDirtyNext; /* Next element in list of dirty pages */
17583 PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
17584 /* NB: pDirtyNext and pDirtyPrev are undefined if the
17585 ** PgHdr object is not dirty */
17586};
17587
17588/* Bit values for PgHdr.flags */
17589#define PGHDR_CLEAN0x001 0x001 /* Page not on the PCache.pDirty list */
17590#define PGHDR_DIRTY0x002 0x002 /* Page is on the PCache.pDirty list */
17591#define PGHDR_WRITEABLE0x004 0x004 /* Journaled and ready to modify */
17592#define PGHDR_NEED_SYNC0x008 0x008 /* Fsync the rollback journal before
17593 ** writing this page to the database */
17594#define PGHDR_DONT_WRITE0x010 0x010 /* Do not write content to disk */
17595#define PGHDR_MMAP0x020 0x020 /* This is an mmap page object */
17596
17597#define PGHDR_WAL_APPEND0x040 0x040 /* Appended to wal file */
17598
17599/* Initialize and shutdown the page cache subsystem */
17600SQLITE_PRIVATEstatic int sqlite3PcacheInitialize(void);
17601SQLITE_PRIVATEstatic void sqlite3PcacheShutdown(void);
17602
17603/* Page cache buffer management:
17604** These routines implement SQLITE_CONFIG_PAGECACHE.
17605*/
17606SQLITE_PRIVATEstatic void sqlite3PCacheBufferSetup(void *, int sz, int n);
17607
17608/* Create a new pager cache.
17609** Under memory stress, invoke xStress to try to make pages clean.
17610** Only clean and unpinned pages can be reclaimed.
17611*/
17612SQLITE_PRIVATEstatic int sqlite3PcacheOpen(
17613 int szPage, /* Size of every page */
17614 int szExtra, /* Extra space associated with each page */
17615 int bPurgeable, /* True if pages are on backing store */
17616 int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
17617 void *pStress, /* Argument to xStress */
17618 PCache *pToInit /* Preallocated space for the PCache */
17619);
17620
17621/* Modify the page-size after the cache has been created. */
17622SQLITE_PRIVATEstatic int sqlite3PcacheSetPageSize(PCache *, int);
17623
17624/* Return the size in bytes of a PCache object. Used to preallocate
17625** storage space.
17626*/
17627SQLITE_PRIVATEstatic int sqlite3PcacheSize(void);
17628
17629/* One release per successful fetch. Page is pinned until released.
17630** Reference counted.
17631*/
17632SQLITE_PRIVATEstatic sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
17633SQLITE_PRIVATEstatic int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
17634SQLITE_PRIVATEstatic PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
17635SQLITE_PRIVATEstatic void sqlite3PcacheRelease(PgHdr*);
17636
17637SQLITE_PRIVATEstatic void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
17638SQLITE_PRIVATEstatic void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
17639SQLITE_PRIVATEstatic void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
17640SQLITE_PRIVATEstatic void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
17641SQLITE_PRIVATEstatic void sqlite3PcacheClearWritable(PCache*);
17642
17643/* Change a page number. Used by incr-vacuum. */
17644SQLITE_PRIVATEstatic void sqlite3PcacheMove(PgHdr*, Pgno);
17645
17646/* Remove all pages with pgno>x. Reset the cache if x==0 */
17647SQLITE_PRIVATEstatic void sqlite3PcacheTruncate(PCache*, Pgno x);
17648
17649/* Get a list of all dirty pages in the cache, sorted by page number */
17650SQLITE_PRIVATEstatic PgHdr *sqlite3PcacheDirtyList(PCache*);
17651
17652/* Reset and close the cache object */
17653SQLITE_PRIVATEstatic void sqlite3PcacheClose(PCache*);
17654
17655/* Clear flags from pages of the page cache */
17656SQLITE_PRIVATEstatic void sqlite3PcacheClearSyncFlags(PCache *);
17657
17658/* Discard the contents of the cache */
17659SQLITE_PRIVATEstatic void sqlite3PcacheClear(PCache*);
17660
17661/* Return the total number of outstanding page references */
17662SQLITE_PRIVATEstatic i64 sqlite3PcacheRefCount(PCache*);
17663
17664/* Increment the reference count of an existing page */
17665SQLITE_PRIVATEstatic void sqlite3PcacheRef(PgHdr*);
17666
17667SQLITE_PRIVATEstatic i64 sqlite3PcachePageRefcount(PgHdr*);
17668
17669/* Return the total number of pages stored in the cache */
17670SQLITE_PRIVATEstatic int sqlite3PcachePagecount(PCache*);
17671
17672#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
17673/* Iterate through all dirty pages currently stored in the cache. This
17674** interface is only available if SQLITE_CHECK_PAGES is defined when the
17675** library is built.
17676*/
17677SQLITE_PRIVATEstatic void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
17678#endif
17679
17680#if defined(SQLITE_DEBUG)
17681/* Check invariants on a PgHdr object */
17682SQLITE_PRIVATEstatic int sqlite3PcachePageSanity(PgHdr*);
17683#endif
17684
17685/* Set and get the suggested cache-size for the specified pager-cache.
17686**
17687** If no global maximum is configured, then the system attempts to limit
17688** the total number of pages cached by purgeable pager-caches to the sum
17689** of the suggested cache-sizes.
17690*/
17691SQLITE_PRIVATEstatic void sqlite3PcacheSetCachesize(PCache *, int);
17692#ifdef SQLITE_TEST
17693SQLITE_PRIVATEstatic int sqlite3PcacheGetCachesize(PCache *);
17694#endif
17695
17696/* Set or get the suggested spill-size for the specified pager-cache.
17697**
17698** The spill-size is the minimum number of pages in cache before the cache
17699** will attempt to spill dirty pages by calling xStress.
17700*/
17701SQLITE_PRIVATEstatic int sqlite3PcacheSetSpillsize(PCache *, int);
17702
17703/* Free up as much memory as possible from the page cache */
17704SQLITE_PRIVATEstatic void sqlite3PcacheShrink(PCache*);
17705
17706#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17707/* Try to return memory used by the pcache module to the main memory heap */
17708SQLITE_PRIVATEstatic int sqlite3PcacheReleaseMemory(int);
17709#endif
17710
17711#ifdef SQLITE_TEST
17712SQLITE_PRIVATEstatic void sqlite3PcacheStats(int*,int*,int*,int*);
17713#endif
17714
17715SQLITE_PRIVATEstatic void sqlite3PCacheSetDefault(void);
17716
17717/* Return the header size */
17718SQLITE_PRIVATEstatic int sqlite3HeaderSizePcache(void);
17719SQLITE_PRIVATEstatic int sqlite3HeaderSizePcache1(void);
17720
17721/* Number of dirty pages as a percentage of the configured cache size */
17722SQLITE_PRIVATEstatic int sqlite3PCachePercentDirty(PCache*);
17723
17724#ifdef SQLITE_DIRECT_OVERFLOW_READ1
17725SQLITE_PRIVATEstatic int sqlite3PCacheIsDirty(PCache *pCache);
17726#endif
17727
17728#endif /* _PCACHE_H_ */
17729
17730/************** End of pcache.h **********************************************/
17731/************** Continuing where we left off in sqliteInt.h ******************/
17732/************** Include mutex.h in the middle of sqliteInt.h *****************/
17733/************** Begin file mutex.h *******************************************/
17734/*
17735** 2007 August 28
17736**
17737** The author disclaims copyright to this source code. In place of
17738** a legal notice, here is a blessing:
17739**
17740** May you do good and not evil.
17741** May you find forgiveness for yourself and forgive others.
17742** May you share freely, never taking more than you give.
17743**
17744*************************************************************************
17745**
17746** This file contains the common header for all mutex implementations.
17747** The sqliteInt.h header #includes this file so that it is available
17748** to all source files. We break it out in an effort to keep the code
17749** better organized.
17750**
17751** NOTE: source files should *not* #include this header file directly.
17752** Source files should #include the sqliteInt.h file and let that file
17753** include this one indirectly.
17754*/
17755
17756
17757/*
17758** Figure out what version of the code to use. The choices are
17759**
17760** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
17761** mutexes implementation cannot be overridden
17762** at start-time.
17763**
17764** SQLITE_MUTEX_NOOP For single-threaded applications. No
17765** mutual exclusion is provided. But this
17766** implementation can be overridden at
17767** start-time.
17768**
17769** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
17770**
17771** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
17772*/
17773#if !SQLITE_THREADSAFE2
17774# define SQLITE_MUTEX_OMIT
17775#endif
17776#if SQLITE_THREADSAFE2 && !defined(SQLITE_MUTEX_NOOP)
17777# if SQLITE_OS_UNIX1
17778# define SQLITE_MUTEX_PTHREADS
17779# elif SQLITE_OS_WIN0
17780# define SQLITE_MUTEX_W32
17781# else
17782# define SQLITE_MUTEX_NOOP
17783# endif
17784#endif
17785
17786#ifdef SQLITE_MUTEX_OMIT
17787/*
17788** If this is a no-op implementation, implement everything as macros.
17789*/
17790#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
17791#define sqlite3_mutex_free(X)
17792#define sqlite3_mutex_enter(X)
17793#define sqlite3_mutex_try(X) SQLITE_OK0
17794#define sqlite3_mutex_leave(X)
17795#define sqlite3_mutex_held(X) ((void)(X),1)
17796#define sqlite3_mutex_notheld(X) ((void)(X),1)
17797#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
17798#define sqlite3MutexInit() SQLITE_OK0
17799#define sqlite3MutexEnd()
17800#define MUTEX_LOGIC(X)X
17801#else
17802#define MUTEX_LOGIC(X)X X
17803SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
17804#endif /* defined(SQLITE_MUTEX_OMIT) */
17805
17806/************** End of mutex.h ***********************************************/
17807/************** Continuing where we left off in sqliteInt.h ******************/
17808
17809/* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
17810** synchronous setting to EXTRA. It is no longer supported.
17811*/
17812#ifdef SQLITE_EXTRA_DURABLE
17813# warning Use SQLITE_DEFAULT_SYNCHRONOUS2=3 instead of SQLITE_EXTRA_DURABLE
17814# define SQLITE_DEFAULT_SYNCHRONOUS2 3
17815#endif
17816
17817/*
17818** Default synchronous levels.
17819**
17820** Note that (for historical reasons) the PAGER_SYNCHRONOUS_* macros differ
17821** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
17822**
17823** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
17824** OFF 1 0
17825** NORMAL 2 1
17826** FULL 3 2
17827** EXTRA 4 3
17828**
17829** The "PRAGMA synchronous" statement also uses the zero-based numbers.
17830** In other words, the zero-based numbers are used for all external interfaces
17831** and the one-based values are used internally.
17832*/
17833#ifndef SQLITE_DEFAULT_SYNCHRONOUS2
17834# define SQLITE_DEFAULT_SYNCHRONOUS2 2
17835#endif
17836#ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS1
17837# define SQLITE_DEFAULT_WAL_SYNCHRONOUS1 SQLITE_DEFAULT_SYNCHRONOUS2
17838#endif
17839
17840/*
17841** Each database file to be accessed by the system is an instance
17842** of the following structure. There are normally two of these structures
17843** in the sqlite.aDb[] array. aDb[0] is the main database file and
17844** aDb[1] is the database file used to hold temporary tables. Additional
17845** databases may be attached.
17846*/
17847struct Db {
17848 char *zDbSName; /* Name of this database. (schema name, not filename) */
17849 Btree *pBt; /* The B*Tree structure for this database file */
17850 u8 safety_level; /* How aggressive at syncing data to disk */
17851 u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
17852 Schema *pSchema; /* Pointer to database schema (possibly shared) */
17853};
17854
17855/*
17856** An instance of the following structure stores a database schema.
17857**
17858** Most Schema objects are associated with a Btree. The exception is
17859** the Schema for the TEMP database (sqlite3.aDb[1]) which is free-standing.
17860** In shared cache mode, a single Schema object can be shared by multiple
17861** Btrees that refer to the same underlying BtShared object.
17862**
17863** Schema objects are automatically deallocated when the last Btree that
17864** references them is destroyed. The TEMP Schema is manually freed by
17865** sqlite3_close().
17866*
17867** A thread must be holding a mutex on the corresponding Btree in order
17868** to access Schema content. This implies that the thread must also be
17869** holding a mutex on the sqlite3 connection pointer that owns the Btree.
17870** For a TEMP Schema, only the connection mutex is required.
17871*/
17872struct Schema {
17873 int schema_cookie; /* Database schema version number for this file */
17874 int iGeneration; /* Generation counter. Incremented with each change */
17875 Hash tblHash; /* All tables indexed by name */
17876 Hash idxHash; /* All (named) indices indexed by name */
17877 Hash trigHash; /* All triggers indexed by name */
17878 Hash fkeyHash; /* All foreign keys by referenced table name */
17879 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
17880 u8 file_format; /* Schema format version for this file */
17881 u8 enc; /* Text encoding used by this database */
17882 u16 schemaFlags; /* Flags associated with this schema */
17883 int cache_size; /* Number of pages to use in the cache */
17884};
17885
17886/*
17887** These macros can be used to test, set, or clear bits in the
17888** Db.pSchema->flags field.
17889*/
17890#define DbHasProperty(D,I,P)(((D)->aDb[I].pSchema->schemaFlags&(P))==(P)) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
17891#define DbHasAnyProperty(D,I,P)(((D)->aDb[I].pSchema->schemaFlags&(P))!=0) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
17892#define DbSetProperty(D,I,P)(D)->aDb[I].pSchema->schemaFlags|=(P) (D)->aDb[I].pSchema->schemaFlags|=(P)
17893#define DbClearProperty(D,I,P)(D)->aDb[I].pSchema->schemaFlags&=~(P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
17894
17895/*
17896** Allowed values for the DB.pSchema->flags field.
17897**
17898** The DB_SchemaLoaded flag is set after the database schema has been
17899** read into internal hash tables.
17900**
17901** DB_UnresetViews means that one or more views have column names that
17902** have been filled out. If the schema changes, these column names might
17903** changes and so the view will need to be reset.
17904*/
17905#define DB_SchemaLoaded0x0001 0x0001 /* The schema has been loaded */
17906#define DB_UnresetViews0x0002 0x0002 /* Some views have defined column names */
17907#define DB_ResetWanted0x0008 0x0008 /* Reset the schema when nSchemaLock==0 */
17908
17909/*
17910** The number of different kinds of things that can be limited
17911** using the sqlite3_limit() interface.
17912*/
17913#define SQLITE_N_LIMIT(11 +1) (SQLITE_LIMIT_WORKER_THREADS11+1)
17914
17915/*
17916** Lookaside malloc is a set of fixed-size buffers that can be used
17917** to satisfy small transient memory allocation requests for objects
17918** associated with a particular database connection. The use of
17919** lookaside malloc provides a significant performance enhancement
17920** (approx 10%) by avoiding numerous malloc/free requests while parsing
17921** SQL statements.
17922**
17923** The Lookaside structure holds configuration information about the
17924** lookaside malloc subsystem. Each available memory allocation in
17925** the lookaside subsystem is stored on a linked list of LookasideSlot
17926** objects.
17927**
17928** Lookaside allocations are only allowed for objects that are associated
17929** with a particular database connection. Hence, schema information cannot
17930** be stored in lookaside because in shared cache mode the schema information
17931** is shared by multiple database connections. Therefore, while parsing
17932** schema information, the Lookaside.bEnabled flag is cleared so that
17933** lookaside allocations are not used to construct the schema objects.
17934**
17935** New lookaside allocations are only allowed if bDisable==0. When
17936** bDisable is greater than zero, sz is set to zero which effectively
17937** disables lookaside without adding a new test for the bDisable flag
17938** in a performance-critical path. sz should be set by to szTrue whenever
17939** bDisable changes back to zero.
17940**
17941** Lookaside buffers are initially held on the pInit list. As they are
17942** used and freed, they are added back to the pFree list. New allocations
17943** come off of pFree first, then pInit as a fallback. This dual-list
17944** allows use to compute a high-water mark - the maximum number of allocations
17945** outstanding at any point in the past - by subtracting the number of
17946** allocations on the pInit list from the total number of allocations.
17947**
17948** Enhancement on 2019-12-12: Two-size-lookaside
17949** The default lookaside configuration is 100 slots of 1200 bytes each.
17950** The larger slot sizes are important for performance, but they waste
17951** a lot of space, as most lookaside allocations are less than 128 bytes.
17952** The two-size-lookaside enhancement breaks up the lookaside allocation
17953** into two pools: One of 128-byte slots and the other of the default size
17954** (1200-byte) slots. Allocations are filled from the small-pool first,
17955** failing over to the full-size pool if that does not work. Thus more
17956** lookaside slots are available while also using less memory.
17957** This enhancement can be omitted by compiling with
17958** SQLITE_OMIT_TWOSIZE_LOOKASIDE.
17959*/
17960struct Lookaside {
17961 u32 bDisable; /* Only operate the lookaside when zero */
17962 u16 sz; /* Size of each buffer in bytes */
17963 u16 szTrue; /* True value of sz, even if disabled */
17964 u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
17965 u32 nSlot; /* Number of lookaside slots allocated */
17966 u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
17967 LookasideSlot *pInit; /* List of buffers not previously used */
17968 LookasideSlot *pFree; /* List of available buffers */
17969#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
17970 LookasideSlot *pSmallInit; /* List of small buffers not previously used */
17971 LookasideSlot *pSmallFree; /* List of available small buffers */
17972 void *pMiddle; /* First byte past end of full-size buffers and
17973 ** the first byte of LOOKASIDE_SMALL buffers */
17974#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
17975 void *pStart; /* First byte of available memory space */
17976 void *pEnd; /* First byte past end of available space */
17977 void *pTrueEnd; /* True value of pEnd, when db->pnBytesFreed!=0 */
17978};
17979struct LookasideSlot {
17980 LookasideSlot *pNext; /* Next buffer in the list of free buffers */
17981};
17982
17983#define DisableLookasidedb->lookaside.bDisable++;db->lookaside.sz=0 db->lookaside.bDisable++;db->lookaside.sz=0
17984#define EnableLookasidedb->lookaside.bDisable--; db->lookaside.sz=db->lookaside
.bDisable?0:db->lookaside.szTrue
db->lookaside.bDisable--;\
17985 db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue
17986
17987/* Size of the smaller allocations in two-size lookaside */
17988#ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
17989# define LOOKASIDE_SMALL128 0
17990#else
17991# define LOOKASIDE_SMALL128 128
17992#endif
17993
17994/*
17995** A hash table for built-in function definitions. (Application-defined
17996** functions use a regular table table from hash.h.)
17997**
17998** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
17999** Collisions are on the FuncDef.u.pHash chain. Use the SQLITE_FUNC_HASH()
18000** macro to compute a hash on the function name.
18001*/
18002#define SQLITE_FUNC_HASH_SZ23 23
18003struct FuncDefHash {
18004 FuncDef *a[SQLITE_FUNC_HASH_SZ23]; /* Hash table for functions */
18005};
18006#define SQLITE_FUNC_HASH(C,L)(((C)+(L))%23) (((C)+(L))%SQLITE_FUNC_HASH_SZ23)
18007
18008/*
18009** typedef for the authorization callback function.
18010*/
18011typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
18012 const char*);
18013
18014#ifndef SQLITE_OMIT_DEPRECATED1
18015/* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
18016** in the style of sqlite3_trace()
18017*/
18018#define SQLITE_TRACE_LEGACY0 0x40 /* Use the legacy xTrace */
18019#define SQLITE_TRACE_XPROFILE0 0x80 /* Use the legacy xProfile */
18020#else
18021#define SQLITE_TRACE_LEGACY0 0
18022#define SQLITE_TRACE_XPROFILE0 0
18023#endif /* SQLITE_OMIT_DEPRECATED */
18024#define SQLITE_TRACE_NONLEGACY_MASK0x0f 0x0f /* Normal flags */
18025
18026/*
18027** Maximum number of sqlite3.aDb[] entries. This is the number of attached
18028** databases plus 2 for "main" and "temp".
18029*/
18030#define SQLITE_MAX_DB(10 +2) (SQLITE_MAX_ATTACHED10+2)
18031
18032/*
18033** Each database connection is an instance of the following structure.
18034*/
18035struct sqlite3 {
18036 sqlite3_vfs *pVfs; /* OS Interface */
18037 struct Vdbe *pVdbe; /* List of active virtual machines */
18038 CollSeq *pDfltColl; /* BINARY collseq for the database encoding */
18039 sqlite3_mutex *mutex; /* Connection mutex */
18040 Db *aDb; /* All backends */
18041 int nDb; /* Number of backends currently in use */
18042 u32 mDbFlags; /* flags recording internal state */
18043 u64 flags; /* flags settable by pragmas. See below */
18044 i64 lastRowid; /* ROWID of most recent insert (see above) */
18045 i64 szMmap; /* Default mmap_size setting */
18046 u32 nSchemaLock; /* Do not reset the schema when non-zero */
18047 unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
18048 int errCode; /* Most recent error code (SQLITE_*) */
18049 int errByteOffset; /* Byte offset of error in SQL statement */
18050 int errMask; /* & result codes with this before returning */
18051 int iSysErrno; /* Errno value from last system error */
18052 u32 dbOptFlags; /* Flags to enable/disable optimizations */
18053 u8 enc; /* Text encoding */
18054 u8 autoCommit; /* The auto-commit flag. */
18055 u8 temp_store; /* 1: file 2: memory 0: default */
18056 u8 mallocFailed; /* True if we have seen a malloc failure */
18057 u8 bBenignMalloc; /* Do not require OOMs if true */
18058 u8 dfltLockMode; /* Default locking-mode for attached dbs */
18059 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
18060 u8 suppressErr; /* Do not issue error messages if true */
18061 u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
18062 u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
18063 u8 mTrace; /* zero or more SQLITE_TRACE flags */
18064 u8 noSharedCache; /* True if no shared-cache backends */
18065 u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
18066 u8 eOpenState; /* Current condition of the connection */
18067 int nextPagesize; /* Pagesize after VACUUM if >0 */
18068 i64 nChange; /* Value returned by sqlite3_changes() */
18069 i64 nTotalChange; /* Value returned by sqlite3_total_changes() */
18070 int aLimit[SQLITE_N_LIMIT(11 +1)]; /* Limits */
18071 int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
18072 struct sqlite3InitInfo { /* Information used during initialization */
18073 Pgno newTnum; /* Rootpage of table being initialized */
18074 u8 iDb; /* Which db file is being initialized */
18075 u8 busy; /* TRUE if currently initializing */
18076 unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
18077 unsigned imposterTable : 1; /* Building an imposter table */
18078 unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */
18079 const char **azInit; /* "type", "name", and "tbl_name" columns */
18080 } init;
18081 int nVdbeActive; /* Number of VDBEs currently running */
18082 int nVdbeRead; /* Number of active VDBEs that read or write */
18083 int nVdbeWrite; /* Number of active VDBEs that read and write */
18084 int nVdbeExec; /* Number of nested calls to VdbeExec() */
18085 int nVDestroy; /* Number of active OP_VDestroy operations */
18086 int nExtension; /* Number of loaded extensions */
18087 void **aExtension; /* Array of shared library handles */
18088 union {
18089 void (*xLegacy)(void*,const char*); /* mTrace==SQLITE_TRACE_LEGACY */
18090 int (*xV2)(u32,void*,void*,void*); /* All other mTrace values */
18091 } trace;
18092 void *pTraceArg; /* Argument to the trace function */
18093#ifndef SQLITE_OMIT_DEPRECATED1
18094 void (*xProfile)(void*,const char*,u64); /* Profiling function */
18095 void *pProfileArg; /* Argument to profile function */
18096#endif
18097 void *pCommitArg; /* Argument to xCommitCallback() */
18098 int (*xCommitCallback)(void*); /* Invoked at every commit. */
18099 void *pRollbackArg; /* Argument to xRollbackCallback() */
18100 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
18101 void *pUpdateArg;
18102 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
18103 void *pAutovacPagesArg; /* Client argument to autovac_pages */
18104 void (*xAutovacDestr)(void*); /* Destructor for pAutovacPAgesArg */
18105 unsigned int (*xAutovacPages)(void*,const char*,u32,u32,u32);
18106 Parse *pParse; /* Current parse */
18107#ifdef SQLITE_ENABLE_PREUPDATE_HOOK1
18108 void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
18109 void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
18110 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
18111 );
18112 PreUpdate *pPreUpdate; /* Context for active pre-update callback */
18113#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
18114#ifndef SQLITE_OMIT_WAL
18115 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
18116 void *pWalArg;
18117#endif
18118 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
18119 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
18120 void *pCollNeededArg;
18121 sqlite3_value *pErr; /* Most recent error message */
18122 union {
18123 volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
18124 double notUsed1; /* Spacer */
18125 } u1;
18126 Lookaside lookaside; /* Lookaside malloc configuration */
18127#ifndef SQLITE_OMIT_AUTHORIZATION
18128 sqlite3_xauth xAuth; /* Access authorization function */
18129 void *pAuthArg; /* 1st argument to the access auth function */
18130#endif
18131#ifndef SQLITE_OMIT_PROGRESS_CALLBACK1
18132 int (*xProgress)(void *); /* The progress callback */
18133 void *pProgressArg; /* Argument to the progress callback */
18134 unsigned nProgressOps; /* Number of opcodes for progress callback */
18135#endif
18136#ifndef SQLITE_OMIT_VIRTUALTABLE
18137 int nVTrans; /* Allocated size of aVTrans */
18138 Hash aModule; /* populated by sqlite3_create_module() */
18139 VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
18140 VTable **aVTrans; /* Virtual tables with open transactions */
18141 VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
18142#endif
18143 Hash aFunc; /* Hash table of connection functions */
18144 Hash aCollSeq; /* All collating sequences */
18145 BusyHandler busyHandler; /* Busy callback */
18146 Db aDbStatic[2]; /* Static space for the 2 default backends */
18147 Savepoint *pSavepoint; /* List of active savepoints */
18148 int nAnalysisLimit; /* Number of index rows to ANALYZE */
18149 int busyTimeout; /* Busy handler timeout, in msec */
18150#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
18151 int setlkTimeout; /* Blocking lock timeout, in msec. -1 -> inf. */
18152 int setlkFlags; /* Flags passed to setlk_timeout() */
18153#endif
18154 int nSavepoint; /* Number of non-transaction savepoints */
18155 int nStatement; /* Number of nested statement-transactions */
18156 i64 nDeferredCons; /* Net deferred constraints this transaction. */
18157 i64 nDeferredImmCons; /* Net deferred immediate constraints */
18158 int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
18159 DbClientData *pDbData; /* sqlite3_set_clientdata() content */
18160#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
18161 /* The following variables are all protected by the STATIC_MAIN
18162 ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
18163 **
18164 ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
18165 ** unlock so that it can proceed.
18166 **
18167 ** When X.pBlockingConnection==Y, that means that something that X tried
18168 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
18169 ** held by Y.
18170 */
18171 sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
18172 sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
18173 void *pUnlockArg; /* Argument to xUnlockNotify */
18174 void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
18175 sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
18176#endif
18177};
18178
18179/*
18180** A macro to discover the encoding of a database.
18181*/
18182#define SCHEMA_ENC(db)((db)->aDb[0].pSchema->enc) ((db)->aDb[0].pSchema->enc)
18183#define ENC(db)((db)->enc) ((db)->enc)
18184
18185/*
18186** A u64 constant where the lower 32 bits are all zeros. Only the
18187** upper 32 bits are included in the argument. Necessary because some
18188** C-compilers still do not accept LL integer literals.
18189*/
18190#define HI(X)((u64)(X)<<32) ((u64)(X)<<32)
18191
18192/*
18193** Possible values for the sqlite3.flags.
18194**
18195** Value constraints (enforced via assert()):
18196** SQLITE_FullFSync == PAGER_FULLFSYNC
18197** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
18198** SQLITE_CacheSpill == PAGER_CACHE_SPILL
18199*/
18200#define SQLITE_WriteSchema0x00000001 0x00000001 /* OK to update SQLITE_SCHEMA */
18201#define SQLITE_LegacyFileFmt0x00000002 0x00000002 /* Create new databases in format 1 */
18202#define SQLITE_FullColNames0x00000004 0x00000004 /* Show full column names on SELECT */
18203#define SQLITE_FullFSync0x00000008 0x00000008 /* Use full fsync on the backend */
18204#define SQLITE_CkptFullFSync0x00000010 0x00000010 /* Use full fsync for checkpoint */
18205#define SQLITE_CacheSpill0x00000020 0x00000020 /* OK to spill pager cache */
18206#define SQLITE_ShortColNames0x00000040 0x00000040 /* Show short columns names */
18207#define SQLITE_TrustedSchema0x00000080 0x00000080 /* Allow unsafe functions and
18208 ** vtabs in the schema definition */
18209#define SQLITE_NullCallback0x00000100 0x00000100 /* Invoke the callback once if the */
18210 /* result set is empty */
18211#define SQLITE_IgnoreChecks0x00000200 0x00000200 /* Do not enforce check constraints */
18212#define SQLITE_StmtScanStatus0x00000400 0x00000400 /* Enable stmt_scanstats() counters */
18213#define SQLITE_NoCkptOnClose0x00000800 0x00000800 /* No checkpoint on close()/DETACH */
18214#define SQLITE_ReverseOrder0x00001000 0x00001000 /* Reverse unordered SELECTs */
18215#define SQLITE_RecTriggers0x00002000 0x00002000 /* Enable recursive triggers */
18216#define SQLITE_ForeignKeys0x00004000 0x00004000 /* Enforce foreign key constraints */
18217#define SQLITE_AutoIndex0x00008000 0x00008000 /* Enable automatic indexes */
18218#define SQLITE_LoadExtension0x00010000 0x00010000 /* Enable load_extension */
18219#define SQLITE_LoadExtFunc0x00020000 0x00020000 /* Enable load_extension() SQL func */
18220#define SQLITE_EnableTrigger0x00040000 0x00040000 /* True to enable triggers */
18221#define SQLITE_DeferFKs0x00080000 0x00080000 /* Defer all FK constraints */
18222#define SQLITE_QueryOnly0x00100000 0x00100000 /* Disable database changes */
18223#define SQLITE_CellSizeCk0x00200000 0x00200000 /* Check btree cell sizes on load */
18224#define SQLITE_Fts3Tokenizer0x00400000 0x00400000 /* Enable fts3_tokenizer(2) */
18225#define SQLITE_EnableQPSG0x00800000 0x00800000 /* Query Planner Stability Guarantee*/
18226#define SQLITE_TriggerEQP0x01000000 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */
18227#define SQLITE_ResetDatabase0x02000000 0x02000000 /* Reset the database */
18228#define SQLITE_LegacyAlter0x04000000 0x04000000 /* Legacy ALTER TABLE behaviour */
18229#define SQLITE_NoSchemaError0x08000000 0x08000000 /* Do not report schema parse errors*/
18230#define SQLITE_Defensive0x10000000 0x10000000 /* Input SQL is likely hostile */
18231#define SQLITE_DqsDDL0x20000000 0x20000000 /* dbl-quoted strings allowed in DDL*/
18232#define SQLITE_DqsDML0x40000000 0x40000000 /* dbl-quoted strings allowed in DML*/
18233#define SQLITE_EnableView0x80000000 0x80000000 /* Enable the use of views */
18234#define SQLITE_CountRows((u64)(0x00001)<<32) HI(0x00001)((u64)(0x00001)<<32) /* Count rows changed by INSERT, */
18235 /* DELETE, or UPDATE and return */
18236 /* the count using a callback. */
18237#define SQLITE_CorruptRdOnly((u64)(0x00002)<<32) HI(0x00002)((u64)(0x00002)<<32) /* Prohibit writes due to error */
18238#define SQLITE_ReadUncommit((u64)(0x00004)<<32) HI(0x00004)((u64)(0x00004)<<32) /* READ UNCOMMITTED in shared-cache */
18239#define SQLITE_FkNoAction((u64)(0x00008)<<32) HI(0x00008)((u64)(0x00008)<<32) /* Treat all FK as NO ACTION */
18240#define SQLITE_AttachCreate((u64)(0x00010)<<32) HI(0x00010)((u64)(0x00010)<<32) /* ATTACH allowed to create new dbs */
18241#define SQLITE_AttachWrite((u64)(0x00020)<<32) HI(0x00020)((u64)(0x00020)<<32) /* ATTACH allowed to open for write */
18242#define SQLITE_Comments((u64)(0x00040)<<32) HI(0x00040)((u64)(0x00040)<<32) /* Enable SQL comments */
18243
18244/* Flags used only if debugging */
18245#ifdef SQLITE_DEBUG
18246#define SQLITE_SqlTrace HI(0x0100000)((u64)(0x0100000)<<32) /* Debug print SQL as it executes */
18247#define SQLITE_VdbeListing HI(0x0200000)((u64)(0x0200000)<<32) /* Debug listings of VDBE progs */
18248#define SQLITE_VdbeTrace HI(0x0400000)((u64)(0x0400000)<<32) /* True to trace VDBE execution */
18249#define SQLITE_VdbeAddopTrace HI(0x0800000)((u64)(0x0800000)<<32) /* Trace sqlite3VdbeAddOp() calls */
18250#define SQLITE_VdbeEQP HI(0x1000000)((u64)(0x1000000)<<32) /* Debug EXPLAIN QUERY PLAN */
18251#define SQLITE_ParserTrace HI(0x2000000)((u64)(0x2000000)<<32) /* PRAGMA parser_trace=ON */
18252#endif
18253
18254/*
18255** Allowed values for sqlite3.mDbFlags
18256*/
18257#define DBFLAG_SchemaChange0x0001 0x0001 /* Uncommitted Hash table changes */
18258#define DBFLAG_PreferBuiltin0x0002 0x0002 /* Preference to built-in funcs */
18259#define DBFLAG_Vacuum0x0004 0x0004 /* Currently in a VACUUM */
18260#define DBFLAG_VacuumInto0x0008 0x0008 /* Currently running VACUUM INTO */
18261#define DBFLAG_SchemaKnownOk0x0010 0x0010 /* Schema is known to be valid */
18262#define DBFLAG_InternalFunc0x0020 0x0020 /* Allow use of internal functions */
18263#define DBFLAG_EncodingFixed0x0040 0x0040 /* No longer possible to change enc. */
18264
18265/*
18266** Bits of the sqlite3.dbOptFlags field that are used by the
18267** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
18268** selectively disable various optimizations.
18269*/
18270#define SQLITE_QueryFlattener0x00000001 0x00000001 /* Query flattening */
18271#define SQLITE_WindowFunc0x00000002 0x00000002 /* Use xInverse for window functions */
18272#define SQLITE_GroupByOrder0x00000004 0x00000004 /* GROUPBY cover of ORDERBY */
18273#define SQLITE_FactorOutConst0x00000008 0x00000008 /* Constant factoring */
18274#define SQLITE_DistinctOpt0x00000010 0x00000010 /* DISTINCT using indexes */
18275#define SQLITE_CoverIdxScan0x00000020 0x00000020 /* Covering index scans */
18276#define SQLITE_OrderByIdxJoin0x00000040 0x00000040 /* ORDER BY of joins via index */
18277#define SQLITE_Transitive0x00000080 0x00000080 /* Transitive constraints */
18278#define SQLITE_OmitNoopJoin0x00000100 0x00000100 /* Omit unused tables in joins */
18279#define SQLITE_CountOfView0x00000200 0x00000200 /* The count-of-view optimization */
18280#define SQLITE_CursorHints0x00000400 0x00000400 /* Add OP_CursorHint opcodes */
18281#define SQLITE_Stat40x00000800 0x00000800 /* Use STAT4 data */
18282 /* TH3 expects this value ^^^^^^^^^^ to be 0x0000800. Don't change it */
18283#define SQLITE_PushDown0x00001000 0x00001000 /* WHERE-clause push-down opt */
18284#define SQLITE_SimplifyJoin0x00002000 0x00002000 /* Convert LEFT JOIN to JOIN */
18285#define SQLITE_SkipScan0x00004000 0x00004000 /* Skip-scans */
18286#define SQLITE_PropagateConst0x00008000 0x00008000 /* The constant propagation opt */
18287#define SQLITE_MinMaxOpt0x00010000 0x00010000 /* The min/max optimization */
18288#define SQLITE_SeekScan0x00020000 0x00020000 /* The OP_SeekScan optimization */
18289#define SQLITE_OmitOrderBy0x00040000 0x00040000 /* Omit pointless ORDER BY */
18290 /* TH3 expects this value ^^^^^^^^^^ to be 0x40000. Coordinate any change */
18291#define SQLITE_BloomFilter0x00080000 0x00080000 /* Use a Bloom filter on searches */
18292#define SQLITE_BloomPulldown0x00100000 0x00100000 /* Run Bloom filters early */
18293#define SQLITE_BalancedMerge0x00200000 0x00200000 /* Balance multi-way merges */
18294#define SQLITE_ReleaseReg0x00400000 0x00400000 /* Use OP_ReleaseReg for testing */
18295#define SQLITE_FlttnUnionAll0x00800000 0x00800000 /* Disable the UNION ALL flattener */
18296 /* TH3 expects this value ^^^^^^^^^^ See flatten04.test */
18297#define SQLITE_IndexedExpr0x01000000 0x01000000 /* Pull exprs from index when able */
18298#define SQLITE_Coroutines0x02000000 0x02000000 /* Co-routines for subqueries */
18299#define SQLITE_NullUnusedCols0x04000000 0x04000000 /* NULL unused columns in subqueries */
18300#define SQLITE_OnePass0x08000000 0x08000000 /* Single-pass DELETE and UPDATE */
18301#define SQLITE_OrderBySubq0x10000000 0x10000000 /* ORDER BY in subquery helps outer */
18302#define SQLITE_StarQuery0x20000000 0x20000000 /* Heurists for star queries */
18303#define SQLITE_AllOpts0xffffffff 0xffffffff /* All optimizations */
18304
18305/*
18306** Macros for testing whether or not optimizations are enabled or disabled.
18307*/
18308#define OptimizationDisabled(db, mask)(((db)->dbOptFlags&(mask))!=0) (((db)->dbOptFlags&(mask))!=0)
18309#define OptimizationEnabled(db, mask)(((db)->dbOptFlags&(mask))==0) (((db)->dbOptFlags&(mask))==0)
18310
18311/*
18312** Return true if it OK to factor constant expressions into the initialization
18313** code. The argument is a Parse object for the code generator.
18314*/
18315#define ConstFactorOk(P)((P)->okConstFactor) ((P)->okConstFactor)
18316
18317/* Possible values for the sqlite3.eOpenState field.
18318** The numbers are randomly selected such that a minimum of three bits must
18319** change to convert any number to another or to zero
18320*/
18321#define SQLITE_STATE_OPEN0x76 0x76 /* Database is open */
18322#define SQLITE_STATE_CLOSED0xce 0xce /* Database is closed */
18323#define SQLITE_STATE_SICK0xba 0xba /* Error and awaiting close */
18324#define SQLITE_STATE_BUSY0x6d 0x6d /* Database currently in use */
18325#define SQLITE_STATE_ERROR0xd5 0xd5 /* An SQLITE_MISUSE error occurred */
18326#define SQLITE_STATE_ZOMBIE0xa7 0xa7 /* Close with last statement close */
18327
18328/*
18329** Each SQL function is defined by an instance of the following
18330** structure. For global built-in functions (ex: substr(), max(), count())
18331** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
18332** For per-connection application-defined functions, a pointer to this
18333** structure is held in the db->aHash hash table.
18334**
18335** The u.pHash field is used by the global built-ins. The u.pDestructor
18336** field is used by per-connection app-def functions.
18337*/
18338struct FuncDef {
18339 i16 nArg; /* Number of arguments. -1 means unlimited */
18340 u32 funcFlags; /* Some combination of SQLITE_FUNC_* */
18341 void *pUserData; /* User data parameter */
18342 FuncDef *pNext; /* Next function with same name */
18343 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
18344 void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
18345 void (*xValue)(sqlite3_context*); /* Current agg value */
18346 void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
18347 const char *zName; /* SQL name of the function. */
18348 union {
18349 FuncDef *pHash; /* Next with a different name but the same hash */
18350 FuncDestructor *pDestructor; /* Reference counted destructor function */
18351 } u; /* pHash if SQLITE_FUNC_BUILTIN, pDestructor otherwise */
18352};
18353
18354/*
18355** This structure encapsulates a user-function destructor callback (as
18356** configured using create_function_v2()) and a reference counter. When
18357** create_function_v2() is called to create a function with a destructor,
18358** a single object of this type is allocated. FuncDestructor.nRef is set to
18359** the number of FuncDef objects created (either 1 or 3, depending on whether
18360** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
18361** member of each of the new FuncDef objects is set to point to the allocated
18362** FuncDestructor.
18363**
18364** Thereafter, when one of the FuncDef objects is deleted, the reference
18365** count on this object is decremented. When it reaches 0, the destructor
18366** is invoked and the FuncDestructor structure freed.
18367*/
18368struct FuncDestructor {
18369 int nRef;
18370 void (*xDestroy)(void *);
18371 void *pUserData;
18372};
18373
18374/*
18375** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
18376** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
18377** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
18378** are assert() statements in the code to verify this.
18379**
18380** Value constraints (enforced via assert()):
18381** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
18382** SQLITE_FUNC_ANYORDER == NC_OrderAgg == SF_OrderByReqd
18383** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
18384** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
18385** SQLITE_FUNC_BYTELEN == OPFLAG_BYTELENARG
18386** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
18387** SQLITE_FUNC_DIRECT == SQLITE_DIRECTONLY from the API
18388** SQLITE_FUNC_UNSAFE == SQLITE_INNOCUOUS -- opposite meanings!!!
18389** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
18390**
18391** Note that even though SQLITE_FUNC_UNSAFE and SQLITE_INNOCUOUS have the
18392** same bit value, their meanings are inverted. SQLITE_FUNC_UNSAFE is
18393** used internally and if set means that the function has side effects.
18394** SQLITE_INNOCUOUS is used by application code and means "not unsafe".
18395** See multiple instances of tag-20230109-1.
18396*/
18397#define SQLITE_FUNC_ENCMASK0x0003 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
18398#define SQLITE_FUNC_LIKE0x0004 0x0004 /* Candidate for the LIKE optimization */
18399#define SQLITE_FUNC_CASE0x0008 0x0008 /* Case-sensitive LIKE-type function */
18400#define SQLITE_FUNC_EPHEM0x0010 0x0010 /* Ephemeral. Delete with VDBE */
18401#define SQLITE_FUNC_NEEDCOLL0x0020 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
18402#define SQLITE_FUNC_LENGTH0x0040 0x0040 /* Built-in length() function */
18403#define SQLITE_FUNC_TYPEOF0x0080 0x0080 /* Built-in typeof() function */
18404#define SQLITE_FUNC_BYTELEN0x00c0 0x00c0 /* Built-in octet_length() function */
18405#define SQLITE_FUNC_COUNT0x0100 0x0100 /* Built-in count(*) aggregate */
18406/* 0x0200 -- available for reuse */
18407#define SQLITE_FUNC_UNLIKELY0x0400 0x0400 /* Built-in unlikely() function */
18408#define SQLITE_FUNC_CONSTANT0x0800 0x0800 /* Constant inputs give a constant output */
18409#define SQLITE_FUNC_MINMAX0x1000 0x1000 /* True for min() and max() aggregates */
18410#define SQLITE_FUNC_SLOCHNG0x2000 0x2000 /* "Slow Change". Value constant during a
18411 ** single query - might change over time */
18412#define SQLITE_FUNC_TEST0x4000 0x4000 /* Built-in testing functions */
18413#define SQLITE_FUNC_RUNONLY0x8000 0x8000 /* Cannot be used by valueFromFunction */
18414#define SQLITE_FUNC_WINDOW0x00010000 0x00010000 /* Built-in window-only function */
18415#define SQLITE_FUNC_INTERNAL0x00040000 0x00040000 /* For use by NestedParse() only */
18416#define SQLITE_FUNC_DIRECT0x00080000 0x00080000 /* Not for use in TRIGGERs or VIEWs */
18417/* SQLITE_SUBTYPE 0x00100000 // Consumer of subtypes */
18418#define SQLITE_FUNC_UNSAFE0x00200000 0x00200000 /* Function has side effects */
18419#define SQLITE_FUNC_INLINE0x00400000 0x00400000 /* Functions implemented in-line */
18420#define SQLITE_FUNC_BUILTIN0x00800000 0x00800000 /* This is a built-in function */
18421/* SQLITE_RESULT_SUBTYPE 0x01000000 // Generator of subtypes */
18422#define SQLITE_FUNC_ANYORDER0x08000000 0x08000000 /* count/min/max aggregate */
18423
18424/* Identifier numbers for each in-line function */
18425#define INLINEFUNC_coalesce0 0
18426#define INLINEFUNC_implies_nonnull_row1 1
18427#define INLINEFUNC_expr_implies_expr2 2
18428#define INLINEFUNC_expr_compare3 3
18429#define INLINEFUNC_affinity4 4
18430#define INLINEFUNC_iif5 5
18431#define INLINEFUNC_sqlite_offset6 6
18432#define INLINEFUNC_unlikely99 99 /* Default case */
18433
18434/*
18435** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
18436** used to create the initializers for the FuncDef structures.
18437**
18438** FUNCTION(zName, nArg, iArg, bNC, xFunc)
18439** Used to create a scalar function definition of a function zName
18440** implemented by C function xFunc that accepts nArg arguments. The
18441** value passed as iArg is cast to a (void*) and made available
18442** as the user-data (sqlite3_user_data()) for the function. If
18443** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
18444**
18445** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
18446** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
18447**
18448** SFUNCTION(zName, nArg, iArg, bNC, xFunc)
18449** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
18450** adds the SQLITE_DIRECTONLY flag.
18451**
18452** INLINE_FUNC(zName, nArg, iFuncId, mFlags)
18453** zName is the name of a function that is implemented by in-line
18454** byte code rather than by the usual callbacks. The iFuncId
18455** parameter determines the function id. The mFlags parameter is
18456** optional SQLITE_FUNC_ flags for this function.
18457**
18458** TEST_FUNC(zName, nArg, iFuncId, mFlags)
18459** zName is the name of a test-only function implemented by in-line
18460** byte code rather than by the usual callbacks. The iFuncId
18461** parameter determines the function id. The mFlags parameter is
18462** optional SQLITE_FUNC_ flags for this function.
18463**
18464** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
18465** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
18466** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
18467** and functions like sqlite_version() that can change, but not during
18468** a single query. The iArg is ignored. The user-data is always set
18469** to a NULL pointer. The bNC parameter is not used.
18470**
18471** MFUNCTION(zName, nArg, xPtr, xFunc)
18472** For math-library functions. xPtr is an arbitrary pointer.
18473**
18474** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
18475** Used for "pure" date/time functions, this macro is like DFUNCTION
18476** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
18477** ignored and the user-data for these functions is set to an
18478** arbitrary non-NULL pointer. The bNC parameter is not used.
18479**
18480** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
18481** Used to create an aggregate function definition implemented by
18482** the C functions xStep and xFinal. The first four parameters
18483** are interpreted in the same way as the first 4 parameters to
18484** FUNCTION().
18485**
18486** WAGGREGATE(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
18487** Used to create an aggregate function definition implemented by
18488** the C functions xStep and xFinal. The first four parameters
18489** are interpreted in the same way as the first 4 parameters to
18490** FUNCTION().
18491**
18492** LIKEFUNC(zName, nArg, pArg, flags)
18493** Used to create a scalar function definition of a function zName
18494** that accepts nArg arguments and is implemented by a call to C
18495** function likeFunc. Argument pArg is cast to a (void *) and made
18496** available as the function user-data (sqlite3_user_data()). The
18497** FuncDef.flags variable is set to the value passed as the flags
18498** parameter.
18499*/
18500#define FUNCTION(zName, nArg, iArg, bNC, xFunc){nArg, 0x00800000| 0x0800|1|(bNC*0x0020), ((void*)(long int)(
iArg)), 0, xFunc, 0, 0, 0, "zName", {0} }
\
18501 {nArg, SQLITE_FUNC_BUILTIN0x00800000|\
18502 SQLITE_FUNC_CONSTANT0x0800|SQLITE_UTF81|(bNC*SQLITE_FUNC_NEEDCOLL0x0020), \
18503 SQLITE_INT_TO_PTR(iArg)((void*)(long int)(iArg)), 0, xFunc, 0, 0, 0, #zName, {0} }
18504#define VFUNCTION(zName, nArg, iArg, bNC, xFunc){nArg, 0x00800000|1|(bNC*0x0020), ((void*)(long int)(iArg)), 0
, xFunc, 0, 0, 0, "zName", {0} }
\
18505 {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_UTF81|(bNC*SQLITE_FUNC_NEEDCOLL0x0020), \
18506 SQLITE_INT_TO_PTR(iArg)((void*)(long int)(iArg)), 0, xFunc, 0, 0, 0, #zName, {0} }
18507#define SFUNCTION(zName, nArg, iArg, bNC, xFunc){nArg, 0x00800000|1|0x000080000|0x00200000, ((void*)(long int
)(iArg)), 0, xFunc, 0, 0, 0, "zName", {0} }
\
18508 {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_UTF81|SQLITE_DIRECTONLY0x000080000|SQLITE_FUNC_UNSAFE0x00200000, \
18509 SQLITE_INT_TO_PTR(iArg)((void*)(long int)(iArg)), 0, xFunc, 0, 0, 0, #zName, {0} }
18510#define MFUNCTION(zName, nArg, xPtr, xFunc){nArg, 0x00800000|0x0800|1, xPtr, 0, xFunc, 0, 0, 0, "zName",
{0} }
\
18511 {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_FUNC_CONSTANT0x0800|SQLITE_UTF81, \
18512 xPtr, 0, xFunc, 0, 0, 0, #zName, {0} }
18513#define JFUNCTION(zName, nArg, bUseCache, bWS, bRS, bJsonB, iArg, xFunc){nArg, 0x00800000|0x000000800|0x0800| 1|((bUseCache)*0x8000)|
((bRS)*0x000100000)|((bWS)*0x001000000), ((void*)(long int)(
iArg|((bJsonB)*0x08))),0,xFunc,0, 0, 0, "zName", {0} }
\
18514 {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_DETERMINISTIC0x000000800|SQLITE_FUNC_CONSTANT0x0800|\
18515 SQLITE_UTF81|((bUseCache)*SQLITE_FUNC_RUNONLY0x8000)|\
18516 ((bRS)*SQLITE_SUBTYPE0x000100000)|((bWS)*SQLITE_RESULT_SUBTYPE0x001000000), \
18517 SQLITE_INT_TO_PTR(iArg|((bJsonB)*JSON_BLOB))((void*)(long int)(iArg|((bJsonB)*0x08))),0,xFunc,0, 0, 0, #zName, {0} }
18518#define INLINE_FUNC(zName, nArg, iArg, mFlags){nArg, 0x00800000| 1|0x00400000|0x0800|(mFlags), ((void*)(long
int)(iArg)), 0, versionFunc, 0, 0, 0, "zName", {0} }
\
18519 {nArg, SQLITE_FUNC_BUILTIN0x00800000|\
18520 SQLITE_UTF81|SQLITE_FUNC_INLINE0x00400000|SQLITE_FUNC_CONSTANT0x0800|(mFlags), \
18521 SQLITE_INT_TO_PTR(iArg)((void*)(long int)(iArg)), 0, noopFuncversionFunc, 0, 0, 0, #zName, {0} }
18522#define TEST_FUNC(zName, nArg, iArg, mFlags){nArg, 0x00800000| 1|0x00040000|0x4000| 0x00400000|0x0800|(mFlags
), ((void*)(long int)(iArg)), 0, versionFunc, 0, 0, 0, "zName"
, {0} }
\
18523 {nArg, SQLITE_FUNC_BUILTIN0x00800000|\
18524 SQLITE_UTF81|SQLITE_FUNC_INTERNAL0x00040000|SQLITE_FUNC_TEST0x4000| \
18525 SQLITE_FUNC_INLINE0x00400000|SQLITE_FUNC_CONSTANT0x0800|(mFlags), \
18526 SQLITE_INT_TO_PTR(iArg)((void*)(long int)(iArg)), 0, noopFuncversionFunc, 0, 0, 0, #zName, {0} }
18527#define DFUNCTION(zName, nArg, iArg, bNC, xFunc){nArg, 0x00800000|0x2000|1, 0, 0, xFunc, 0, 0, 0, "zName", {0
} }
\
18528 {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_FUNC_SLOCHNG0x2000|SQLITE_UTF81, \
18529 0, 0, xFunc, 0, 0, 0, #zName, {0} }
18530#define PURE_DATE(zName, nArg, iArg, bNC, xFunc){nArg, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config
, 0, xFunc, 0, 0, 0, "zName", {0} }
\
18531 {nArg, SQLITE_FUNC_BUILTIN0x00800000|\
18532 SQLITE_FUNC_SLOCHNG0x2000|SQLITE_UTF81|SQLITE_FUNC_CONSTANT0x0800, \
18533 (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
18534#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags){nArg, 0x00800000| 0x0800|1|(bNC*0x0020)|extraFlags, ((void*)
(long int)(iArg)), 0, xFunc, 0, 0, 0, "zName", {0} }
\
18535 {nArg, SQLITE_FUNC_BUILTIN0x00800000|\
18536 SQLITE_FUNC_CONSTANT0x0800|SQLITE_UTF81|(bNC*SQLITE_FUNC_NEEDCOLL0x0020)|extraFlags,\
18537 SQLITE_INT_TO_PTR(iArg)((void*)(long int)(iArg)), 0, xFunc, 0, 0, 0, #zName, {0} }
18538#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc){nArg, 0x00800000| 0x2000|1|(bNC*0x0020), pArg, 0, xFunc, 0, 0
, 0, "zName", }
\
18539 {nArg, SQLITE_FUNC_BUILTIN0x00800000|\
18540 SQLITE_FUNC_SLOCHNG0x2000|SQLITE_UTF81|(bNC*SQLITE_FUNC_NEEDCOLL0x0020), \
18541 pArg, 0, xFunc, 0, 0, 0, #zName, }
18542#define LIKEFUNC(zName, nArg, arg, flags){nArg, 0x00800000|0x0800|1|flags, (void *)arg, 0, likeFunc, 0
, 0, 0, "zName", {0} }
\
18543 {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_FUNC_CONSTANT0x0800|SQLITE_UTF81|flags, \
18544 (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
18545#define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f){nArg, 0x00800000|1|(nc*0x0020)|f, ((void*)(long int)(arg)), 0
, xStep,xFinal,xValue,xInverse,"zName", {0}}
\
18546 {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_UTF81|(nc*SQLITE_FUNC_NEEDCOLL0x0020)|f, \
18547 SQLITE_INT_TO_PTR(arg)((void*)(long int)(arg)), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
18548#define INTERNAL_FUNCTION(zName, nArg, xFunc){nArg, 0x00800000| 0x00040000|1|0x0800, 0, 0, xFunc, 0, 0, 0,
"zName", {0} }
\
18549 {nArg, SQLITE_FUNC_BUILTIN0x00800000|\
18550 SQLITE_FUNC_INTERNAL0x00040000|SQLITE_UTF81|SQLITE_FUNC_CONSTANT0x0800, \
18551 0, 0, xFunc, 0, 0, 0, #zName, {0} }
18552
18553
18554/*
18555** All current savepoints are stored in a linked list starting at
18556** sqlite3.pSavepoint. The first element in the list is the most recently
18557** opened savepoint. Savepoints are added to the list by the vdbe
18558** OP_Savepoint instruction.
18559*/
18560struct Savepoint {
18561 char *zName; /* Savepoint name (nul-terminated) */
18562 i64 nDeferredCons; /* Number of deferred fk violations */
18563 i64 nDeferredImmCons; /* Number of deferred imm fk. */
18564 Savepoint *pNext; /* Parent savepoint (if any) */
18565};
18566
18567/*
18568** The following are used as the second parameter to sqlite3Savepoint(),
18569** and as the P1 argument to the OP_Savepoint instruction.
18570*/
18571#define SAVEPOINT_BEGIN0 0
18572#define SAVEPOINT_RELEASE1 1
18573#define SAVEPOINT_ROLLBACK2 2
18574
18575
18576/*
18577** Each SQLite module (virtual table definition) is defined by an
18578** instance of the following structure, stored in the sqlite3.aModule
18579** hash table.
18580*/
18581struct Module {
18582 const sqlite3_module *pModule; /* Callback pointers */
18583 const char *zName; /* Name passed to create_module() */
18584 int nRefModule; /* Number of pointers to this object */
18585 void *pAux; /* pAux passed to create_module() */
18586 void (*xDestroy)(void *); /* Module destructor function */
18587 Table *pEpoTab; /* Eponymous table for this module */
18588};
18589
18590/*
18591** Information about each column of an SQL table is held in an instance
18592** of the Column structure, in the Table.aCol[] array.
18593**
18594** Definitions:
18595**
18596** "table column index" This is the index of the column in the
18597** Table.aCol[] array, and also the index of
18598** the column in the original CREATE TABLE stmt.
18599**
18600** "storage column index" This is the index of the column in the
18601** record BLOB generated by the OP_MakeRecord
18602** opcode. The storage column index is less than
18603** or equal to the table column index. It is
18604** equal if and only if there are no VIRTUAL
18605** columns to the left.
18606**
18607** Notes on zCnName:
18608** The zCnName field stores the name of the column, the datatype of the
18609** column, and the collating sequence for the column, in that order, all in
18610** a single allocation. Each string is 0x00 terminated. The datatype
18611** is only included if the COLFLAG_HASTYPE bit of colFlags is set and the
18612** collating sequence name is only included if the COLFLAG_HASCOLL bit is
18613** set.
18614*/
18615struct Column {
18616 char *zCnName; /* Name of this column */
18617 unsigned notNull :4; /* An OE_ code for handling a NOT NULL constraint */
18618 unsigned eCType :4; /* One of the standard types */
18619 char affinity; /* One of the SQLITE_AFF_... values */
18620 u8 szEst; /* Est size of value in this column. sizeof(INT)==1 */
18621 u8 hName; /* Column name hash for faster lookup */
18622 u16 iDflt; /* 1-based index of DEFAULT. 0 means "none" */
18623 u16 colFlags; /* Boolean properties. See COLFLAG_ defines below */
18624};
18625
18626/* Allowed values for Column.eCType.
18627**
18628** Values must match entries in the global constant arrays
18629** sqlite3StdTypeLen[] and sqlite3StdType[]. Each value is one more
18630** than the offset into these arrays for the corresponding name.
18631** Adjust the SQLITE_N_STDTYPE value if adding or removing entries.
18632*/
18633#define COLTYPE_CUSTOM0 0 /* Type appended to zName */
18634#define COLTYPE_ANY1 1
18635#define COLTYPE_BLOB2 2
18636#define COLTYPE_INT3 3
18637#define COLTYPE_INTEGER4 4
18638#define COLTYPE_REAL5 5
18639#define COLTYPE_TEXT6 6
18640#define SQLITE_N_STDTYPE6 6 /* Number of standard types */
18641
18642/* Allowed values for Column.colFlags.
18643**
18644** Constraints:
18645** TF_HasVirtual == COLFLAG_VIRTUAL
18646** TF_HasStored == COLFLAG_STORED
18647** TF_HasHidden == COLFLAG_HIDDEN
18648*/
18649#define COLFLAG_PRIMKEY0x0001 0x0001 /* Column is part of the primary key */
18650#define COLFLAG_HIDDEN0x0002 0x0002 /* A hidden column in a virtual table */
18651#define COLFLAG_HASTYPE0x0004 0x0004 /* Type name follows column name */
18652#define COLFLAG_UNIQUE0x0008 0x0008 /* Column def contains "UNIQUE" or "PK" */
18653#define COLFLAG_SORTERREF0x0010 0x0010 /* Use sorter-refs with this column */
18654#define COLFLAG_VIRTUAL0x0020 0x0020 /* GENERATED ALWAYS AS ... VIRTUAL */
18655#define COLFLAG_STORED0x0040 0x0040 /* GENERATED ALWAYS AS ... STORED */
18656#define COLFLAG_NOTAVAIL0x0080 0x0080 /* STORED column not yet calculated */
18657#define COLFLAG_BUSY0x0100 0x0100 /* Blocks recursion on GENERATED columns */
18658#define COLFLAG_HASCOLL0x0200 0x0200 /* Has collating sequence name in zCnName */
18659#define COLFLAG_NOEXPAND0x0400 0x0400 /* Omit this column when expanding "*" */
18660#define COLFLAG_GENERATED0x0060 0x0060 /* Combo: _STORED, _VIRTUAL */
18661#define COLFLAG_NOINSERT0x0062 0x0062 /* Combo: _HIDDEN, _STORED, _VIRTUAL */
18662
18663/*
18664** A "Collating Sequence" is defined by an instance of the following
18665** structure. Conceptually, a collating sequence consists of a name and
18666** a comparison routine that defines the order of that sequence.
18667**
18668** If CollSeq.xCmp is NULL, it means that the
18669** collating sequence is undefined. Indices built on an undefined
18670** collating sequence may not be read or written.
18671*/
18672struct CollSeq {
18673 char *zName; /* Name of the collating sequence, UTF-8 encoded */
18674 u8 enc; /* Text encoding handled by xCmp() */
18675 void *pUser; /* First argument to xCmp() */
18676 int (*xCmp)(void*,int, const void*, int, const void*);
18677 void (*xDel)(void*); /* Destructor for pUser */
18678};
18679
18680/*
18681** A sort order can be either ASC or DESC.
18682*/
18683#define SQLITE_SO_ASC0 0 /* Sort in ascending order */
18684#define SQLITE_SO_DESC1 1 /* Sort in ascending order */
18685#define SQLITE_SO_UNDEFINED-1 -1 /* No sort order specified */
18686
18687/*
18688** Column affinity types.
18689**
18690** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
18691** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
18692** the speed a little by numbering the values consecutively.
18693**
18694** But rather than start with 0 or 1, we begin with 'A'. That way,
18695** when multiple affinity types are concatenated into a string and
18696** used as the P4 operand, they will be more readable.
18697**
18698** Note also that the numeric types are grouped together so that testing
18699** for a numeric type is a single comparison. And the BLOB type is first.
18700*/
18701#define SQLITE_AFF_NONE0x40 0x40 /* '@' */
18702#define SQLITE_AFF_BLOB0x41 0x41 /* 'A' */
18703#define SQLITE_AFF_TEXT0x42 0x42 /* 'B' */
18704#define SQLITE_AFF_NUMERIC0x43 0x43 /* 'C' */
18705#define SQLITE_AFF_INTEGER0x44 0x44 /* 'D' */
18706#define SQLITE_AFF_REAL0x45 0x45 /* 'E' */
18707#define SQLITE_AFF_FLEXNUM0x46 0x46 /* 'F' */
18708#define SQLITE_AFF_DEFER0x58 0x58 /* 'X' - defer computation until later */
18709
18710#define sqlite3IsNumericAffinity(X)((X)>=0x43) ((X)>=SQLITE_AFF_NUMERIC0x43)
18711
18712/*
18713** The SQLITE_AFF_MASK values masks off the significant bits of an
18714** affinity value.
18715*/
18716#define SQLITE_AFF_MASK0x47 0x47
18717
18718/*
18719** Additional bit values that can be ORed with an affinity without
18720** changing the affinity.
18721**
18722** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
18723** It causes an assert() to fire if either operand to a comparison
18724** operator is NULL. It is added to certain comparison operators to
18725** prove that the operands are always NOT NULL.
18726*/
18727#define SQLITE_JUMPIFNULL0x10 0x10 /* jumps if either operand is NULL */
18728#define SQLITE_NULLEQ0x80 0x80 /* NULL=NULL */
18729#define SQLITE_NOTNULL0x90 0x90 /* Assert that operands are never NULL */
18730
18731/*
18732** An object of this type is created for each virtual table present in
18733** the database schema.
18734**
18735** If the database schema is shared, then there is one instance of this
18736** structure for each database connection (sqlite3*) that uses the shared
18737** schema. This is because each database connection requires its own unique
18738** instance of the sqlite3_vtab* handle used to access the virtual table
18739** implementation. sqlite3_vtab* handles can not be shared between
18740** database connections, even when the rest of the in-memory database
18741** schema is shared, as the implementation often stores the database
18742** connection handle passed to it via the xConnect() or xCreate() method
18743** during initialization internally. This database connection handle may
18744** then be used by the virtual table implementation to access real tables
18745** within the database. So that they appear as part of the callers
18746** transaction, these accesses need to be made via the same database
18747** connection as that used to execute SQL operations on the virtual table.
18748**
18749** All VTable objects that correspond to a single table in a shared
18750** database schema are initially stored in a linked-list pointed to by
18751** the Table.pVTable member variable of the corresponding Table object.
18752** When an sqlite3_prepare() operation is required to access the virtual
18753** table, it searches the list for the VTable that corresponds to the
18754** database connection doing the preparing so as to use the correct
18755** sqlite3_vtab* handle in the compiled query.
18756**
18757** When an in-memory Table object is deleted (for example when the
18758** schema is being reloaded for some reason), the VTable objects are not
18759** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
18760** immediately. Instead, they are moved from the Table.pVTable list to
18761** another linked list headed by the sqlite3.pDisconnect member of the
18762** corresponding sqlite3 structure. They are then deleted/xDisconnected
18763** next time a statement is prepared using said sqlite3*. This is done
18764** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
18765** Refer to comments above function sqlite3VtabUnlockList() for an
18766** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
18767** list without holding the corresponding sqlite3.mutex mutex.
18768**
18769** The memory for objects of this type is always allocated by
18770** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
18771** the first argument.
18772*/
18773struct VTable {
18774 sqlite3 *db; /* Database connection associated with this table */
18775 Module *pMod; /* Pointer to module implementation */
18776 sqlite3_vtab *pVtab; /* Pointer to vtab instance */
18777 int nRef; /* Number of pointers to this structure */
18778 u8 bConstraint; /* True if constraints are supported */
18779 u8 bAllSchemas; /* True if might use any attached schema */
18780 u8 eVtabRisk; /* Riskiness of allowing hacker access */
18781 int iSavepoint; /* Depth of the SAVEPOINT stack */
18782 VTable *pNext; /* Next in linked list (see above) */
18783};
18784
18785/* Allowed values for VTable.eVtabRisk
18786*/
18787#define SQLITE_VTABRISK_Low0 0
18788#define SQLITE_VTABRISK_Normal1 1
18789#define SQLITE_VTABRISK_High2 2
18790
18791/*
18792** The schema for each SQL table, virtual table, and view is represented
18793** in memory by an instance of the following structure.
18794*/
18795struct Table {
18796 char *zName; /* Name of the table or view */
18797 Column *aCol; /* Information about each column */
18798 Index *pIndex; /* List of SQL indexes on this table. */
18799 char *zColAff; /* String defining the affinity of each column */
18800 ExprList *pCheck; /* All CHECK constraints */
18801 /* ... also used as column name list in a VIEW */
18802 Pgno tnum; /* Root BTree page for this table */
18803 u32 nTabRef; /* Number of pointers to this Table */
18804 u32 tabFlags; /* Mask of TF_* values */
18805 i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
18806 i16 nCol; /* Number of columns in this table */
18807 i16 nNVCol; /* Number of columns that are not VIRTUAL */
18808 LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
18809 LogEst szTabRow; /* Estimated size of each table row in bytes */
18810#ifdef SQLITE_ENABLE_COSTMULT
18811 LogEst costMult; /* Cost multiplier for using this table */
18812#endif
18813 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
18814 u8 eTabType; /* 0: normal, 1: virtual, 2: view */
18815 union {
18816 struct { /* Used by ordinary tables: */
18817 int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
18818 FKey *pFKey; /* Linked list of all foreign keys in this table */
18819 ExprList *pDfltList; /* DEFAULT clauses on various columns.
18820 ** Or the AS clause for generated columns. */
18821 } tab;
18822 struct { /* Used by views: */
18823 Select *pSelect; /* View definition */
18824 } view;
18825 struct { /* Used by virtual tables only: */
18826 int nArg; /* Number of arguments to the module */
18827 char **azArg; /* 0: module 1: schema 2: vtab name 3...: args */
18828 VTable *p; /* List of VTable objects. */
18829 } vtab;
18830 } u;
18831 Trigger *pTrigger; /* List of triggers on this object */
18832 Schema *pSchema; /* Schema that contains this table */
18833 u8 aHx[16]; /* Column aHt[K%sizeof(aHt)] might have hash K */
18834};
18835
18836/*
18837** Allowed values for Table.tabFlags.
18838**
18839** TF_OOOHidden applies to tables or view that have hidden columns that are
18840** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
18841** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
18842** the TF_OOOHidden attribute would apply in this case. Such tables require
18843** special handling during INSERT processing. The "OOO" means "Out Of Order".
18844**
18845** Constraints:
18846**
18847** TF_HasVirtual == COLFLAG_VIRTUAL
18848** TF_HasStored == COLFLAG_STORED
18849** TF_HasHidden == COLFLAG_HIDDEN
18850*/
18851#define TF_Readonly0x00000001 0x00000001 /* Read-only system table */
18852#define TF_HasHidden0x00000002 0x00000002 /* Has one or more hidden columns */
18853#define TF_HasPrimaryKey0x00000004 0x00000004 /* Table has a primary key */
18854#define TF_Autoincrement0x00000008 0x00000008 /* Integer primary key is autoincrement */
18855#define TF_HasStat10x00000010 0x00000010 /* nRowLogEst set from sqlite_stat1 */
18856#define TF_HasVirtual0x00000020 0x00000020 /* Has one or more VIRTUAL columns */
18857#define TF_HasStored0x00000040 0x00000040 /* Has one or more STORED columns */
18858#define TF_HasGenerated0x00000060 0x00000060 /* Combo: HasVirtual + HasStored */
18859#define TF_WithoutRowid0x00000080 0x00000080 /* No rowid. PRIMARY KEY is the key */
18860#define TF_MaybeReanalyze0x00000100 0x00000100 /* Maybe run ANALYZE on this table */
18861#define TF_NoVisibleRowid0x00000200 0x00000200 /* No user-visible "rowid" column */
18862#define TF_OOOHidden0x00000400 0x00000400 /* Out-of-Order hidden columns */
18863#define TF_HasNotNull0x00000800 0x00000800 /* Contains NOT NULL constraints */
18864#define TF_Shadow0x00001000 0x00001000 /* True for a shadow table */
18865#define TF_HasStat40x00002000 0x00002000 /* STAT4 info available for this table */
18866#define TF_Ephemeral0x00004000 0x00004000 /* An ephemeral table */
18867#define TF_Eponymous0x00008000 0x00008000 /* An eponymous virtual table */
18868#define TF_Strict0x00010000 0x00010000 /* STRICT mode */
18869
18870/*
18871** Allowed values for Table.eTabType
18872*/
18873#define TABTYP_NORM0 0 /* Ordinary table */
18874#define TABTYP_VTAB1 1 /* Virtual table */
18875#define TABTYP_VIEW2 2 /* A view */
18876
18877#define IsView(X)((X)->eTabType==2) ((X)->eTabType==TABTYP_VIEW2)
18878#define IsOrdinaryTable(X)((X)->eTabType==0) ((X)->eTabType==TABTYP_NORM0)
18879
18880/*
18881** Test to see whether or not a table is a virtual table. This is
18882** done as a macro so that it will be optimized out when virtual
18883** table support is omitted from the build.
18884*/
18885#ifndef SQLITE_OMIT_VIRTUALTABLE
18886# define IsVirtual(X)((X)->eTabType==1) ((X)->eTabType==TABTYP_VTAB1)
18887# define ExprIsVtab(X)((X)->op==168 && (X)->y.pTab->eTabType==1) \
18888 ((X)->op==TK_COLUMN168 && (X)->y.pTab->eTabType==TABTYP_VTAB1)
18889#else
18890# define IsVirtual(X)((X)->eTabType==1) 0
18891# define ExprIsVtab(X)((X)->op==168 && (X)->y.pTab->eTabType==1) 0
18892#endif
18893
18894/*
18895** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
18896** only works for non-virtual tables (ordinary tables and views) and is
18897** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
18898** IsHiddenColumn() macro is general purpose.
18899*/
18900#if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
18901# define IsHiddenColumn(X)(((X)->colFlags & 0x0002)!=0) (((X)->colFlags & COLFLAG_HIDDEN0x0002)!=0)
18902# define IsOrdinaryHiddenColumn(X)0 (((X)->colFlags & COLFLAG_HIDDEN0x0002)!=0)
18903#elif !defined(SQLITE_OMIT_VIRTUALTABLE)
18904# define IsHiddenColumn(X)(((X)->colFlags & 0x0002)!=0) (((X)->colFlags & COLFLAG_HIDDEN0x0002)!=0)
18905# define IsOrdinaryHiddenColumn(X)0 0
18906#else
18907# define IsHiddenColumn(X)(((X)->colFlags & 0x0002)!=0) 0
18908# define IsOrdinaryHiddenColumn(X)0 0
18909#endif
18910
18911
18912/* Does the table have a rowid */
18913#define HasRowid(X)(((X)->tabFlags & 0x00000080)==0) (((X)->tabFlags & TF_WithoutRowid0x00000080)==0)
18914#define VisibleRowid(X)(((X)->tabFlags & 0x00000200)==0) (((X)->tabFlags & TF_NoVisibleRowid0x00000200)==0)
18915
18916/* Macro is true if the SQLITE_ALLOW_ROWID_IN_VIEW (mis-)feature is
18917** available. By default, this macro is false
18918*/
18919#ifndef SQLITE_ALLOW_ROWID_IN_VIEW
18920# define ViewCanHaveRowid0 0
18921#else
18922# define ViewCanHaveRowid0 (sqlite3Config.mNoVisibleRowid==0)
18923#endif
18924
18925/*
18926** Each foreign key constraint is an instance of the following structure.
18927**
18928** A foreign key is associated with two tables. The "from" table is
18929** the table that contains the REFERENCES clause that creates the foreign
18930** key. The "to" table is the table that is named in the REFERENCES clause.
18931** Consider this example:
18932**
18933** CREATE TABLE ex1(
18934** a INTEGER PRIMARY KEY,
18935** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
18936** );
18937**
18938** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
18939** Equivalent names:
18940**
18941** from-table == child-table
18942** to-table == parent-table
18943**
18944** Each REFERENCES clause generates an instance of the following structure
18945** which is attached to the from-table. The to-table need not exist when
18946** the from-table is created. The existence of the to-table is not checked.
18947**
18948** The list of all parents for child Table X is held at X.pFKey.
18949**
18950** A list of all children for a table named Z (which might not even exist)
18951** is held in Schema.fkeyHash with a hash key of Z.
18952*/
18953struct FKey {
18954 Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
18955 FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
18956 char *zTo; /* Name of table that the key points to (aka: Parent) */
18957 FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
18958 FKey *pPrevTo; /* Previous with the same zTo */
18959 int nCol; /* Number of columns in this key */
18960 /* EV: R-30323-21917 */
18961 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
18962 u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
18963 Trigger *apTrigger[2];/* Triggers for aAction[] actions */
18964 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
18965 int iFrom; /* Index of column in pFrom */
18966 char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
18967 } aCol[FLEXARRAY]; /* One entry for each of nCol columns */
18968};
18969
18970/* The size (in bytes) of an FKey object holding N columns. The answer
18971** does NOT include space to hold the zTo name. */
18972#define SZ_FKEY(N)(__builtin_offsetof(FKey, aCol)+(N)*sizeof(struct sColMap)) (offsetof(FKey,aCol)__builtin_offsetof(FKey, aCol)+(N)*sizeof(struct sColMap))
18973
18974/*
18975** SQLite supports many different ways to resolve a constraint
18976** error. ROLLBACK processing means that a constraint violation
18977** causes the operation in process to fail and for the current transaction
18978** to be rolled back. ABORT processing means the operation in process
18979** fails and any prior changes from that one operation are backed out,
18980** but the transaction is not rolled back. FAIL processing means that
18981** the operation in progress stops and returns an error code. But prior
18982** changes due to the same operation are not backed out and no rollback
18983** occurs. IGNORE means that the particular row that caused the constraint
18984** error is not inserted or updated. Processing continues and no error
18985** is returned. REPLACE means that preexisting database rows that caused
18986** a UNIQUE constraint violation are removed so that the new insert or
18987** update can proceed. Processing continues and no error is reported.
18988** UPDATE applies to insert operations only and means that the insert
18989** is omitted and the DO UPDATE clause of an upsert is run instead.
18990**
18991** RESTRICT, SETNULL, SETDFLT, and CASCADE actions apply only to foreign keys.
18992** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
18993** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
18994** key is set to NULL. SETDFLT means that the foreign key is set
18995** to its default value. CASCADE means that a DELETE or UPDATE of the
18996** referenced table row is propagated into the row that holds the
18997** foreign key.
18998**
18999** The OE_Default value is a place holder that means to use whatever
19000** conflict resolution algorithm is required from context.
19001**
19002** The following symbolic values are used to record which type
19003** of conflict resolution action to take.
19004*/
19005#define OE_None0 0 /* There is no constraint to check */
19006#define OE_Rollback1 1 /* Fail the operation and rollback the transaction */
19007#define OE_Abort2 2 /* Back out changes but do no rollback transaction */
19008#define OE_Fail3 3 /* Stop the operation but leave all prior changes */
19009#define OE_Ignore4 4 /* Ignore the error. Do not do the INSERT or UPDATE */
19010#define OE_Replace5 5 /* Delete existing record, then do INSERT or UPDATE */
19011#define OE_Update6 6 /* Process as a DO UPDATE in an upsert */
19012#define OE_Restrict7 7 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
19013#define OE_SetNull8 8 /* Set the foreign key value to NULL */
19014#define OE_SetDflt9 9 /* Set the foreign key value to its default */
19015#define OE_Cascade10 10 /* Cascade the changes */
19016#define OE_Default11 11 /* Do whatever the default action is */
19017
19018
19019/*
19020** An instance of the following structure is passed as the first
19021** argument to sqlite3VdbeKeyCompare and is used to control the
19022** comparison of the two index keys.
19023**
19024** Note that aSortOrder[] and aColl[] have nField+1 slots. There
19025** are nField slots for the columns of an index then one extra slot
19026** for the rowid at the end.
19027*/
19028struct KeyInfo {
19029 u32 nRef; /* Number of references to this KeyInfo object */
19030 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
19031 u16 nKeyField; /* Number of key columns in the index */
19032 u16 nAllField; /* Total columns, including key plus others */
19033 sqlite3 *db; /* The database connection */
19034 u8 *aSortFlags; /* Sort order for each column. */
19035 CollSeq *aColl[FLEXARRAY]; /* Collating sequence for each term of the key */
19036};
19037
19038/* The size (in bytes) of a KeyInfo object with up to N fields */
19039#define SZ_KEYINFO(N)(__builtin_offsetof(KeyInfo, aColl) + (N)*sizeof(CollSeq*)) (offsetof(KeyInfo,aColl)__builtin_offsetof(KeyInfo, aColl) + (N)*sizeof(CollSeq*))
19040
19041/*
19042** Allowed bit values for entries in the KeyInfo.aSortFlags[] array.
19043*/
19044#define KEYINFO_ORDER_DESC0x01 0x01 /* DESC sort order */
19045#define KEYINFO_ORDER_BIGNULL0x02 0x02 /* NULL is larger than any other value */
19046
19047/*
19048** This object holds a record which has been parsed out into individual
19049** fields, for the purposes of doing a comparison.
19050**
19051** A record is an object that contains one or more fields of data.
19052** Records are used to store the content of a table row and to store
19053** the key of an index. A blob encoding of a record is created by
19054** the OP_MakeRecord opcode of the VDBE and is disassembled by the
19055** OP_Column opcode.
19056**
19057** An instance of this object serves as a "key" for doing a search on
19058** an index b+tree. The goal of the search is to find the entry that
19059** is closed to the key described by this object. This object might hold
19060** just a prefix of the key. The number of fields is given by
19061** pKeyInfo->nField.
19062**
19063** The r1 and r2 fields are the values to return if this key is less than
19064** or greater than a key in the btree, respectively. These are normally
19065** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
19066** is in DESC order.
19067**
19068** The key comparison functions actually return default_rc when they find
19069** an equals comparison. default_rc can be -1, 0, or +1. If there are
19070** multiple entries in the b-tree with the same key (when only looking
19071** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
19072** cause the search to find the last match, or +1 to cause the search to
19073** find the first match.
19074**
19075** The key comparison functions will set eqSeen to true if they ever
19076** get and equal results when comparing this structure to a b-tree record.
19077** When default_rc!=0, the search might end up on the record immediately
19078** before the first match or immediately after the last match. The
19079** eqSeen field will indicate whether or not an exact match exists in the
19080** b-tree.
19081*/
19082struct UnpackedRecord {
19083 KeyInfo *pKeyInfo; /* Collation and sort-order information */
19084 Mem *aMem; /* Values */
19085 union {
19086 char *z; /* Cache of aMem[0].z for vdbeRecordCompareString() */
19087 i64 i; /* Cache of aMem[0].u.i for vdbeRecordCompareInt() */
19088 } u;
19089 int n; /* Cache of aMem[0].n used by vdbeRecordCompareString() */
19090 u16 nField; /* Number of entries in apMem[] */
19091 i8 default_rc; /* Comparison result if keys are equal */
19092 u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
19093 i8 r1; /* Value to return if (lhs < rhs) */
19094 i8 r2; /* Value to return if (lhs > rhs) */
19095 u8 eqSeen; /* True if an equality comparison has been seen */
19096};
19097
19098
19099/*
19100** Each SQL index is represented in memory by an
19101** instance of the following structure.
19102**
19103** The columns of the table that are to be indexed are described
19104** by the aiColumn[] field of this structure. For example, suppose
19105** we have the following table and index:
19106**
19107** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
19108** CREATE INDEX Ex2 ON Ex1(c3,c1);
19109**
19110** In the Table structure describing Ex1, nCol==3 because there are
19111** three columns in the table. In the Index structure describing
19112** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
19113** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
19114** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
19115** The second column to be indexed (c1) has an index of 0 in
19116** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
19117**
19118** The Index.onError field determines whether or not the indexed columns
19119** must be unique and what to do if they are not. When Index.onError=OE_None,
19120** it means this is not a unique index. Otherwise it is a unique index
19121** and the value of Index.onError indicates which conflict resolution
19122** algorithm to employ when an attempt is made to insert a non-unique
19123** element.
19124**
19125** The colNotIdxed bitmask is used in combination with SrcItem.colUsed
19126** for a fast test to see if an index can serve as a covering index.
19127** colNotIdxed has a 1 bit for every column of the original table that
19128** is *not* available in the index. Thus the expression
19129** "colUsed & colNotIdxed" will be non-zero if the index is not a
19130** covering index. The most significant bit of of colNotIdxed will always
19131** be true (note-20221022-a). If a column beyond the 63rd column of the
19132** table is used, the "colUsed & colNotIdxed" test will always be non-zero
19133** and we have to assume either that the index is not covering, or use
19134** an alternative (slower) algorithm to determine whether or not
19135** the index is covering.
19136**
19137** While parsing a CREATE TABLE or CREATE INDEX statement in order to
19138** generate VDBE code (as opposed to parsing one read from an sqlite_schema
19139** table as part of parsing an existing database schema), transient instances
19140** of this structure may be created. In this case the Index.tnum variable is
19141** used to store the address of a VDBE instruction, not a database page
19142** number (it cannot - the database page is not allocated until the VDBE
19143** program is executed). See convertToWithoutRowidTable() for details.
19144*/
19145struct Index {
19146 char *zName; /* Name of this index */
19147 i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
19148 LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
19149 Table *pTable; /* The SQL table being indexed */
19150 char *zColAff; /* String defining the affinity of each column */
19151 Index *pNext; /* The next index associated with the same table */
19152 Schema *pSchema; /* Schema containing this index */
19153 u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
19154 const char **azColl; /* Array of collation sequence names for index */
19155 Expr *pPartIdxWhere; /* WHERE clause for partial indices */
19156 ExprList *aColExpr; /* Column expressions */
19157 Pgno tnum; /* DB Page containing root of this index */
19158 LogEst szIdxRow; /* Estimated average row size in bytes */
19159 u16 nKeyCol; /* Number of columns forming the key */
19160 u16 nColumn; /* Nr columns in btree. Can be 2*Table.nCol */
19161 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
19162 unsigned idxType:2; /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */
19163 unsigned bUnordered:1; /* Use this index for == or IN queries only */
19164 unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
19165 unsigned isResized:1; /* True if resizeIndexObject() has been called */
19166 unsigned isCovering:1; /* True if this is a covering index */
19167 unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
19168 unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
19169 unsigned bNoQuery:1; /* Do not use this index to optimize queries */
19170 unsigned bAscKeyBug:1; /* True if the bba7b69f9849b5bf bug applies */
19171 unsigned bHasVCol:1; /* Index references one or more VIRTUAL columns */
19172 unsigned bHasExpr:1; /* Index contains an expression, either a literal
19173 ** expression, or a reference to a VIRTUAL column */
19174#ifdef SQLITE_ENABLE_STAT4
19175 int nSample; /* Number of elements in aSample[] */
19176 int mxSample; /* Number of slots allocated to aSample[] */
19177 int nSampleCol; /* Size of IndexSample.anEq[] and so on */
19178 tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
19179 IndexSample *aSample; /* Samples of the left-most key */
19180 tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
19181 tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
19182#endif
19183 Bitmask colNotIdxed; /* Unindexed columns in pTab */
19184};
19185
19186/*
19187** Allowed values for Index.idxType
19188*/
19189#define SQLITE_IDXTYPE_APPDEF0 0 /* Created using CREATE INDEX */
19190#define SQLITE_IDXTYPE_UNIQUE1 1 /* Implements a UNIQUE constraint */
19191#define SQLITE_IDXTYPE_PRIMARYKEY2 2 /* Is the PRIMARY KEY for the table */
19192#define SQLITE_IDXTYPE_IPK3 3 /* INTEGER PRIMARY KEY index */
19193
19194/* Return true if index X is a PRIMARY KEY index */
19195#define IsPrimaryKeyIndex(X)((X)->idxType==2) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY2)
19196
19197/* Return true if index X is a UNIQUE index */
19198#define IsUniqueIndex(X)((X)->onError!=0) ((X)->onError!=OE_None0)
19199
19200/* The Index.aiColumn[] values are normally positive integer. But
19201** there are some negative values that have special meaning:
19202*/
19203#define XN_ROWID(-1) (-1) /* Indexed column is the rowid */
19204#define XN_EXPR(-2) (-2) /* Indexed column is an expression */
19205
19206/*
19207** Each sample stored in the sqlite_stat4 table is represented in memory
19208** using a structure of this type. See documentation at the top of the
19209** analyze.c source file for additional information.
19210*/
19211struct IndexSample {
19212 void *p; /* Pointer to sampled record */
19213 int n; /* Size of record in bytes */
19214 tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
19215 tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
19216 tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
19217};
19218
19219/*
19220** Possible values to use within the flags argument to sqlite3GetToken().
19221*/
19222#define SQLITE_TOKEN_QUOTED0x1 0x1 /* Token is a quoted identifier. */
19223#define SQLITE_TOKEN_KEYWORD0x2 0x2 /* Token is a keyword. */
19224
19225/*
19226** Each token coming out of the lexer is an instance of
19227** this structure. Tokens are also used as part of an expression.
19228**
19229** The memory that "z" points to is owned by other objects. Take care
19230** that the owner of the "z" string does not deallocate the string before
19231** the Token goes out of scope! Very often, the "z" points to some place
19232** in the middle of the Parse.zSql text. But it might also point to a
19233** static string.
19234*/
19235struct Token {
19236 const char *z; /* Text of the token. Not NULL-terminated! */
19237 unsigned int n; /* Number of characters in this token */
19238};
19239
19240/*
19241** An instance of this structure contains information needed to generate
19242** code for a SELECT that contains aggregate functions.
19243**
19244** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
19245** pointer to this structure. The Expr.iAgg field is the index in
19246** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
19247** code for that node.
19248**
19249** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
19250** original Select structure that describes the SELECT statement. These
19251** fields do not need to be freed when deallocating the AggInfo structure.
19252*/
19253struct AggInfo {
19254 u8 directMode; /* Direct rendering mode means take data directly
19255 ** from source tables rather than from accumulators */
19256 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
19257 ** than the source table */
19258 u32 nSortingColumn; /* Number of columns in the sorting index */
19259 int sortingIdx; /* Cursor number of the sorting index */
19260 int sortingIdxPTab; /* Cursor number of pseudo-table */
19261 int iFirstReg; /* First register in range for aCol[] and aFunc[] */
19262 ExprList *pGroupBy; /* The group by clause */
19263 struct AggInfo_col { /* For each column used in source tables */
19264 Table *pTab; /* Source table */
19265 Expr *pCExpr; /* The original expression */
19266 int iTable; /* Cursor number of the source table */
19267 int iColumn; /* Column number within the source table */
19268 int iSorterColumn; /* Column number in the sorting index */
19269 } *aCol;
19270 int nColumn; /* Number of used entries in aCol[] */
19271 int nAccumulator; /* Number of columns that show through to the output.
19272 ** Additional columns are used only as parameters to
19273 ** aggregate functions */
19274 struct AggInfo_func { /* For each aggregate function */
19275 Expr *pFExpr; /* Expression encoding the function */
19276 FuncDef *pFunc; /* The aggregate function implementation */
19277 int iDistinct; /* Ephemeral table used to enforce DISTINCT */
19278 int iDistAddr; /* Address of OP_OpenEphemeral */
19279 int iOBTab; /* Ephemeral table to implement ORDER BY */
19280 u8 bOBPayload; /* iOBTab has payload columns separate from key */
19281 u8 bOBUnique; /* Enforce uniqueness on iOBTab keys */
19282 u8 bUseSubtype; /* Transfer subtype info through sorter */
19283 } *aFunc;
19284 int nFunc; /* Number of entries in aFunc[] */
19285 u32 selId; /* Select to which this AggInfo belongs */
19286#ifdef SQLITE_DEBUG
19287 Select *pSelect; /* SELECT statement that this AggInfo supports */
19288#endif
19289};
19290
19291/*
19292** Macros to compute aCol[] and aFunc[] register numbers.
19293**
19294** These macros should not be used prior to the call to
19295** assignAggregateRegisters() that computes the value of pAggInfo->iFirstReg.
19296** The assert()s that are part of this macro verify that constraint.
19297*/
19298#ifndef NDEBUG1
19299#define AggInfoColumnReg(A,I)((A)->iFirstReg+(I)) (assert((A)->iFirstReg)((void) (0)),(A)->iFirstReg+(I))
19300#define AggInfoFuncReg(A,I)((A)->iFirstReg+(A)->nColumn+(I)) \
19301 (assert((A)->iFirstReg)((void) (0)),(A)->iFirstReg+(A)->nColumn+(I))
19302#else
19303#define AggInfoColumnReg(A,I)((A)->iFirstReg+(I)) ((A)->iFirstReg+(I))
19304#define AggInfoFuncReg(A,I)((A)->iFirstReg+(A)->nColumn+(I)) \
19305 ((A)->iFirstReg+(A)->nColumn+(I))
19306#endif
19307
19308/*
19309** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
19310** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
19311** than 32767 we have to make it 32-bit. 16-bit is preferred because
19312** it uses less memory in the Expr object, which is a big memory user
19313** in systems with lots of prepared statements. And few applications
19314** need more than about 10 or 20 variables. But some extreme users want
19315** to have prepared statements with over 32766 variables, and for them
19316** the option is available (at compile-time).
19317*/
19318#if SQLITE_MAX_VARIABLE_NUMBER500000<32767
19319typedef i16 ynVar;
19320#else
19321typedef int ynVar;
19322#endif
19323
19324/*
19325** Each node of an expression in the parse tree is an instance
19326** of this structure.
19327**
19328** Expr.op is the opcode. The integer parser token codes are reused
19329** as opcodes here. For example, the parser defines TK_GE to be an integer
19330** code representing the ">=" operator. This same integer code is reused
19331** to represent the greater-than-or-equal-to operator in the expression
19332** tree.
19333**
19334** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
19335** or TK_STRING), then Expr.u.zToken contains the text of the SQL literal. If
19336** the expression is a variable (TK_VARIABLE), then Expr.u.zToken contains the
19337** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
19338** then Expr.u.zToken contains the name of the function.
19339**
19340** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
19341** binary operator. Either or both may be NULL.
19342**
19343** Expr.x.pList is a list of arguments if the expression is an SQL function,
19344** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
19345** Expr.x.pSelect is used if the expression is a sub-select or an expression of
19346** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
19347** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
19348** valid.
19349**
19350** An expression of the form ID or ID.ID refers to a column in a table.
19351** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
19352** the integer cursor number of a VDBE cursor pointing to that table and
19353** Expr.iColumn is the column number for the specific column. If the
19354** expression is used as a result in an aggregate SELECT, then the
19355** value is also stored in the Expr.iAgg column in the aggregate so that
19356** it can be accessed after all aggregates are computed.
19357**
19358** If the expression is an unbound variable marker (a question mark
19359** character '?' in the original SQL) then the Expr.iTable holds the index
19360** number for that variable.
19361**
19362** If the expression is a subquery then Expr.iColumn holds an integer
19363** register number containing the result of the subquery. If the
19364** subquery gives a constant result, then iTable is -1. If the subquery
19365** gives a different answer at different times during statement processing
19366** then iTable is the address of a subroutine that computes the subquery.
19367**
19368** If the Expr is of type OP_Column, and the table it is selecting from
19369** is a disk table or the "old.*" pseudo-table, then pTab points to the
19370** corresponding table definition.
19371**
19372** ALLOCATION NOTES:
19373**
19374** Expr objects can use a lot of memory space in database schema. To
19375** help reduce memory requirements, sometimes an Expr object will be
19376** truncated. And to reduce the number of memory allocations, sometimes
19377** two or more Expr objects will be stored in a single memory allocation,
19378** together with Expr.u.zToken strings.
19379**
19380** If the EP_Reduced and EP_TokenOnly flags are set when
19381** an Expr object is truncated. When EP_Reduced is set, then all
19382** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
19383** are contained within the same memory allocation. Note, however, that
19384** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
19385** allocated, regardless of whether or not EP_Reduced is set.
19386*/
19387struct Expr {
19388 u8 op; /* Operation performed by this node */
19389 char affExpr; /* affinity, or RAISE type */
19390 u8 op2; /* TK_REGISTER/TK_TRUTH: original value of Expr.op
19391 ** TK_COLUMN: the value of p5 for OP_Column
19392 ** TK_AGG_FUNCTION: nesting depth
19393 ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */
19394#ifdef SQLITE_DEBUG
19395 u8 vvaFlags; /* Verification flags. */
19396#endif
19397 u32 flags; /* Various flags. EP_* See below */
19398 union {
19399 char *zToken; /* Token value. Zero terminated and dequoted */
19400 int iValue; /* Non-negative integer value if EP_IntValue */
19401 } u;
19402
19403 /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
19404 ** space is allocated for the fields below this point. An attempt to
19405 ** access them will result in a segfault or malfunction.
19406 *********************************************************************/
19407
19408 Expr *pLeft; /* Left subnode */
19409 Expr *pRight; /* Right subnode */
19410 union {
19411 ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
19412 Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
19413 } x;
19414
19415 /* If the EP_Reduced flag is set in the Expr.flags mask, then no
19416 ** space is allocated for the fields below this point. An attempt to
19417 ** access them will result in a segfault or malfunction.
19418 *********************************************************************/
19419
19420#if SQLITE_MAX_EXPR_DEPTH1000>0
19421 int nHeight; /* Height of the tree headed by this node */
19422#endif
19423 int iTable; /* TK_COLUMN: cursor number of table holding column
19424 ** TK_REGISTER: register number
19425 ** TK_TRIGGER: 1 -> new, 0 -> old
19426 ** EP_Unlikely: 134217728 times likelihood
19427 ** TK_IN: ephemeral table holding RHS
19428 ** TK_SELECT_COLUMN: Number of columns on the LHS
19429 ** TK_SELECT: 1st register of result vector */
19430 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
19431 ** TK_VARIABLE: variable number (always >= 1).
19432 ** TK_SELECT_COLUMN: column of the result vector */
19433 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
19434 union {
19435 int iJoin; /* If EP_OuterON or EP_InnerON, the right table */
19436 int iOfst; /* else: start of token from start of statement */
19437 } w;
19438 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
19439 union {
19440 Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL
19441 ** for a column of an index on an expression */
19442 Window *pWin; /* EP_WinFunc: Window/Filter defn for a function */
19443 struct { /* TK_IN, TK_SELECT, and TK_EXISTS */
19444 int iAddr; /* Subroutine entry address */
19445 int regReturn; /* Register used to hold return address */
19446 } sub;
19447 } y;
19448};
19449
19450/* The following are the meanings of bits in the Expr.flags field.
19451** Value restrictions:
19452**
19453** EP_Agg == NC_HasAgg == SF_HasAgg
19454** EP_Win == NC_HasWin
19455*/
19456#define EP_OuterON0x000001 0x000001 /* Originates in ON/USING clause of outer join */
19457#define EP_InnerON0x000002 0x000002 /* Originates in ON/USING of an inner join */
19458#define EP_Distinct0x000004 0x000004 /* Aggregate function with DISTINCT keyword */
19459#define EP_HasFunc0x000008 0x000008 /* Contains one or more functions of any kind */
19460#define EP_Agg0x000010 0x000010 /* Contains one or more aggregate functions */
19461#define EP_FixedCol0x000020 0x000020 /* TK_Column with a known fixed value */
19462#define EP_VarSelect0x000040 0x000040 /* pSelect is correlated, not constant */
19463#define EP_DblQuoted0x000080 0x000080 /* token.z was originally in "..." */
19464#define EP_InfixFunc0x000100 0x000100 /* True for an infix function: LIKE, GLOB, etc */
19465#define EP_Collate0x000200 0x000200 /* Tree contains a TK_COLLATE operator */
19466#define EP_Commuted0x000400 0x000400 /* Comparison operator has been commuted */
19467#define EP_IntValue0x000800 0x000800 /* Integer value contained in u.iValue */
19468#define EP_xIsSelect0x001000 0x001000 /* x.pSelect is valid (otherwise x.pList is) */
19469#define EP_Skip0x002000 0x002000 /* Operator does not contribute to affinity */
19470#define EP_Reduced0x004000 0x004000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
19471#define EP_Win0x008000 0x008000 /* Contains window functions */
19472#define EP_TokenOnly0x010000 0x010000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
19473#define EP_FullSize0x020000 0x020000 /* Expr structure must remain full sized */
19474#define EP_IfNullRow0x040000 0x040000 /* The TK_IF_NULL_ROW opcode */
19475#define EP_Unlikely0x080000 0x080000 /* unlikely() or likelihood() function */
19476#define EP_ConstFunc0x100000 0x100000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
19477#define EP_CanBeNull0x200000 0x200000 /* Can be null despite NOT NULL constraint */
19478#define EP_Subquery0x400000 0x400000 /* Tree contains a TK_SELECT operator */
19479#define EP_Leaf0x800000 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
19480#define EP_WinFunc0x1000000 0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
19481#define EP_Subrtn0x2000000 0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
19482#define EP_Quoted0x4000000 0x4000000 /* TK_ID was originally quoted */
19483#define EP_Static0x8000000 0x8000000 /* Held in memory not obtained from malloc() */
19484#define EP_IsTrue0x10000000 0x10000000 /* Always has boolean value of TRUE */
19485#define EP_IsFalse0x20000000 0x20000000 /* Always has boolean value of FALSE */
19486#define EP_FromDDL0x40000000 0x40000000 /* Originates from sqlite_schema */
19487#define EP_SubtArg0x80000000 0x80000000 /* Is argument to SQLITE_SUBTYPE function */
19488
19489/* The EP_Propagate mask is a set of properties that automatically propagate
19490** upwards into parent nodes.
19491*/
19492#define EP_Propagate(0x000200|0x400000|0x000008) (EP_Collate0x000200|EP_Subquery0x400000|EP_HasFunc0x000008)
19493
19494/* Macros can be used to test, set, or clear bits in the
19495** Expr.flags field.
19496*/
19497#define ExprHasProperty(E,P)(((E)->flags&(u32)(P))!=0) (((E)->flags&(u32)(P))!=0)
19498#define ExprHasAllProperty(E,P)(((E)->flags&(u32)(P))==(u32)(P)) (((E)->flags&(u32)(P))==(u32)(P))
19499#define ExprSetProperty(E,P)(E)->flags|=(u32)(P) (E)->flags|=(u32)(P)
19500#define ExprClearProperty(E,P)(E)->flags&=~(u32)(P) (E)->flags&=~(u32)(P)
19501#define ExprAlwaysTrue(E)(((E)->flags&(0x000001|0x10000000))==0x10000000) (((E)->flags&(EP_OuterON0x000001|EP_IsTrue0x10000000))==EP_IsTrue0x10000000)
19502#define ExprAlwaysFalse(E)(((E)->flags&(0x000001|0x20000000))==0x20000000) (((E)->flags&(EP_OuterON0x000001|EP_IsFalse0x20000000))==EP_IsFalse0x20000000)
19503#define ExprIsFullSize(E)(((E)->flags&(0x004000|0x010000))==0) (((E)->flags&(EP_Reduced0x004000|EP_TokenOnly0x010000))==0)
19504
19505/* Macros used to ensure that the correct members of unions are accessed
19506** in Expr.
19507*/
19508#define ExprUseUToken(E)(((E)->flags&0x000800)==0) (((E)->flags&EP_IntValue0x000800)==0)
19509#define ExprUseUValue(E)(((E)->flags&0x000800)!=0) (((E)->flags&EP_IntValue0x000800)!=0)
19510#define ExprUseWOfst(E)(((E)->flags&(0x000002|0x000001))==0) (((E)->flags&(EP_InnerON0x000002|EP_OuterON0x000001))==0)
19511#define ExprUseWJoin(E)(((E)->flags&(0x000002|0x000001))!=0) (((E)->flags&(EP_InnerON0x000002|EP_OuterON0x000001))!=0)
19512#define ExprUseXList(E)(((E)->flags&0x001000)==0) (((E)->flags&EP_xIsSelect0x001000)==0)
19513#define ExprUseXSelect(E)(((E)->flags&0x001000)!=0) (((E)->flags&EP_xIsSelect0x001000)!=0)
19514#define ExprUseYTab(E)(((E)->flags&(0x1000000|0x2000000))==0) (((E)->flags&(EP_WinFunc0x1000000|EP_Subrtn0x2000000))==0)
19515#define ExprUseYWin(E)(((E)->flags&0x1000000)!=0) (((E)->flags&EP_WinFunc0x1000000)!=0)
19516#define ExprUseYSub(E)(((E)->flags&0x2000000)!=0) (((E)->flags&EP_Subrtn0x2000000)!=0)
19517
19518/* Flags for use with Expr.vvaFlags
19519*/
19520#define EP_NoReduce0x01 0x01 /* Cannot EXPRDUP_REDUCE this Expr */
19521#define EP_Immutable0x02 0x02 /* Do not change this Expr node */
19522
19523/* The ExprSetVVAProperty() macro is used for Verification, Validation,
19524** and Accreditation only. It works like ExprSetProperty() during VVA
19525** processes but is a no-op for delivery.
19526*/
19527#ifdef SQLITE_DEBUG
19528# define ExprSetVVAProperty(E,P) (E)->vvaFlags|=(P)
19529# define ExprHasVVAProperty(E,P)0 (((E)->vvaFlags&(P))!=0)
19530# define ExprClearVVAProperties(E) (E)->vvaFlags = 0
19531#else
19532# define ExprSetVVAProperty(E,P)
19533# define ExprHasVVAProperty(E,P)0 0
19534# define ExprClearVVAProperties(E)
19535#endif
19536
19537/*
19538** Macros to determine the number of bytes required by a normal Expr
19539** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
19540** and an Expr struct with the EP_TokenOnly flag set.
19541*/
19542#define EXPR_FULLSIZEsizeof(Expr) sizeof(Expr) /* Full size */
19543#define EXPR_REDUCEDSIZE__builtin_offsetof(Expr, iTable) offsetof(Expr,iTable)__builtin_offsetof(Expr, iTable) /* Common features */
19544#define EXPR_TOKENONLYSIZE__builtin_offsetof(Expr, pLeft) offsetof(Expr,pLeft)__builtin_offsetof(Expr, pLeft) /* Fewer features */
19545
19546/*
19547** Flags passed to the sqlite3ExprDup() function. See the header comment
19548** above sqlite3ExprDup() for details.
19549*/
19550#define EXPRDUP_REDUCE0x0001 0x0001 /* Used reduced-size Expr nodes */
19551
19552/*
19553** True if the expression passed as an argument was a function with
19554** an OVER() clause (a window function).
19555*/
19556#ifdef SQLITE_OMIT_WINDOWFUNC
19557# define IsWindowFunc(p)( ((((p))->flags&(u32)(0x1000000))!=0) && p->
y.pWin->eFrmType!=167 )
0
19558#else
19559# define IsWindowFunc(p)( ((((p))->flags&(u32)(0x1000000))!=0) && p->
y.pWin->eFrmType!=167 )
( \
19560 ExprHasProperty((p), EP_WinFunc)((((p))->flags&(u32)(0x1000000))!=0) && p->y.pWin->eFrmType!=TK_FILTER167 \
19561 )
19562#endif
19563
19564/*
19565** A list of expressions. Each expression may optionally have a
19566** name. An expr/name combination can be used in several ways, such
19567** as the list of "expr AS ID" fields following a "SELECT" or in the
19568** list of "ID = expr" items in an UPDATE. A list of expressions can
19569** also be used as the argument to a function, in which case the a.zName
19570** field is not used.
19571**
19572** In order to try to keep memory usage down, the Expr.a.zEName field
19573** is used for multiple purposes:
19574**
19575** eEName Usage
19576** ---------- -------------------------
19577** ENAME_NAME (1) the AS of result set column
19578** (2) COLUMN= of an UPDATE
19579**
19580** ENAME_TAB DB.TABLE.NAME used to resolve names
19581** of subqueries
19582**
19583** ENAME_SPAN Text of the original result set
19584** expression.
19585*/
19586struct ExprList {
19587 int nExpr; /* Number of expressions on the list */
19588 int nAlloc; /* Number of a[] slots allocated */
19589 struct ExprList_item { /* For each expression in the list */
19590 Expr *pExpr; /* The parse tree for this expression */
19591 char *zEName; /* Token associated with this expression */
19592 struct {
19593 u8 sortFlags; /* Mask of KEYINFO_ORDER_* flags */
19594 unsigned eEName :2; /* Meaning of zEName */
19595 unsigned done :1; /* Indicates when processing is finished */
19596 unsigned reusable :1; /* Constant expression is reusable */
19597 unsigned bSorterRef :1; /* Defer evaluation until after sorting */
19598 unsigned bNulls :1; /* True if explicit "NULLS FIRST/LAST" */
19599 unsigned bUsed :1; /* This column used in a SF_NestedFrom subquery */
19600 unsigned bUsingTerm:1; /* Term from the USING clause of a NestedFrom */
19601 unsigned bNoExpand: 1; /* Term is an auxiliary in NestedFrom and should
19602 ** not be expanded by "*" in parent queries */
19603 } fg;
19604 union {
19605 struct { /* Used by any ExprList other than Parse.pConsExpr */
19606 u16 iOrderByCol; /* For ORDER BY, column number in result set */
19607 u16 iAlias; /* Index into Parse.aAlias[] for zName */
19608 } x;
19609 int iConstExprReg; /* Register in which Expr value is cached. Used only
19610 ** by Parse.pConstExpr */
19611 } u;
19612 } a[FLEXARRAY]; /* One slot for each expression in the list */
19613};
19614
19615/* The size (in bytes) of an ExprList object that is big enough to hold
19616** as many as N expressions. */
19617#define SZ_EXPRLIST(N)(__builtin_offsetof(ExprList, a) + (N)*sizeof(struct ExprList_item
))
\
19618 (offsetof(ExprList,a)__builtin_offsetof(ExprList, a) + (N)*sizeof(struct ExprList_item))
19619
19620/*
19621** Allowed values for Expr.a.eEName
19622*/
19623#define ENAME_NAME0 0 /* The AS clause of a result set */
19624#define ENAME_SPAN1 1 /* Complete text of the result set expression */
19625#define ENAME_TAB2 2 /* "DB.TABLE.NAME" for the result set */
19626#define ENAME_ROWID3 3 /* "DB.TABLE._rowid_" for * expansion of rowid */
19627
19628/*
19629** An instance of this structure can hold a simple list of identifiers,
19630** such as the list "a,b,c" in the following statements:
19631**
19632** INSERT INTO t(a,b,c) VALUES ...;
19633** CREATE INDEX idx ON t(a,b,c);
19634** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
19635**
19636** The IdList.a.idx field is used when the IdList represents the list of
19637** column names after a table name in an INSERT statement. In the statement
19638**
19639** INSERT INTO t(a,b,c) ...
19640**
19641** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
19642*/
19643struct IdList {
19644 int nId; /* Number of identifiers on the list */
19645 struct IdList_item {
19646 char *zName; /* Name of the identifier */
19647 } a[FLEXARRAY];
19648};
19649
19650/* The size (in bytes) of an IdList object that can hold up to N IDs. */
19651#define SZ_IDLIST(N)(__builtin_offsetof(IdList, a)+(N)*sizeof(struct IdList_item)
)
(offsetof(IdList,a)__builtin_offsetof(IdList, a)+(N)*sizeof(struct IdList_item))
19652
19653/*
19654** Allowed values for IdList.eType, which determines which value of the a.u4
19655** is valid.
19656*/
19657#define EU4_NONE0 0 /* Does not use IdList.a.u4 */
19658#define EU4_IDX1 1 /* Uses IdList.a.u4.idx */
19659#define EU4_EXPR2 2 /* Uses IdList.a.u4.pExpr -- NOT CURRENTLY USED */
19660
19661/*
19662** Details of the implementation of a subquery.
19663*/
19664struct Subquery {
19665 Select *pSelect; /* A SELECT statement used in place of a table name */
19666 int addrFillSub; /* Address of subroutine to initialize a subquery */
19667 int regReturn; /* Register holding return address of addrFillSub */
19668 int regResult; /* Registers holding results of a co-routine */
19669};
19670
19671/*
19672** The SrcItem object represents a single term in the FROM clause of a query.
19673** The SrcList object is mostly an array of SrcItems.
19674**
19675** The jointype starts out showing the join type between the current table
19676** and the next table on the list. The parser builds the list this way.
19677** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
19678** jointype expresses the join between the table and the previous table.
19679**
19680** In the colUsed field, the high-order bit (bit 63) is set if the table
19681** contains more than 63 columns and the 64-th or later column is used.
19682**
19683** Aggressive use of "union" helps keep the size of the object small. This
19684** has been shown to boost performance, in addition to saving memory.
19685** Access to union elements is gated by the following rules which should
19686** always be checked, either by an if-statement or by an assert().
19687**
19688** Field Only access if this is true
19689** --------------- -----------------------------------
19690** u1.zIndexedBy fg.isIndexedBy
19691** u1.pFuncArg fg.isTabFunc
19692** u1.nRow !fg.isTabFunc && !fg.isIndexedBy
19693**
19694** u2.pIBIndex fg.isIndexedBy
19695** u2.pCteUse fg.isCte
19696**
19697** u3.pOn !fg.isUsing
19698** u3.pUsing fg.isUsing
19699**
19700** u4.zDatabase !fg.fixedSchema && !fg.isSubquery
19701** u4.pSchema fg.fixedSchema
19702** u4.pSubq fg.isSubquery
19703**
19704** See also the sqlite3SrcListDelete() routine for assert() statements that
19705** check invariants on the fields of this object, especially the flags
19706** inside the fg struct.
19707*/
19708struct SrcItem {
19709 char *zName; /* Name of the table */
19710 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
19711 Table *pSTab; /* Table object for zName. Mnemonic: Srcitem-TABle */
19712 struct {
19713 u8 jointype; /* Type of join between this table and the previous */
19714 unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
19715 unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
19716 unsigned isSubquery :1; /* True if this term is a subquery */
19717 unsigned isTabFunc :1; /* True if table-valued-function syntax */
19718 unsigned isCorrelated :1; /* True if sub-query is correlated */
19719 unsigned isMaterialized:1; /* This is a materialized view */
19720 unsigned viaCoroutine :1; /* Implemented as a co-routine */
19721 unsigned isRecursive :1; /* True for recursive reference in WITH */
19722 unsigned fromDDL :1; /* Comes from sqlite_schema */
19723 unsigned isCte :1; /* This is a CTE */
19724 unsigned notCte :1; /* This item may not match a CTE */
19725 unsigned isUsing :1; /* u3.pUsing is valid */
19726 unsigned isOn :1; /* u3.pOn was once valid and non-NULL */
19727 unsigned isSynthUsing :1; /* u3.pUsing is synthesized from NATURAL */
19728 unsigned isNestedFrom :1; /* pSelect is a SF_NestedFrom subquery */
19729 unsigned rowidUsed :1; /* The ROWID of this table is referenced */
19730 unsigned fixedSchema :1; /* Uses u4.pSchema, not u4.zDatabase */
19731 unsigned hadSchema :1; /* Had u4.zDatabase before u4.pSchema */
19732 } fg;
19733 int iCursor; /* The VDBE cursor number used to access this table */
19734 Bitmask colUsed; /* Bit N set if column N used. Details above for N>62 */
19735 union {
19736 char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
19737 ExprList *pFuncArg; /* Arguments to table-valued-function */
19738 u32 nRow; /* Number of rows in a VALUES clause */
19739 } u1;
19740 union {
19741 Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
19742 CteUse *pCteUse; /* CTE Usage info when fg.isCte is true */
19743 } u2;
19744 union {
19745 Expr *pOn; /* fg.isUsing==0 => The ON clause of a join */
19746 IdList *pUsing; /* fg.isUsing==1 => The USING clause of a join */
19747 } u3;
19748 union {
19749 Schema *pSchema; /* Schema to which this item is fixed */
19750 char *zDatabase; /* Name of database holding this table */
19751 Subquery *pSubq; /* Description of a subquery */
19752 } u4;
19753};
19754
19755/*
19756** The OnOrUsing object represents either an ON clause or a USING clause.
19757** It can never be both at the same time, but it can be neither.
19758*/
19759struct OnOrUsing {
19760 Expr *pOn; /* The ON clause of a join */
19761 IdList *pUsing; /* The USING clause of a join */
19762};
19763
19764/*
19765** This object represents one or more tables that are the source of
19766** content for an SQL statement. For example, a single SrcList object
19767** is used to hold the FROM clause of a SELECT statement. SrcList also
19768** represents the target tables for DELETE, INSERT, and UPDATE statements.
19769**
19770*/
19771struct SrcList {
19772 int nSrc; /* Number of tables or subqueries in the FROM clause */
19773 u32 nAlloc; /* Number of entries allocated in a[] below */
19774 SrcItem a[FLEXARRAY]; /* One entry for each identifier on the list */
19775};
19776
19777/* Size (in bytes) of a SrcList object that can hold as many as N
19778** SrcItem objects. */
19779#define SZ_SRCLIST(N)(__builtin_offsetof(SrcList, a)+(N)*sizeof(SrcItem)) (offsetof(SrcList,a)__builtin_offsetof(SrcList, a)+(N)*sizeof(SrcItem))
19780
19781/* Size (in bytes( of a SrcList object that holds 1 SrcItem. This is a
19782** special case of SZ_SRCITEM(1) that comes up often. */
19783#define SZ_SRCLIST_1(__builtin_offsetof(SrcList, a)+sizeof(SrcItem)) (offsetof(SrcList,a)__builtin_offsetof(SrcList, a)+sizeof(SrcItem))
19784
19785/*
19786** Permitted values of the SrcList.a.jointype field
19787*/
19788#define JT_INNER0x01 0x01 /* Any kind of inner or cross join */
19789#define JT_CROSS0x02 0x02 /* Explicit use of the CROSS keyword */
19790#define JT_NATURAL0x04 0x04 /* True for a "natural" join */
19791#define JT_LEFT0x08 0x08 /* Left outer join */
19792#define JT_RIGHT0x10 0x10 /* Right outer join */
19793#define JT_OUTER0x20 0x20 /* The "OUTER" keyword is present */
19794#define JT_LTORJ0x40 0x40 /* One of the LEFT operands of a RIGHT JOIN
19795 ** Mnemonic: Left Table Of Right Join */
19796#define JT_ERROR0x80 0x80 /* unknown or unsupported join type */
19797
19798/*
19799** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
19800** and the WhereInfo.wctrlFlags member.
19801**
19802** Value constraints (enforced via assert()):
19803** WHERE_USE_LIMIT == SF_FixedLimit
19804*/
19805#define WHERE_ORDERBY_NORMAL0x0000 0x0000 /* No-op */
19806#define WHERE_ORDERBY_MIN0x0001 0x0001 /* ORDER BY processing for min() func */
19807#define WHERE_ORDERBY_MAX0x0002 0x0002 /* ORDER BY processing for max() func */
19808#define WHERE_ONEPASS_DESIRED0x0004 0x0004 /* Want to do one-pass UPDATE/DELETE */
19809#define WHERE_ONEPASS_MULTIROW0x0008 0x0008 /* ONEPASS is ok with multiple rows */
19810#define WHERE_DUPLICATES_OK0x0010 0x0010 /* Ok to return a row more than once */
19811#define WHERE_OR_SUBCLAUSE0x0020 0x0020 /* Processing a sub-WHERE as part of
19812 ** the OR optimization */
19813#define WHERE_GROUPBY0x0040 0x0040 /* pOrderBy is really a GROUP BY */
19814#define WHERE_DISTINCTBY0x0080 0x0080 /* pOrderby is really a DISTINCT clause */
19815#define WHERE_WANT_DISTINCT0x0100 0x0100 /* All output needs to be distinct */
19816#define WHERE_SORTBYGROUP0x0200 0x0200 /* Support sqlite3WhereIsSorted() */
19817#define WHERE_AGG_DISTINCT0x0400 0x0400 /* Query is "SELECT agg(DISTINCT ...)" */
19818#define WHERE_ORDERBY_LIMIT0x0800 0x0800 /* ORDERBY+LIMIT on the inner loop */
19819#define WHERE_RIGHT_JOIN0x1000 0x1000 /* Processing a RIGHT JOIN */
19820#define WHERE_KEEP_ALL_JOINS0x2000 0x2000 /* Do not do the omit-noop-join opt */
19821#define WHERE_USE_LIMIT0x4000 0x4000 /* Use the LIMIT in cost estimates */
19822 /* 0x8000 not currently used */
19823
19824/* Allowed return values from sqlite3WhereIsDistinct()
19825*/
19826#define WHERE_DISTINCT_NOOP0 0 /* DISTINCT keyword not used */
19827#define WHERE_DISTINCT_UNIQUE1 1 /* No duplicates */
19828#define WHERE_DISTINCT_ORDERED2 2 /* All duplicates are adjacent */
19829#define WHERE_DISTINCT_UNORDERED3 3 /* Duplicates are scattered */
19830
19831/*
19832** A NameContext defines a context in which to resolve table and column
19833** names. The context consists of a list of tables (the pSrcList) field and
19834** a list of named expression (pEList). The named expression list may
19835** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
19836** to the table being operated on by INSERT, UPDATE, or DELETE. The
19837** pEList corresponds to the result set of a SELECT and is NULL for
19838** other statements.
19839**
19840** NameContexts can be nested. When resolving names, the inner-most
19841** context is searched first. If no match is found, the next outer
19842** context is checked. If there is still no match, the next context
19843** is checked. This process continues until either a match is found
19844** or all contexts are check. When a match is found, the nRef member of
19845** the context containing the match is incremented.
19846**
19847** Each subquery gets a new NameContext. The pNext field points to the
19848** NameContext in the parent query. Thus the process of scanning the
19849** NameContext list corresponds to searching through successively outer
19850** subqueries looking for a match.
19851*/
19852struct NameContext {
19853 Parse *pParse; /* The parser */
19854 SrcList *pSrcList; /* One or more tables used to resolve names */
19855 union {
19856 ExprList *pEList; /* Optional list of result-set columns */
19857 AggInfo *pAggInfo; /* Information about aggregates at this level */
19858 Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */
19859 int iBaseReg; /* For TK_REGISTER when parsing RETURNING */
19860 } uNC;
19861 NameContext *pNext; /* Next outer name context. NULL for outermost */
19862 int nRef; /* Number of names resolved by this context */
19863 int nNcErr; /* Number of errors encountered while resolving names */
19864 int ncFlags; /* Zero or more NC_* flags defined below */
19865 u32 nNestedSelect; /* Number of nested selects using this NC */
19866 Select *pWinSelect; /* SELECT statement for any window functions */
19867};
19868
19869/*
19870** Allowed values for the NameContext, ncFlags field.
19871**
19872** Value constraints (all checked via assert()):
19873** NC_HasAgg == SF_HasAgg == EP_Agg
19874** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
19875** NC_OrderAgg == SF_OrderByReqd == SQLITE_FUNC_ANYORDER
19876** NC_HasWin == EP_Win
19877**
19878*/
19879#define NC_AllowAgg0x000001 0x000001 /* Aggregate functions are allowed here */
19880#define NC_PartIdx0x000002 0x000002 /* True if resolving a partial index WHERE */
19881#define NC_IsCheck0x000004 0x000004 /* True if resolving a CHECK constraint */
19882#define NC_GenCol0x000008 0x000008 /* True for a GENERATED ALWAYS AS clause */
19883#define NC_HasAgg0x000010 0x000010 /* One or more aggregate functions seen */
19884#define NC_IdxExpr0x000020 0x000020 /* True if resolving columns of CREATE INDEX */
19885#define NC_SelfRef0x00002e 0x00002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
19886#define NC_Subquery0x000040 0x000040 /* A subquery has been seen */
19887#define NC_UEList0x000080 0x000080 /* True if uNC.pEList is used */
19888#define NC_UAggInfo0x000100 0x000100 /* True if uNC.pAggInfo is used */
19889#define NC_UUpsert0x000200 0x000200 /* True if uNC.pUpsert is used */
19890#define NC_UBaseReg0x000400 0x000400 /* True if uNC.iBaseReg is used */
19891#define NC_MinMaxAgg0x001000 0x001000 /* min/max aggregates seen. See note above */
19892/* 0x002000 // available for reuse */
19893#define NC_AllowWin0x004000 0x004000 /* Window functions are allowed here */
19894#define NC_HasWin0x008000 0x008000 /* One or more window functions seen */
19895#define NC_IsDDL0x010000 0x010000 /* Resolving names in a CREATE statement */
19896#define NC_InAggFunc0x020000 0x020000 /* True if analyzing arguments to an agg func */
19897#define NC_FromDDL0x040000 0x040000 /* SQL text comes from sqlite_schema */
19898#define NC_NoSelect0x080000 0x080000 /* Do not descend into sub-selects */
19899#define NC_Where0x100000 0x100000 /* Processing WHERE clause of a SELECT */
19900#define NC_OrderAgg0x8000000 0x8000000 /* Has an aggregate other than count/min/max */
19901
19902/*
19903** An instance of the following object describes a single ON CONFLICT
19904** clause in an upsert.
19905**
19906** The pUpsertTarget field is only set if the ON CONFLICT clause includes
19907** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the
19908** conflict-target clause.) The pUpsertTargetWhere is the optional
19909** WHERE clause used to identify partial unique indexes.
19910**
19911** pUpsertSet is the list of column=expr terms of the UPDATE statement.
19912** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING. The
19913** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
19914** WHERE clause is omitted.
19915*/
19916struct Upsert {
19917 ExprList *pUpsertTarget; /* Optional description of conflict target */
19918 Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
19919 ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */
19920 Expr *pUpsertWhere; /* WHERE clause for the ON CONFLICT UPDATE */
19921 Upsert *pNextUpsert; /* Next ON CONFLICT clause in the list */
19922 u8 isDoUpdate; /* True for DO UPDATE. False for DO NOTHING */
19923 u8 isDup; /* True if 2nd or later with same pUpsertIdx */
19924 /* Above this point is the parse tree for the ON CONFLICT clauses.
19925 ** The next group of fields stores intermediate data. */
19926 void *pToFree; /* Free memory when deleting the Upsert object */
19927 /* All fields above are owned by the Upsert object and must be freed
19928 ** when the Upsert is destroyed. The fields below are used to transfer
19929 ** information from the INSERT processing down into the UPDATE processing
19930 ** while generating code. The fields below are owned by the INSERT
19931 ** statement and will be freed by INSERT processing. */
19932 Index *pUpsertIdx; /* UNIQUE constraint specified by pUpsertTarget */
19933 SrcList *pUpsertSrc; /* Table to be updated */
19934 int regData; /* First register holding array of VALUES */
19935 int iDataCur; /* Index of the data cursor */
19936 int iIdxCur; /* Index of the first index cursor */
19937};
19938
19939/*
19940** An instance of the following structure contains all information
19941** needed to generate code for a single SELECT statement.
19942**
19943** See the header comment on the computeLimitRegisters() routine for a
19944** detailed description of the meaning of the iLimit and iOffset fields.
19945**
19946** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
19947** These addresses must be stored so that we can go back and fill in
19948** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
19949** the number of columns in P2 can be computed at the same time
19950** as the OP_OpenEphm instruction is coded because not
19951** enough information about the compound query is known at that point.
19952** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
19953** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
19954** sequences for the ORDER BY clause.
19955*/
19956struct Select {
19957 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
19958 LogEst nSelectRow; /* Estimated number of result rows */
19959 u32 selFlags; /* Various SF_* values */
19960 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
19961 u32 selId; /* Unique identifier number for this SELECT */
19962 int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
19963 ExprList *pEList; /* The fields of the result */
19964 SrcList *pSrc; /* The FROM clause */
19965 Expr *pWhere; /* The WHERE clause */
19966 ExprList *pGroupBy; /* The GROUP BY clause */
19967 Expr *pHaving; /* The HAVING clause */
19968 ExprList *pOrderBy; /* The ORDER BY clause */
19969 Select *pPrior; /* Prior select in a compound select statement */
19970 Select *pNext; /* Next select to the left in a compound */
19971 Expr *pLimit; /* LIMIT expression. NULL means not used. */
19972 With *pWith; /* WITH clause attached to this select. Or NULL. */
19973#ifndef SQLITE_OMIT_WINDOWFUNC
19974 Window *pWin; /* List of window functions */
19975 Window *pWinDefn; /* List of named window definitions */
19976#endif
19977};
19978
19979/*
19980** Allowed values for Select.selFlags. The "SF" prefix stands for
19981** "Select Flag".
19982**
19983** Value constraints (all checked via assert())
19984** SF_HasAgg == NC_HasAgg
19985** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
19986** SF_OrderByReqd == NC_OrderAgg == SQLITE_FUNC_ANYORDER
19987** SF_FixedLimit == WHERE_USE_LIMIT
19988*/
19989#define SF_Distinct0x0000001 0x0000001 /* Output should be DISTINCT */
19990#define SF_All0x0000002 0x0000002 /* Includes the ALL keyword */
19991#define SF_Resolved0x0000004 0x0000004 /* Identifiers have been resolved */
19992#define SF_Aggregate0x0000008 0x0000008 /* Contains agg functions or a GROUP BY */
19993#define SF_HasAgg0x0000010 0x0000010 /* Contains aggregate functions */
19994#define SF_UsesEphemeral0x0000020 0x0000020 /* Uses the OpenEphemeral opcode */
19995#define SF_Expanded0x0000040 0x0000040 /* sqlite3SelectExpand() called on this */
19996#define SF_HasTypeInfo0x0000080 0x0000080 /* FROM subqueries have Table metadata */
19997#define SF_Compound0x0000100 0x0000100 /* Part of a compound query */
19998#define SF_Values0x0000200 0x0000200 /* Synthesized from VALUES clause */
19999#define SF_MultiValue0x0000400 0x0000400 /* Single VALUES term with multiple rows */
20000#define SF_NestedFrom0x0000800 0x0000800 /* Part of a parenthesized FROM clause */
20001#define SF_MinMaxAgg0x0001000 0x0001000 /* Aggregate containing min() or max() */
20002#define SF_Recursive0x0002000 0x0002000 /* The recursive part of a recursive CTE */
20003#define SF_FixedLimit0x0004000 0x0004000 /* nSelectRow set by a constant LIMIT */
20004#define SF_MaybeConvert0x0008000 0x0008000 /* Need convertCompoundSelectToSubquery() */
20005#define SF_Converted0x0010000 0x0010000 /* By convertCompoundSelectToSubquery() */
20006#define SF_IncludeHidden0x0020000 0x0020000 /* Include hidden columns in output */
20007#define SF_ComplexResult0x0040000 0x0040000 /* Result contains subquery or function */
20008#define SF_WhereBegin0x0080000 0x0080000 /* Really a WhereBegin() call. Debug Only */
20009#define SF_WinRewrite0x0100000 0x0100000 /* Window function rewrite accomplished */
20010#define SF_View0x0200000 0x0200000 /* SELECT statement is a view */
20011#define SF_NoopOrderBy0x0400000 0x0400000 /* ORDER BY is ignored for this query */
20012#define SF_UFSrcCheck0x0800000 0x0800000 /* Check pSrc as required by UPDATE...FROM */
20013#define SF_PushDown0x1000000 0x1000000 /* Modified by WHERE-clause push-down opt */
20014#define SF_MultiPart0x2000000 0x2000000 /* Has multiple incompatible PARTITIONs */
20015#define SF_CopyCte0x4000000 0x4000000 /* SELECT statement is a copy of a CTE */
20016#define SF_OrderByReqd0x8000000 0x8000000 /* The ORDER BY clause may not be omitted */
20017#define SF_UpdateFrom0x10000000 0x10000000 /* Query originates with UPDATE FROM */
20018#define SF_Correlated0x20000000 0x20000000 /* True if references the outer context */
20019
20020/* True if SrcItem X is a subquery that has SF_NestedFrom */
20021#define IsNestedFrom(X)((X)->fg.isSubquery && ((X)->u4.pSubq->pSelect
->selFlags&0x0000800)!=0)
\
20022 ((X)->fg.isSubquery && \
20023 ((X)->u4.pSubq->pSelect->selFlags&SF_NestedFrom0x0000800)!=0)
20024
20025/*
20026** The results of a SELECT can be distributed in several ways, as defined
20027** by one of the following macros. The "SRT" prefix means "SELECT Result
20028** Type".
20029**
20030** SRT_Union Store results as a key in a temporary index
20031** identified by pDest->iSDParm.
20032**
20033** SRT_Except Remove results from the temporary index pDest->iSDParm.
20034**
20035** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
20036** set is not empty.
20037**
20038** SRT_Discard Throw the results away. This is used by SELECT
20039** statements within triggers whose only purpose is
20040** the side-effects of functions.
20041**
20042** SRT_Output Generate a row of output (using the OP_ResultRow
20043** opcode) for each row in the result set.
20044**
20045** SRT_Mem Only valid if the result is a single column.
20046** Store the first column of the first result row
20047** in register pDest->iSDParm then abandon the rest
20048** of the query. This destination implies "LIMIT 1".
20049**
20050** SRT_Set The result must be a single column. Store each
20051** row of result as the key in table pDest->iSDParm.
20052** Apply the affinity pDest->affSdst before storing
20053** results. if pDest->iSDParm2 is positive, then it is
20054** a register holding a Bloom filter for the IN operator
20055** that should be populated in addition to the
20056** pDest->iSDParm table. This SRT is used to
20057** implement "IN (SELECT ...)".
20058**
20059** SRT_EphemTab Create an temporary table pDest->iSDParm and store
20060** the result there. The cursor is left open after
20061** returning. This is like SRT_Table except that
20062** this destination uses OP_OpenEphemeral to create
20063** the table first.
20064**
20065** SRT_Coroutine Generate a co-routine that returns a new row of
20066** results each time it is invoked. The entry point
20067** of the co-routine is stored in register pDest->iSDParm
20068** and the result row is stored in pDest->nDest registers
20069** starting with pDest->iSdst.
20070**
20071** SRT_Table Store results in temporary table pDest->iSDParm.
20072** SRT_Fifo This is like SRT_EphemTab except that the table
20073** is assumed to already be open. SRT_Fifo has
20074** the additional property of being able to ignore
20075** the ORDER BY clause.
20076**
20077** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
20078** But also use temporary table pDest->iSDParm+1 as
20079** a record of all prior results and ignore any duplicate
20080** rows. Name means: "Distinct Fifo".
20081**
20082** SRT_Queue Store results in priority queue pDest->iSDParm (really
20083** an index). Append a sequence number so that all entries
20084** are distinct.
20085**
20086** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
20087** the same record has never been stored before. The
20088** index at pDest->iSDParm+1 hold all prior stores.
20089**
20090** SRT_Upfrom Store results in the temporary table already opened by
20091** pDest->iSDParm. If (pDest->iSDParm<0), then the temp
20092** table is an intkey table - in this case the first
20093** column returned by the SELECT is used as the integer
20094** key. If (pDest->iSDParm>0), then the table is an index
20095** table. (pDest->iSDParm) is the number of key columns in
20096** each index record in this case.
20097*/
20098#define SRT_Union1 1 /* Store result as keys in an index */
20099#define SRT_Except2 2 /* Remove result from a UNION index */
20100#define SRT_Exists3 3 /* Store 1 if the result is not empty */
20101#define SRT_Discard4 4 /* Do not save the results anywhere */
20102#define SRT_DistFifo5 5 /* Like SRT_Fifo, but unique results only */
20103#define SRT_DistQueue6 6 /* Like SRT_Queue, but unique results only */
20104
20105/* The DISTINCT clause is ignored for all of the above. Not that
20106** IgnorableDistinct() implies IgnorableOrderby() */
20107#define IgnorableDistinct(X)((X->eDest)<=6) ((X->eDest)<=SRT_DistQueue6)
20108
20109#define SRT_Queue7 7 /* Store result in an queue */
20110#define SRT_Fifo8 8 /* Store result as data with an automatic rowid */
20111
20112/* The ORDER BY clause is ignored for all of the above */
20113#define IgnorableOrderby(X)((X->eDest)<=8) ((X->eDest)<=SRT_Fifo8)
20114
20115#define SRT_Output9 9 /* Output each row of result */
20116#define SRT_Mem10 10 /* Store result in a memory cell */
20117#define SRT_Set11 11 /* Store results as keys in an index */
20118#define SRT_EphemTab12 12 /* Create transient tab and store like SRT_Table */
20119#define SRT_Coroutine13 13 /* Generate a single row of result */
20120#define SRT_Table14 14 /* Store result as data with an automatic rowid */
20121#define SRT_Upfrom15 15 /* Store result as data with rowid */
20122
20123/*
20124** An instance of this object describes where to put of the results of
20125** a SELECT statement.
20126*/
20127struct SelectDest {
20128 u8 eDest; /* How to dispose of the results. One of SRT_* above. */
20129 int iSDParm; /* A parameter used by the eDest disposal method */
20130 int iSDParm2; /* A second parameter for the eDest disposal method */
20131 int iSdst; /* Base register where results are written */
20132 int nSdst; /* Number of registers allocated */
20133 char *zAffSdst; /* Affinity used for SRT_Set */
20134 ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
20135};
20136
20137/*
20138** During code generation of statements that do inserts into AUTOINCREMENT
20139** tables, the following information is attached to the Table.u.autoInc.p
20140** pointer of each autoincrement table to record some side information that
20141** the code generator needs. We have to keep per-table autoincrement
20142** information in case inserts are done within triggers. Triggers do not
20143** normally coordinate their activities, but we do need to coordinate the
20144** loading and saving of autoincrement information.
20145*/
20146struct AutoincInfo {
20147 AutoincInfo *pNext; /* Next info block in a list of them all */
20148 Table *pTab; /* Table this info block refers to */
20149 int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
20150 int regCtr; /* Memory register holding the rowid counter */
20151};
20152
20153/*
20154** At least one instance of the following structure is created for each
20155** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
20156** statement. All such objects are stored in the linked list headed at
20157** Parse.pTriggerPrg and deleted once statement compilation has been
20158** completed.
20159**
20160** A Vdbe sub-program that implements the body and WHEN clause of trigger
20161** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
20162** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
20163** The Parse.pTriggerPrg list never contains two entries with the same
20164** values for both pTrigger and orconf.
20165**
20166** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
20167** accessed (or set to 0 for triggers fired as a result of INSERT
20168** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
20169** a mask of new.* columns used by the program.
20170*/
20171struct TriggerPrg {
20172 Trigger *pTrigger; /* Trigger this program was coded from */
20173 TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
20174 SubProgram *pProgram; /* Program implementing pTrigger/orconf */
20175 int orconf; /* Default ON CONFLICT policy */
20176 u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
20177};
20178
20179/*
20180** The yDbMask datatype for the bitmask of all attached databases.
20181*/
20182#if SQLITE_MAX_ATTACHED10>30
20183 typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED10+9)/8];
20184# define DbMaskTest(M,I)(((M)&(((yDbMask)1)<<(I)))!=0) (((M)[(I)/8]&(1<<((I)&7)))!=0)
20185# define DbMaskZero(M)((M)=0) memset((M),0,sizeof(M))
20186# define DbMaskSet(M,I)((M)|=(((yDbMask)1)<<(I))) (M)[(I)/8]|=(1<<((I)&7))
20187# define DbMaskAllZero(M)((M)==0) sqlite3DbMaskAllZero(M)
20188# define DbMaskNonZero(M)((M)!=0) (sqlite3DbMaskAllZero(M)==0)
20189#else
20190 typedef unsigned int yDbMask;
20191# define DbMaskTest(M,I)(((M)&(((yDbMask)1)<<(I)))!=0) (((M)&(((yDbMask)1)<<(I)))!=0)
20192# define DbMaskZero(M)((M)=0) ((M)=0)
20193# define DbMaskSet(M,I)((M)|=(((yDbMask)1)<<(I))) ((M)|=(((yDbMask)1)<<(I)))
20194# define DbMaskAllZero(M)((M)==0) ((M)==0)
20195# define DbMaskNonZero(M)((M)!=0) ((M)!=0)
20196#endif
20197
20198/*
20199** For each index X that has as one of its arguments either an expression
20200** or the name of a virtual generated column, and if X is in scope such that
20201** the value of the expression can simply be read from the index, then
20202** there is an instance of this object on the Parse.pIdxExpr list.
20203**
20204** During code generation, while generating code to evaluate expressions,
20205** this list is consulted and if a matching expression is found, the value
20206** is read from the index rather than being recomputed.
20207*/
20208struct IndexedExpr {
20209 Expr *pExpr; /* The expression contained in the index */
20210 int iDataCur; /* The data cursor associated with the index */
20211 int iIdxCur; /* The index cursor */
20212 int iIdxCol; /* The index column that contains value of pExpr */
20213 u8 bMaybeNullRow; /* True if we need an OP_IfNullRow check */
20214 u8 aff; /* Affinity of the pExpr expression */
20215 IndexedExpr *pIENext; /* Next in a list of all indexed expressions */
20216#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
20217 const char *zIdxName; /* Name of index, used only for bytecode comments */
20218#endif
20219};
20220
20221/*
20222** An instance of the ParseCleanup object specifies an operation that
20223** should be performed after parsing to deallocation resources obtained
20224** during the parse and which are no longer needed.
20225*/
20226struct ParseCleanup {
20227 ParseCleanup *pNext; /* Next cleanup task */
20228 void *pPtr; /* Pointer to object to deallocate */
20229 void (*xCleanup)(sqlite3*,void*); /* Deallocation routine */
20230};
20231
20232/*
20233** An SQL parser context. A copy of this structure is passed through
20234** the parser and down into all the parser action routine in order to
20235** carry around information that is global to the entire parse.
20236**
20237** The structure is divided into two parts. When the parser and code
20238** generate call themselves recursively, the first part of the structure
20239** is constant but the second part is reset at the beginning and end of
20240** each recursion.
20241**
20242** The nTableLock and aTableLock variables are only used if the shared-cache
20243** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
20244** used to store the set of table-locks required by the statement being
20245** compiled. Function sqlite3TableLock() is used to add entries to the
20246** list.
20247*/
20248struct Parse {
20249 sqlite3 *db; /* The main database structure */
20250 char *zErrMsg; /* An error message */
20251 Vdbe *pVdbe; /* An engine for executing database bytecode */
20252 int rc; /* Return code from execution */
20253 LogEst nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
20254 u8 nested; /* Number of nested calls to the parser/code generator */
20255 u8 nTempReg; /* Number of temporary registers in aTempReg[] */
20256 u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
20257 u8 mayAbort; /* True if statement may throw an ABORT exception */
20258 u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
20259 u8 disableLookaside; /* Number of times lookaside has been disabled */
20260 u8 prepFlags; /* SQLITE_PREPARE_* flags */
20261 u8 withinRJSubrtn; /* Nesting level for RIGHT JOIN body subroutines */
20262 u8 mSubrtnSig; /* mini Bloom filter on available SubrtnSig.selId */
20263 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
20264 u8 bReturning; /* Coding a RETURNING trigger */
20265 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
20266 u8 disableTriggers; /* True to disable triggers */
20267#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
20268 u8 earlyCleanup; /* OOM inside sqlite3ParserAddCleanup() */
20269#endif
20270#ifdef SQLITE_DEBUG
20271 u8 ifNotExists; /* Might be true if IF NOT EXISTS. Assert()s only */
20272 u8 isCreate; /* CREATE TABLE, INDEX, or VIEW (but not TRIGGER)
20273 ** and ALTER TABLE ADD COLUMN. */
20274#endif
20275 bft colNamesSet :1; /* TRUE after OP_ColumnName has been issued to pVdbe */
20276 bft bHasWith :1; /* True if statement contains WITH */
20277 bft okConstFactor :1; /* OK to factor out constants */
20278 bft checkSchema :1; /* Causes schema cookie check after an error */
20279 int nRangeReg; /* Size of the temporary register block */
20280 int iRangeReg; /* First register in temporary register block */
20281 int nErr; /* Number of errors seen */
20282 int nTab; /* Number of previously allocated VDBE cursors */
20283 int nMem; /* Number of memory cells used so far */
20284 int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
20285 int iSelfTab; /* Table associated with an index on expr, or negative
20286 ** of the base register during check-constraint eval */
20287 int nLabel; /* The *negative* of the number of labels used */
20288 int nLabelAlloc; /* Number of slots in aLabel */
20289 int *aLabel; /* Space to hold the labels */
20290 ExprList *pConstExpr;/* Constant expressions */
20291 IndexedExpr *pIdxEpr;/* List of expressions used by active indexes */
20292 IndexedExpr *pIdxPartExpr; /* Exprs constrained by index WHERE clauses */
20293 yDbMask writeMask; /* Start a write transaction on these databases */
20294 yDbMask cookieMask; /* Bitmask of schema verified databases */
20295 int nMaxArg; /* Max args to xUpdate and xFilter vtab methods */
20296 int nSelect; /* Number of SELECT stmts. Counter for Select.selId */
20297#ifndef SQLITE_OMIT_PROGRESS_CALLBACK1
20298 u32 nProgressSteps; /* xProgress steps taken during sqlite3_prepare() */
20299#endif
20300#ifndef SQLITE_OMIT_SHARED_CACHE
20301 int nTableLock; /* Number of locks in aTableLock */
20302 TableLock *aTableLock; /* Required table locks for shared-cache mode */
20303#endif
20304 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
20305 Parse *pToplevel; /* Parse structure for main program (or NULL) */
20306 Table *pTriggerTab; /* Table triggers are being coded for */
20307 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
20308 ParseCleanup *pCleanup; /* List of cleanup operations to run after parse */
20309
20310 /**************************************************************************
20311 ** Fields above must be initialized to zero. The fields that follow,
20312 ** down to the beginning of the recursive section, do not need to be
20313 ** initialized as they will be set before being used. The boundary is
20314 ** determined by offsetof(Parse,aTempReg).
20315 **************************************************************************/
20316
20317 int aTempReg[8]; /* Holding area for temporary registers */
20318 Parse *pOuterParse; /* Outer Parse object when nested */
20319 Token sNameToken; /* Token with unqualified schema object name */
20320 u32 oldmask; /* Mask of old.* columns referenced */
20321 u32 newmask; /* Mask of new.* columns referenced */
20322 union {
20323 struct { /* These fields available when isCreate is true */
20324 int addrCrTab; /* Address of OP_CreateBtree on CREATE TABLE */
20325 int regRowid; /* Register holding rowid of CREATE TABLE entry */
20326 int regRoot; /* Register holding root page for new objects */
20327 Token constraintName; /* Name of the constraint currently being parsed */
20328 } cr;
20329 struct { /* These fields available to all other statements */
20330 Returning *pReturning; /* The RETURNING clause */
20331 } d;
20332 } u1;
20333
20334 /************************************************************************
20335 ** Above is constant between recursions. Below is reset before and after
20336 ** each recursion. The boundary between these two regions is determined
20337 ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
20338 ** first field in the recursive region.
20339 ************************************************************************/
20340
20341 Token sLastToken; /* The last token parsed */
20342 ynVar nVar; /* Number of '?' variables seen in the SQL so far */
20343 u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
20344 u8 explain; /* True if the EXPLAIN flag is found on the query */
20345 u8 eParseMode; /* PARSE_MODE_XXX constant */
20346#ifndef SQLITE_OMIT_VIRTUALTABLE
20347 int nVtabLock; /* Number of virtual tables to lock */
20348#endif
20349 int nHeight; /* Expression tree height of current sub-select */
20350 int addrExplain; /* Address of current OP_Explain opcode */
20351 VList *pVList; /* Mapping between variable names and numbers */
20352 Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
20353 const char *zTail; /* All SQL text past the last semicolon parsed */
20354 Table *pNewTable; /* A table being constructed by CREATE TABLE */
20355 Index *pNewIndex; /* An index being constructed by CREATE INDEX.
20356 ** Also used to hold redundant UNIQUE constraints
20357 ** during a RENAME COLUMN */
20358 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
20359 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
20360#ifndef SQLITE_OMIT_VIRTUALTABLE
20361 Token sArg; /* Complete text of a module argument */
20362 Table **apVtabLock; /* Pointer to virtual tables needing locking */
20363#endif
20364 With *pWith; /* Current WITH clause, or NULL */
20365#ifndef SQLITE_OMIT_ALTERTABLE
20366 RenameToken *pRename; /* Tokens subject to renaming by ALTER TABLE */
20367#endif
20368};
20369
20370/* Allowed values for Parse.eParseMode
20371*/
20372#define PARSE_MODE_NORMAL0 0
20373#define PARSE_MODE_DECLARE_VTAB1 1
20374#define PARSE_MODE_RENAME2 2
20375#define PARSE_MODE_UNMAP3 3
20376
20377/*
20378** Sizes and pointers of various parts of the Parse object.
20379*/
20380#define PARSE_HDR(X)(((char*)(X))+__builtin_offsetof(Parse, zErrMsg)) (((char*)(X))+offsetof(Parse,zErrMsg)__builtin_offsetof(Parse, zErrMsg))
20381#define PARSE_HDR_SZ(__builtin_offsetof(Parse, aTempReg)-__builtin_offsetof(Parse
, zErrMsg))
(offsetof(Parse,aTempReg)__builtin_offsetof(Parse, aTempReg)-offsetof(Parse,zErrMsg)__builtin_offsetof(Parse, zErrMsg)) /* Recursive part w/o aColCache*/
20382#define PARSE_RECURSE_SZ__builtin_offsetof(Parse, sLastToken) offsetof(Parse,sLastToken)__builtin_offsetof(Parse, sLastToken) /* Recursive part */
20383#define PARSE_TAIL_SZ(sizeof(Parse)-__builtin_offsetof(Parse, sLastToken)) (sizeof(Parse)-PARSE_RECURSE_SZ__builtin_offsetof(Parse, sLastToken)) /* Non-recursive part */
20384#define PARSE_TAIL(X)(((char*)(X))+__builtin_offsetof(Parse, sLastToken)) (((char*)(X))+PARSE_RECURSE_SZ__builtin_offsetof(Parse, sLastToken)) /* Pointer to tail */
20385
20386/*
20387** Return true if currently inside an sqlite3_declare_vtab() call.
20388*/
20389#ifdef SQLITE_OMIT_VIRTUALTABLE
20390 #define IN_DECLARE_VTAB(pParse->eParseMode==1) 0
20391#else
20392 #define IN_DECLARE_VTAB(pParse->eParseMode==1) (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB1)
20393#endif
20394
20395#if defined(SQLITE_OMIT_ALTERTABLE)
20396 #define IN_RENAME_OBJECT(pParse->eParseMode>=2) 0
20397#else
20398 #define IN_RENAME_OBJECT(pParse->eParseMode>=2) (pParse->eParseMode>=PARSE_MODE_RENAME2)
20399#endif
20400
20401#if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
20402 #define IN_SPECIAL_PARSE(pParse->eParseMode!=0) 0
20403#else
20404 #define IN_SPECIAL_PARSE(pParse->eParseMode!=0) (pParse->eParseMode!=PARSE_MODE_NORMAL0)
20405#endif
20406
20407/*
20408** An instance of the following structure can be declared on a stack and used
20409** to save the Parse.zAuthContext value so that it can be restored later.
20410*/
20411struct AuthContext {
20412 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
20413 Parse *pParse; /* The Parse structure */
20414};
20415
20416/*
20417** Bitfield flags for P5 value in various opcodes.
20418**
20419** Value constraints (enforced via assert()):
20420** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
20421** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
20422** OPFLAG_BULKCSR == BTREE_BULKLOAD
20423** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
20424** OPFLAG_FORDELETE == BTREE_FORDELETE
20425** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
20426** OPFLAG_AUXDELETE == BTREE_AUXDELETE
20427*/
20428#define OPFLAG_NCHANGE0x01 0x01 /* OP_Insert: Set to update db->nChange */
20429 /* Also used in P2 (not P5) of OP_Delete */
20430#define OPFLAG_NOCHNG0x01 0x01 /* OP_VColumn nochange for UPDATE */
20431#define OPFLAG_EPHEM0x01 0x01 /* OP_Column: Ephemeral output is ok */
20432#define OPFLAG_LASTROWID0x20 0x20 /* Set to update db->lastRowid */
20433#define OPFLAG_ISUPDATE0x04 0x04 /* This OP_Insert is an sql UPDATE */
20434#define OPFLAG_APPEND0x08 0x08 /* This is likely to be an append */
20435#define OPFLAG_USESEEKRESULT0x10 0x10 /* Try to avoid a seek in BtreeInsert() */
20436#define OPFLAG_ISNOOP0x40 0x40 /* OP_Delete does pre-update-hook only */
20437#define OPFLAG_LENGTHARG0x40 0x40 /* OP_Column only used for length() */
20438#define OPFLAG_TYPEOFARG0x80 0x80 /* OP_Column only used for typeof() */
20439#define OPFLAG_BYTELENARG0xc0 0xc0 /* OP_Column only for octet_length() */
20440#define OPFLAG_BULKCSR0x01 0x01 /* OP_Open** used to open bulk cursor */
20441#define OPFLAG_SEEKEQ0x02 0x02 /* OP_Open** cursor uses EQ seek only */
20442#define OPFLAG_FORDELETE0x08 0x08 /* OP_Open should use BTREE_FORDELETE */
20443#define OPFLAG_P2ISREG0x10 0x10 /* P2 to OP_Open** is a register number */
20444#define OPFLAG_PERMUTE0x01 0x01 /* OP_Compare: use the permutation */
20445#define OPFLAG_SAVEPOSITION0x02 0x02 /* OP_Delete/Insert: save cursor pos */
20446#define OPFLAG_AUXDELETE0x04 0x04 /* OP_Delete: index in a DELETE op */
20447#define OPFLAG_NOCHNG_MAGIC0x6d 0x6d /* OP_MakeRecord: serialtype 10 is ok */
20448#define OPFLAG_PREFORMAT0x80 0x80 /* OP_Insert uses preformatted cell */
20449
20450/*
20451** Each trigger present in the database schema is stored as an instance of
20452** struct Trigger.
20453**
20454** Pointers to instances of struct Trigger are stored in two ways.
20455** 1. In the "trigHash" hash table (part of the sqlite3* that represents the
20456** database). This allows Trigger structures to be retrieved by name.
20457** 2. All triggers associated with a single table form a linked list, using the
20458** pNext member of struct Trigger. A pointer to the first element of the
20459** linked list is stored as the "pTrigger" member of the associated
20460** struct Table.
20461**
20462** The "step_list" member points to the first element of a linked list
20463** containing the SQL statements specified as the trigger program.
20464*/
20465struct Trigger {
20466 char *zName; /* The name of the trigger */
20467 char *table; /* The table or view to which the trigger applies */
20468 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
20469 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
20470 u8 bReturning; /* This trigger implements a RETURNING clause */
20471 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
20472 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
20473 the <column-list> is stored here */
20474 Schema *pSchema; /* Schema containing the trigger */
20475 Schema *pTabSchema; /* Schema containing the table */
20476 TriggerStep *step_list; /* Link list of trigger program steps */
20477 Trigger *pNext; /* Next trigger associated with the table */
20478};
20479
20480/*
20481** A trigger is either a BEFORE or an AFTER trigger. The following constants
20482** determine which.
20483**
20484** If there are multiple triggers, you might of some BEFORE and some AFTER.
20485** In that cases, the constants below can be ORed together.
20486*/
20487#define TRIGGER_BEFORE1 1
20488#define TRIGGER_AFTER2 2
20489
20490/*
20491** An instance of struct TriggerStep is used to store a single SQL statement
20492** that is a part of a trigger-program.
20493**
20494** Instances of struct TriggerStep are stored in a singly linked list (linked
20495** using the "pNext" member) referenced by the "step_list" member of the
20496** associated struct Trigger instance. The first element of the linked list is
20497** the first step of the trigger-program.
20498**
20499** The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
20500** "SELECT" statement. The meanings of the other members is determined by the
20501** value of "op" as follows:
20502**
20503** (op == TK_INSERT)
20504** orconf -> stores the ON CONFLICT algorithm
20505** pSelect -> The content to be inserted - either a SELECT statement or
20506** a VALUES clause.
20507** zTarget -> Dequoted name of the table to insert into.
20508** pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
20509** statement, then this stores the column-names to be
20510** inserted into.
20511** pUpsert -> The ON CONFLICT clauses for an Upsert
20512**
20513** (op == TK_DELETE)
20514** zTarget -> Dequoted name of the table to delete from.
20515** pWhere -> The WHERE clause of the DELETE statement if one is specified.
20516** Otherwise NULL.
20517**
20518** (op == TK_UPDATE)
20519** zTarget -> Dequoted name of the table to update.
20520** pWhere -> The WHERE clause of the UPDATE statement if one is specified.
20521** Otherwise NULL.
20522** pExprList -> A list of the columns to update and the expressions to update
20523** them to. See sqlite3Update() documentation of "pChanges"
20524** argument.
20525**
20526** (op == TK_SELECT)
20527** pSelect -> The SELECT statement
20528**
20529** (op == TK_RETURNING)
20530** pExprList -> The list of expressions that follow the RETURNING keyword.
20531**
20532*/
20533struct TriggerStep {
20534 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT,
20535 ** or TK_RETURNING */
20536 u8 orconf; /* OE_Rollback etc. */
20537 Trigger *pTrig; /* The trigger that this step is a part of */
20538 Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
20539 char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
20540 SrcList *pFrom; /* FROM clause for UPDATE statement (if any) */
20541 Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
20542 ExprList *pExprList; /* SET clause for UPDATE, or RETURNING clause */
20543 IdList *pIdList; /* Column names for INSERT */
20544 Upsert *pUpsert; /* Upsert clauses on an INSERT */
20545 char *zSpan; /* Original SQL text of this command */
20546 TriggerStep *pNext; /* Next in the link-list */
20547 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
20548};
20549
20550/*
20551** Information about a RETURNING clause
20552*/
20553struct Returning {
20554 Parse *pParse; /* The parse that includes the RETURNING clause */
20555 ExprList *pReturnEL; /* List of expressions to return */
20556 Trigger retTrig; /* The transient trigger that implements RETURNING */
20557 TriggerStep retTStep; /* The trigger step */
20558 int iRetCur; /* Transient table holding RETURNING results */
20559 int nRetCol; /* Number of in pReturnEL after expansion */
20560 int iRetReg; /* Register array for holding a row of RETURNING */
20561 char zName[40]; /* Name of trigger: "sqlite_returning_%p" */
20562};
20563
20564/*
20565** An object used to accumulate the text of a string where we
20566** do not necessarily know how big the string will be in the end.
20567*/
20568struct sqlite3_str {
20569 sqlite3 *db; /* Optional database for lookaside. Can be NULL */
20570 char *zText; /* The string collected so far */
20571 u32 nAlloc; /* Amount of space allocated in zText */
20572 u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
20573 u32 nChar; /* Length of the string so far */
20574 u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */
20575 u8 printfFlags; /* SQLITE_PRINTF flags below */
20576};
20577#define SQLITE_PRINTF_INTERNAL0x01 0x01 /* Internal-use-only converters allowed */
20578#define SQLITE_PRINTF_SQLFUNC0x02 0x02 /* SQL function arguments to VXPrintf */
20579#define SQLITE_PRINTF_MALLOCED0x04 0x04 /* True if zText is allocated space */
20580
20581#define isMalloced(X)(((X)->printfFlags & 0x04)!=0) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED0x04)!=0)
20582
20583/*
20584** The following object is the header for an "RCStr" or "reference-counted
20585** string". An RCStr is passed around and used like any other char*
20586** that has been dynamically allocated. The important interface
20587** differences:
20588**
20589** 1. RCStr strings are reference counted. They are deallocated
20590** when the reference count reaches zero.
20591**
20592** 2. Use sqlite3RCStrUnref() to free an RCStr string rather than
20593** sqlite3_free()
20594**
20595** 3. Make a (read-only) copy of a read-only RCStr string using
20596** sqlite3RCStrRef().
20597**
20598** "String" is in the name, but an RCStr object can also be used to hold
20599** binary data.
20600*/
20601struct RCStr {
20602 u64 nRCRef; /* Number of references */
20603 /* Total structure size should be a multiple of 8 bytes for alignment */
20604};
20605
20606/*
20607** A pointer to this structure is used to communicate information
20608** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
20609*/
20610typedef struct {
20611 sqlite3 *db; /* The database being initialized */
20612 char **pzErrMsg; /* Error message stored here */
20613 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
20614 int rc; /* Result code stored here */
20615 u32 mInitFlags; /* Flags controlling error messages */
20616 u32 nInitRow; /* Number of rows processed */
20617 Pgno mxPage; /* Maximum page number. 0 for no limit. */
20618} InitData;
20619
20620/*
20621** Allowed values for mInitFlags
20622*/
20623#define INITFLAG_AlterMask0x0003 0x0003 /* Types of ALTER */
20624#define INITFLAG_AlterRename0x0001 0x0001 /* Reparse after a RENAME */
20625#define INITFLAG_AlterDrop0x0002 0x0002 /* Reparse after a DROP COLUMN */
20626#define INITFLAG_AlterAdd0x0003 0x0003 /* Reparse after an ADD COLUMN */
20627
20628/* Tuning parameters are set using SQLITE_TESTCTRL_TUNE and are controlled
20629** on debug-builds of the CLI using ".testctrl tune ID VALUE". Tuning
20630** parameters are for temporary use during development, to help find
20631** optimal values for parameters in the query planner. The should not
20632** be used on trunk check-ins. They are a temporary mechanism available
20633** for transient development builds only.
20634**
20635** Tuning parameters are numbered starting with 1.
20636*/
20637#define SQLITE_NTUNE6 6 /* Should be zero for all trunk check-ins */
20638#ifdef SQLITE_DEBUG
20639# define Tuning(X)0 (sqlite3Config.aTune[(X)-1])
20640#else
20641# define Tuning(X)0 0
20642#endif
20643
20644/*
20645** Structure containing global configuration data for the SQLite library.
20646**
20647** This structure also contains some state information.
20648*/
20649struct Sqlite3Config {
20650 int bMemstat; /* True to enable memory status */
20651 u8 bCoreMutex; /* True to enable core mutexing */
20652 u8 bFullMutex; /* True to enable full mutexing */
20653 u8 bOpenUri; /* True to interpret filenames as URIs */
20654 u8 bUseCis; /* Use covering indices for full-scans */
20655 u8 bSmallMalloc; /* Avoid large memory allocations if true */
20656 u8 bExtraSchemaChecks; /* Verify type,name,tbl_name in schema */
20657#ifdef SQLITE_DEBUG
20658 u8 bJsonSelfcheck; /* Double-check JSON parsing */
20659#endif
20660 int mxStrlen; /* Maximum string length */
20661 int neverCorrupt; /* Database is always well-formed */
20662 int szLookaside; /* Default lookaside buffer size */
20663 int nLookaside; /* Default lookaside buffer count */
20664 int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
20665 sqlite3_mem_methods m; /* Low-level memory allocation interface */
20666 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
20667 sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
20668 void *pHeap; /* Heap storage space */
20669 int nHeap; /* Size of pHeap[] */
20670 int mnReq, mxReq; /* Min and max heap requests sizes */
20671 sqlite3_int64 szMmap; /* mmap() space per open file */
20672 sqlite3_int64 mxMmap; /* Maximum value for szMmap */
20673 void *pPage; /* Page cache memory */
20674 int szPage; /* Size of each page in pPage[] */
20675 int nPage; /* Number of pages in pPage[] */
20676 int mxParserStack; /* maximum depth of the parser stack */
20677 int sharedCacheEnabled; /* true if shared-cache mode enabled */
20678 u32 szPma; /* Maximum Sorter PMA size */
20679 /* The above might be initialized to non-zero. The following need to always
20680 ** initially be zero, however. */
20681 int isInit; /* True after initialization has finished */
20682 int inProgress; /* True while initialization in progress */
20683 int isMutexInit; /* True after mutexes are initialized */
20684 int isMallocInit; /* True after malloc is initialized */
20685 int isPCacheInit; /* True after malloc is initialized */
20686 int nRefInitMutex; /* Number of users of pInitMutex */
20687 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
20688 void (*xLog)(void*,int,const char*); /* Function for logging */
20689 void *pLogArg; /* First argument to xLog() */
20690#ifdef SQLITE_ENABLE_SQLLOG
20691 void(*xSqllog)(void*,sqlite3*,const char*, int);
20692 void *pSqllogArg;
20693#endif
20694#ifdef SQLITE_VDBE_COVERAGE
20695 /* The following callback (if not NULL) is invoked on every VDBE branch
20696 ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
20697 */
20698 void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx); /* Callback */
20699 void *pVdbeBranchArg; /* 1st argument */
20700#endif
20701#ifndef SQLITE_OMIT_DESERIALIZE
20702 sqlite3_int64 mxMemdbSize; /* Default max memdb size */
20703#endif
20704#ifndef SQLITE_UNTESTABLE
20705 int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
20706#endif
20707#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
20708 u32 mNoVisibleRowid; /* TF_NoVisibleRowid if the ROWID_IN_VIEW
20709 ** feature is disabled. 0 if rowids can
20710 ** occur in views. */
20711#endif
20712 int bLocaltimeFault; /* True to fail localtime() calls */
20713 int (*xAltLocaltime)(const void*,void*); /* Alternative localtime() routine */
20714 int iOnceResetThreshold; /* When to reset OP_Once counters */
20715 u32 szSorterRef; /* Min size in bytes to use sorter-refs */
20716 unsigned int iPrngSeed; /* Alternative fixed seed for the PRNG */
20717 /* vvvv--- must be last ---vvv */
20718#ifdef SQLITE_DEBUG
20719 sqlite3_int64 aTune[SQLITE_NTUNE6]; /* Tuning parameters */
20720#endif
20721};
20722
20723/*
20724** This macro is used inside of assert() statements to indicate that
20725** the assert is only valid on a well-formed database. Instead of:
20726**
20727** assert( X );
20728**
20729** One writes:
20730**
20731** assert( X || CORRUPT_DB );
20732**
20733** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
20734** that the database is definitely corrupt, only that it might be corrupt.
20735** For most test cases, CORRUPT_DB is set to false using a special
20736** sqlite3_test_control(). This enables assert() statements to prove
20737** things that are always true for well-formed databases.
20738*/
20739#define CORRUPT_DB(sqlite3Config.neverCorrupt==0) (sqlite3Config.neverCorrupt==0)
20740
20741/*
20742** Context pointer passed down through the tree-walk.
20743*/
20744struct Walker {
20745 Parse *pParse; /* Parser context. */
20746 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
20747 int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
20748 void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
20749 int walkerDepth; /* Number of subqueries */
20750 u16 eCode; /* A small processing code */
20751 u16 mWFlags; /* Use-dependent flags */
20752 union { /* Extra data for callback */
20753 NameContext *pNC; /* Naming context */
20754 int n; /* A counter */
20755 int iCur; /* A cursor number */
20756 SrcList *pSrcList; /* FROM clause */
20757 struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
20758 struct RefSrcList *pRefSrcList; /* sqlite3ReferencesSrcList() */
20759 int *aiCol; /* array of column indexes */
20760 struct IdxCover *pIdxCover; /* Check for index coverage */
20761 ExprList *pGroupBy; /* GROUP BY clause */
20762 Select *pSelect; /* HAVING to WHERE clause ctx */
20763 struct WindowRewrite *pRewrite; /* Window rewrite context */
20764 struct WhereConst *pConst; /* WHERE clause constants */
20765 struct RenameCtx *pRename; /* RENAME COLUMN context */
20766 struct Table *pTab; /* Table of generated column */
20767 struct CoveringIndexCheck *pCovIdxCk; /* Check for covering index */
20768 SrcItem *pSrcItem; /* A single FROM clause item */
20769 DbFixer *pFix; /* See sqlite3FixSelect() */
20770 Mem *aMem; /* See sqlite3BtreeCursorHint() */
20771 } u;
20772};
20773
20774/*
20775** The following structure contains information used by the sqliteFix...
20776** routines as they walk the parse tree to make database references
20777** explicit.
20778*/
20779struct DbFixer {
20780 Parse *pParse; /* The parsing context. Error messages written here */
20781 Walker w; /* Walker object */
20782 Schema *pSchema; /* Fix items to this schema */
20783 u8 bTemp; /* True for TEMP schema entries */
20784 const char *zDb; /* Make sure all objects are contained in this database */
20785 const char *zType; /* Type of the container - used for error messages */
20786 const Token *pName; /* Name of the container - used for error messages */
20787};
20788
20789/* Forward declarations */
20790SQLITE_PRIVATEstatic int sqlite3WalkExpr(Walker*, Expr*);
20791SQLITE_PRIVATEstatic int sqlite3WalkExprNN(Walker*, Expr*);
20792SQLITE_PRIVATEstatic int sqlite3WalkExprList(Walker*, ExprList*);
20793SQLITE_PRIVATEstatic int sqlite3WalkSelect(Walker*, Select*);
20794SQLITE_PRIVATEstatic int sqlite3WalkSelectExpr(Walker*, Select*);
20795SQLITE_PRIVATEstatic int sqlite3WalkSelectFrom(Walker*, Select*);
20796SQLITE_PRIVATEstatic int sqlite3ExprWalkNoop(Walker*, Expr*);
20797SQLITE_PRIVATEstatic int sqlite3SelectWalkNoop(Walker*, Select*);
20798SQLITE_PRIVATEstatic int sqlite3SelectWalkFail(Walker*, Select*);
20799SQLITE_PRIVATEstatic int sqlite3WalkerDepthIncrease(Walker*,Select*);
20800SQLITE_PRIVATEstatic void sqlite3WalkerDepthDecrease(Walker*,Select*);
20801SQLITE_PRIVATEstatic void sqlite3WalkWinDefnDummyCallback(Walker*,Select*);
20802
20803#ifdef SQLITE_DEBUG
20804SQLITE_PRIVATEstatic void sqlite3SelectWalkAssert2(Walker*, Select*);
20805#endif
20806
20807#ifndef SQLITE_OMIT_CTE
20808SQLITE_PRIVATEstatic void sqlite3SelectPopWith(Walker*, Select*);
20809#else
20810# define sqlite3SelectPopWith 0
20811#endif
20812
20813/*
20814** Return code from the parse-tree walking primitives and their
20815** callbacks.
20816*/
20817#define WRC_Continue0 0 /* Continue down into children */
20818#define WRC_Prune1 1 /* Omit children but continue walking siblings */
20819#define WRC_Abort2 2 /* Abandon the tree walk */
20820
20821/*
20822** A single common table expression
20823*/
20824struct Cte {
20825 char *zName; /* Name of this CTE */
20826 ExprList *pCols; /* List of explicit column names, or NULL */
20827 Select *pSelect; /* The definition of this CTE */
20828 const char *zCteErr; /* Error message for circular references */
20829 CteUse *pUse; /* Usage information for this CTE */
20830 u8 eM10d; /* The MATERIALIZED flag */
20831};
20832
20833/*
20834** Allowed values for the materialized flag (eM10d):
20835*/
20836#define M10d_Yes0 0 /* AS MATERIALIZED */
20837#define M10d_Any1 1 /* Not specified. Query planner's choice */
20838#define M10d_No2 2 /* AS NOT MATERIALIZED */
20839
20840/*
20841** An instance of the With object represents a WITH clause containing
20842** one or more CTEs (common table expressions).
20843*/
20844struct With {
20845 int nCte; /* Number of CTEs in the WITH clause */
20846 int bView; /* Belongs to the outermost Select of a view */
20847 With *pOuter; /* Containing WITH clause, or NULL */
20848 Cte a[FLEXARRAY]; /* For each CTE in the WITH clause.... */
20849};
20850
20851/* The size (in bytes) of a With object that can hold as many
20852** as N different CTEs. */
20853#define SZ_WITH(N)(__builtin_offsetof(With, a) + (N)*sizeof(Cte)) (offsetof(With,a)__builtin_offsetof(With, a) + (N)*sizeof(Cte))
20854
20855/*
20856** The Cte object is not guaranteed to persist for the entire duration
20857** of code generation. (The query flattener or other parser tree
20858** edits might delete it.) The following object records information
20859** about each Common Table Expression that must be preserved for the
20860** duration of the parse.
20861**
20862** The CteUse objects are freed using sqlite3ParserAddCleanup() rather
20863** than sqlite3SelectDelete(), which is what enables them to persist
20864** until the end of code generation.
20865*/
20866struct CteUse {
20867 int nUse; /* Number of users of this CTE */
20868 int addrM9e; /* Start of subroutine to compute materialization */
20869 int regRtn; /* Return address register for addrM9e subroutine */
20870 int iCur; /* Ephemeral table holding the materialization */
20871 LogEst nRowEst; /* Estimated number of rows in the table */
20872 u8 eM10d; /* The MATERIALIZED flag */
20873};
20874
20875
20876/* Client data associated with sqlite3_set_clientdata() and
20877** sqlite3_get_clientdata().
20878*/
20879struct DbClientData {
20880 DbClientData *pNext; /* Next in a linked list */
20881 void *pData; /* The data */
20882 void (*xDestructor)(void*); /* Destructor. Might be NULL */
20883 char zName[FLEXARRAY]; /* Name of this client data. MUST BE LAST */
20884};
20885
20886/* The size (in bytes) of a DbClientData object that can has a name
20887** that is N bytes long, including the zero-terminator. */
20888#define SZ_DBCLIENTDATA(N)(__builtin_offsetof(DbClientData, zName)+(N)) (offsetof(DbClientData,zName)__builtin_offsetof(DbClientData, zName)+(N))
20889
20890#ifdef SQLITE_DEBUG
20891/*
20892** An instance of the TreeView object is used for printing the content of
20893** data structures on sqlite3DebugPrintf() using a tree-like view.
20894*/
20895struct TreeView {
20896 int iLevel; /* Which level of the tree we are on */
20897 u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
20898};
20899#endif /* SQLITE_DEBUG */
20900
20901/*
20902** This object is used in various ways, most (but not all) related to window
20903** functions.
20904**
20905** (1) A single instance of this structure is attached to the
20906** the Expr.y.pWin field for each window function in an expression tree.
20907** This object holds the information contained in the OVER clause,
20908** plus additional fields used during code generation.
20909**
20910** (2) All window functions in a single SELECT form a linked-list
20911** attached to Select.pWin. The Window.pFunc and Window.pExpr
20912** fields point back to the expression that is the window function.
20913**
20914** (3) The terms of the WINDOW clause of a SELECT are instances of this
20915** object on a linked list attached to Select.pWinDefn.
20916**
20917** (4) For an aggregate function with a FILTER clause, an instance
20918** of this object is stored in Expr.y.pWin with eFrmType set to
20919** TK_FILTER. In this case the only field used is Window.pFilter.
20920**
20921** The uses (1) and (2) are really the same Window object that just happens
20922** to be accessible in two different ways. Use case (3) are separate objects.
20923*/
20924struct Window {
20925 char *zName; /* Name of window (may be NULL) */
20926 char *zBase; /* Name of base window for chaining (may be NULL) */
20927 ExprList *pPartition; /* PARTITION BY clause */
20928 ExprList *pOrderBy; /* ORDER BY clause */
20929 u8 eFrmType; /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */
20930 u8 eStart; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
20931 u8 eEnd; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
20932 u8 bImplicitFrame; /* True if frame was implicitly specified */
20933 u8 eExclude; /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */
20934 Expr *pStart; /* Expression for "<expr> PRECEDING" */
20935 Expr *pEnd; /* Expression for "<expr> FOLLOWING" */
20936 Window **ppThis; /* Pointer to this object in Select.pWin list */
20937 Window *pNextWin; /* Next window function belonging to this SELECT */
20938 Expr *pFilter; /* The FILTER expression */
20939 FuncDef *pWFunc; /* The function */
20940 int iEphCsr; /* Partition buffer or Peer buffer */
20941 int regAccum; /* Accumulator */
20942 int regResult; /* Interim result */
20943 int csrApp; /* Function cursor (used by min/max) */
20944 int regApp; /* Function register (also used by min/max) */
20945 int regPart; /* Array of registers for PARTITION BY values */
20946 Expr *pOwner; /* Expression object this window is attached to */
20947 int nBufferCol; /* Number of columns in buffer table */
20948 int iArgCol; /* Offset of first argument for this function */
20949 int regOne; /* Register containing constant value 1 */
20950 int regStartRowid;
20951 int regEndRowid;
20952 u8 bExprArgs; /* Defer evaluation of window function arguments
20953 ** due to the SQLITE_SUBTYPE flag */
20954};
20955
20956SQLITE_PRIVATEstatic Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow);
20957SQLITE_PRIVATEstatic void sqlite3MultiValuesEnd(Parse *pParse, Select *pVal);
20958
20959#ifndef SQLITE_OMIT_WINDOWFUNC
20960SQLITE_PRIVATEstatic void sqlite3WindowDelete(sqlite3*, Window*);
20961SQLITE_PRIVATEstatic void sqlite3WindowUnlinkFromSelect(Window*);
20962SQLITE_PRIVATEstatic void sqlite3WindowListDelete(sqlite3 *db, Window *p);
20963SQLITE_PRIVATEstatic Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);
20964SQLITE_PRIVATEstatic void sqlite3WindowAttach(Parse*, Expr*, Window*);
20965SQLITE_PRIVATEstatic void sqlite3WindowLink(Select *pSel, Window *pWin);
20966SQLITE_PRIVATEstatic int sqlite3WindowCompare(const Parse*, const Window*, const Window*, int);
20967SQLITE_PRIVATEstatic void sqlite3WindowCodeInit(Parse*, Select*);
20968SQLITE_PRIVATEstatic void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
20969SQLITE_PRIVATEstatic int sqlite3WindowRewrite(Parse*, Select*);
20970SQLITE_PRIVATEstatic void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
20971SQLITE_PRIVATEstatic Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
20972SQLITE_PRIVATEstatic Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
20973SQLITE_PRIVATEstatic void sqlite3WindowFunctions(void);
20974SQLITE_PRIVATEstatic void sqlite3WindowChain(Parse*, Window*, Window*);
20975SQLITE_PRIVATEstatic Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*);
20976#else
20977# define sqlite3WindowDelete(a,b)
20978# define sqlite3WindowFunctions()
20979# define sqlite3WindowAttach(a,b,c)
20980#endif
20981
20982/*
20983** Assuming zIn points to the first byte of a UTF-8 character,
20984** advance zIn to point to the first byte of the next UTF-8 character.
20985*/
20986#define SQLITE_SKIP_UTF8(zIn){ if( (*(zIn++))>=0xc0 ){ while( (*zIn & 0xc0)==0x80 )
{ zIn++; } } }
{ \
20987 if( (*(zIn++))>=0xc0 ){ \
20988 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
20989 } \
20990}
20991
20992/*
20993** The SQLITE_*_BKPT macros are substitutes for the error codes with
20994** the same name but without the _BKPT suffix. These macros invoke
20995** routines that report the line-number on which the error originated
20996** using sqlite3_log(). The routines also provide a convenient place
20997** to set a debugger breakpoint.
20998*/
20999SQLITE_PRIVATEstatic int sqlite3ReportError(int iErr, int lineno, const char *zType);
21000SQLITE_PRIVATEstatic int sqlite3CorruptError(int);
21001SQLITE_PRIVATEstatic int sqlite3MisuseError(int);
21002SQLITE_PRIVATEstatic int sqlite3CantopenError(int);
21003#define SQLITE_CORRUPT_BKPTsqlite3CorruptError(21003) sqlite3CorruptError(__LINE__21003)
21004#define SQLITE_MISUSE_BKPTsqlite3MisuseError(21004) sqlite3MisuseError(__LINE__21004)
21005#define SQLITE_CANTOPEN_BKPTsqlite3CantopenError(21005) sqlite3CantopenError(__LINE__21005)
21006#ifdef SQLITE_DEBUG
21007SQLITE_PRIVATEstatic int sqlite3NomemError(int);
21008SQLITE_PRIVATEstatic int sqlite3IoerrnomemError(int);
21009# define SQLITE_NOMEM_BKPT7 sqlite3NomemError(__LINE__21009)
21010# define SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)) sqlite3IoerrnomemError(__LINE__21010)
21011#else
21012# define SQLITE_NOMEM_BKPT7 SQLITE_NOMEM7
21013# define SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)) SQLITE_IOERR_NOMEM(10 | (12<<8))
21014#endif
21015#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
21016SQLITE_PRIVATEstatic int sqlite3CorruptPgnoError(int,Pgno);
21017# define SQLITE_CORRUPT_PGNO(P)sqlite3CorruptError(21017) sqlite3CorruptPgnoError(__LINE__21017,(P))
21018#else
21019# define SQLITE_CORRUPT_PGNO(P)sqlite3CorruptError(21019) sqlite3CorruptError(__LINE__21019)
21020#endif
21021
21022/*
21023** FTS3 and FTS4 both require virtual table support
21024*/
21025#if defined(SQLITE_OMIT_VIRTUALTABLE)
21026# undef SQLITE_ENABLE_FTS31
21027# undef SQLITE_ENABLE_FTS41
21028#endif
21029
21030/*
21031** FTS4 is really an extension for FTS3. It is enabled using the
21032** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
21033** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
21034*/
21035#if defined(SQLITE_ENABLE_FTS41) && !defined(SQLITE_ENABLE_FTS31)
21036# define SQLITE_ENABLE_FTS31 1
21037#endif
21038
21039/*
21040** The following macros mimic the standard library functions toupper(),
21041** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
21042** sqlite versions only work for ASCII characters, regardless of locale.
21043*/
21044#ifdef SQLITE_ASCII1
21045# define sqlite3Toupper(x)((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20)) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
21046# define sqlite3Isspace(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x01) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
21047# define sqlite3Isalnum(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x06) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
21048# define sqlite3Isalpha(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x02) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
21049# define sqlite3Isdigit(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x04) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
21050# define sqlite3Isxdigit(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x08) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
21051# define sqlite3Tolower(x)(sqlite3UpperToLower[(unsigned char)(x)]) (sqlite3UpperToLower[(unsigned char)(x)])
21052# define sqlite3Isquote(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x80) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
21053# define sqlite3JsonId1(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x42) (sqlite3CtypeMap[(unsigned char)(x)]&0x42)
21054# define sqlite3JsonId2(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x46) (sqlite3CtypeMap[(unsigned char)(x)]&0x46)
21055#else
21056# define sqlite3Toupper(x)((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20)) toupper((unsigned char)(x))(__extension__ ({ int __res; if (sizeof ((unsigned char)(x)) >
1) { if (__builtin_constant_p ((unsigned char)(x))) { int __c
= ((unsigned char)(x)); __res = __c < -128 || __c > 255
? __c : (*__ctype_toupper_loc ())[__c]; } else __res = toupper
((unsigned char)(x)); } else __res = (*__ctype_toupper_loc (
))[(int) ((unsigned char)(x))]; __res; }))
21057# define sqlite3Isspace(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x01) isspace((unsigned char)(x))((*__ctype_b_loc ())[(int) (((unsigned char)(x)))] & (unsigned
short int) _ISspace)
21058# define sqlite3Isalnum(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x06) isalnum((unsigned char)(x))((*__ctype_b_loc ())[(int) (((unsigned char)(x)))] & (unsigned
short int) _ISalnum)
21059# define sqlite3Isalpha(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x02) isalpha((unsigned char)(x))((*__ctype_b_loc ())[(int) (((unsigned char)(x)))] & (unsigned
short int) _ISalpha)
21060# define sqlite3Isdigit(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x04) isdigit((unsigned char)(x))((*__ctype_b_loc ())[(int) (((unsigned char)(x)))] & (unsigned
short int) _ISdigit)
21061# define sqlite3Isxdigit(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x08) isxdigit((unsigned char)(x))((*__ctype_b_loc ())[(int) (((unsigned char)(x)))] & (unsigned
short int) _ISxdigit)
21062# define sqlite3Tolower(x)(sqlite3UpperToLower[(unsigned char)(x)]) tolower((unsigned char)(x))(__extension__ ({ int __res; if (sizeof ((unsigned char)(x)) >
1) { if (__builtin_constant_p ((unsigned char)(x))) { int __c
= ((unsigned char)(x)); __res = __c < -128 || __c > 255
? __c : (*__ctype_tolower_loc ())[__c]; } else __res = tolower
((unsigned char)(x)); } else __res = (*__ctype_tolower_loc (
))[(int) ((unsigned char)(x))]; __res; }))
21063# define sqlite3Isquote(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x80) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
21064# define sqlite3JsonId1(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x42) (sqlite3IsIdChar(x)&&(x)<'0')
21065# define sqlite3JsonId2(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x46) sqlite3IsIdChar(x)
21066#endif
21067SQLITE_PRIVATEstatic int sqlite3IsIdChar(u8);
21068
21069/*
21070** Internal function prototypes
21071*/
21072SQLITE_PRIVATEstatic int sqlite3StrICmp(const char*,const char*);
21073SQLITE_PRIVATEstatic int sqlite3Strlen30(const char*);
21074#define sqlite3Strlen30NN(C)(strlen(C)&0x3fffffff) (strlen(C)&0x3fffffff)
21075SQLITE_PRIVATEstatic char *sqlite3ColumnType(Column*,char*);
21076#define sqlite3StrNICmpsqlite3_strnicmp sqlite3_strnicmp
21077
21078SQLITE_PRIVATEstatic int sqlite3MallocInit(void);
21079SQLITE_PRIVATEstatic void sqlite3MallocEnd(void);
21080SQLITE_PRIVATEstatic void *sqlite3Malloc(u64);
21081SQLITE_PRIVATEstatic void *sqlite3MallocZero(u64);
21082SQLITE_PRIVATEstatic void *sqlite3DbMallocZero(sqlite3*, u64);
21083SQLITE_PRIVATEstatic void *sqlite3DbMallocRaw(sqlite3*, u64);
21084SQLITE_PRIVATEstatic void *sqlite3DbMallocRawNN(sqlite3*, u64);
21085SQLITE_PRIVATEstatic char *sqlite3DbStrDup(sqlite3*,const char*);
21086SQLITE_PRIVATEstatic char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
21087SQLITE_PRIVATEstatic char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
21088SQLITE_PRIVATEstatic void *sqlite3Realloc(void*, u64);
21089SQLITE_PRIVATEstatic void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
21090SQLITE_PRIVATEstatic void *sqlite3DbRealloc(sqlite3 *, void *, u64);
21091SQLITE_PRIVATEstatic void sqlite3DbFree(sqlite3*, void*);
21092SQLITE_PRIVATEstatic void sqlite3DbFreeNN(sqlite3*, void*);
21093SQLITE_PRIVATEstatic void sqlite3DbNNFreeNN(sqlite3*, void*);
21094SQLITE_PRIVATEstatic int sqlite3MallocSize(const void*);
21095SQLITE_PRIVATEstatic int sqlite3DbMallocSize(sqlite3*, const void*);
21096SQLITE_PRIVATEstatic void *sqlite3PageMalloc(int);
21097SQLITE_PRIVATEstatic void sqlite3PageFree(void*);
21098SQLITE_PRIVATEstatic void sqlite3MemSetDefault(void);
21099#ifndef SQLITE_UNTESTABLE
21100SQLITE_PRIVATEstatic void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
21101#endif
21102SQLITE_PRIVATEstatic int sqlite3HeapNearlyFull(void);
21103
21104/*
21105** On systems with ample stack space and that support alloca(), make
21106** use of alloca() to obtain space for large automatic objects. By default,
21107** obtain space from malloc().
21108**
21109** The alloca() routine never returns NULL. This will cause code paths
21110** that deal with sqlite3StackAlloc() failures to be unreachable.
21111*/
21112#ifdef SQLITE_USE_ALLOCA
21113# define sqlite3StackAllocRaw(D,N)sqlite3DbMallocRaw(D,N) alloca(N)__builtin_alloca (N)
21114# define sqlite3StackAllocRawNN(D,N)sqlite3DbMallocRawNN(D,N) alloca(N)__builtin_alloca (N)
21115# define sqlite3StackFree(D,P)sqlite3DbFree(D,P)
21116# define sqlite3StackFreeNN(D,P)sqlite3DbFreeNN(D,P)
21117#else
21118# define sqlite3StackAllocRaw(D,N)sqlite3DbMallocRaw(D,N) sqlite3DbMallocRaw(D,N)
21119# define sqlite3StackAllocRawNN(D,N)sqlite3DbMallocRawNN(D,N) sqlite3DbMallocRawNN(D,N)
21120# define sqlite3StackFree(D,P)sqlite3DbFree(D,P) sqlite3DbFree(D,P)
21121# define sqlite3StackFreeNN(D,P)sqlite3DbFreeNN(D,P) sqlite3DbFreeNN(D,P)
21122#endif
21123
21124/* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
21125** are, disable MEMSYS3
21126*/
21127#ifdef SQLITE_ENABLE_MEMSYS5
21128SQLITE_PRIVATEstatic const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
21129#undef SQLITE_ENABLE_MEMSYS3
21130#endif
21131#ifdef SQLITE_ENABLE_MEMSYS3
21132SQLITE_PRIVATEstatic const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
21133#endif
21134
21135
21136#ifndef SQLITE_MUTEX_OMIT
21137SQLITE_PRIVATEstatic sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
21138SQLITE_PRIVATEstatic sqlite3_mutex_methods const *sqlite3NoopMutex(void);
21139SQLITE_PRIVATEstatic sqlite3_mutex *sqlite3MutexAlloc(int);
21140SQLITE_PRIVATEstatic int sqlite3MutexInit(void);
21141SQLITE_PRIVATEstatic int sqlite3MutexEnd(void);
21142#endif
21143#if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
21144SQLITE_PRIVATEstatic void sqlite3MemoryBarrier(void);
21145#else
21146# define sqlite3MemoryBarrier()
21147#endif
21148
21149SQLITE_PRIVATEstatic sqlite3_int64 sqlite3StatusValue(int);
21150SQLITE_PRIVATEstatic void sqlite3StatusUp(int, int);
21151SQLITE_PRIVATEstatic void sqlite3StatusDown(int, int);
21152SQLITE_PRIVATEstatic void sqlite3StatusHighwater(int, int);
21153SQLITE_PRIVATEstatic int sqlite3LookasideUsed(sqlite3*,int*);
21154
21155/* Access to mutexes used by sqlite3_status() */
21156SQLITE_PRIVATEstatic sqlite3_mutex *sqlite3Pcache1Mutex(void);
21157SQLITE_PRIVATEstatic sqlite3_mutex *sqlite3MallocMutex(void);
21158
21159#if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
21160SQLITE_PRIVATEstatic void sqlite3MutexWarnOnContention(sqlite3_mutex*);
21161#else
21162# define sqlite3MutexWarnOnContention(x)
21163#endif
21164
21165#ifndef SQLITE_OMIT_FLOATING_POINT
21166# define EXP754(((u64)0x7ff)<<52) (((u64)0x7ff)<<52)
21167# define MAN754((((u64)1)<<52)-1) ((((u64)1)<<52)-1)
21168# define IsNaN(X)(((X)&(((u64)0x7ff)<<52))==(((u64)0x7ff)<<52)
&& ((X)&((((u64)1)<<52)-1))!=0)
(((X)&EXP754(((u64)0x7ff)<<52))==EXP754(((u64)0x7ff)<<52) && ((X)&MAN754((((u64)1)<<52)-1))!=0)
21169# define IsOvfl(X)(((X)&(((u64)0x7ff)<<52))==(((u64)0x7ff)<<52)
)
(((X)&EXP754(((u64)0x7ff)<<52))==EXP754(((u64)0x7ff)<<52))
21170SQLITE_PRIVATEstatic int sqlite3IsNaN(double);
21171SQLITE_PRIVATEstatic int sqlite3IsOverflow(double);
21172#else
21173# define IsNaN(X)(((X)&(((u64)0x7ff)<<52))==(((u64)0x7ff)<<52)
&& ((X)&((((u64)1)<<52)-1))!=0)
0
21174# define sqlite3IsNaN(X) 0
21175# define sqlite3IsOVerflow(X) 0
21176#endif
21177
21178/*
21179** An instance of the following structure holds information about SQL
21180** functions arguments that are the parameters to the printf() function.
21181*/
21182struct PrintfArguments {
21183 int nArg; /* Total number of arguments */
21184 int nUsed; /* Number of arguments used so far */
21185 sqlite3_value **apArg; /* The argument values */
21186};
21187
21188/*
21189** An instance of this object receives the decoding of a floating point
21190** value into an approximate decimal representation.
21191*/
21192struct FpDecode {
21193 char sign; /* '+' or '-' */
21194 char isSpecial; /* 1: Infinity 2: NaN */
21195 int n; /* Significant digits in the decode */
21196 int iDP; /* Location of the decimal point */
21197 char *z; /* Start of significant digits */
21198 char zBuf[24]; /* Storage for significant digits */
21199};
21200
21201SQLITE_PRIVATEstatic void sqlite3FpDecode(FpDecode*,double,int,int);
21202SQLITE_PRIVATEstatic char *sqlite3MPrintf(sqlite3*,const char*, ...);
21203SQLITE_PRIVATEstatic char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
21204#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
21205SQLITE_PRIVATEstatic void sqlite3DebugPrintf(const char*, ...);
21206#endif
21207#if defined(SQLITE_TEST)
21208SQLITE_PRIVATEstatic void *sqlite3TestTextToPtr(const char*);
21209#endif
21210
21211#if defined(SQLITE_DEBUG)
21212SQLITE_PRIVATEstatic void sqlite3TreeViewLine(TreeView*, const char *zFormat, ...);
21213SQLITE_PRIVATEstatic void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
21214SQLITE_PRIVATEstatic void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
21215SQLITE_PRIVATEstatic void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
21216SQLITE_PRIVATEstatic void sqlite3TreeViewBareIdList(TreeView*, const IdList*, const char*);
21217SQLITE_PRIVATEstatic void sqlite3TreeViewIdList(TreeView*, const IdList*, u8, const char*);
21218SQLITE_PRIVATEstatic void sqlite3TreeViewColumnList(TreeView*, const Column*, int, u8);
21219SQLITE_PRIVATEstatic void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
21220SQLITE_PRIVATEstatic void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
21221SQLITE_PRIVATEstatic void sqlite3TreeViewWith(TreeView*, const With*, u8);
21222SQLITE_PRIVATEstatic void sqlite3TreeViewUpsert(TreeView*, const Upsert*, u8);
21223#if TREETRACE_ENABLED0
21224SQLITE_PRIVATEstatic void sqlite3TreeViewDelete(const With*, const SrcList*, const Expr*,
21225 const ExprList*,const Expr*, const Trigger*);
21226SQLITE_PRIVATEstatic void sqlite3TreeViewInsert(const With*, const SrcList*,
21227 const IdList*, const Select*, const ExprList*,
21228 int, const Upsert*, const Trigger*);
21229SQLITE_PRIVATEstatic void sqlite3TreeViewUpdate(const With*, const SrcList*, const ExprList*,
21230 const Expr*, int, const ExprList*, const Expr*,
21231 const Upsert*, const Trigger*);
21232#endif
21233#ifndef SQLITE_OMIT_TRIGGER
21234SQLITE_PRIVATEstatic void sqlite3TreeViewTriggerStep(TreeView*, const TriggerStep*, u8, u8);
21235SQLITE_PRIVATEstatic void sqlite3TreeViewTrigger(TreeView*, const Trigger*, u8, u8);
21236#endif
21237#ifndef SQLITE_OMIT_WINDOWFUNC
21238SQLITE_PRIVATEstatic void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
21239SQLITE_PRIVATEstatic void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
21240#endif
21241SQLITE_PRIVATEstatic void sqlite3ShowExpr(const Expr*);
21242SQLITE_PRIVATEstatic void sqlite3ShowExprList(const ExprList*);
21243SQLITE_PRIVATEstatic void sqlite3ShowIdList(const IdList*);
21244SQLITE_PRIVATEstatic void sqlite3ShowSrcList(const SrcList*);
21245SQLITE_PRIVATEstatic void sqlite3ShowSelect(const Select*);
21246SQLITE_PRIVATEstatic void sqlite3ShowWith(const With*);
21247SQLITE_PRIVATEstatic void sqlite3ShowUpsert(const Upsert*);
21248#ifndef SQLITE_OMIT_TRIGGER
21249SQLITE_PRIVATEstatic void sqlite3ShowTriggerStep(const TriggerStep*);
21250SQLITE_PRIVATEstatic void sqlite3ShowTriggerStepList(const TriggerStep*);
21251SQLITE_PRIVATEstatic void sqlite3ShowTrigger(const Trigger*);
21252SQLITE_PRIVATEstatic void sqlite3ShowTriggerList(const Trigger*);
21253#endif
21254#ifndef SQLITE_OMIT_WINDOWFUNC
21255SQLITE_PRIVATEstatic void sqlite3ShowWindow(const Window*);
21256SQLITE_PRIVATEstatic void sqlite3ShowWinFunc(const Window*);
21257#endif
21258#endif
21259
21260SQLITE_PRIVATEstatic void sqlite3SetString(char **, sqlite3*, const char*);
21261SQLITE_PRIVATEstatic void sqlite3ProgressCheck(Parse*);
21262SQLITE_PRIVATEstatic void sqlite3ErrorMsg(Parse*, const char*, ...);
21263SQLITE_PRIVATEstatic int sqlite3ErrorToParser(sqlite3*,int);
21264SQLITE_PRIVATEstatic void sqlite3Dequote(char*);
21265SQLITE_PRIVATEstatic void sqlite3DequoteExpr(Expr*);
21266SQLITE_PRIVATEstatic void sqlite3DequoteToken(Token*);
21267SQLITE_PRIVATEstatic void sqlite3DequoteNumber(Parse*, Expr*);
21268SQLITE_PRIVATEstatic void sqlite3TokenInit(Token*,char*);
21269SQLITE_PRIVATEstatic int sqlite3KeywordCode(const unsigned char*, int);
21270SQLITE_PRIVATEstatic int sqlite3RunParser(Parse*, const char*);
21271SQLITE_PRIVATEstatic void sqlite3FinishCoding(Parse*);
21272SQLITE_PRIVATEstatic int sqlite3GetTempReg(Parse*);
21273SQLITE_PRIVATEstatic void sqlite3ReleaseTempReg(Parse*,int);
21274SQLITE_PRIVATEstatic int sqlite3GetTempRange(Parse*,int);
21275SQLITE_PRIVATEstatic void sqlite3ReleaseTempRange(Parse*,int,int);
21276SQLITE_PRIVATEstatic void sqlite3ClearTempRegCache(Parse*);
21277SQLITE_PRIVATEstatic void sqlite3TouchRegister(Parse*,int);
21278#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
21279SQLITE_PRIVATEstatic int sqlite3FirstAvailableRegister(Parse*,int);
21280#endif
21281#ifdef SQLITE_DEBUG
21282SQLITE_PRIVATEstatic int sqlite3NoTempsInRange(Parse*,int,int);
21283#endif
21284SQLITE_PRIVATEstatic Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
21285SQLITE_PRIVATEstatic Expr *sqlite3Expr(sqlite3*,int,const char*);
21286SQLITE_PRIVATEstatic void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
21287SQLITE_PRIVATEstatic Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
21288SQLITE_PRIVATEstatic void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
21289SQLITE_PRIVATEstatic Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);
21290SQLITE_PRIVATEstatic Expr *sqlite3ExprSimplifiedAndOr(Expr*);
21291SQLITE_PRIVATEstatic Expr *sqlite3ExprFunction(Parse*,ExprList*, const Token*, int);
21292SQLITE_PRIVATEstatic void sqlite3ExprAddFunctionOrderBy(Parse*,Expr*,ExprList*);
21293SQLITE_PRIVATEstatic void sqlite3ExprOrderByAggregateError(Parse*,Expr*);
21294SQLITE_PRIVATEstatic void sqlite3ExprFunctionUsable(Parse*,const Expr*,const FuncDef*);
21295SQLITE_PRIVATEstatic void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
21296SQLITE_PRIVATEstatic void sqlite3ExprDelete(sqlite3*, Expr*);
21297SQLITE_PRIVATEstatic void sqlite3ExprDeleteGeneric(sqlite3*,void*);
21298SQLITE_PRIVATEstatic int sqlite3ExprDeferredDelete(Parse*, Expr*);
21299SQLITE_PRIVATEstatic void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
21300SQLITE_PRIVATEstatic ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
21301SQLITE_PRIVATEstatic ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
21302SQLITE_PRIVATEstatic Select *sqlite3ExprListToValues(Parse*, int, ExprList*);
21303SQLITE_PRIVATEstatic void sqlite3ExprListSetSortOrder(ExprList*,int,int);
21304SQLITE_PRIVATEstatic void sqlite3ExprListSetName(Parse*,ExprList*,const Token*,int);
21305SQLITE_PRIVATEstatic void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
21306SQLITE_PRIVATEstatic void sqlite3ExprListDelete(sqlite3*, ExprList*);
21307SQLITE_PRIVATEstatic void sqlite3ExprListDeleteGeneric(sqlite3*,void*);
21308SQLITE_PRIVATEstatic u32 sqlite3ExprListFlags(const ExprList*);
21309SQLITE_PRIVATEstatic int sqlite3IndexHasDuplicateRootPage(Index*);
21310SQLITE_PRIVATEstatic int sqlite3Init(sqlite3*, char**);
21311SQLITE_PRIVATEstatic int sqlite3InitCallback(void*, int, char**, char**);
21312SQLITE_PRIVATEstatic int sqlite3InitOne(sqlite3*, int, char**, u32);
21313SQLITE_PRIVATEstatic void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
21314#ifndef SQLITE_OMIT_VIRTUALTABLE
21315SQLITE_PRIVATEstatic Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
21316#endif
21317SQLITE_PRIVATEstatic void sqlite3ResetAllSchemasOfConnection(sqlite3*);
21318SQLITE_PRIVATEstatic void sqlite3ResetOneSchema(sqlite3*,int);
21319SQLITE_PRIVATEstatic void sqlite3CollapseDatabaseArray(sqlite3*);
21320SQLITE_PRIVATEstatic void sqlite3CommitInternalChanges(sqlite3*);
21321SQLITE_PRIVATEstatic void sqlite3ColumnSetExpr(Parse*,Table*,Column*,Expr*);
21322SQLITE_PRIVATEstatic Expr *sqlite3ColumnExpr(Table*,Column*);
21323SQLITE_PRIVATEstatic void sqlite3ColumnSetColl(sqlite3*,Column*,const char*zColl);
21324SQLITE_PRIVATEstatic const char *sqlite3ColumnColl(Column*);
21325SQLITE_PRIVATEstatic void sqlite3DeleteColumnNames(sqlite3*,Table*);
21326SQLITE_PRIVATEstatic void sqlite3GenerateColumnNames(Parse *pParse, Select *pSelect);
21327SQLITE_PRIVATEstatic int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
21328SQLITE_PRIVATEstatic void sqlite3SubqueryColumnTypes(Parse*,Table*,Select*,char);
21329SQLITE_PRIVATEstatic Table *sqlite3ResultSetOfSelect(Parse*,Select*,char);
21330SQLITE_PRIVATEstatic void sqlite3OpenSchemaTable(Parse *, int);
21331SQLITE_PRIVATEstatic Index *sqlite3PrimaryKeyIndex(Table*);
21332SQLITE_PRIVATEstatic int sqlite3TableColumnToIndex(Index*, int);
21333#ifdef SQLITE_OMIT_GENERATED_COLUMNS
21334# define sqlite3TableColumnToStorage(T,X) (X) /* No-op pass-through */
21335# define sqlite3StorageColumnToTable(T,X) (X) /* No-op pass-through */
21336#else
21337SQLITE_PRIVATEstatic i16 sqlite3TableColumnToStorage(Table*, i16);
21338SQLITE_PRIVATEstatic i16 sqlite3StorageColumnToTable(Table*, i16);
21339#endif
21340SQLITE_PRIVATEstatic void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
21341#if SQLITE_ENABLE_HIDDEN_COLUMNS
21342SQLITE_PRIVATEstatic void sqlite3ColumnPropertiesFromName(Table*, Column*);
21343#else
21344# define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
21345#endif
21346SQLITE_PRIVATEstatic void sqlite3AddColumn(Parse*,Token,Token);
21347SQLITE_PRIVATEstatic void sqlite3AddNotNull(Parse*, int);
21348SQLITE_PRIVATEstatic void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
21349SQLITE_PRIVATEstatic void sqlite3AddCheckConstraint(Parse*, Expr*, const char*, const char*);
21350SQLITE_PRIVATEstatic void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
21351SQLITE_PRIVATEstatic void sqlite3AddCollateType(Parse*, Token*);
21352SQLITE_PRIVATEstatic void sqlite3AddGenerated(Parse*,Expr*,Token*);
21353SQLITE_PRIVATEstatic void sqlite3EndTable(Parse*,Token*,Token*,u32,Select*);
21354SQLITE_PRIVATEstatic void sqlite3AddReturning(Parse*,ExprList*);
21355SQLITE_PRIVATEstatic int sqlite3ParseUri(const char*,const char*,unsigned int*,
21356 sqlite3_vfs**,char**,char **);
21357#define sqlite3CodecQueryParameters(A,B,C)0 0
21358SQLITE_PRIVATEstatic Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
21359
21360#ifdef SQLITE_UNTESTABLE
21361# define sqlite3FaultSim(X) SQLITE_OK0
21362#else
21363SQLITE_PRIVATEstatic int sqlite3FaultSim(int);
21364#endif
21365
21366SQLITE_PRIVATEstatic Bitvec *sqlite3BitvecCreate(u32);
21367SQLITE_PRIVATEstatic int sqlite3BitvecTest(Bitvec*, u32);
21368SQLITE_PRIVATEstatic int sqlite3BitvecTestNotNull(Bitvec*, u32);
21369SQLITE_PRIVATEstatic int sqlite3BitvecSet(Bitvec*, u32);
21370SQLITE_PRIVATEstatic void sqlite3BitvecClear(Bitvec*, u32, void*);
21371SQLITE_PRIVATEstatic void sqlite3BitvecDestroy(Bitvec*);
21372SQLITE_PRIVATEstatic u32 sqlite3BitvecSize(Bitvec*);
21373#ifndef SQLITE_UNTESTABLE
21374SQLITE_PRIVATEstatic int sqlite3BitvecBuiltinTest(int,int*);
21375#endif
21376
21377SQLITE_PRIVATEstatic RowSet *sqlite3RowSetInit(sqlite3*);
21378SQLITE_PRIVATEstatic void sqlite3RowSetDelete(void*);
21379SQLITE_PRIVATEstatic void sqlite3RowSetClear(void*);
21380SQLITE_PRIVATEstatic void sqlite3RowSetInsert(RowSet*, i64);
21381SQLITE_PRIVATEstatic int sqlite3RowSetTest(RowSet*, int iBatch, i64);
21382SQLITE_PRIVATEstatic int sqlite3RowSetNext(RowSet*, i64*);
21383
21384SQLITE_PRIVATEstatic void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
21385
21386#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
21387SQLITE_PRIVATEstatic int sqlite3ViewGetColumnNames(Parse*,Table*);
21388#else
21389# define sqlite3ViewGetColumnNames(A,B) 0
21390#endif
21391
21392#if SQLITE_MAX_ATTACHED10>30
21393SQLITE_PRIVATEstatic int sqlite3DbMaskAllZero(yDbMask);
21394#endif
21395SQLITE_PRIVATEstatic void sqlite3DropTable(Parse*, SrcList*, int, int);
21396SQLITE_PRIVATEstatic void sqlite3CodeDropTable(Parse*, Table*, int, int);
21397SQLITE_PRIVATEstatic void sqlite3DeleteTable(sqlite3*, Table*);
21398SQLITE_PRIVATEstatic void sqlite3DeleteTableGeneric(sqlite3*, void*);
21399SQLITE_PRIVATEstatic void sqlite3FreeIndex(sqlite3*, Index*);
21400#ifndef SQLITE_OMIT_AUTOINCREMENT
21401SQLITE_PRIVATEstatic void sqlite3AutoincrementBegin(Parse *pParse);
21402SQLITE_PRIVATEstatic void sqlite3AutoincrementEnd(Parse *pParse);
21403#else
21404# define sqlite3AutoincrementBegin(X)
21405# define sqlite3AutoincrementEnd(X)
21406#endif
21407SQLITE_PRIVATEstatic void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
21408#ifndef SQLITE_OMIT_GENERATED_COLUMNS
21409SQLITE_PRIVATEstatic void sqlite3ComputeGeneratedColumns(Parse*, int, Table*);
21410#endif
21411SQLITE_PRIVATEstatic void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
21412SQLITE_PRIVATEstatic IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
21413SQLITE_PRIVATEstatic int sqlite3IdListIndex(IdList*,const char*);
21414SQLITE_PRIVATEstatic SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);
21415SQLITE_PRIVATEstatic SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2);
21416SQLITE_PRIVATEstatic SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);
21417SQLITE_PRIVATEstatic void sqlite3SubqueryDelete(sqlite3*,Subquery*);
21418SQLITE_PRIVATEstatic Select *sqlite3SubqueryDetach(sqlite3*,SrcItem*);
21419SQLITE_PRIVATEstatic int sqlite3SrcItemAttachSubquery(Parse*, SrcItem*, Select*, int);
21420SQLITE_PRIVATEstatic SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
21421 Token*, Select*, OnOrUsing*);
21422SQLITE_PRIVATEstatic void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
21423SQLITE_PRIVATEstatic void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
21424SQLITE_PRIVATEstatic int sqlite3IndexedByLookup(Parse *, SrcItem *);
21425SQLITE_PRIVATEstatic void sqlite3SrcListShiftJoinType(Parse*,SrcList*);
21426SQLITE_PRIVATEstatic void sqlite3SrcListAssignCursors(Parse*, SrcList*);
21427SQLITE_PRIVATEstatic void sqlite3IdListDelete(sqlite3*, IdList*);
21428SQLITE_PRIVATEstatic void sqlite3ClearOnOrUsing(sqlite3*, OnOrUsing*);
21429SQLITE_PRIVATEstatic void sqlite3SrcListDelete(sqlite3*, SrcList*);
21430SQLITE_PRIVATEstatic Index *sqlite3AllocateIndexObject(sqlite3*,int,int,char**);
21431SQLITE_PRIVATEstatic void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
21432 Expr*, int, int, u8);
21433SQLITE_PRIVATEstatic void sqlite3DropIndex(Parse*, SrcList*, int);
21434SQLITE_PRIVATEstatic int sqlite3Select(Parse*, Select*, SelectDest*);
21435SQLITE_PRIVATEstatic Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
21436 Expr*,ExprList*,u32,Expr*);
21437SQLITE_PRIVATEstatic void sqlite3SelectDelete(sqlite3*, Select*);
21438SQLITE_PRIVATEstatic void sqlite3SelectDeleteGeneric(sqlite3*,void*);
21439SQLITE_PRIVATEstatic Table *sqlite3SrcListLookup(Parse*, SrcList*);
21440SQLITE_PRIVATEstatic int sqlite3IsReadOnly(Parse*, Table*, Trigger*);
21441SQLITE_PRIVATEstatic void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
21442#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT1) && !defined(SQLITE_OMIT_SUBQUERY)
21443SQLITE_PRIVATEstatic Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
21444#endif
21445SQLITE_PRIVATEstatic void sqlite3CodeChangeCount(Vdbe*,int,const char*);
21446SQLITE_PRIVATEstatic void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
21447SQLITE_PRIVATEstatic void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
21448 Upsert*);
21449SQLITE_PRIVATEstatic WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,
21450 ExprList*,Select*,u16,int);
21451SQLITE_PRIVATEstatic void sqlite3WhereEnd(WhereInfo*);
21452SQLITE_PRIVATEstatic LogEst sqlite3WhereOutputRowCount(WhereInfo*);
21453SQLITE_PRIVATEstatic int sqlite3WhereIsDistinct(WhereInfo*);
21454SQLITE_PRIVATEstatic int sqlite3WhereIsOrdered(WhereInfo*);
21455SQLITE_PRIVATEstatic int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
21456SQLITE_PRIVATEstatic void sqlite3WhereMinMaxOptEarlyOut(Vdbe*,WhereInfo*);
21457SQLITE_PRIVATEstatic int sqlite3WhereIsSorted(WhereInfo*);
21458SQLITE_PRIVATEstatic int sqlite3WhereContinueLabel(WhereInfo*);
21459SQLITE_PRIVATEstatic int sqlite3WhereBreakLabel(WhereInfo*);
21460SQLITE_PRIVATEstatic int sqlite3WhereOkOnePass(WhereInfo*, int*);
21461#define ONEPASS_OFF0 0 /* Use of ONEPASS not allowed */
21462#define ONEPASS_SINGLE1 1 /* ONEPASS valid for a single row update */
21463#define ONEPASS_MULTI2 2 /* ONEPASS is valid for multiple rows */
21464SQLITE_PRIVATEstatic int sqlite3WhereUsesDeferredSeek(WhereInfo*);
21465SQLITE_PRIVATEstatic void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
21466SQLITE_PRIVATEstatic int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
21467SQLITE_PRIVATEstatic void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
21468SQLITE_PRIVATEstatic void sqlite3ExprCodeMove(Parse*, int, int, int);
21469SQLITE_PRIVATEstatic void sqlite3ExprToRegister(Expr *pExpr, int iReg);
21470SQLITE_PRIVATEstatic void sqlite3ExprCode(Parse*, Expr*, int);
21471#ifndef SQLITE_OMIT_GENERATED_COLUMNS
21472SQLITE_PRIVATEstatic void sqlite3ExprCodeGeneratedColumn(Parse*, Table*, Column*, int);
21473#endif
21474SQLITE_PRIVATEstatic void sqlite3ExprCodeCopy(Parse*, Expr*, int);
21475SQLITE_PRIVATEstatic void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
21476SQLITE_PRIVATEstatic int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);
21477SQLITE_PRIVATEstatic int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
21478SQLITE_PRIVATEstatic int sqlite3ExprCodeTarget(Parse*, Expr*, int);
21479SQLITE_PRIVATEstatic int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
21480#define SQLITE_ECEL_DUP0x01 0x01 /* Deep, not shallow copies */
21481#define SQLITE_ECEL_FACTOR0x02 0x02 /* Factor out constant terms */
21482#define SQLITE_ECEL_REF0x04 0x04 /* Use ExprList.u.x.iOrderByCol */
21483#define SQLITE_ECEL_OMITREF0x08 0x08 /* Omit if ExprList.u.x.iOrderByCol */
21484SQLITE_PRIVATEstatic void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
21485SQLITE_PRIVATEstatic void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
21486SQLITE_PRIVATEstatic void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
21487SQLITE_PRIVATEstatic Table *sqlite3FindTable(sqlite3*,const char*, const char*);
21488#define LOCATE_VIEW0x01 0x01
21489#define LOCATE_NOERR0x02 0x02
21490SQLITE_PRIVATEstatic Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
21491SQLITE_PRIVATEstatic const char *sqlite3PreferredTableName(const char*);
21492SQLITE_PRIVATEstatic Table *sqlite3LocateTableItem(Parse*,u32 flags,SrcItem *);
21493SQLITE_PRIVATEstatic Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
21494SQLITE_PRIVATEstatic void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
21495SQLITE_PRIVATEstatic void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
21496SQLITE_PRIVATEstatic void sqlite3Vacuum(Parse*,Token*,Expr*);
21497SQLITE_PRIVATEstatic int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);
21498SQLITE_PRIVATEstatic char *sqlite3NameFromToken(sqlite3*, const Token*);
21499SQLITE_PRIVATEstatic int sqlite3ExprCompare(const Parse*,const Expr*,const Expr*, int);
21500SQLITE_PRIVATEstatic int sqlite3ExprCompareSkip(Expr*,Expr*,int);
21501SQLITE_PRIVATEstatic int sqlite3ExprListCompare(const ExprList*,const ExprList*, int);
21502SQLITE_PRIVATEstatic int sqlite3ExprImpliesExpr(const Parse*,const Expr*,const Expr*, int);
21503SQLITE_PRIVATEstatic int sqlite3ExprImpliesNonNullRow(Expr*,int,int);
21504SQLITE_PRIVATEstatic void sqlite3AggInfoPersistWalkerInit(Walker*,Parse*);
21505SQLITE_PRIVATEstatic void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
21506SQLITE_PRIVATEstatic void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
21507SQLITE_PRIVATEstatic int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
21508SQLITE_PRIVATEstatic int sqlite3ReferencesSrcList(Parse*, Expr*, SrcList*);
21509SQLITE_PRIVATEstatic Vdbe *sqlite3GetVdbe(Parse*);
21510#ifndef SQLITE_UNTESTABLE
21511SQLITE_PRIVATEstatic void sqlite3PrngSaveState(void);
21512SQLITE_PRIVATEstatic void sqlite3PrngRestoreState(void);
21513#endif
21514SQLITE_PRIVATEstatic void sqlite3RollbackAll(sqlite3*,int);
21515SQLITE_PRIVATEstatic void sqlite3CodeVerifySchema(Parse*, int);
21516SQLITE_PRIVATEstatic void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
21517SQLITE_PRIVATEstatic void sqlite3BeginTransaction(Parse*, int);
21518SQLITE_PRIVATEstatic void sqlite3EndTransaction(Parse*,int);
21519SQLITE_PRIVATEstatic void sqlite3Savepoint(Parse*, int, Token*);
21520SQLITE_PRIVATEstatic void sqlite3CloseSavepoints(sqlite3 *);
21521SQLITE_PRIVATEstatic void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
21522SQLITE_PRIVATEstatic u32 sqlite3IsTrueOrFalse(const char*);
21523SQLITE_PRIVATEstatic int sqlite3ExprIdToTrueFalse(Expr*);
21524SQLITE_PRIVATEstatic int sqlite3ExprTruthValue(const Expr*);
21525SQLITE_PRIVATEstatic int sqlite3ExprIsConstant(Parse*,Expr*);
21526SQLITE_PRIVATEstatic int sqlite3ExprIsConstantOrFunction(Expr*, u8);
21527SQLITE_PRIVATEstatic int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
21528SQLITE_PRIVATEstatic int sqlite3ExprIsSingleTableConstraint(Expr*,const SrcList*,int,int);
21529#ifdef SQLITE_ENABLE_CURSOR_HINTS
21530SQLITE_PRIVATEstatic int sqlite3ExprContainsSubquery(Expr*);
21531#endif
21532SQLITE_PRIVATEstatic int sqlite3ExprIsInteger(const Expr*, int*, Parse*);
21533SQLITE_PRIVATEstatic int sqlite3ExprCanBeNull(const Expr*);
21534SQLITE_PRIVATEstatic int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
21535SQLITE_PRIVATEstatic int sqlite3IsRowid(const char*);
21536SQLITE_PRIVATEstatic const char *sqlite3RowidAlias(Table *pTab);
21537SQLITE_PRIVATEstatic void sqlite3GenerateRowDelete(
21538 Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
21539SQLITE_PRIVATEstatic void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
21540SQLITE_PRIVATEstatic int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
21541SQLITE_PRIVATEstatic void sqlite3ResolvePartIdxLabel(Parse*,int);
21542SQLITE_PRIVATEstatic int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
21543SQLITE_PRIVATEstatic void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
21544 u8,u8,int,int*,int*,Upsert*);
21545#ifdef SQLITE_ENABLE_NULL_TRIM
21546SQLITE_PRIVATEstatic void sqlite3SetMakeRecordP5(Vdbe*,Table*);
21547#else
21548# define sqlite3SetMakeRecordP5(A,B)
21549#endif
21550SQLITE_PRIVATEstatic void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
21551SQLITE_PRIVATEstatic int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
21552SQLITE_PRIVATEstatic void sqlite3BeginWriteOperation(Parse*, int, int);
21553SQLITE_PRIVATEstatic void sqlite3MultiWrite(Parse*);
21554SQLITE_PRIVATEstatic void sqlite3MayAbort(Parse*);
21555SQLITE_PRIVATEstatic void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
21556SQLITE_PRIVATEstatic void sqlite3UniqueConstraint(Parse*, int, Index*);
21557SQLITE_PRIVATEstatic void sqlite3RowidConstraint(Parse*, int, Table*);
21558SQLITE_PRIVATEstatic Expr *sqlite3ExprDup(sqlite3*,const Expr*,int);
21559SQLITE_PRIVATEstatic ExprList *sqlite3ExprListDup(sqlite3*,const ExprList*,int);
21560SQLITE_PRIVATEstatic SrcList *sqlite3SrcListDup(sqlite3*,const SrcList*,int);
21561SQLITE_PRIVATEstatic IdList *sqlite3IdListDup(sqlite3*,const IdList*);
21562SQLITE_PRIVATEstatic Select *sqlite3SelectDup(sqlite3*,const Select*,int);
21563SQLITE_PRIVATEstatic FuncDef *sqlite3FunctionSearch(int,const char*);
21564SQLITE_PRIVATEstatic void sqlite3InsertBuiltinFuncs(FuncDef*,int);
21565SQLITE_PRIVATEstatic FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
21566SQLITE_PRIVATEstatic void sqlite3QuoteValue(StrAccum*,sqlite3_value*,int);
21567SQLITE_PRIVATEstatic int sqlite3AppendOneUtf8Character(char*, u32);
21568SQLITE_PRIVATEstatic void sqlite3RegisterBuiltinFunctions(void);
21569SQLITE_PRIVATEstatic void sqlite3RegisterDateTimeFunctions(void);
21570SQLITE_PRIVATEstatic void sqlite3RegisterJsonFunctions(void);
21571SQLITE_PRIVATEstatic void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
21572#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
21573SQLITE_PRIVATEstatic int sqlite3JsonTableFunctions(sqlite3*);
21574#endif
21575SQLITE_PRIVATEstatic int sqlite3SafetyCheckOk(sqlite3*);
21576SQLITE_PRIVATEstatic int sqlite3SafetyCheckSickOrOk(sqlite3*);
21577SQLITE_PRIVATEstatic void sqlite3ChangeCookie(Parse*, int);
21578SQLITE_PRIVATEstatic With *sqlite3WithDup(sqlite3 *db, With *p);
21579
21580#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
21581SQLITE_PRIVATEstatic void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
21582#endif
21583
21584#ifndef SQLITE_OMIT_TRIGGER
21585SQLITE_PRIVATEstatic void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
21586 Expr*,int, int);
21587SQLITE_PRIVATEstatic void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
21588SQLITE_PRIVATEstatic void sqlite3DropTrigger(Parse*, SrcList*, int);
21589SQLITE_PRIVATEstatic void sqlite3DropTriggerPtr(Parse*, Trigger*);
21590SQLITE_PRIVATEstatic Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
21591SQLITE_PRIVATEstatic Trigger *sqlite3TriggerList(Parse *, Table *);
21592SQLITE_PRIVATEstatic void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
21593 int, int, int);
21594SQLITE_PRIVATEstatic void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
21595 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
21596SQLITE_PRIVATEstatic void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
21597SQLITE_PRIVATEstatic TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
21598 const char*,const char*);
21599SQLITE_PRIVATEstatic TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
21600 Select*,u8,Upsert*,
21601 const char*,const char*);
21602SQLITE_PRIVATEstatic TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,SrcList*,ExprList*,
21603 Expr*, u8, const char*,const char*);
21604SQLITE_PRIVATEstatic TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
21605 const char*,const char*);
21606SQLITE_PRIVATEstatic void sqlite3DeleteTrigger(sqlite3*, Trigger*);
21607SQLITE_PRIVATEstatic void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
21608SQLITE_PRIVATEstatic u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
21609SQLITE_PRIVATEstatic SrcList *sqlite3TriggerStepSrc(Parse*, TriggerStep*);
21610# define sqlite3ParseToplevel(p)((p)->pToplevel ? (p)->pToplevel : (p)) ((p)->pToplevel ? (p)->pToplevel : (p))
21611# define sqlite3IsToplevel(p)((p)->pToplevel==0) ((p)->pToplevel==0)
21612#else
21613# define sqlite3TriggersExist(B,C,D,E,F) 0
21614# define sqlite3DeleteTrigger(A,B)
21615# define sqlite3DropTriggerPtr(A,B)
21616# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
21617# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
21618# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
21619# define sqlite3TriggerList(X, Y) 0
21620# define sqlite3ParseToplevel(p)((p)->pToplevel ? (p)->pToplevel : (p)) p
21621# define sqlite3IsToplevel(p)((p)->pToplevel==0) 1
21622# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
21623# define sqlite3TriggerStepSrc(A,B) 0
21624#endif
21625
21626SQLITE_PRIVATEstatic int sqlite3JoinType(Parse*, Token*, Token*, Token*);
21627SQLITE_PRIVATEstatic int sqlite3ColumnIndex(Table *pTab, const char *zCol);
21628SQLITE_PRIVATEstatic void sqlite3SrcItemColumnUsed(SrcItem*,int);
21629SQLITE_PRIVATEstatic void sqlite3SetJoinExpr(Expr*,int,u32);
21630SQLITE_PRIVATEstatic void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
21631SQLITE_PRIVATEstatic void sqlite3DeferForeignKey(Parse*, int);
21632#ifndef SQLITE_OMIT_AUTHORIZATION
21633SQLITE_PRIVATEstatic void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
21634SQLITE_PRIVATEstatic int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
21635SQLITE_PRIVATEstatic void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
21636SQLITE_PRIVATEstatic void sqlite3AuthContextPop(AuthContext*);
21637SQLITE_PRIVATEstatic int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
21638#else
21639# define sqlite3AuthRead(a,b,c,d)
21640# define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK0
21641# define sqlite3AuthContextPush(a,b,c)
21642# define sqlite3AuthContextPop(a) ((void)(a))
21643#endif
21644SQLITE_PRIVATEstatic int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName);
21645SQLITE_PRIVATEstatic void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
21646SQLITE_PRIVATEstatic void sqlite3Detach(Parse*, Expr*);
21647SQLITE_PRIVATEstatic void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
21648SQLITE_PRIVATEstatic int sqlite3FixSrcList(DbFixer*, SrcList*);
21649SQLITE_PRIVATEstatic int sqlite3FixSelect(DbFixer*, Select*);
21650SQLITE_PRIVATEstatic int sqlite3FixExpr(DbFixer*, Expr*);
21651SQLITE_PRIVATEstatic int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
21652
21653SQLITE_PRIVATEstatic int sqlite3RealSameAsInt(double,sqlite3_int64);
21654SQLITE_PRIVATEstatic i64 sqlite3RealToI64(double);
21655SQLITE_PRIVATEstatic int sqlite3Int64ToText(i64,char*);
21656SQLITE_PRIVATEstatic int sqlite3AtoF(const char *z, double*, int, u8);
21657SQLITE_PRIVATEstatic int sqlite3GetInt32(const char *, int*);
21658SQLITE_PRIVATEstatic int sqlite3GetUInt32(const char*, u32*);
21659SQLITE_PRIVATEstatic int sqlite3Atoi(const char*);
21660#ifndef SQLITE_OMIT_UTF16
21661SQLITE_PRIVATEstatic int sqlite3Utf16ByteLen(const void *pData, int nByte, int nChar);
21662#endif
21663SQLITE_PRIVATEstatic int sqlite3Utf8CharLen(const char *pData, int nByte);
21664SQLITE_PRIVATEstatic u32 sqlite3Utf8Read(const u8**);
21665SQLITE_PRIVATEstatic int sqlite3Utf8ReadLimited(const u8*, int, u32*);
21666SQLITE_PRIVATEstatic LogEst sqlite3LogEst(u64);
21667SQLITE_PRIVATEstatic LogEst sqlite3LogEstAdd(LogEst,LogEst);
21668SQLITE_PRIVATEstatic LogEst sqlite3LogEstFromDouble(double);
21669SQLITE_PRIVATEstatic u64 sqlite3LogEstToInt(LogEst);
21670SQLITE_PRIVATEstatic VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
21671SQLITE_PRIVATEstatic const char *sqlite3VListNumToName(VList*,int);
21672SQLITE_PRIVATEstatic int sqlite3VListNameToNum(VList*,const char*,int);
21673
21674/*
21675** Routines to read and write variable-length integers. These used to
21676** be defined locally, but now we use the varint routines in the util.c
21677** file.
21678*/
21679SQLITE_PRIVATEstatic int sqlite3PutVarint(unsigned char*, u64);
21680SQLITE_PRIVATEstatic u8 sqlite3GetVarint(const unsigned char *, u64 *);
21681SQLITE_PRIVATEstatic u8 sqlite3GetVarint32(const unsigned char *, u32 *);
21682SQLITE_PRIVATEstatic int sqlite3VarintLen(u64 v);
21683
21684/*
21685** The common case is for a varint to be a single byte. They following
21686** macros handle the common case without a procedure call, but then call
21687** the procedure for larger varints.
21688*/
21689#define getVarint32(A,B)(u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32(
(A),(u32 *)&(B)))
\
21690 (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
21691#define getVarint32NR(A,B)B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&(
B))
\
21692 B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&(B))
21693#define putVarint32(A,B)(u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1: sqlite3PutVarint
((A),(B)))
\
21694 (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
21695 sqlite3PutVarint((A),(B)))
21696#define getVarintsqlite3GetVarint sqlite3GetVarint
21697#define putVarintsqlite3PutVarint sqlite3PutVarint
21698
21699
21700SQLITE_PRIVATEstatic const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
21701SQLITE_PRIVATEstatic char *sqlite3TableAffinityStr(sqlite3*,const Table*);
21702SQLITE_PRIVATEstatic void sqlite3TableAffinity(Vdbe*, Table*, int);
21703SQLITE_PRIVATEstatic char sqlite3CompareAffinity(const Expr *pExpr, char aff2);
21704SQLITE_PRIVATEstatic int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity);
21705SQLITE_PRIVATEstatic char sqlite3TableColumnAffinity(const Table*,int);
21706SQLITE_PRIVATEstatic char sqlite3ExprAffinity(const Expr *pExpr);
21707SQLITE_PRIVATEstatic int sqlite3ExprDataType(const Expr *pExpr);
21708SQLITE_PRIVATEstatic int sqlite3Atoi64(const char*, i64*, int, u8);
21709SQLITE_PRIVATEstatic int sqlite3DecOrHexToI64(const char*, i64*);
21710SQLITE_PRIVATEstatic void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
21711SQLITE_PRIVATEstatic void sqlite3Error(sqlite3*,int);
21712SQLITE_PRIVATEstatic void sqlite3ErrorClear(sqlite3*);
21713SQLITE_PRIVATEstatic void sqlite3SystemError(sqlite3*,int);
21714#if !defined(SQLITE_OMIT_BLOB_LITERAL)
21715SQLITE_PRIVATEstatic void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
21716#endif
21717SQLITE_PRIVATEstatic u8 sqlite3HexToInt(int h);
21718SQLITE_PRIVATEstatic int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
21719
21720#if defined(SQLITE_NEED_ERR_NAME)
21721SQLITE_PRIVATEstatic const char *sqlite3ErrName(int);
21722#endif
21723
21724#ifndef SQLITE_OMIT_DESERIALIZE
21725SQLITE_PRIVATEstatic int sqlite3MemdbInit(void);
21726SQLITE_PRIVATEstatic int sqlite3IsMemdb(const sqlite3_vfs*);
21727#else
21728# define sqlite3IsMemdb(X) 0
21729#endif
21730
21731SQLITE_PRIVATEstatic const char *sqlite3ErrStr(int);
21732SQLITE_PRIVATEstatic int sqlite3ReadSchema(Parse *pParse);
21733SQLITE_PRIVATEstatic CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
21734SQLITE_PRIVATEstatic int sqlite3IsBinary(const CollSeq*);
21735SQLITE_PRIVATEstatic CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
21736SQLITE_PRIVATEstatic void sqlite3SetTextEncoding(sqlite3 *db, u8);
21737SQLITE_PRIVATEstatic CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr);
21738SQLITE_PRIVATEstatic CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr);
21739SQLITE_PRIVATEstatic int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*);
21740SQLITE_PRIVATEstatic Expr *sqlite3ExprAddCollateToken(const Parse *pParse, Expr*, const Token*, int);
21741SQLITE_PRIVATEstatic Expr *sqlite3ExprAddCollateString(const Parse*,Expr*,const char*);
21742SQLITE_PRIVATEstatic Expr *sqlite3ExprSkipCollate(Expr*);
21743SQLITE_PRIVATEstatic Expr *sqlite3ExprSkipCollateAndLikely(Expr*);
21744SQLITE_PRIVATEstatic int sqlite3CheckCollSeq(Parse *, CollSeq *);
21745SQLITE_PRIVATEstatic int sqlite3WritableSchema(sqlite3*);
21746SQLITE_PRIVATEstatic int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*);
21747SQLITE_PRIVATEstatic void sqlite3VdbeSetChanges(sqlite3 *, i64);
21748SQLITE_PRIVATEstatic int sqlite3AddInt64(i64*,i64);
21749SQLITE_PRIVATEstatic int sqlite3SubInt64(i64*,i64);
21750SQLITE_PRIVATEstatic int sqlite3MulInt64(i64*,i64);
21751SQLITE_PRIVATEstatic int sqlite3AbsInt32(int);
21752#ifdef SQLITE_ENABLE_8_3_NAMES
21753SQLITE_PRIVATEstatic void sqlite3FileSuffix3(const char*, char*);
21754#else
21755# define sqlite3FileSuffix3(X,Y)
21756#endif
21757SQLITE_PRIVATEstatic u8 sqlite3GetBoolean(const char *z,u8);
21758
21759SQLITE_PRIVATEstatic const void *sqlite3ValueText(sqlite3_value*, u8);
21760SQLITE_PRIVATEstatic int sqlite3ValueIsOfClass(const sqlite3_value*, void(*)(void*));
21761SQLITE_PRIVATEstatic int sqlite3ValueBytes(sqlite3_value*, u8);
21762SQLITE_PRIVATEstatic void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
21763 void(*)(void*));
21764SQLITE_PRIVATEstatic void sqlite3ValueSetNull(sqlite3_value*);
21765SQLITE_PRIVATEstatic void sqlite3ValueFree(sqlite3_value*);
21766#ifndef SQLITE_UNTESTABLE
21767SQLITE_PRIVATEstatic void sqlite3ResultIntReal(sqlite3_context*);
21768#endif
21769SQLITE_PRIVATEstatic sqlite3_value *sqlite3ValueNew(sqlite3 *);
21770#ifndef SQLITE_OMIT_UTF16
21771SQLITE_PRIVATEstatic char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
21772#endif
21773SQLITE_PRIVATEstatic int sqlite3ValueFromExpr(sqlite3 *, const Expr *, u8, u8, sqlite3_value **);
21774SQLITE_PRIVATEstatic void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
21775#ifndef SQLITE_AMALGAMATION1
21776SQLITE_PRIVATEstatic const unsigned char sqlite3OpcodeProperty[];
21777SQLITE_PRIVATEstatic const char sqlite3StrBINARY[];
21778SQLITE_PRIVATEstatic const unsigned char sqlite3StdTypeLen[];
21779SQLITE_PRIVATEstatic const char sqlite3StdTypeAffinity[];
21780SQLITE_PRIVATEstatic const char *sqlite3StdType[];
21781SQLITE_PRIVATEstatic const unsigned char sqlite3UpperToLower[];
21782SQLITE_PRIVATEstatic const unsigned char *sqlite3aLTb;
21783SQLITE_PRIVATEstatic const unsigned char *sqlite3aEQb;
21784SQLITE_PRIVATEstatic const unsigned char *sqlite3aGTb;
21785SQLITE_PRIVATEstatic const unsigned char sqlite3CtypeMap[];
21786SQLITE_PRIVATEstatic SQLITE_WSD struct Sqlite3Config sqlite3Config;
21787SQLITE_PRIVATEstatic FuncDefHash sqlite3BuiltinFunctions;
21788#ifndef SQLITE_OMIT_WSD
21789SQLITE_PRIVATEstatic int sqlite3PendingByte;
21790#endif
21791#endif /* SQLITE_AMALGAMATION */
21792#ifdef VDBE_PROFILE
21793SQLITE_PRIVATEstatic sqlite3_uint64 sqlite3NProfileCnt;
21794#endif
21795SQLITE_PRIVATEstatic void sqlite3RootPageMoved(sqlite3*, int, Pgno, Pgno);
21796SQLITE_PRIVATEstatic void sqlite3Reindex(Parse*, Token*, Token*);
21797SQLITE_PRIVATEstatic void sqlite3AlterFunctions(void);
21798SQLITE_PRIVATEstatic void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
21799SQLITE_PRIVATEstatic void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
21800SQLITE_PRIVATEstatic int sqlite3GetToken(const unsigned char *, int *);
21801SQLITE_PRIVATEstatic void sqlite3NestedParse(Parse*, const char*, ...);
21802SQLITE_PRIVATEstatic void sqlite3ExpirePreparedStatements(sqlite3*, int);
21803SQLITE_PRIVATEstatic void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
21804SQLITE_PRIVATEstatic int sqlite3CodeSubselect(Parse*, Expr*);
21805SQLITE_PRIVATEstatic void sqlite3SelectPrep(Parse*, Select*, NameContext*);
21806SQLITE_PRIVATEstatic int sqlite3ExpandSubquery(Parse*, SrcItem*);
21807SQLITE_PRIVATEstatic void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
21808SQLITE_PRIVATEstatic int sqlite3MatchEName(
21809 const struct ExprList_item*,
21810 const char*,
21811 const char*,
21812 const char*,
21813 int*
21814);
21815SQLITE_PRIVATEstatic Bitmask sqlite3ExprColUsed(Expr*);
21816SQLITE_PRIVATEstatic u8 sqlite3StrIHash(const char*);
21817SQLITE_PRIVATEstatic int sqlite3ResolveExprNames(NameContext*, Expr*);
21818SQLITE_PRIVATEstatic int sqlite3ResolveExprListNames(NameContext*, ExprList*);
21819SQLITE_PRIVATEstatic void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
21820SQLITE_PRIVATEstatic int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
21821SQLITE_PRIVATEstatic int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
21822SQLITE_PRIVATEstatic void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
21823SQLITE_PRIVATEstatic void sqlite3AlterFinishAddColumn(Parse *, Token *);
21824SQLITE_PRIVATEstatic void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
21825SQLITE_PRIVATEstatic void sqlite3AlterDropColumn(Parse*, SrcList*, const Token*);
21826SQLITE_PRIVATEstatic const void *sqlite3RenameTokenMap(Parse*, const void*, const Token*);
21827SQLITE_PRIVATEstatic void sqlite3RenameTokenRemap(Parse*, const void *pTo, const void *pFrom);
21828SQLITE_PRIVATEstatic void sqlite3RenameExprUnmap(Parse*, Expr*);
21829SQLITE_PRIVATEstatic void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
21830SQLITE_PRIVATEstatic CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
21831SQLITE_PRIVATEstatic char sqlite3AffinityType(const char*, Column*);
21832SQLITE_PRIVATEstatic void sqlite3Analyze(Parse*, Token*, Token*);
21833SQLITE_PRIVATEstatic int sqlite3InvokeBusyHandler(BusyHandler*);
21834SQLITE_PRIVATEstatic int sqlite3FindDb(sqlite3*, Token*);
21835SQLITE_PRIVATEstatic int sqlite3FindDbName(sqlite3 *, const char *);
21836SQLITE_PRIVATEstatic int sqlite3AnalysisLoad(sqlite3*,int iDB);
21837SQLITE_PRIVATEstatic void sqlite3DeleteIndexSamples(sqlite3*,Index*);
21838SQLITE_PRIVATEstatic void sqlite3DefaultRowEst(Index*);
21839SQLITE_PRIVATEstatic void sqlite3RegisterLikeFunctions(sqlite3*, int);
21840SQLITE_PRIVATEstatic int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
21841SQLITE_PRIVATEstatic void sqlite3SchemaClear(void *);
21842SQLITE_PRIVATEstatic Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
21843SQLITE_PRIVATEstatic int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
21844SQLITE_PRIVATEstatic KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
21845SQLITE_PRIVATEstatic void sqlite3KeyInfoUnref(KeyInfo*);
21846SQLITE_PRIVATEstatic KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
21847SQLITE_PRIVATEstatic KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
21848SQLITE_PRIVATEstatic KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
21849SQLITE_PRIVATEstatic const char *sqlite3SelectOpName(int);
21850SQLITE_PRIVATEstatic int sqlite3HasExplicitNulls(Parse*, ExprList*);
21851
21852#ifdef SQLITE_DEBUG
21853SQLITE_PRIVATEstatic int sqlite3KeyInfoIsWriteable(KeyInfo*);
21854#endif
21855SQLITE_PRIVATEstatic int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
21856 void (*)(sqlite3_context*,int,sqlite3_value **),
21857 void (*)(sqlite3_context*,int,sqlite3_value **),
21858 void (*)(sqlite3_context*),
21859 void (*)(sqlite3_context*),
21860 void (*)(sqlite3_context*,int,sqlite3_value **),
21861 FuncDestructor *pDestructor
21862);
21863SQLITE_PRIVATEstatic void sqlite3NoopDestructor(void*);
21864SQLITE_PRIVATEstatic void *sqlite3OomFault(sqlite3*);
21865SQLITE_PRIVATEstatic void sqlite3OomClear(sqlite3*);
21866SQLITE_PRIVATEstatic int sqlite3ApiExit(sqlite3 *db, int);
21867SQLITE_PRIVATEstatic int sqlite3OpenTempDatabase(Parse *);
21868
21869SQLITE_PRIVATEstatic char *sqlite3RCStrRef(char*);
21870SQLITE_PRIVATEstatic void sqlite3RCStrUnref(void*);
21871SQLITE_PRIVATEstatic char *sqlite3RCStrNew(u64);
21872SQLITE_PRIVATEstatic char *sqlite3RCStrResize(char*,u64);
21873
21874SQLITE_PRIVATEstatic void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
21875SQLITE_PRIVATEstatic int sqlite3StrAccumEnlarge(StrAccum*, i64);
21876SQLITE_PRIVATEstatic char *sqlite3StrAccumFinish(StrAccum*);
21877SQLITE_PRIVATEstatic void sqlite3StrAccumSetError(StrAccum*, u8);
21878SQLITE_PRIVATEstatic void sqlite3ResultStrAccum(sqlite3_context*,StrAccum*);
21879SQLITE_PRIVATEstatic void sqlite3SelectDestInit(SelectDest*,int,int);
21880SQLITE_PRIVATEstatic Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
21881SQLITE_PRIVATEstatic void sqlite3RecordErrorByteOffset(sqlite3*,const char*);
21882SQLITE_PRIVATEstatic void sqlite3RecordErrorOffsetOfExpr(sqlite3*,const Expr*);
21883
21884SQLITE_PRIVATEstatic void sqlite3BackupRestart(sqlite3_backup *);
21885SQLITE_PRIVATEstatic void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
21886
21887#ifndef SQLITE_OMIT_SUBQUERY
21888SQLITE_PRIVATEstatic int sqlite3ExprCheckIN(Parse*, Expr*);
21889#else
21890# define sqlite3ExprCheckIN(x,y) SQLITE_OK0
21891#endif
21892
21893#ifdef SQLITE_ENABLE_STAT4
21894SQLITE_PRIVATEstatic int sqlite3Stat4ProbeSetValue(
21895 Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
21896SQLITE_PRIVATEstatic int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
21897SQLITE_PRIVATEstatic void sqlite3Stat4ProbeFree(UnpackedRecord*);
21898SQLITE_PRIVATEstatic int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
21899SQLITE_PRIVATEstatic char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
21900#endif
21901
21902/*
21903** The interface to the LEMON-generated parser
21904*/
21905#ifndef SQLITE_AMALGAMATION1
21906SQLITE_PRIVATEstatic void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
21907SQLITE_PRIVATEstatic void sqlite3ParserFree(void*, void(*)(void*));
21908#endif
21909SQLITE_PRIVATEstatic void sqlite3Parser(void*, int, Token);
21910SQLITE_PRIVATEstatic int sqlite3ParserFallback(int);
21911#ifdef YYTRACKMAXSTACKDEPTH
21912SQLITE_PRIVATEstatic int sqlite3ParserStackPeak(void*);
21913#endif
21914
21915SQLITE_PRIVATEstatic void sqlite3AutoLoadExtensions(sqlite3*);
21916#ifndef SQLITE_OMIT_LOAD_EXTENSION1
21917SQLITE_PRIVATEstatic void sqlite3CloseExtensions(sqlite3*);
21918#else
21919# define sqlite3CloseExtensions(X)
21920#endif
21921
21922#ifndef SQLITE_OMIT_SHARED_CACHE
21923SQLITE_PRIVATEstatic void sqlite3TableLock(Parse *, int, Pgno, u8, const char *);
21924#else
21925 #define sqlite3TableLock(v,w,x,y,z)
21926#endif
21927
21928#ifdef SQLITE_TEST
21929SQLITE_PRIVATEstatic int sqlite3Utf8To8(unsigned char*);
21930#endif
21931
21932#ifdef SQLITE_OMIT_VIRTUALTABLE
21933# define sqlite3VtabClear(D,T)
21934# define sqlite3VtabSync(X,Y) SQLITE_OK0
21935# define sqlite3VtabRollback(X)
21936# define sqlite3VtabCommit(X)
21937# define sqlite3VtabInSync(db)((db)->nVTrans>0 && (db)->aVTrans==0) 0
21938# define sqlite3VtabLock(X)
21939# define sqlite3VtabUnlock(X)
21940# define sqlite3VtabModuleUnref(D,X)
21941# define sqlite3VtabUnlockList(X)
21942# define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK0
21943# define sqlite3GetVTable(X,Y) ((VTable*)0)
21944#else
21945SQLITE_PRIVATEstatic void sqlite3VtabClear(sqlite3 *db, Table*);
21946SQLITE_PRIVATEstatic void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
21947SQLITE_PRIVATEstatic int sqlite3VtabSync(sqlite3 *db, Vdbe*);
21948SQLITE_PRIVATEstatic int sqlite3VtabRollback(sqlite3 *db);
21949SQLITE_PRIVATEstatic int sqlite3VtabCommit(sqlite3 *db);
21950SQLITE_PRIVATEstatic void sqlite3VtabLock(VTable *);
21951SQLITE_PRIVATEstatic void sqlite3VtabUnlock(VTable *);
21952SQLITE_PRIVATEstatic void sqlite3VtabModuleUnref(sqlite3*,Module*);
21953SQLITE_PRIVATEstatic void sqlite3VtabUnlockList(sqlite3*);
21954SQLITE_PRIVATEstatic int sqlite3VtabSavepoint(sqlite3 *, int, int);
21955SQLITE_PRIVATEstatic void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
21956SQLITE_PRIVATEstatic VTable *sqlite3GetVTable(sqlite3*, Table*);
21957SQLITE_PRIVATEstatic Module *sqlite3VtabCreateModule(
21958 sqlite3*,
21959 const char*,
21960 const sqlite3_module*,
21961 void*,
21962 void(*)(void*)
21963 );
21964# define sqlite3VtabInSync(db)((db)->nVTrans>0 && (db)->aVTrans==0) ((db)->nVTrans>0 && (db)->aVTrans==0)
21965#endif
21966SQLITE_PRIVATEstatic int sqlite3ReadOnlyShadowTables(sqlite3 *db);
21967#ifndef SQLITE_OMIT_VIRTUALTABLE
21968SQLITE_PRIVATEstatic int sqlite3ShadowTableName(sqlite3 *db, const char *zName);
21969SQLITE_PRIVATEstatic int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);
21970SQLITE_PRIVATEstatic void sqlite3MarkAllShadowTablesOf(sqlite3*, Table*);
21971#else
21972# define sqlite3ShadowTableName(A,B) 0
21973# define sqlite3IsShadowTableOf(A,B,C) 0
21974# define sqlite3MarkAllShadowTablesOf(A,B)
21975#endif
21976SQLITE_PRIVATEstatic int sqlite3VtabEponymousTableInit(Parse*,Module*);
21977SQLITE_PRIVATEstatic void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
21978SQLITE_PRIVATEstatic void sqlite3VtabMakeWritable(Parse*,Table*);
21979SQLITE_PRIVATEstatic void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
21980SQLITE_PRIVATEstatic void sqlite3VtabFinishParse(Parse*, Token*);
21981SQLITE_PRIVATEstatic void sqlite3VtabArgInit(Parse*);
21982SQLITE_PRIVATEstatic void sqlite3VtabArgExtend(Parse*, Token*);
21983SQLITE_PRIVATEstatic int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
21984SQLITE_PRIVATEstatic int sqlite3VtabCallConnect(Parse*, Table*);
21985SQLITE_PRIVATEstatic int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
21986SQLITE_PRIVATEstatic int sqlite3VtabBegin(sqlite3 *, VTable *);
21987
21988SQLITE_PRIVATEstatic FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
21989SQLITE_PRIVATEstatic void sqlite3VtabUsesAllSchemas(Parse*);
21990SQLITE_PRIVATEstatic sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
21991SQLITE_PRIVATEstatic int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
21992SQLITE_PRIVATEstatic int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
21993SQLITE_PRIVATEstatic void sqlite3ParseObjectInit(Parse*,sqlite3*);
21994SQLITE_PRIVATEstatic void sqlite3ParseObjectReset(Parse*);
21995SQLITE_PRIVATEstatic void *sqlite3ParserAddCleanup(Parse*,void(*)(sqlite3*,void*),void*);
21996#ifdef SQLITE_ENABLE_NORMALIZE
21997SQLITE_PRIVATEstatic char *sqlite3Normalize(Vdbe*, const char*);
21998#endif
21999SQLITE_PRIVATEstatic int sqlite3Reprepare(Vdbe*);
22000SQLITE_PRIVATEstatic void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
22001SQLITE_PRIVATEstatic CollSeq *sqlite3ExprCompareCollSeq(Parse*,const Expr*);
22002SQLITE_PRIVATEstatic CollSeq *sqlite3BinaryCompareCollSeq(Parse *, const Expr*, const Expr*);
22003SQLITE_PRIVATEstatic int sqlite3TempInMemory(const sqlite3*);
22004SQLITE_PRIVATEstatic const char *sqlite3JournalModename(int);
22005#ifndef SQLITE_OMIT_WAL
22006SQLITE_PRIVATEstatic int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
22007SQLITE_PRIVATEstatic int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
22008#endif
22009#ifndef SQLITE_OMIT_CTE
22010SQLITE_PRIVATEstatic Cte *sqlite3CteNew(Parse*,Token*,ExprList*,Select*,u8);
22011SQLITE_PRIVATEstatic void sqlite3CteDelete(sqlite3*,Cte*);
22012SQLITE_PRIVATEstatic With *sqlite3WithAdd(Parse*,With*,Cte*);
22013SQLITE_PRIVATEstatic void sqlite3WithDelete(sqlite3*,With*);
22014SQLITE_PRIVATEstatic void sqlite3WithDeleteGeneric(sqlite3*,void*);
22015SQLITE_PRIVATEstatic With *sqlite3WithPush(Parse*, With*, u8);
22016#else
22017# define sqlite3CteNew(P,T,E,S) ((void*)0)
22018# define sqlite3CteDelete(D,C)
22019# define sqlite3CteWithAdd(P,W,C) ((void*)0)
22020# define sqlite3WithDelete(x,y)
22021# define sqlite3WithPush(x,y,z) ((void*)0)
22022#endif
22023#ifndef SQLITE_OMIT_UPSERT
22024SQLITE_PRIVATEstatic Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*,Upsert*);
22025SQLITE_PRIVATEstatic void sqlite3UpsertDelete(sqlite3*,Upsert*);
22026SQLITE_PRIVATEstatic Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
22027SQLITE_PRIVATEstatic int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*,Upsert*);
22028SQLITE_PRIVATEstatic void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
22029SQLITE_PRIVATEstatic Upsert *sqlite3UpsertOfIndex(Upsert*,Index*);
22030SQLITE_PRIVATEstatic int sqlite3UpsertNextIsIPK(Upsert*);
22031#else
22032#define sqlite3UpsertNew(u,v,w,x,y,z) ((Upsert*)0)
22033#define sqlite3UpsertDelete(x,y)
22034#define sqlite3UpsertDup(x,y) ((Upsert*)0)
22035#define sqlite3UpsertOfIndex(x,y) ((Upsert*)0)
22036#define sqlite3UpsertNextIsIPK(x) 0
22037#endif
22038
22039
22040/* Declarations for functions in fkey.c. All of these are replaced by
22041** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
22042** key functionality is available. If OMIT_TRIGGER is defined but
22043** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
22044** this case foreign keys are parsed, but no other functionality is
22045** provided (enforcement of FK constraints requires the triggers sub-system).
22046*/
22047#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
22048SQLITE_PRIVATEstatic void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
22049SQLITE_PRIVATEstatic void sqlite3FkDropTable(Parse*, SrcList *, Table*);
22050SQLITE_PRIVATEstatic void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
22051SQLITE_PRIVATEstatic int sqlite3FkRequired(Parse*, Table*, int*, int);
22052SQLITE_PRIVATEstatic u32 sqlite3FkOldmask(Parse*, Table*);
22053SQLITE_PRIVATEstatic FKey *sqlite3FkReferences(Table *);
22054SQLITE_PRIVATEstatic void sqlite3FkClearTriggerCache(sqlite3*,int);
22055#else
22056 #define sqlite3FkActions(a,b,c,d,e,f)
22057 #define sqlite3FkCheck(a,b,c,d,e,f)
22058 #define sqlite3FkDropTable(a,b,c)
22059 #define sqlite3FkOldmask(a,b) 0
22060 #define sqlite3FkRequired(a,b,c,d) 0
22061 #define sqlite3FkReferences(a) 0
22062 #define sqlite3FkClearTriggerCache(a,b)
22063#endif
22064#ifndef SQLITE_OMIT_FOREIGN_KEY
22065SQLITE_PRIVATEstatic void sqlite3FkDelete(sqlite3 *, Table*);
22066SQLITE_PRIVATEstatic int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
22067#else
22068 #define sqlite3FkDelete(a,b)
22069 #define sqlite3FkLocateIndex(a,b,c,d,e)
22070#endif
22071
22072
22073/*
22074** Available fault injectors. Should be numbered beginning with 0.
22075*/
22076#define SQLITE_FAULTINJECTOR_MALLOC0 0
22077#define SQLITE_FAULTINJECTOR_COUNT1 1
22078
22079/*
22080** The interface to the code in fault.c used for identifying "benign"
22081** malloc failures. This is only present if SQLITE_UNTESTABLE
22082** is not defined.
22083*/
22084#ifndef SQLITE_UNTESTABLE
22085SQLITE_PRIVATEstatic void sqlite3BeginBenignMalloc(void);
22086SQLITE_PRIVATEstatic void sqlite3EndBenignMalloc(void);
22087#else
22088 #define sqlite3BeginBenignMalloc()
22089 #define sqlite3EndBenignMalloc()
22090#endif
22091
22092/*
22093** Allowed return values from sqlite3FindInIndex()
22094*/
22095#define IN_INDEX_ROWID1 1 /* Search the rowid of the table */
22096#define IN_INDEX_EPH2 2 /* Search an ephemeral b-tree */
22097#define IN_INDEX_INDEX_ASC3 3 /* Existing index ASCENDING */
22098#define IN_INDEX_INDEX_DESC4 4 /* Existing index DESCENDING */
22099#define IN_INDEX_NOOP5 5 /* No table available. Use comparisons */
22100/*
22101** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
22102*/
22103#define IN_INDEX_NOOP_OK0x0001 0x0001 /* OK to return IN_INDEX_NOOP */
22104#define IN_INDEX_MEMBERSHIP0x0002 0x0002 /* IN operator used for membership test */
22105#define IN_INDEX_LOOP0x0004 0x0004 /* IN operator used as a loop */
22106SQLITE_PRIVATEstatic int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);
22107
22108SQLITE_PRIVATEstatic int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
22109SQLITE_PRIVATEstatic int sqlite3JournalSize(sqlite3_vfs *);
22110#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
22111 || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
22112SQLITE_PRIVATEstatic int sqlite3JournalCreate(sqlite3_file *);
22113#endif
22114
22115SQLITE_PRIVATEstatic int sqlite3JournalIsInMemory(sqlite3_file *p);
22116SQLITE_PRIVATEstatic void sqlite3MemJournalOpen(sqlite3_file *);
22117
22118SQLITE_PRIVATEstatic void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
22119#if SQLITE_MAX_EXPR_DEPTH1000>0
22120SQLITE_PRIVATEstatic int sqlite3SelectExprHeight(const Select *);
22121SQLITE_PRIVATEstatic int sqlite3ExprCheckHeight(Parse*, int);
22122#else
22123 #define sqlite3SelectExprHeight(x) 0
22124 #define sqlite3ExprCheckHeight(x,y)
22125#endif
22126SQLITE_PRIVATEstatic void sqlite3ExprSetErrorOffset(Expr*,int);
22127
22128SQLITE_PRIVATEstatic u32 sqlite3Get4byte(const u8*);
22129SQLITE_PRIVATEstatic void sqlite3Put4byte(u8*, u32);
22130
22131#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
22132SQLITE_PRIVATEstatic void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
22133SQLITE_PRIVATEstatic void sqlite3ConnectionUnlocked(sqlite3 *db);
22134SQLITE_PRIVATEstatic void sqlite3ConnectionClosed(sqlite3 *db);
22135#else
22136 #define sqlite3ConnectionBlocked(x,y)
22137 #define sqlite3ConnectionUnlocked(x)
22138 #define sqlite3ConnectionClosed(x)
22139#endif
22140
22141#ifdef SQLITE_DEBUG
22142SQLITE_PRIVATEstatic void sqlite3ParserTrace(FILE*, char *);
22143#endif
22144#if defined(YYCOVERAGE)
22145SQLITE_PRIVATEstatic int sqlite3ParserCoverage(FILE*);
22146#endif
22147
22148/*
22149** If the SQLITE_ENABLE IOTRACE exists then the global variable
22150** sqlite3IoTrace is a pointer to a printf-like routine used to
22151** print I/O tracing messages.
22152*/
22153#ifdef SQLITE_ENABLE_IOTRACE
22154# define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
22155SQLITE_PRIVATEstatic void sqlite3VdbeIOTraceSql(Vdbe*);
22156SQLITE_API SQLITE_EXTERNextern void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
22157#else
22158# define IOTRACE(A)
22159# define sqlite3VdbeIOTraceSql(X)
22160#endif
22161
22162/*
22163** These routines are available for the mem2.c debugging memory allocator
22164** only. They are used to verify that different "types" of memory
22165** allocations are properly tracked by the system.
22166**
22167** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
22168** the MEMTYPE_* macros defined below. The type must be a bitmask with
22169** a single bit set.
22170**
22171** sqlite3MemdebugHasType() returns true if any of the bits in its second
22172** argument match the type set by the previous sqlite3MemdebugSetType().
22173** sqlite3MemdebugHasType() is intended for use inside assert() statements.
22174**
22175** sqlite3MemdebugNoType() returns true if none of the bits in its second
22176** argument match the type set by the previous sqlite3MemdebugSetType().
22177**
22178** Perhaps the most important point is the difference between MEMTYPE_HEAP
22179** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
22180** it might have been allocated by lookaside, except the allocation was
22181** too large or lookaside was already full. It is important to verify
22182** that allocations that might have been satisfied by lookaside are not
22183** passed back to non-lookaside free() routines. Asserts such as the
22184** example above are placed on the non-lookaside free() routines to verify
22185** this constraint.
22186**
22187** All of this is no-op for a production build. It only comes into
22188** play when the SQLITE_MEMDEBUG compile-time option is used.
22189*/
22190#ifdef SQLITE_MEMDEBUG
22191SQLITE_PRIVATEstatic void sqlite3MemdebugSetType(void*,u8);
22192SQLITE_PRIVATEstatic int sqlite3MemdebugHasType(const void*,u8)1;
22193SQLITE_PRIVATEstatic int sqlite3MemdebugNoType(const void*,u8)1;
22194#else
22195# define sqlite3MemdebugSetType(X,Y) /* no-op */
22196# define sqlite3MemdebugHasType(X,Y)1 1
22197# define sqlite3MemdebugNoType(X,Y)1 1
22198#endif
22199#define MEMTYPE_HEAP0x01 0x01 /* General heap allocations */
22200#define MEMTYPE_LOOKASIDE0x02 0x02 /* Heap that might have been lookaside */
22201#define MEMTYPE_PCACHE0x04 0x04 /* Page cache allocations */
22202
22203/*
22204** Threading interface
22205*/
22206#if SQLITE_MAX_WORKER_THREADS8>0
22207SQLITE_PRIVATEstatic int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
22208SQLITE_PRIVATEstatic int sqlite3ThreadJoin(SQLiteThread*, void**);
22209#endif
22210
22211#if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
22212SQLITE_PRIVATEstatic int sqlite3DbpageRegister(sqlite3*);
22213#endif
22214#if defined(SQLITE_ENABLE_DBSTAT_VTAB1) || defined(SQLITE_TEST)
22215SQLITE_PRIVATEstatic int sqlite3DbstatRegister(sqlite3*);
22216#endif
22217
22218SQLITE_PRIVATEstatic int sqlite3ExprVectorSize(const Expr *pExpr);
22219SQLITE_PRIVATEstatic int sqlite3ExprIsVector(const Expr *pExpr);
22220SQLITE_PRIVATEstatic Expr *sqlite3VectorFieldSubexpr(Expr*, int);
22221SQLITE_PRIVATEstatic Expr *sqlite3ExprForVectorField(Parse*,Expr*,int,int);
22222SQLITE_PRIVATEstatic void sqlite3VectorErrorMsg(Parse*, Expr*);
22223
22224#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
22225SQLITE_PRIVATEstatic const char **sqlite3CompileOptions(int *pnOpt);
22226#endif
22227
22228#if SQLITE_OS_UNIX1 && defined(SQLITE_OS_KV_OPTIONAL)
22229SQLITE_PRIVATEstatic int sqlite3KvvfsInit(void);
22230#endif
22231
22232#if defined(VDBE_PROFILE) \
22233 || defined(SQLITE_PERFORMANCE_TRACE) \
22234 || defined(SQLITE_ENABLE_STMT_SCANSTATUS1)
22235SQLITE_PRIVATEstatic sqlite3_uint64 sqlite3Hwtime(void);
22236#endif
22237
22238#ifdef SQLITE_ENABLE_STMT_SCANSTATUS1
22239# define IS_STMT_SCANSTATUS(db)(db->flags & 0x00000400) (db->flags & SQLITE_StmtScanStatus0x00000400)
22240#else
22241# define IS_STMT_SCANSTATUS(db)(db->flags & 0x00000400) 0
22242#endif
22243
22244#endif /* SQLITEINT_H */
22245
22246/************** End of sqliteInt.h *******************************************/
22247/************** Begin file os_common.h ***************************************/
22248/*
22249** 2004 May 22
22250**
22251** The author disclaims copyright to this source code. In place of
22252** a legal notice, here is a blessing:
22253**
22254** May you do good and not evil.
22255** May you find forgiveness for yourself and forgive others.
22256** May you share freely, never taking more than you give.
22257**
22258******************************************************************************
22259**
22260** This file contains macros and a little bit of code that is common to
22261** all of the platform-specific files (os_*.c) and is #included into those
22262** files.
22263**
22264** This file should be #included by the os_*.c files only. It is not a
22265** general purpose header file.
22266*/
22267#ifndef _OS_COMMON_H_
22268#define _OS_COMMON_H_
22269
22270/*
22271** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22272** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22273** switch. The following code should catch this problem at compile-time.
22274*/
22275#ifdef MEMORY_DEBUG
22276# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
22277#endif
22278
22279/*
22280** Macros for performance tracing. Normally turned off. Only works
22281** on i486 hardware.
22282*/
22283#ifdef SQLITE_PERFORMANCE_TRACE
22284
22285static sqlite_uint64 g_start;
22286static sqlite_uint64 g_elapsed;
22287#define TIMER_START g_start=sqlite3Hwtime()
22288#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
22289#define TIMER_ELAPSED((sqlite_uint64)0) g_elapsed
22290#else
22291#define TIMER_START
22292#define TIMER_END
22293#define TIMER_ELAPSED((sqlite_uint64)0) ((sqlite_uint64)0)
22294#endif
22295
22296/*
22297** If we compile with the SQLITE_TEST macro set, then the following block
22298** of code will give us the ability to simulate a disk I/O error. This
22299** is used for testing the I/O recovery logic.
22300*/
22301#if defined(SQLITE_TEST)
22302SQLITE_API extern int sqlite3_io_error_hit;
22303SQLITE_API extern int sqlite3_io_error_hardhit;
22304SQLITE_API extern int sqlite3_io_error_pending;
22305SQLITE_API extern int sqlite3_io_error_persist;
22306SQLITE_API extern int sqlite3_io_error_benign;
22307SQLITE_API extern int sqlite3_diskfull_pending;
22308SQLITE_API extern int sqlite3_diskfull;
22309#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22310#define SimulateIOError(CODE) \
22311 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22312 || sqlite3_io_error_pending-- == 1 ) \
22313 { local_ioerr(); CODE; }
22314static void local_ioerr(){
22315 IOTRACE(("IOERR\n"));
22316 sqlite3_io_error_hit++;
22317 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22318}
22319#define SimulateDiskfullError(CODE) \
22320 if( sqlite3_diskfull_pending ){ \
22321 if( sqlite3_diskfull_pending == 1 ){ \
22322 local_ioerr(); \
22323 sqlite3_diskfull = 1; \
22324 sqlite3_io_error_hit = 1; \
22325 CODE; \
22326 }else{ \
22327 sqlite3_diskfull_pending--; \
22328 } \
22329 }
22330#else
22331#define SimulateIOErrorBenign(X)
22332#define SimulateIOError(A)
22333#define SimulateDiskfullError(A)
22334#endif /* defined(SQLITE_TEST) */
22335
22336/*
22337** When testing, keep a count of the number of open files.
22338*/
22339#if defined(SQLITE_TEST)
22340SQLITE_API extern int sqlite3_open_file_count;
22341#define OpenCounter(X) sqlite3_open_file_count+=(X)
22342#else
22343#define OpenCounter(X)
22344#endif /* defined(SQLITE_TEST) */
22345
22346#endif /* !defined(_OS_COMMON_H_) */
22347
22348/************** End of os_common.h *******************************************/
22349/************** Begin file ctime.c *******************************************/
22350/* DO NOT EDIT!
22351** This file is automatically generated by the script in the canonical
22352** SQLite source tree at tool/mkctimec.tcl.
22353**
22354** To modify this header, edit any of the various lists in that script
22355** which specify categories of generated conditionals in this file.
22356*/
22357
22358/*
22359** 2010 February 23
22360**
22361** The author disclaims copyright to this source code. In place of
22362** a legal notice, here is a blessing:
22363**
22364** May you do good and not evil.
22365** May you find forgiveness for yourself and forgive others.
22366** May you share freely, never taking more than you give.
22367**
22368*************************************************************************
22369**
22370** This file implements routines used to report what compile-time options
22371** SQLite was built with.
22372*/
22373#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */
22374
22375/*
22376** Include the configuration header output by 'configure' if we're using the
22377** autoconf-based build
22378*/
22379#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
22380/* #include "sqlite_cfg.h" */
22381#define SQLITECONFIG_H 1
22382#endif
22383
22384/* These macros are provided to "stringify" the value of the define
22385** for those options in which the value is meaningful. */
22386#define CTIMEOPT_VAL_(opt)"opt" #opt
22387#define CTIMEOPT_VAL(opt)"opt" CTIMEOPT_VAL_(opt)"opt"
22388
22389/* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This
22390** option requires a separate macro because legal values contain a single
22391** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
22392#define CTIMEOPT_VAL2_(opt1,opt2)"opt1" "," "opt2" #opt1 "," #opt2
22393#define CTIMEOPT_VAL2(opt)CTIMEOPT_VAL2_ CTIMEOPT_VAL2_(opt)
22394/* #include "sqliteInt.h" */
22395
22396/*
22397** An array of names of all compile-time options. This array should
22398** be sorted A-Z.
22399**
22400** This array looks large, but in a typical installation actually uses
22401** only a handful of compile-time options, so most times this array is usually
22402** rather short and uses little memory space.
22403*/
22404static const char * const sqlite3azCompileOpt[] = {
22405
22406#ifdef SQLITE_32BIT_ROWID
22407 "32BIT_ROWID",
22408#endif
22409#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
22410 "4_BYTE_ALIGNED_MALLOC",
22411#endif
22412#ifdef SQLITE_ALLOW_COVERING_INDEX_SCAN1
22413# if SQLITE_ALLOW_COVERING_INDEX_SCAN1 != 1
22414 "ALLOW_COVERING_INDEX_SCAN=" CTIMEOPT_VAL(SQLITE_ALLOW_COVERING_INDEX_SCAN)"1",
22415# endif
22416#endif
22417#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
22418 "ALLOW_ROWID_IN_VIEW",
22419#endif
22420#ifdef SQLITE_ALLOW_URI_AUTHORITY
22421 "ALLOW_URI_AUTHORITY",
22422#endif
22423#ifdef SQLITE_ATOMIC_INTRINSICS1
22424 "ATOMIC_INTRINSICS=" CTIMEOPT_VAL(SQLITE_ATOMIC_INTRINSICS)"1",
22425#endif
22426#ifdef SQLITE_BITMASK_TYPE
22427 "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE)"SQLITE_BITMASK_TYPE",
22428#endif
22429#ifdef SQLITE_BUG_COMPATIBLE_20160819
22430 "BUG_COMPATIBLE_20160819",
22431#endif
22432#ifdef SQLITE_BUG_COMPATIBLE_20250510
22433 "BUG_COMPATIBLE_20250510",
22434#endif
22435#ifdef SQLITE_CASE_SENSITIVE_LIKE
22436 "CASE_SENSITIVE_LIKE",
22437#endif
22438#ifdef SQLITE_CHECK_PAGES
22439 "CHECK_PAGES",
22440#endif
22441#if defined(__clang__1) && defined(__clang_major__19)
22442 "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__)"19" "."
22443 CTIMEOPT_VAL(__clang_minor__)"1" "."
22444 CTIMEOPT_VAL(__clang_patchlevel__)"2",
22445#elif defined(_MSC_VER)
22446 "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER)"_MSC_VER",
22447#elif defined(__GNUC__4) && defined(__VERSION__"Clang 19.1.2")
22448 "COMPILER=gcc-" __VERSION__"Clang 19.1.2",
22449#endif
22450#ifdef SQLITE_COVERAGE_TEST
22451 "COVERAGE_TEST",
22452#endif
22453#ifdef SQLITE_DEBUG
22454 "DEBUG",
22455#endif
22456#ifdef SQLITE_DEFAULT_AUTOMATIC_INDEX
22457 "DEFAULT_AUTOMATIC_INDEX",
22458#endif
22459#ifdef SQLITE_DEFAULT_AUTOVACUUM0
22460 "DEFAULT_AUTOVACUUM",
22461#endif
22462#ifdef SQLITE_DEFAULT_CACHE_SIZE128
22463 "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE)"128",
22464#endif
22465#ifdef SQLITE_DEFAULT_CKPTFULLFSYNC1
22466 "DEFAULT_CKPTFULLFSYNC",
22467#endif
22468#ifdef SQLITE_DEFAULT_FILE_FORMAT4
22469 "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT)"4",
22470#endif
22471#ifdef SQLITE_DEFAULT_FILE_PERMISSIONS0644
22472 "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS)"0644",
22473#endif
22474#ifdef SQLITE_DEFAULT_FOREIGN_KEYS
22475 "DEFAULT_FOREIGN_KEYS",
22476#endif
22477#ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT32768
22478 "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT)"32768",
22479#endif
22480#ifdef SQLITE_DEFAULT_LOCKING_MODE
22481 "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE)"SQLITE_DEFAULT_LOCKING_MODE",
22482#endif
22483#ifdef SQLITE_DEFAULT_LOOKASIDE1200,40
22484 "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE)"1200" "," "40",
22485#endif
22486#ifdef SQLITE_DEFAULT_MEMSTATUS1
22487# if SQLITE_DEFAULT_MEMSTATUS1 != 1
22488 "DEFAULT_MEMSTATUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_MEMSTATUS)"1",
22489# endif
22490#endif
22491#ifdef SQLITE_DEFAULT_MMAP_SIZE0
22492 "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE)"0",
22493#endif
22494#ifdef SQLITE_DEFAULT_PAGE_SIZE4096
22495 "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE)"4096",
22496#endif
22497#ifdef SQLITE_DEFAULT_PCACHE_INITSZ20
22498 "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ)"20",
22499#endif
22500#ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS0755
22501 "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS)"0755",
22502#endif
22503#ifdef SQLITE_DEFAULT_RECURSIVE_TRIGGERS0
22504 "DEFAULT_RECURSIVE_TRIGGERS",
22505#endif
22506#ifdef SQLITE_DEFAULT_ROWEST
22507 "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST)"SQLITE_DEFAULT_ROWEST",
22508#endif
22509#ifdef SQLITE_DEFAULT_SECTOR_SIZE4096
22510 "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE)"4096",
22511#endif
22512#ifdef SQLITE_DEFAULT_SYNCHRONOUS2
22513 "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS)"2",
22514#endif
22515#ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT1000
22516 "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT)"1000",
22517#endif
22518#ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS1
22519 "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS)"1",
22520#endif
22521#ifdef SQLITE_DEFAULT_WORKER_THREADS0
22522 "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS)"0",
22523#endif
22524#ifdef SQLITE_DIRECT_OVERFLOW_READ1
22525 "DIRECT_OVERFLOW_READ",
22526#endif
22527#ifdef SQLITE_DISABLE_DIRSYNC
22528 "DISABLE_DIRSYNC",
22529#endif
22530#ifdef SQLITE_DISABLE_FTS3_UNICODE
22531 "DISABLE_FTS3_UNICODE",
22532#endif
22533#ifdef SQLITE_DISABLE_FTS4_DEFERRED
22534 "DISABLE_FTS4_DEFERRED",
22535#endif
22536#ifdef SQLITE_DISABLE_INTRINSIC
22537 "DISABLE_INTRINSIC",
22538#endif
22539#ifdef SQLITE_DISABLE_LFS
22540 "DISABLE_LFS",
22541#endif
22542#ifdef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
22543 "DISABLE_PAGECACHE_OVERFLOW_STATS",
22544#endif
22545#ifdef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
22546 "DISABLE_SKIPAHEAD_DISTINCT",
22547#endif
22548#ifdef SQLITE_DQS0
22549 "DQS=" CTIMEOPT_VAL(SQLITE_DQS)"0",
22550#endif
22551#ifdef SQLITE_ENABLE_8_3_NAMES
22552 "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES)"SQLITE_ENABLE_8_3_NAMES",
22553#endif
22554#ifdef SQLITE_ENABLE_API_ARMOR1
22555 "ENABLE_API_ARMOR",
22556#endif
22557#ifdef SQLITE_ENABLE_ATOMIC_WRITE
22558 "ENABLE_ATOMIC_WRITE",
22559#endif
22560#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
22561 "ENABLE_BATCH_ATOMIC_WRITE",
22562#endif
22563#ifdef SQLITE_ENABLE_BYTECODE_VTAB
22564 "ENABLE_BYTECODE_VTAB",
22565#endif
22566#ifdef SQLITE_ENABLE_CEROD
22567 "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD)"SQLITE_ENABLE_CEROD",
22568#endif
22569#ifdef SQLITE_ENABLE_COLUMN_METADATA1
22570 "ENABLE_COLUMN_METADATA",
22571#endif
22572#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
22573 "ENABLE_COLUMN_USED_MASK",
22574#endif
22575#ifdef SQLITE_ENABLE_COSTMULT
22576 "ENABLE_COSTMULT",
22577#endif
22578#ifdef SQLITE_ENABLE_CURSOR_HINTS
22579 "ENABLE_CURSOR_HINTS",
22580#endif
22581#ifdef SQLITE_ENABLE_DBPAGE_VTAB
22582 "ENABLE_DBPAGE_VTAB",
22583#endif
22584#ifdef SQLITE_ENABLE_DBSTAT_VTAB1
22585 "ENABLE_DBSTAT_VTAB",
22586#endif
22587#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
22588 "ENABLE_EXPENSIVE_ASSERT",
22589#endif
22590#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
22591 "ENABLE_EXPLAIN_COMMENTS",
22592#endif
22593#ifdef SQLITE_ENABLE_FTS31
22594 "ENABLE_FTS3",
22595#endif
22596#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS1
22597 "ENABLE_FTS3_PARENTHESIS",
22598#endif
22599#ifdef SQLITE_ENABLE_FTS3_TOKENIZER1
22600 "ENABLE_FTS3_TOKENIZER",
22601#endif
22602#ifdef SQLITE_ENABLE_FTS41
22603 "ENABLE_FTS4",
22604#endif
22605#ifdef SQLITE_ENABLE_FTS51
22606 "ENABLE_FTS5",
22607#endif
22608#ifdef SQLITE_ENABLE_GEOPOLY
22609 "ENABLE_GEOPOLY",
22610#endif
22611#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
22612 "ENABLE_HIDDEN_COLUMNS",
22613#endif
22614#ifdef SQLITE_ENABLE_ICU
22615 "ENABLE_ICU",
22616#endif
22617#ifdef SQLITE_ENABLE_IOTRACE
22618 "ENABLE_IOTRACE",
22619#endif
22620#ifdef SQLITE_ENABLE_LOAD_EXTENSION
22621 "ENABLE_LOAD_EXTENSION",
22622#endif
22623#ifdef SQLITE_ENABLE_LOCKING_STYLE0
22624 "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE)"0",
22625#endif
22626#ifdef SQLITE_ENABLE_MATH_FUNCTIONS1
22627 "ENABLE_MATH_FUNCTIONS",
22628#endif
22629#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
22630 "ENABLE_MEMORY_MANAGEMENT",
22631#endif
22632#ifdef SQLITE_ENABLE_MEMSYS3
22633 "ENABLE_MEMSYS3",
22634#endif
22635#ifdef SQLITE_ENABLE_MEMSYS5
22636 "ENABLE_MEMSYS5",
22637#endif
22638#ifdef SQLITE_ENABLE_MULTIPLEX
22639 "ENABLE_MULTIPLEX",
22640#endif
22641#ifdef SQLITE_ENABLE_NORMALIZE
22642 "ENABLE_NORMALIZE",
22643#endif
22644#ifdef SQLITE_ENABLE_NULL_TRIM
22645 "ENABLE_NULL_TRIM",
22646#endif
22647#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
22648 "ENABLE_OFFSET_SQL_FUNC",
22649#endif
22650#ifdef SQLITE_ENABLE_ORDERED_SET_AGGREGATES
22651 "ENABLE_ORDERED_SET_AGGREGATES",
22652#endif
22653#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
22654 "ENABLE_OVERSIZE_CELL_CHECK",
22655#endif
22656#ifdef SQLITE_ENABLE_PREUPDATE_HOOK1
22657 "ENABLE_PREUPDATE_HOOK",
22658#endif
22659#ifdef SQLITE_ENABLE_QPSG
22660 "ENABLE_QPSG",
22661#endif
22662#ifdef SQLITE_ENABLE_RBU
22663 "ENABLE_RBU",
22664#endif
22665#ifdef SQLITE_ENABLE_RTREE1
22666 "ENABLE_RTREE",
22667#endif
22668#ifdef SQLITE_ENABLE_SESSION1
22669 "ENABLE_SESSION",
22670#endif
22671#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
22672 "ENABLE_SETLK_TIMEOUT",
22673#endif
22674#ifdef SQLITE_ENABLE_SNAPSHOT1
22675 "ENABLE_SNAPSHOT",
22676#endif
22677#ifdef SQLITE_ENABLE_SORTER_REFERENCES
22678 "ENABLE_SORTER_REFERENCES",
22679#endif
22680#ifdef SQLITE_ENABLE_SQLLOG
22681 "ENABLE_SQLLOG",
22682#endif
22683#ifdef SQLITE_ENABLE_STAT4
22684 "ENABLE_STAT4",
22685#endif
22686#ifdef SQLITE_ENABLE_STMTVTAB
22687 "ENABLE_STMTVTAB",
22688#endif
22689#ifdef SQLITE_ENABLE_STMT_SCANSTATUS1
22690 "ENABLE_STMT_SCANSTATUS",
22691#endif
22692#ifdef SQLITE_ENABLE_TREETRACE
22693 "ENABLE_TREETRACE",
22694#endif
22695#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION1
22696 "ENABLE_UNKNOWN_SQL_FUNCTION",
22697#endif
22698#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
22699 "ENABLE_UNLOCK_NOTIFY",
22700#endif
22701#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT1
22702 "ENABLE_UPDATE_DELETE_LIMIT",
22703#endif
22704#ifdef SQLITE_ENABLE_URI_00_ERROR
22705 "ENABLE_URI_00_ERROR",
22706#endif
22707#ifdef SQLITE_ENABLE_VFSTRACE
22708 "ENABLE_VFSTRACE",
22709#endif
22710#ifdef SQLITE_ENABLE_WHERETRACE
22711 "ENABLE_WHERETRACE",
22712#endif
22713#ifdef SQLITE_ENABLE_ZIPVFS
22714 "ENABLE_ZIPVFS",
22715#endif
22716#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
22717 "EXPLAIN_ESTIMATED_ROWS",
22718#endif
22719#ifdef SQLITE_EXTRA_AUTOEXT
22720 "EXTRA_AUTOEXT=" CTIMEOPT_VAL(SQLITE_EXTRA_AUTOEXT)"SQLITE_EXTRA_AUTOEXT",
22721#endif
22722#ifdef SQLITE_EXTRA_IFNULLROW
22723 "EXTRA_IFNULLROW",
22724#endif
22725#ifdef SQLITE_EXTRA_INIT
22726 "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT)"SQLITE_EXTRA_INIT",
22727#endif
22728#ifdef SQLITE_EXTRA_INIT_MUTEXED
22729 "EXTRA_INIT_MUTEXED=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT_MUTEXED)"SQLITE_EXTRA_INIT_MUTEXED",
22730#endif
22731#ifdef SQLITE_EXTRA_SHUTDOWN
22732 "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN)"SQLITE_EXTRA_SHUTDOWN",
22733#endif
22734#ifdef SQLITE_FTS3_MAX_EXPR_DEPTH12
22735 "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH)"12",
22736#endif
22737#ifdef SQLITE_FTS5_ENABLE_TEST_MI
22738 "FTS5_ENABLE_TEST_MI",
22739#endif
22740#ifdef SQLITE_FTS5_NO_WITHOUT_ROWID
22741 "FTS5_NO_WITHOUT_ROWID",
22742#endif
22743#if HAVE_ISNAN || SQLITE_HAVE_ISNAN1
22744 "HAVE_ISNAN",
22745#endif
22746#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22747# if SQLITE_HOMEGROWN_RECURSIVE_MUTEX != 1
22748 "HOMEGROWN_RECURSIVE_MUTEX=" CTIMEOPT_VAL(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)"SQLITE_HOMEGROWN_RECURSIVE_MUTEX",
22749# endif
22750#endif
22751#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
22752 "IGNORE_AFP_LOCK_ERRORS",
22753#endif
22754#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
22755 "IGNORE_FLOCK_LOCK_ERRORS",
22756#endif
22757#ifdef SQLITE_INLINE_MEMCPY
22758 "INLINE_MEMCPY",
22759#endif
22760#ifdef SQLITE_INT64_TYPE
22761 "INT64_TYPE",
22762#endif
22763#ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX100
22764 "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX)"100",
22765#endif
22766#ifdef SQLITE_LEGACY_JSON_VALID
22767 "LEGACY_JSON_VALID",
22768#endif
22769#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
22770 "LIKE_DOESNT_MATCH_BLOBS",
22771#endif
22772#ifdef SQLITE_LOCK_TRACE
22773 "LOCK_TRACE",
22774#endif
22775#ifdef SQLITE_LOG_CACHE_SPILL
22776 "LOG_CACHE_SPILL",
22777#endif
22778#ifdef SQLITE_MALLOC_SOFT_LIMIT1024
22779 "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT)"1024",
22780#endif
22781#ifdef SQLITE_MAX_ATTACHED10
22782 "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED)"10",
22783#endif
22784#ifdef SQLITE_MAX_COLUMN2000
22785 "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN)"2000",
22786#endif
22787#ifdef SQLITE_MAX_COMPOUND_SELECT500
22788 "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT)"500",
22789#endif
22790#ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE8192
22791 "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE)"8192",
22792#endif
22793#ifdef SQLITE_MAX_EXPR_DEPTH1000
22794 "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH)"1000",
22795#endif
22796#ifdef SQLITE_MAX_FUNCTION_ARG1000
22797 "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG)"1000",
22798#endif
22799#ifdef SQLITE_MAX_LENGTH2147483645
22800 "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH)"2147483645",
22801#endif
22802#ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH50000
22803 "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH)"50000",
22804#endif
22805#ifdef SQLITE_MAX_MEMORY0
22806 "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY)"0",
22807#endif
22808#ifdef SQLITE_MAX_MMAP_SIZE20971520
22809 "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE)"20971520",
22810#endif
22811#ifdef SQLITE_MAX_MMAP_SIZE_
22812 "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_)"SQLITE_MAX_MMAP_SIZE_",
22813#endif
22814#ifdef SQLITE_MAX_PAGE_COUNT0xfffffffe
22815 "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT)"0xfffffffe",
22816#endif
22817#ifdef SQLITE_MAX_PAGE_SIZE65536
22818 "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE)"65536",
22819#endif
22820#ifdef SQLITE_MAX_SCHEMA_RETRY50
22821 "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY)"50",
22822#endif
22823#ifdef SQLITE_MAX_SQL_LENGTH1000000000
22824 "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH)"1000000000",
22825#endif
22826#ifdef SQLITE_MAX_TRIGGER_DEPTH1000
22827 "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH)"1000",
22828#endif
22829#ifdef SQLITE_MAX_VARIABLE_NUMBER500000
22830 "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER)"500000",
22831#endif
22832#ifdef SQLITE_MAX_VDBE_OP250000000
22833 "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP)"250000000",
22834#endif
22835#ifdef SQLITE_MAX_WORKER_THREADS8
22836 "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS)"8",
22837#endif
22838#ifdef SQLITE_MEMDEBUG
22839 "MEMDEBUG",
22840#endif
22841#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
22842 "MIXED_ENDIAN_64BIT_FLOAT",
22843#endif
22844#ifdef SQLITE_MMAP_READWRITE
22845 "MMAP_READWRITE",
22846#endif
22847#ifdef SQLITE_MUTEX_NOOP
22848 "MUTEX_NOOP",
22849#endif
22850#ifdef SQLITE_MUTEX_OMIT
22851 "MUTEX_OMIT",
22852#endif
22853#ifdef SQLITE_MUTEX_PTHREADS
22854 "MUTEX_PTHREADS",
22855#endif
22856#ifdef SQLITE_MUTEX_W32
22857 "MUTEX_W32",
22858#endif
22859#ifdef SQLITE_NEED_ERR_NAME
22860 "NEED_ERR_NAME",
22861#endif
22862#ifdef SQLITE_NO_SYNC
22863 "NO_SYNC",
22864#endif
22865#ifdef SQLITE_OMIT_ALTERTABLE
22866 "OMIT_ALTERTABLE",
22867#endif
22868#ifdef SQLITE_OMIT_ANALYZE
22869 "OMIT_ANALYZE",
22870#endif
22871#ifdef SQLITE_OMIT_ATTACH
22872 "OMIT_ATTACH",
22873#endif
22874#ifdef SQLITE_OMIT_AUTHORIZATION
22875 "OMIT_AUTHORIZATION",
22876#endif
22877#ifdef SQLITE_OMIT_AUTOINCREMENT
22878 "OMIT_AUTOINCREMENT",
22879#endif
22880#ifdef SQLITE_OMIT_AUTOINIT
22881 "OMIT_AUTOINIT",
22882#endif
22883#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
22884 "OMIT_AUTOMATIC_INDEX",
22885#endif
22886#ifdef SQLITE_OMIT_AUTORESET1
22887 "OMIT_AUTORESET",
22888#endif
22889#ifdef SQLITE_OMIT_AUTOVACUUM
22890 "OMIT_AUTOVACUUM",
22891#endif
22892#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
22893 "OMIT_BETWEEN_OPTIMIZATION",
22894#endif
22895#ifdef SQLITE_OMIT_BLOB_LITERAL
22896 "OMIT_BLOB_LITERAL",
22897#endif
22898#ifdef SQLITE_OMIT_CAST
22899 "OMIT_CAST",
22900#endif
22901#ifdef SQLITE_OMIT_CHECK
22902 "OMIT_CHECK",
22903#endif
22904#ifdef SQLITE_OMIT_COMPLETE
22905 "OMIT_COMPLETE",
22906#endif
22907#ifdef SQLITE_OMIT_COMPOUND_SELECT
22908 "OMIT_COMPOUND_SELECT",
22909#endif
22910#ifdef SQLITE_OMIT_CONFLICT_CLAUSE
22911 "OMIT_CONFLICT_CLAUSE",
22912#endif
22913#ifdef SQLITE_OMIT_CTE
22914 "OMIT_CTE",
22915#endif
22916#if defined(SQLITE_OMIT_DATETIME_FUNCS) || defined(SQLITE_OMIT_FLOATING_POINT)
22917 "OMIT_DATETIME_FUNCS",
22918#endif
22919#ifdef SQLITE_OMIT_DECLTYPE
22920 "OMIT_DECLTYPE",
22921#endif
22922#ifdef SQLITE_OMIT_DEPRECATED1
22923 "OMIT_DEPRECATED",
22924#endif
22925#ifdef SQLITE_OMIT_DESERIALIZE
22926 "OMIT_DESERIALIZE",
22927#endif
22928#ifdef SQLITE_OMIT_DISKIO
22929 "OMIT_DISKIO",
22930#endif
22931#ifdef SQLITE_OMIT_EXPLAIN
22932 "OMIT_EXPLAIN",
22933#endif
22934#ifdef SQLITE_OMIT_FLAG_PRAGMAS
22935 "OMIT_FLAG_PRAGMAS",
22936#endif
22937#ifdef SQLITE_OMIT_FLOATING_POINT
22938 "OMIT_FLOATING_POINT",
22939#endif
22940#ifdef SQLITE_OMIT_FOREIGN_KEY
22941 "OMIT_FOREIGN_KEY",
22942#endif
22943#ifdef SQLITE_OMIT_GET_TABLE
22944 "OMIT_GET_TABLE",
22945#endif
22946#ifdef SQLITE_OMIT_HEX_INTEGER
22947 "OMIT_HEX_INTEGER",
22948#endif
22949#ifdef SQLITE_OMIT_INCRBLOB
22950 "OMIT_INCRBLOB",
22951#endif
22952#ifdef SQLITE_OMIT_INTEGRITY_CHECK
22953 "OMIT_INTEGRITY_CHECK",
22954#endif
22955#ifdef SQLITE_OMIT_INTROSPECTION_PRAGMAS
22956 "OMIT_INTROSPECTION_PRAGMAS",
22957#endif
22958#ifdef SQLITE_OMIT_JSON
22959 "OMIT_JSON",
22960#endif
22961#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
22962 "OMIT_LIKE_OPTIMIZATION",
22963#endif
22964#ifdef SQLITE_OMIT_LOAD_EXTENSION1
22965 "OMIT_LOAD_EXTENSION",
22966#endif
22967#ifdef SQLITE_OMIT_LOCALTIME
22968 "OMIT_LOCALTIME",
22969#endif
22970#ifdef SQLITE_OMIT_LOOKASIDE
22971 "OMIT_LOOKASIDE",
22972#endif
22973#ifdef SQLITE_OMIT_MEMORYDB
22974 "OMIT_MEMORYDB",
22975#endif
22976#ifdef SQLITE_OMIT_OR_OPTIMIZATION
22977 "OMIT_OR_OPTIMIZATION",
22978#endif
22979#ifdef SQLITE_OMIT_PAGER_PRAGMAS
22980 "OMIT_PAGER_PRAGMAS",
22981#endif
22982#ifdef SQLITE_OMIT_PARSER_TRACE
22983 "OMIT_PARSER_TRACE",
22984#endif
22985#ifdef SQLITE_OMIT_POPEN
22986 "OMIT_POPEN",
22987#endif
22988#ifdef SQLITE_OMIT_PRAGMA
22989 "OMIT_PRAGMA",
22990#endif
22991#ifdef SQLITE_OMIT_PROGRESS_CALLBACK1
22992 "OMIT_PROGRESS_CALLBACK",
22993#endif
22994#ifdef SQLITE_OMIT_QUICKBALANCE
22995 "OMIT_QUICKBALANCE",
22996#endif
22997#ifdef SQLITE_OMIT_REINDEX
22998 "OMIT_REINDEX",
22999#endif
23000#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
23001 "OMIT_SCHEMA_PRAGMAS",
23002#endif
23003#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
23004 "OMIT_SCHEMA_VERSION_PRAGMAS",
23005#endif
23006#ifdef SQLITE_OMIT_SEH
23007 "OMIT_SEH",
23008#endif
23009#ifdef SQLITE_OMIT_SHARED_CACHE
23010 "OMIT_SHARED_CACHE",
23011#endif
23012#ifdef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
23013 "OMIT_SHUTDOWN_DIRECTORIES",
23014#endif
23015#ifdef SQLITE_OMIT_SUBQUERY
23016 "OMIT_SUBQUERY",
23017#endif
23018#ifdef SQLITE_OMIT_TCL_VARIABLE
23019 "OMIT_TCL_VARIABLE",
23020#endif
23021#ifdef SQLITE_OMIT_TEMPDB
23022 "OMIT_TEMPDB",
23023#endif
23024#ifdef SQLITE_OMIT_TEST_CONTROL
23025 "OMIT_TEST_CONTROL",
23026#endif
23027#ifdef SQLITE_OMIT_TRACE
23028# if SQLITE_OMIT_TRACE != 1
23029 "OMIT_TRACE=" CTIMEOPT_VAL(SQLITE_OMIT_TRACE)"SQLITE_OMIT_TRACE",
23030# endif
23031#endif
23032#ifdef SQLITE_OMIT_TRIGGER
23033 "OMIT_TRIGGER",
23034#endif
23035#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
23036 "OMIT_TRUNCATE_OPTIMIZATION",
23037#endif
23038#ifdef SQLITE_OMIT_UTF16
23039 "OMIT_UTF16",
23040#endif
23041#ifdef SQLITE_OMIT_VACUUM
23042 "OMIT_VACUUM",
23043#endif
23044#ifdef SQLITE_OMIT_VIEW
23045 "OMIT_VIEW",
23046#endif
23047#ifdef SQLITE_OMIT_VIRTUALTABLE
23048 "OMIT_VIRTUALTABLE",
23049#endif
23050#ifdef SQLITE_OMIT_WAL
23051 "OMIT_WAL",
23052#endif
23053#ifdef SQLITE_OMIT_WSD
23054 "OMIT_WSD",
23055#endif
23056#ifdef SQLITE_OMIT_XFER_OPT
23057 "OMIT_XFER_OPT",
23058#endif
23059#ifdef SQLITE_PERFORMANCE_TRACE
23060 "PERFORMANCE_TRACE",
23061#endif
23062#ifdef SQLITE_POWERSAFE_OVERWRITE1
23063# if SQLITE_POWERSAFE_OVERWRITE1 != 1
23064 "POWERSAFE_OVERWRITE=" CTIMEOPT_VAL(SQLITE_POWERSAFE_OVERWRITE)"1",
23065# endif
23066#endif
23067#ifdef SQLITE_PREFER_PROXY_LOCKING
23068 "PREFER_PROXY_LOCKING",
23069#endif
23070#ifdef SQLITE_PROXY_DEBUG
23071 "PROXY_DEBUG",
23072#endif
23073#ifdef SQLITE_REVERSE_UNORDERED_SELECTS
23074 "REVERSE_UNORDERED_SELECTS",
23075#endif
23076#ifdef SQLITE_RTREE_INT_ONLY
23077 "RTREE_INT_ONLY",
23078#endif
23079#ifdef SQLITE_SECURE_DELETE
23080 "SECURE_DELETE",
23081#endif
23082#ifdef SQLITE_SMALL_STACK
23083 "SMALL_STACK",
23084#endif
23085#ifdef SQLITE_SORTER_PMASZ250
23086 "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ)"250",
23087#endif
23088#ifdef SQLITE_SOUNDEX
23089 "SOUNDEX",
23090#endif
23091#ifdef SQLITE_STAT4_SAMPLES1
23092 "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES)"1",
23093#endif
23094#ifdef SQLITE_STMTJRNL_SPILL131072
23095 "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL)"131072",
23096#endif
23097#ifdef SQLITE_SUBSTR_COMPATIBILITY1
23098 "SUBSTR_COMPATIBILITY",
23099#endif
23100#if (!defined(SQLITE_WIN32_MALLOC) \
23101 && !defined(SQLITE_ZERO_MALLOC) \
23102 && !defined(SQLITE_MEMDEBUG) \
23103 ) || defined(SQLITE_SYSTEM_MALLOC1)
23104 "SYSTEM_MALLOC",
23105#endif
23106#ifdef SQLITE_TCL
23107 "TCL",
23108#endif
23109#ifdef SQLITE_TEMP_STORE1
23110 "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE)"1",
23111#endif
23112#ifdef SQLITE_TEST
23113 "TEST",
23114#endif
23115#if defined(SQLITE_THREADSAFE2)
23116 "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE)"2",
23117#elif defined(THREADSAFE)
23118 "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE)"THREADSAFE",
23119#else
23120 "THREADSAFE=1",
23121#endif
23122#ifdef SQLITE_UNLINK_AFTER_CLOSE
23123 "UNLINK_AFTER_CLOSE",
23124#endif
23125#ifdef SQLITE_UNTESTABLE
23126 "UNTESTABLE",
23127#endif
23128#ifdef SQLITE_USE_ALLOCA
23129 "USE_ALLOCA",
23130#endif
23131#ifdef SQLITE_USE_FCNTL_TRACE
23132 "USE_FCNTL_TRACE",
23133#endif
23134#ifdef SQLITE_USE_URI1
23135 "USE_URI",
23136#endif
23137#ifdef SQLITE_VDBE_COVERAGE
23138 "VDBE_COVERAGE",
23139#endif
23140#ifdef SQLITE_WIN32_MALLOC
23141 "WIN32_MALLOC",
23142#endif
23143#ifdef SQLITE_ZERO_MALLOC
23144 "ZERO_MALLOC",
23145#endif
23146
23147} ;
23148
23149SQLITE_PRIVATEstatic const char **sqlite3CompileOptions(int *pnOpt){
23150 *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
23151 return (const char**)sqlite3azCompileOpt;
23152}
23153
23154#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
23155
23156/************** End of ctime.c ***********************************************/
23157/************** Begin file global.c ******************************************/
23158/*
23159** 2008 June 13
23160**
23161** The author disclaims copyright to this source code. In place of
23162** a legal notice, here is a blessing:
23163**
23164** May you do good and not evil.
23165** May you find forgiveness for yourself and forgive others.
23166** May you share freely, never taking more than you give.
23167**
23168*************************************************************************
23169**
23170** This file contains definitions of global variables and constants.
23171*/
23172/* #include "sqliteInt.h" */
23173
23174/* An array to map all upper-case characters into their corresponding
23175** lower-case character.
23176**
23177** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
23178** handle case conversions for the UTF character set since the tables
23179** involved are nearly as big or bigger than SQLite itself.
23180*/
23181SQLITE_PRIVATEstatic const unsigned char sqlite3UpperToLower[] = {
23182#ifdef SQLITE_ASCII1
23183 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
23184 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
23185 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
23186 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
23187 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
23188 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
23189 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
23190 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
23191 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
23192 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
23193 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
23194 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
23195 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
23196 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
23197 252,253,254,255,
23198#endif
23199#ifdef SQLITE_EBCDIC
23200 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
23201 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
23202 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
23203 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
23204 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
23205 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
23206 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
23207 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
23208 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
23209 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
23210 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
23211 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
23212 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
23213 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
23214 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
23215 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
23216#endif
23217/* All of the upper-to-lower conversion data is above. The following
23218** 18 integers are completely unrelated. They are appended to the
23219** sqlite3UpperToLower[] array to avoid UBSAN warnings. Here's what is
23220** going on:
23221**
23222** The SQL comparison operators (<>, =, >, <=, <, and >=) are implemented
23223** by invoking sqlite3MemCompare(A,B) which compares values A and B and
23224** returns negative, zero, or positive if A is less then, equal to, or
23225** greater than B, respectively. Then the true false results is found by
23226** consulting sqlite3aLTb[opcode], sqlite3aEQb[opcode], or
23227** sqlite3aGTb[opcode] depending on whether the result of compare(A,B)
23228** is negative, zero, or positive, where opcode is the specific opcode.
23229** The only works because the comparison opcodes are consecutive and in
23230** this order: NE EQ GT LE LT GE. Various assert()s throughout the code
23231** ensure that is the case.
23232**
23233** These elements must be appended to another array. Otherwise the
23234** index (here shown as [256-OP_Ne]) would be out-of-bounds and thus
23235** be undefined behavior. That's goofy, but the C-standards people thought
23236** it was a good idea, so here we are.
23237*/
23238/* NE EQ GT LE LT GE */
23239 1, 0, 0, 1, 1, 0, /* aLTb[]: Use when compare(A,B) less than zero */
23240 0, 1, 0, 1, 0, 1, /* aEQb[]: Use when compare(A,B) equals zero */
23241 1, 0, 1, 0, 0, 1 /* aGTb[]: Use when compare(A,B) greater than zero*/
23242};
23243SQLITE_PRIVATEstatic const unsigned char *sqlite3aLTb = &sqlite3UpperToLower[256-OP_Ne53];
23244SQLITE_PRIVATEstatic const unsigned char *sqlite3aEQb = &sqlite3UpperToLower[256+6-OP_Ne53];
23245SQLITE_PRIVATEstatic const unsigned char *sqlite3aGTb = &sqlite3UpperToLower[256+12-OP_Ne53];
23246
23247/*
23248** The following 256 byte lookup table is used to support SQLites built-in
23249** equivalents to the following standard library functions:
23250**
23251** isspace() 0x01
23252** isalpha() 0x02
23253** isdigit() 0x04
23254** isalnum() 0x06
23255** isxdigit() 0x08
23256** toupper() 0x20
23257** SQLite identifier character 0x40 $, _, or non-ascii
23258** Quote character 0x80
23259**
23260** Bit 0x20 is set if the mapped character requires translation to upper
23261** case. i.e. if the character is a lower-case ASCII character.
23262** If x is a lower-case ASCII character, then its upper-case equivalent
23263** is (x - 0x20). Therefore toupper() can be implemented as:
23264**
23265** (x & ~(map[x]&0x20))
23266**
23267** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
23268** array. tolower() is used more often than toupper() by SQLite.
23269**
23270** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
23271** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
23272** non-ASCII UTF character. Hence the test for whether or not a character is
23273** part of an identifier is 0x46.
23274*/
23275SQLITE_PRIVATEstatic const unsigned char sqlite3CtypeMap[256] = {
23276 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
23277 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
23278 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
23279 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
23280 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
23281 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
23282 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
23283 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
23284
23285 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
23286 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
23287 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
23288 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
23289 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
23290 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
23291 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
23292 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
23293
23294 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
23295 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
23296 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
23297 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
23298 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
23299 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
23300 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
23301 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
23302
23303 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
23304 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
23305 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
23306 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
23307 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
23308 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
23309 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
23310 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
23311};
23312
23313/* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
23314** compatibility for legacy applications, the URI filename capability is
23315** disabled by default.
23316**
23317** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
23318** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
23319**
23320** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
23321** disabled. The default value may be changed by compiling with the
23322** SQLITE_USE_URI symbol defined.
23323*/
23324#ifndef SQLITE_USE_URI1
23325# define SQLITE_USE_URI1 0
23326#endif
23327
23328/* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
23329** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
23330** that compile-time option is omitted.
23331*/
23332#if !defined(SQLITE_ALLOW_COVERING_INDEX_SCAN1)
23333# define SQLITE_ALLOW_COVERING_INDEX_SCAN1 1
23334#else
23335# if !SQLITE_ALLOW_COVERING_INDEX_SCAN1
23336# error "Compile-time disabling of covering index scan using the\
23337 -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\
23338 Contact SQLite developers if this is a problem for you, and\
23339 delete this #error macro to continue with your build."
23340# endif
23341#endif
23342
23343/* The minimum PMA size is set to this value multiplied by the database
23344** page size in bytes.
23345*/
23346#ifndef SQLITE_SORTER_PMASZ250
23347# define SQLITE_SORTER_PMASZ250 250
23348#endif
23349
23350/* Statement journals spill to disk when their size exceeds the following
23351** threshold (in bytes). 0 means that statement journals are created and
23352** written to disk immediately (the default behavior for SQLite versions
23353** before 3.12.0). -1 means always keep the entire statement journal in
23354** memory. (The statement journal is also always held entirely in memory
23355** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
23356** setting.)
23357*/
23358#ifndef SQLITE_STMTJRNL_SPILL131072
23359# define SQLITE_STMTJRNL_SPILL131072 (64*1024)
23360#endif
23361
23362/*
23363** The default lookaside-configuration, the format "SZ,N". SZ is the
23364** number of bytes in each lookaside slot (should be a multiple of 8)
23365** and N is the number of slots. The lookaside-configuration can be
23366** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
23367** or at run-time for an individual database connection using
23368** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
23369**
23370** With the two-size-lookaside enhancement, less lookaside is required.
23371** The default configuration of 1200,40 actually provides 30 1200-byte slots
23372** and 93 128-byte slots, which is more lookaside than is available
23373** using the older 1200,100 configuration without two-size-lookaside.
23374*/
23375#ifndef SQLITE_DEFAULT_LOOKASIDE1200,40
23376# ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
23377# define SQLITE_DEFAULT_LOOKASIDE1200,40 1200,100 /* 120KB of memory */
23378# else
23379# define SQLITE_DEFAULT_LOOKASIDE1200,40 1200,40 /* 48KB of memory */
23380# endif
23381#endif
23382
23383
23384/* The default maximum size of an in-memory database created using
23385** sqlite3_deserialize()
23386*/
23387#ifndef SQLITE_MEMDB_DEFAULT_MAXSIZE1073741824
23388# define SQLITE_MEMDB_DEFAULT_MAXSIZE1073741824 1073741824
23389#endif
23390
23391/*
23392** The following singleton contains the global configuration for
23393** the SQLite library.
23394*/
23395SQLITE_PRIVATEstatic SQLITE_WSD struct Sqlite3Config sqlite3Config = {
23396 SQLITE_DEFAULT_MEMSTATUS1, /* bMemstat */
23397 1, /* bCoreMutex */
23398 SQLITE_THREADSAFE2==1, /* bFullMutex */
23399 SQLITE_USE_URI1, /* bOpenUri */
23400 SQLITE_ALLOW_COVERING_INDEX_SCAN1, /* bUseCis */
23401 0, /* bSmallMalloc */
23402 1, /* bExtraSchemaChecks */
23403#ifdef SQLITE_DEBUG
23404 0, /* bJsonSelfcheck */
23405#endif
23406 0x7ffffffe, /* mxStrlen */
23407 0, /* neverCorrupt */
23408 SQLITE_DEFAULT_LOOKASIDE1200,40, /* szLookaside, nLookaside */
23409 SQLITE_STMTJRNL_SPILL131072, /* nStmtSpill */
23410 {0,0,0,0,0,0,0,0}, /* m */
23411 {0,0,0,0,0,0,0,0,0}, /* mutex */
23412 {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
23413 (void*)0, /* pHeap */
23414 0, /* nHeap */
23415 0, 0, /* mnHeap, mxHeap */
23416 SQLITE_DEFAULT_MMAP_SIZE0, /* szMmap */
23417 SQLITE_MAX_MMAP_SIZE20971520, /* mxMmap */
23418 (void*)0, /* pPage */
23419 0, /* szPage */
23420 SQLITE_DEFAULT_PCACHE_INITSZ20, /* nPage */
23421 0, /* mxParserStack */
23422 0, /* sharedCacheEnabled */
23423 SQLITE_SORTER_PMASZ250, /* szPma */
23424 /* All the rest should always be initialized to zero */
23425 0, /* isInit */
23426 0, /* inProgress */
23427 0, /* isMutexInit */
23428 0, /* isMallocInit */
23429 0, /* isPCacheInit */
23430 0, /* nRefInitMutex */
23431 0, /* pInitMutex */
23432 0, /* xLog */
23433 0, /* pLogArg */
23434#ifdef SQLITE_ENABLE_SQLLOG
23435 0, /* xSqllog */
23436 0, /* pSqllogArg */
23437#endif
23438#ifdef SQLITE_VDBE_COVERAGE
23439 0, /* xVdbeBranch */
23440 0, /* pVbeBranchArg */
23441#endif
23442#ifndef SQLITE_OMIT_DESERIALIZE
23443 SQLITE_MEMDB_DEFAULT_MAXSIZE1073741824, /* mxMemdbSize */
23444#endif
23445#ifndef SQLITE_UNTESTABLE
23446 0, /* xTestCallback */
23447#endif
23448#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
23449 0, /* mNoVisibleRowid. 0 == allow rowid-in-view */
23450#endif
23451 0, /* bLocaltimeFault */
23452 0, /* xAltLocaltime */
23453 0x7ffffffe, /* iOnceResetThreshold */
23454 SQLITE_DEFAULT_SORTERREF_SIZE0x7fffffff, /* szSorterRef */
23455 0, /* iPrngSeed */
23456#ifdef SQLITE_DEBUG
23457 {0,0,0,0,0,0}, /* aTune */
23458#endif
23459};
23460
23461/*
23462** Hash table for global functions - functions common to all
23463** database connections. After initialization, this table is
23464** read-only.
23465*/
23466SQLITE_PRIVATEstatic FuncDefHash sqlite3BuiltinFunctions;
23467
23468#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
23469/*
23470** Counter used for coverage testing. Does not come into play for
23471** release builds.
23472**
23473** Access to this global variable is not mutex protected. This might
23474** result in TSAN warnings. But as the variable does not exist in
23475** release builds, that should not be a concern.
23476*/
23477SQLITE_PRIVATEstatic unsigned int sqlite3CoverageCounter;
23478#endif /* SQLITE_COVERAGE_TEST || SQLITE_DEBUG */
23479
23480#ifdef VDBE_PROFILE
23481/*
23482** The following performance counter can be used in place of
23483** sqlite3Hwtime() for profiling. This is a no-op on standard builds.
23484*/
23485SQLITE_PRIVATEstatic sqlite3_uint64 sqlite3NProfileCnt = 0;
23486#endif
23487
23488/*
23489** The value of the "pending" byte must be 0x40000000 (1 byte past the
23490** 1-gibabyte boundary) in a compatible database. SQLite never uses
23491** the database page that contains the pending byte. It never attempts
23492** to read or write that page. The pending byte page is set aside
23493** for use by the VFS layers as space for managing file locks.
23494**
23495** During testing, it is often desirable to move the pending byte to
23496** a different position in the file. This allows code that has to
23497** deal with the pending byte to run on files that are much smaller
23498** than 1 GiB. The sqlite3_test_control() interface can be used to
23499** move the pending byte.
23500**
23501** IMPORTANT: Changing the pending byte to any value other than
23502** 0x40000000 results in an incompatible database file format!
23503** Changing the pending byte during operation will result in undefined
23504** and incorrect behavior.
23505*/
23506#ifndef SQLITE_OMIT_WSD
23507SQLITE_PRIVATEstatic int sqlite3PendingByte = 0x40000000;
23508#endif
23509
23510/*
23511** Tracing flags set by SQLITE_TESTCTRL_TRACEFLAGS.
23512*/
23513SQLITE_PRIVATEstatic u32 sqlite3TreeTrace = 0;
23514SQLITE_PRIVATEstatic u32 sqlite3WhereTrace = 0;
23515
23516/* #include "opcodes.h" */
23517/*
23518** Properties of opcodes. The OPFLG_INITIALIZER macro is
23519** created by mkopcodeh.awk during compilation. Data is obtained
23520** from the comments following the "case OP_xxxx:" statements in
23521** the vdbe.c file.
23522*/
23523SQLITE_PRIVATEstatic const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER{ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x41, 0x00, 0x81, 0x01,
0x01, 0x81, 0x83, 0x83, 0x01, 0x01, 0x03, 0x03, 0x01, 0x12, 0x01
, 0xc9, 0xc9, 0xc9, 0xc9, 0x01, 0x49, 0x49, 0x49, 0x49, 0xc9,
0x49, 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x41, 0x41, 0x41, 0x41
, 0x41, 0x26, 0x26, 0x41, 0x23, 0x0b, 0x81, 0x01, 0x03, 0x03,
0x03, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x01
, 0x41, 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10,
0x10, 0x00, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00
, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20,
0x40, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x40, 0x26, 0x26
, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x40,
0x12, 0x40, 0x40, 0x10, 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x40
, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x50,
0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40, 0x10, 0x00, 0x00
, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x06,
0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50, 0x40, 0x00,
0x10, 0x10, 0x02, 0x12, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
, 0x00,}
;
23524
23525/*
23526** Name of the default collating sequence
23527*/
23528SQLITE_PRIVATEstatic const char sqlite3StrBINARY[] = "BINARY";
23529
23530/*
23531** Standard typenames. These names must match the COLTYPE_* definitions.
23532** Adjust the SQLITE_N_STDTYPE value if adding or removing entries.
23533**
23534** sqlite3StdType[] The actual names of the datatypes.
23535**
23536** sqlite3StdTypeLen[] The length (in bytes) of each entry
23537** in sqlite3StdType[].
23538**
23539** sqlite3StdTypeAffinity[] The affinity associated with each entry
23540** in sqlite3StdType[].
23541*/
23542SQLITE_PRIVATEstatic const unsigned char sqlite3StdTypeLen[] = { 3, 4, 3, 7, 4, 4 };
23543SQLITE_PRIVATEstatic const char sqlite3StdTypeAffinity[] = {
23544 SQLITE_AFF_NUMERIC0x43,
23545 SQLITE_AFF_BLOB0x41,
23546 SQLITE_AFF_INTEGER0x44,
23547 SQLITE_AFF_INTEGER0x44,
23548 SQLITE_AFF_REAL0x45,
23549 SQLITE_AFF_TEXT0x42
23550};
23551SQLITE_PRIVATEstatic const char *sqlite3StdType[] = {
23552 "ANY",
23553 "BLOB",
23554 "INT",
23555 "INTEGER",
23556 "REAL",
23557 "TEXT"
23558};
23559
23560/************** End of global.c **********************************************/
23561/************** Begin file status.c ******************************************/
23562/*
23563** 2008 June 18
23564**
23565** The author disclaims copyright to this source code. In place of
23566** a legal notice, here is a blessing:
23567**
23568** May you do good and not evil.
23569** May you find forgiveness for yourself and forgive others.
23570** May you share freely, never taking more than you give.
23571**
23572*************************************************************************
23573**
23574** This module implements the sqlite3_status() interface and related
23575** functionality.
23576*/
23577/* #include "sqliteInt.h" */
23578/************** Include vdbeInt.h in the middle of status.c ******************/
23579/************** Begin file vdbeInt.h *****************************************/
23580/*
23581** 2003 September 6
23582**
23583** The author disclaims copyright to this source code. In place of
23584** a legal notice, here is a blessing:
23585**
23586** May you do good and not evil.
23587** May you find forgiveness for yourself and forgive others.
23588** May you share freely, never taking more than you give.
23589**
23590*************************************************************************
23591** This is the header file for information that is private to the
23592** VDBE. This information used to all be at the top of the single
23593** source code file "vdbe.c". When that file became too big (over
23594** 6000 lines long) it was split up into several smaller files and
23595** this header information was factored out.
23596*/
23597#ifndef SQLITE_VDBEINT_H
23598#define SQLITE_VDBEINT_H
23599
23600/*
23601** The maximum number of times that a statement will try to reparse
23602** itself before giving up and returning SQLITE_SCHEMA.
23603*/
23604#ifndef SQLITE_MAX_SCHEMA_RETRY50
23605# define SQLITE_MAX_SCHEMA_RETRY50 50
23606#endif
23607
23608/*
23609** VDBE_DISPLAY_P4 is true or false depending on whether or not the
23610** "explain" P4 display logic is enabled.
23611*/
23612#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG1) \
23613 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) \
23614 || defined(SQLITE_ENABLE_BYTECODE_VTAB)
23615# define VDBE_DISPLAY_P41 1
23616#else
23617# define VDBE_DISPLAY_P41 0
23618#endif
23619
23620/*
23621** SQL is translated into a sequence of instructions to be
23622** executed by a virtual machine. Each instruction is an instance
23623** of the following structure.
23624*/
23625typedef struct VdbeOp Op;
23626
23627/*
23628** Boolean values
23629*/
23630typedef unsigned Bool;
23631
23632/* Opaque type used by code in vdbesort.c */
23633typedef struct VdbeSorter VdbeSorter;
23634
23635/* Elements of the linked list at Vdbe.pAuxData */
23636typedef struct AuxData AuxData;
23637
23638/* A cache of large TEXT or BLOB values in a VdbeCursor */
23639typedef struct VdbeTxtBlbCache VdbeTxtBlbCache;
23640
23641/* Types of VDBE cursors */
23642#define CURTYPE_BTREE0 0
23643#define CURTYPE_SORTER1 1
23644#define CURTYPE_VTAB2 2
23645#define CURTYPE_PSEUDO3 3
23646
23647/*
23648** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
23649**
23650** * A b-tree cursor
23651** - In the main database or in an ephemeral database
23652** - On either an index or a table
23653** * A sorter
23654** * A virtual table
23655** * A one-row "pseudotable" stored in a single register
23656*/
23657typedef struct VdbeCursor VdbeCursor;
23658struct VdbeCursor {
23659 u8 eCurType; /* One of the CURTYPE_* values above */
23660 i8 iDb; /* Index of cursor database in db->aDb[] */
23661 u8 nullRow; /* True if pointing to a row with no data */
23662 u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
23663 u8 isTable; /* True for rowid tables. False for indexes */
23664#ifdef SQLITE_DEBUG
23665 u8 seekOp; /* Most recent seek operation on this cursor */
23666 u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
23667#endif
23668 Bool isEphemeral:1; /* True for an ephemeral table */
23669 Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
23670 Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
23671 Bool noReuse:1; /* OpenEphemeral may not reuse this cursor */
23672 Bool colCache:1; /* pCache pointer is initialized and non-NULL */
23673 u16 seekHit; /* See the OP_SeekHit and OP_IfNoHope opcodes */
23674 union { /* pBtx for isEphermeral. pAltMap otherwise */
23675 Btree *pBtx; /* Separate file holding temporary table */
23676 u32 *aAltMap; /* Mapping from table to index column numbers */
23677 } ub;
23678 i64 seqCount; /* Sequence counter */
23679
23680 /* Cached OP_Column parse information is only valid if cacheStatus matches
23681 ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
23682 ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
23683 ** the cache is out of date. */
23684 u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
23685 int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
23686 ** if there have been no prior seeks on the cursor. */
23687 /* seekResult does not distinguish between "no seeks have ever occurred
23688 ** on this cursor" and "the most recent seek was an exact match".
23689 ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
23690
23691 /* When a new VdbeCursor is allocated, only the fields above are zeroed.
23692 ** The fields that follow are uninitialized, and must be individually
23693 ** initialized prior to first use. */
23694 VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
23695 union {
23696 BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */
23697 sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
23698 VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
23699 } uc;
23700 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
23701 u32 iHdrOffset; /* Offset to next unparsed byte of the header */
23702 Pgno pgnoRoot; /* Root page of the open btree cursor */
23703 i16 nField; /* Number of fields in the header */
23704 u16 nHdrParsed; /* Number of header fields parsed so far */
23705 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
23706 u32 *aOffset; /* Pointer to aType[nField] */
23707 const u8 *aRow; /* Data for the current row, if all on one page */
23708 u32 payloadSize; /* Total number of bytes in the record */
23709 u32 szRow; /* Byte available in aRow */
23710#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
23711 u64 maskUsed; /* Mask of columns used by this cursor */
23712#endif
23713 VdbeTxtBlbCache *pCache; /* Cache of large TEXT or BLOB values */
23714
23715 /* Space is allocated for aType to hold at least 2*nField+1 entries:
23716 ** nField slots for aType[] and nField+1 array slots for aOffset[] */
23717 u32 aType[FLEXARRAY]; /* Type values record decode. MUST BE LAST */
23718};
23719
23720/*
23721** The size (in bytes) of a VdbeCursor object that has an nField value of N
23722** or less. The value of SZ_VDBECURSOR(n) is guaranteed to be a multiple
23723** of 8.
23724*/
23725#define SZ_VDBECURSOR(N)((((__builtin_offsetof(VdbeCursor, aType))+7)&~7) + ((N)+
1)*sizeof(u64))
\
23726 (ROUND8(offsetof(VdbeCursor,aType))(((__builtin_offsetof(VdbeCursor, aType))+7)&~7) + ((N)+1)*sizeof(u64))
23727
23728/* Return true if P is a null-only cursor
23729*/
23730#define IsNullCursor(P)((P)->eCurType==3 && (P)->nullRow && (P
)->seekResult==0)
\
23731 ((P)->eCurType==CURTYPE_PSEUDO3 && (P)->nullRow && (P)->seekResult==0)
23732
23733/*
23734** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
23735*/
23736#define CACHE_STALE0 0
23737
23738/*
23739** Large TEXT or BLOB values can be slow to load, so we want to avoid
23740** loading them more than once. For that reason, large TEXT and BLOB values
23741** can be stored in a cache defined by this object, and attached to the
23742** VdbeCursor using the pCache field.
23743*/
23744struct VdbeTxtBlbCache {
23745 char *pCValue; /* A RCStr buffer to hold the value */
23746 i64 iOffset; /* File offset of the row being cached */
23747 int iCol; /* Column for which the cache is valid */
23748 u32 cacheStatus; /* Vdbe.cacheCtr value */
23749 u32 colCacheCtr; /* Column cache counter */
23750};
23751
23752/*
23753** When a sub-program is executed (OP_Program), a structure of this type
23754** is allocated to store the current value of the program counter, as
23755** well as the current memory cell array and various other frame specific
23756** values stored in the Vdbe struct. When the sub-program is finished,
23757** these values are copied back to the Vdbe from the VdbeFrame structure,
23758** restoring the state of the VM to as it was before the sub-program
23759** began executing.
23760**
23761** The memory for a VdbeFrame object is allocated and managed by a memory
23762** cell in the parent (calling) frame. When the memory cell is deleted or
23763** overwritten, the VdbeFrame object is not freed immediately. Instead, it
23764** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
23765** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
23766** this instead of deleting the VdbeFrame immediately is to avoid recursive
23767** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
23768** child frame are released.
23769**
23770** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
23771** set to NULL if the currently executing frame is the main program.
23772*/
23773typedef struct VdbeFrame VdbeFrame;
23774struct VdbeFrame {
23775 Vdbe *v; /* VM this frame belongs to */
23776 VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
23777 Op *aOp; /* Program instructions for parent frame */
23778 Mem *aMem; /* Array of memory cells for parent frame */
23779 VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
23780 u8 *aOnce; /* Bitmask used by OP_Once */
23781 void *token; /* Copy of SubProgram.token */
23782 i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
23783 AuxData *pAuxData; /* Linked list of auxdata allocations */
23784#if SQLITE_DEBUG
23785 u32 iFrameMagic; /* magic number for sanity checking */
23786#endif
23787 int nCursor; /* Number of entries in apCsr */
23788 int pc; /* Program Counter in parent (calling) frame */
23789 int nOp; /* Size of aOp array */
23790 int nMem; /* Number of entries in aMem */
23791 int nChildMem; /* Number of memory cells for child frame */
23792 int nChildCsr; /* Number of cursors for child frame */
23793 i64 nChange; /* Statement changes (Vdbe.nChange) */
23794 i64 nDbChange; /* Value of db->nChange */
23795};
23796
23797/* Magic number for sanity checking on VdbeFrame objects */
23798#define SQLITE_FRAME_MAGIC0x879fb71e 0x879fb71e
23799
23800/*
23801** Return a pointer to the array of registers allocated for use
23802** by a VdbeFrame.
23803*/
23804#define VdbeFrameMem(p)((Mem *)&((u8 *)p)[(((sizeof(VdbeFrame))+7)&~7)]) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))(((sizeof(VdbeFrame))+7)&~7)])
23805
23806/*
23807** Internally, the vdbe manipulates nearly all SQL values as Mem
23808** structures. Each Mem struct may cache multiple representations (string,
23809** integer etc.) of the same value.
23810*/
23811struct sqlite3_value {
23812 union MemValue {
23813 double r; /* Real value used when MEM_Real is set in flags */
23814 i64 i; /* Integer value used when MEM_Int is set in flags */
23815 int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
23816 const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
23817 FuncDef *pDef; /* Used only when flags==MEM_Agg */
23818 } u;
23819 char *z; /* String or BLOB value */
23820 int n; /* Number of characters in string value, excluding '\0' */
23821 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
23822 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
23823 u8 eSubtype; /* Subtype for this value */
23824 /* ShallowCopy only needs to copy the information above */
23825 sqlite3 *db; /* The associated database connection */
23826 int szMalloc; /* Size of the zMalloc allocation */
23827 u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
23828 char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
23829 void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
23830#ifdef SQLITE_DEBUG
23831 Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
23832 u16 mScopyFlags; /* flags value immediately after the shallow copy */
23833 u8 bScopy; /* The pScopyFrom of some other Mem *might* point here */
23834#endif
23835};
23836
23837/*
23838** Size of struct Mem not including the Mem.zMalloc member or anything that
23839** follows.
23840*/
23841#define MEMCELLSIZE__builtin_offsetof(Mem, db) offsetof(Mem,db)__builtin_offsetof(Mem, db)
23842
23843/* One or more of the following flags are set to indicate the
23844** representations of the value stored in the Mem struct.
23845**
23846** * MEM_Null An SQL NULL value
23847**
23848** * MEM_Null|MEM_Zero An SQL NULL with the virtual table
23849** UPDATE no-change flag set
23850**
23851** * MEM_Null|MEM_Term| An SQL NULL, but also contains a
23852** MEM_Subtype pointer accessible using
23853** sqlite3_value_pointer().
23854**
23855** * MEM_Null|MEM_Cleared Special SQL NULL that compares non-equal
23856** to other NULLs even using the IS operator.
23857**
23858** * MEM_Str A string, stored in Mem.z with
23859** length Mem.n. Zero-terminated if
23860** MEM_Term is set. This flag is
23861** incompatible with MEM_Blob and
23862** MEM_Null, but can appear with MEM_Int,
23863** MEM_Real, and MEM_IntReal.
23864**
23865** * MEM_Blob A blob, stored in Mem.z length Mem.n.
23866** Incompatible with MEM_Str, MEM_Null,
23867** MEM_Int, MEM_Real, and MEM_IntReal.
23868**
23869** * MEM_Blob|MEM_Zero A blob in Mem.z of length Mem.n plus
23870** MEM.u.i extra 0x00 bytes at the end.
23871**
23872** * MEM_Int Integer stored in Mem.u.i.
23873**
23874** * MEM_Real Real stored in Mem.u.r.
23875**
23876** * MEM_IntReal Real stored as an integer in Mem.u.i.
23877**
23878** If the MEM_Null flag is set, then the value is an SQL NULL value.
23879** For a pointer type created using sqlite3_bind_pointer() or
23880** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
23881**
23882** If the MEM_Str flag is set then Mem.z points at a string representation.
23883** Usually this is encoded in the same unicode encoding as the main
23884** database (see below for exceptions). If the MEM_Term flag is also
23885** set, then the string is nul terminated. The MEM_Int and MEM_Real
23886** flags may coexist with the MEM_Str flag.
23887*/
23888#define MEM_Undefined0x0000 0x0000 /* Value is undefined */
23889#define MEM_Null0x0001 0x0001 /* Value is NULL (or a pointer) */
23890#define MEM_Str0x0002 0x0002 /* Value is a string */
23891#define MEM_Int0x0004 0x0004 /* Value is an integer */
23892#define MEM_Real0x0008 0x0008 /* Value is a real number */
23893#define MEM_Blob0x0010 0x0010 /* Value is a BLOB */
23894#define MEM_IntReal0x0020 0x0020 /* MEM_Int that stringifies like MEM_Real */
23895#define MEM_AffMask0x003f 0x003f /* Mask of affinity bits */
23896
23897/* Extra bits that modify the meanings of the core datatypes above
23898*/
23899#define MEM_FromBind0x0040 0x0040 /* Value originates from sqlite3_bind() */
23900 /* 0x0080 // Available */
23901#define MEM_Cleared0x0100 0x0100 /* NULL set by OP_Null, not from data */
23902#define MEM_Term0x0200 0x0200 /* String in Mem.z is zero terminated */
23903#define MEM_Zero0x0400 0x0400 /* Mem.i contains count of 0s appended to blob */
23904#define MEM_Subtype0x0800 0x0800 /* Mem.eSubtype is valid */
23905#define MEM_TypeMask0x0dbf 0x0dbf /* Mask of type bits */
23906
23907/* Bits that determine the storage for Mem.z for a string or blob or
23908** aggregate accumulator.
23909*/
23910#define MEM_Dyn0x1000 0x1000 /* Need to call Mem.xDel() on Mem.z */
23911#define MEM_Static0x2000 0x2000 /* Mem.z points to a static string */
23912#define MEM_Ephem0x4000 0x4000 /* Mem.z points to an ephemeral string */
23913#define MEM_Agg0x8000 0x8000 /* Mem.z points to an agg function context */
23914
23915/* Return TRUE if Mem X contains dynamically allocated content - anything
23916** that needs to be deallocated to avoid a leak.
23917*/
23918#define VdbeMemDynamic(X)(((X)->flags&(0x8000|0x1000))!=0) \
23919 (((X)->flags&(MEM_Agg0x8000|MEM_Dyn0x1000))!=0)
23920
23921/*
23922** Clear any existing type flags from a Mem and replace them with f
23923*/
23924#define MemSetTypeFlag(p, f)((p)->flags = ((p)->flags&~(0x0dbf|0x0400))|f) \
23925 ((p)->flags = ((p)->flags&~(MEM_TypeMask0x0dbf|MEM_Zero0x0400))|f)
23926
23927/*
23928** True if Mem X is a NULL-nochng type.
23929*/
23930#define MemNullNochng(X)(((X)->flags&0x0dbf)==(0x0001|0x0400) && (X)->
n==0 && (X)->u.nZero==0)
\
23931 (((X)->flags&MEM_TypeMask0x0dbf)==(MEM_Null0x0001|MEM_Zero0x0400) \
23932 && (X)->n==0 && (X)->u.nZero==0)
23933
23934/*
23935** Return true if a memory cell has been initialized and is valid.
23936** is for use inside assert() statements only.
23937**
23938** A Memory cell is initialized if at least one of the
23939** MEM_Null, MEM_Str, MEM_Int, MEM_Real, MEM_Blob, or MEM_IntReal bits
23940** is set. It is "undefined" if all those bits are zero.
23941*/
23942#ifdef SQLITE_DEBUG
23943#define memIsValid(M) ((M)->flags & MEM_AffMask0x003f)!=0
23944#endif
23945
23946/*
23947** Each auxiliary data pointer stored by a user defined function
23948** implementation calling sqlite3_set_auxdata() is stored in an instance
23949** of this structure. All such structures associated with a single VM
23950** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
23951** when the VM is halted (if not before).
23952*/
23953struct AuxData {
23954 int iAuxOp; /* Instruction number of OP_Function opcode */
23955 int iAuxArg; /* Index of function argument. */
23956 void *pAux; /* Aux data pointer */
23957 void (*xDeleteAux)(void*); /* Destructor for the aux data */
23958 AuxData *pNextAux; /* Next element in list */
23959};
23960
23961/*
23962** The "context" argument for an installable function. A pointer to an
23963** instance of this structure is the first argument to the routines used
23964** implement the SQL functions.
23965**
23966** There is a typedef for this structure in sqlite.h. So all routines,
23967** even the public interface to SQLite, can use a pointer to this structure.
23968** But this file is the only place where the internal details of this
23969** structure are known.
23970**
23971** This structure is defined inside of vdbeInt.h because it uses substructures
23972** (Mem) which are only defined there.
23973*/
23974struct sqlite3_context {
23975 Mem *pOut; /* The return value is stored here */
23976 FuncDef *pFunc; /* Pointer to function information */
23977 Mem *pMem; /* Memory cell used to store aggregate context */
23978 Vdbe *pVdbe; /* The VM that owns this context */
23979 int iOp; /* Instruction number of OP_Function */
23980 int isError; /* Error code returned by the function. */
23981 u8 enc; /* Encoding to use for results */
23982 u8 skipFlag; /* Skip accumulator loading if true */
23983 u16 argc; /* Number of arguments */
23984 sqlite3_value *argv[FLEXARRAY]; /* Argument set */
23985};
23986
23987/*
23988** The size (in bytes) of an sqlite3_context object that holds N
23989** argv[] arguments.
23990*/
23991#define SZ_CONTEXT(N)(__builtin_offsetof(sqlite3_context, argv)+(N)*sizeof(sqlite3_value
*))
\
23992 (offsetof(sqlite3_context,argv)__builtin_offsetof(sqlite3_context, argv)+(N)*sizeof(sqlite3_value*))
23993
23994
23995/* The ScanStatus object holds a single value for the
23996** sqlite3_stmt_scanstatus() interface.
23997**
23998** aAddrRange[]:
23999** This array is used by ScanStatus elements associated with EQP
24000** notes that make an SQLITE_SCANSTAT_NCYCLE value available. It is
24001** an array of up to 3 ranges of VM addresses for which the Vdbe.anCycle[]
24002** values should be summed to calculate the NCYCLE value. Each pair of
24003** integer addresses is a start and end address (both inclusive) for a range
24004** instructions. A start value of 0 indicates an empty range.
24005*/
24006typedef struct ScanStatus ScanStatus;
24007struct ScanStatus {
24008 int addrExplain; /* OP_Explain for loop */
24009 int aAddrRange[6];
24010 int addrLoop; /* Address of "loops" counter */
24011 int addrVisit; /* Address of "rows visited" counter */
24012 int iSelectID; /* The "Select-ID" for this loop */
24013 LogEst nEst; /* Estimated output rows per loop */
24014 char *zName; /* Name of table or index */
24015};
24016
24017/* The DblquoteStr object holds the text of a double-quoted
24018** string for a prepared statement. A linked list of these objects
24019** is constructed during statement parsing and is held on Vdbe.pDblStr.
24020** When computing a normalized SQL statement for an SQL statement, that
24021** list is consulted for each double-quoted identifier to see if the
24022** identifier should really be a string literal.
24023*/
24024typedef struct DblquoteStr DblquoteStr;
24025struct DblquoteStr {
24026 DblquoteStr *pNextStr; /* Next string literal in the list */
24027 char z[8]; /* Dequoted value for the string */
24028};
24029
24030/*
24031** An instance of the virtual machine. This structure contains the complete
24032** state of the virtual machine.
24033**
24034** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
24035** is really a pointer to an instance of this structure.
24036*/
24037struct Vdbe {
24038 sqlite3 *db; /* The database connection that owns this statement */
24039 Vdbe **ppVPrev,*pVNext; /* Linked list of VDBEs with the same Vdbe.db */
24040 Parse *pParse; /* Parsing context used to create this Vdbe */
24041 ynVar nVar; /* Number of entries in aVar[] */
24042 int nMem; /* Number of memory locations currently allocated */
24043 int nCursor; /* Number of slots in apCsr[] */
24044 u32 cacheCtr; /* VdbeCursor row cache generation counter */
24045 int pc; /* The program counter */
24046 int rc; /* Value to return */
24047 i64 nChange; /* Number of db changes made since last reset */
24048 int iStatement; /* Statement number (or 0 if has no opened stmt) */
24049 i64 iCurrentTime; /* Value of julianday('now') for this statement */
24050 i64 nFkConstraint; /* Number of imm. FK constraints this VM */
24051 i64 nStmtDefCons; /* Number of def. constraints when stmt started */
24052 i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
24053 Mem *aMem; /* The memory locations */
24054 Mem **apArg; /* Arguments xUpdate and xFilter vtab methods */
24055 VdbeCursor **apCsr; /* One element of this array for each open cursor */
24056 Mem *aVar; /* Values for the OP_Variable opcode. */
24057
24058 /* When allocating a new Vdbe object, all of the fields below should be
24059 ** initialized to zero or NULL */
24060
24061 Op *aOp; /* Space to hold the virtual machine's program */
24062 int nOp; /* Number of instructions in the program */
24063 int nOpAlloc; /* Slots allocated for aOp[] */
24064 Mem *aColName; /* Column names to return */
24065 Mem *pResultRow; /* Current output row */
24066 char *zErrMsg; /* Error message written here */
24067 VList *pVList; /* Name of variables */
24068#ifndef SQLITE_OMIT_TRACE
24069 i64 startTime; /* Time when query started - used for profiling */
24070#endif
24071#ifdef SQLITE_DEBUG
24072 int rcApp; /* errcode set by sqlite3_result_error_code() */
24073 u32 nWrite; /* Number of write operations that have occurred */
24074 int napArg; /* Size of the apArg[] array */
24075#endif
24076 u16 nResColumn; /* Number of columns in one row of the result set */
24077 u16 nResAlloc; /* Column slots allocated to aColName[] */
24078 u8 errorAction; /* Recovery action to do in case of an error */
24079 u8 minWriteFileFormat; /* Minimum file format for writable database files */
24080 u8 prepFlags; /* SQLITE_PREPARE_* flags */
24081 u8 eVdbeState; /* On of the VDBE_*_STATE values */
24082 bft expired:2; /* 1: recompile VM immediately 2: when convenient */
24083 bft explain:2; /* 0: normal, 1: EXPLAIN, 2: EXPLAIN QUERY PLAN */
24084 bft changeCntOn:1; /* True to update the change-counter */
24085 bft usesStmtJournal:1; /* True if uses a statement journal */
24086 bft readOnly:1; /* True for statements that do not write */
24087 bft bIsReader:1; /* True for statements that read */
24088 bft haveEqpOps:1; /* Bytecode supports EXPLAIN QUERY PLAN */
24089 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
24090 yDbMask lockMask; /* Subset of btreeMask that requires a lock */
24091 u32 aCounter[9]; /* Counters used by sqlite3_stmt_status() */
24092 char *zSql; /* Text of the SQL statement that generated this */
24093#ifdef SQLITE_ENABLE_NORMALIZE
24094 char *zNormSql; /* Normalization of the associated SQL statement */
24095 DblquoteStr *pDblStr; /* List of double-quoted string literals */
24096#endif
24097 void *pFree; /* Free this when deleting the vdbe */
24098 VdbeFrame *pFrame; /* Parent frame */
24099 VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
24100 int nFrame; /* Number of frames in pFrame list */
24101 u32 expmask; /* Binding to these vars invalidates VM */
24102 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
24103 AuxData *pAuxData; /* Linked list of auxdata allocations */
24104#ifdef SQLITE_ENABLE_STMT_SCANSTATUS1
24105 int nScan; /* Entries in aScan[] */
24106 ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
24107#endif
24108};
24109
24110/*
24111** The following are allowed values for Vdbe.eVdbeState
24112*/
24113#define VDBE_INIT_STATE0 0 /* Prepared statement under construction */
24114#define VDBE_READY_STATE1 1 /* Ready to run but not yet started */
24115#define VDBE_RUN_STATE2 2 /* Run in progress */
24116#define VDBE_HALT_STATE3 3 /* Finished. Need reset() or finalize() */
24117
24118/*
24119** Structure used to store the context required by the
24120** sqlite3_preupdate_*() API functions.
24121*/
24122struct PreUpdate {
24123 Vdbe *v;
24124 VdbeCursor *pCsr; /* Cursor to read old values from */
24125 int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
24126 u8 *aRecord; /* old.* database record */
24127 KeyInfo *pKeyinfo; /* Key information */
24128 UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
24129 UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
24130 int iNewReg; /* Register for new.* values */
24131 int iBlobWrite; /* Value returned by preupdate_blobwrite() */
24132 i64 iKey1; /* First key value passed to hook */
24133 i64 iKey2; /* Second key value passed to hook */
24134 Mem oldipk; /* Memory cell holding "old" IPK value */
24135 Mem *aNew; /* Array of new.* values */
24136 Table *pTab; /* Schema object being updated */
24137 Index *pPk; /* PK index if pTab is WITHOUT ROWID */
24138 sqlite3_value **apDflt; /* Array of default values, if required */
24139 u8 keyinfoSpace[SZ_KEYINFO(0)(__builtin_offsetof(KeyInfo, aColl) + (0)*sizeof(CollSeq*))]; /* Space to hold pKeyinfo[0] content */
24140};
24141
24142/*
24143** An instance of this object is used to pass an vector of values into
24144** OP_VFilter, the xFilter method of a virtual table. The vector is the
24145** set of values on the right-hand side of an IN constraint.
24146**
24147** The value as passed into xFilter is an sqlite3_value with a "pointer"
24148** type, such as is generated by sqlite3_result_pointer() and read by
24149** sqlite3_value_pointer. Such values have MEM_Term|MEM_Subtype|MEM_Null
24150** and a subtype of 'p'. The sqlite3_vtab_in_first() and _next() interfaces
24151** know how to use this object to step through all the values in the
24152** right operand of the IN constraint.
24153*/
24154typedef struct ValueList ValueList;
24155struct ValueList {
24156 BtCursor *pCsr; /* An ephemeral table holding all values */
24157 sqlite3_value *pOut; /* Register to hold each decoded output value */
24158};
24159
24160/* Size of content associated with serial types that fit into a
24161** single-byte varint.
24162*/
24163#ifndef SQLITE_AMALGAMATION1
24164SQLITE_PRIVATEstatic const u8 sqlite3SmallTypeSizes[];
24165#endif
24166
24167/*
24168** Function prototypes
24169*/
24170SQLITE_PRIVATEstatic void sqlite3VdbeError(Vdbe*, const char *, ...);
24171SQLITE_PRIVATEstatic void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
24172SQLITE_PRIVATEstatic void sqlite3VdbeFreeCursorNN(Vdbe*,VdbeCursor*);
24173void sqliteVdbePopStack(Vdbe*,int);
24174SQLITE_PRIVATEstatic int SQLITE_NOINLINE__attribute__((noinline)) sqlite3VdbeHandleMovedCursor(VdbeCursor *p);
24175SQLITE_PRIVATEstatic int SQLITE_NOINLINE__attribute__((noinline)) sqlite3VdbeFinishMoveto(VdbeCursor*);
24176SQLITE_PRIVATEstatic int sqlite3VdbeCursorRestore(VdbeCursor*);
24177SQLITE_PRIVATEstatic u32 sqlite3VdbeSerialTypeLen(u32);
24178SQLITE_PRIVATEstatic u8 sqlite3VdbeOneByteSerialTypeLen(u8);
24179#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
24180SQLITE_PRIVATEstatic u64 sqlite3FloatSwap(u64 in);
24181# define swapMixedEndianFloat(X) X = sqlite3FloatSwap(X)
24182#else
24183# define swapMixedEndianFloat(X)
24184#endif
24185SQLITE_PRIVATEstatic void sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
24186SQLITE_PRIVATEstatic void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
24187
24188int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
24189SQLITE_PRIVATEstatic int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
24190SQLITE_PRIVATEstatic int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
24191SQLITE_PRIVATEstatic int sqlite3VdbeExec(Vdbe*);
24192#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)
24193SQLITE_PRIVATEstatic int sqlite3VdbeNextOpcode(Vdbe*,Mem*,int,int*,int*,Op**);
24194SQLITE_PRIVATEstatic char *sqlite3VdbeDisplayP4(sqlite3*,Op*);
24195#endif
24196#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
24197SQLITE_PRIVATEstatic char *sqlite3VdbeDisplayComment(sqlite3*,const Op*,const char*);
24198#endif
24199#if !defined(SQLITE_OMIT_EXPLAIN)
24200SQLITE_PRIVATEstatic int sqlite3VdbeList(Vdbe*);
24201#endif
24202SQLITE_PRIVATEstatic int sqlite3VdbeHalt(Vdbe*);
24203SQLITE_PRIVATEstatic int sqlite3VdbeChangeEncoding(Mem *, int);
24204SQLITE_PRIVATEstatic int sqlite3VdbeMemTooBig(Mem*);
24205SQLITE_PRIVATEstatic int sqlite3VdbeMemCopy(Mem*, const Mem*);
24206SQLITE_PRIVATEstatic void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
24207SQLITE_PRIVATEstatic void sqlite3VdbeMemMove(Mem*, Mem*);
24208SQLITE_PRIVATEstatic int sqlite3VdbeMemNulTerminate(Mem*);
24209SQLITE_PRIVATEstatic int sqlite3VdbeMemSetStr(Mem*, const char*, i64, u8, void(*)(void*));
24210SQLITE_PRIVATEstatic void sqlite3VdbeMemSetInt64(Mem*, i64);
24211#ifdef SQLITE_OMIT_FLOATING_POINT
24212# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
24213#else
24214SQLITE_PRIVATEstatic void sqlite3VdbeMemSetDouble(Mem*, double);
24215#endif
24216SQLITE_PRIVATEstatic void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
24217SQLITE_PRIVATEstatic void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
24218SQLITE_PRIVATEstatic void sqlite3VdbeMemSetNull(Mem*);
24219#ifndef SQLITE_OMIT_INCRBLOB
24220SQLITE_PRIVATEstatic void sqlite3VdbeMemSetZeroBlob(Mem*,int);
24221#else
24222SQLITE_PRIVATEstatic int sqlite3VdbeMemSetZeroBlob(Mem*,int);
24223#endif
24224#ifdef SQLITE_DEBUG
24225SQLITE_PRIVATEstatic int sqlite3VdbeMemIsRowSet(const Mem*);
24226#endif
24227SQLITE_PRIVATEstatic int sqlite3VdbeMemSetRowSet(Mem*);
24228SQLITE_PRIVATEstatic void sqlite3VdbeMemZeroTerminateIfAble(Mem*);
24229SQLITE_PRIVATEstatic int sqlite3VdbeMemMakeWriteable(Mem*);
24230SQLITE_PRIVATEstatic int sqlite3VdbeMemStringify(Mem*, u8, u8);
24231SQLITE_PRIVATEstatic int sqlite3IntFloatCompare(i64,double);
24232SQLITE_PRIVATEstatic i64 sqlite3VdbeIntValue(const Mem*);
24233SQLITE_PRIVATEstatic int sqlite3VdbeMemIntegerify(Mem*);
24234SQLITE_PRIVATEstatic double sqlite3VdbeRealValue(Mem*);
24235SQLITE_PRIVATEstatic int sqlite3VdbeBooleanValue(Mem*, int ifNull);
24236SQLITE_PRIVATEstatic void sqlite3VdbeIntegerAffinity(Mem*);
24237SQLITE_PRIVATEstatic int sqlite3VdbeMemRealify(Mem*);
24238SQLITE_PRIVATEstatic int sqlite3VdbeMemNumerify(Mem*);
24239SQLITE_PRIVATEstatic int sqlite3VdbeMemCast(Mem*,u8,u8);
24240SQLITE_PRIVATEstatic int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
24241SQLITE_PRIVATEstatic int sqlite3VdbeMemFromBtreeZeroOffset(BtCursor*,u32,Mem*);
24242SQLITE_PRIVATEstatic void sqlite3VdbeMemRelease(Mem *p);
24243SQLITE_PRIVATEstatic void sqlite3VdbeMemReleaseMalloc(Mem*p);
24244SQLITE_PRIVATEstatic int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
24245#ifndef SQLITE_OMIT_WINDOWFUNC
24246SQLITE_PRIVATEstatic int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);
24247#endif
24248#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)
24249SQLITE_PRIVATEstatic const char *sqlite3OpcodeName(int);
24250#endif
24251SQLITE_PRIVATEstatic int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
24252SQLITE_PRIVATEstatic int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
24253SQLITE_PRIVATEstatic int sqlite3VdbeCloseStatement(Vdbe *, int);
24254#ifdef SQLITE_DEBUG
24255SQLITE_PRIVATEstatic int sqlite3VdbeFrameIsValid(VdbeFrame*);
24256#endif
24257SQLITE_PRIVATEstatic void sqlite3VdbeFrameMemDel(void*); /* Destructor on Mem */
24258SQLITE_PRIVATEstatic void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */
24259SQLITE_PRIVATEstatic int sqlite3VdbeFrameRestore(VdbeFrame *);
24260#ifdef SQLITE_ENABLE_PREUPDATE_HOOK1
24261SQLITE_PRIVATEstatic void sqlite3VdbePreUpdateHook(
24262 Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int,int);
24263#endif
24264SQLITE_PRIVATEstatic int sqlite3VdbeTransferError(Vdbe *p);
24265
24266SQLITE_PRIVATEstatic int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
24267SQLITE_PRIVATEstatic void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
24268SQLITE_PRIVATEstatic void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
24269SQLITE_PRIVATEstatic int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
24270SQLITE_PRIVATEstatic int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
24271SQLITE_PRIVATEstatic int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
24272SQLITE_PRIVATEstatic int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
24273SQLITE_PRIVATEstatic int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
24274
24275SQLITE_PRIVATEstatic void sqlite3VdbeValueListFree(void*);
24276
24277#ifdef SQLITE_DEBUG
24278SQLITE_PRIVATEstatic void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);
24279SQLITE_PRIVATEstatic void sqlite3VdbeAssertAbortable(Vdbe*);
24280#else
24281# define sqlite3VdbeIncrWriteCounter(V,C)
24282# define sqlite3VdbeAssertAbortable(V)
24283#endif
24284
24285#if !defined(SQLITE_OMIT_SHARED_CACHE)
24286SQLITE_PRIVATEstatic void sqlite3VdbeEnter(Vdbe*);
24287#else
24288# define sqlite3VdbeEnter(X)
24289#endif
24290
24291#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE2>0
24292SQLITE_PRIVATEstatic void sqlite3VdbeLeave(Vdbe*);
24293#else
24294# define sqlite3VdbeLeave(X)
24295#endif
24296
24297#ifdef SQLITE_DEBUG
24298SQLITE_PRIVATEstatic void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
24299SQLITE_PRIVATEstatic int sqlite3VdbeCheckMemInvariants(Mem*);
24300#endif
24301
24302#ifndef SQLITE_OMIT_FOREIGN_KEY
24303SQLITE_PRIVATEstatic int sqlite3VdbeCheckFk(Vdbe *, int);
24304#else
24305# define sqlite3VdbeCheckFk(p,i) 0
24306#endif
24307
24308#ifdef SQLITE_DEBUG
24309SQLITE_PRIVATEstatic void sqlite3VdbePrintSql(Vdbe*);
24310SQLITE_PRIVATEstatic void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr);
24311#endif
24312#ifndef SQLITE_OMIT_UTF16
24313SQLITE_PRIVATEstatic int sqlite3VdbeMemTranslate(Mem*, u8);
24314SQLITE_PRIVATEstatic int sqlite3VdbeMemHandleBom(Mem *pMem);
24315#endif
24316
24317#ifndef SQLITE_OMIT_INCRBLOB
24318SQLITE_PRIVATEstatic int sqlite3VdbeMemExpandBlob(Mem *);
24319 #define ExpandBlob(P)(((P)->flags&0x0400)?sqlite3VdbeMemExpandBlob(P):0) (((P)->flags&MEM_Zero0x0400)?sqlite3VdbeMemExpandBlob(P):0)
24320#else
24321 #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK0
24322 #define ExpandBlob(P)(((P)->flags&0x0400)?sqlite3VdbeMemExpandBlob(P):0) SQLITE_OK0
24323#endif
24324
24325#endif /* !defined(SQLITE_VDBEINT_H) */
24326
24327/************** End of vdbeInt.h *********************************************/
24328/************** Continuing where we left off in status.c *********************/
24329
24330/*
24331** Variables in which to record status information.
24332*/
24333#if SQLITE_PTRSIZE8>4
24334typedef sqlite3_int64 sqlite3StatValueType;
24335#else
24336typedef u32 sqlite3StatValueType;
24337#endif
24338typedef struct sqlite3StatType sqlite3StatType;
24339static SQLITE_WSD struct sqlite3StatType {
24340 sqlite3StatValueType nowValue[10]; /* Current value */
24341 sqlite3StatValueType mxValue[10]; /* Maximum value */
24342} sqlite3Stat = { {0,}, {0,} };
24343
24344/*
24345** Elements of sqlite3Stat[] are protected by either the memory allocator
24346** mutex, or by the pcache1 mutex. The following array determines which.
24347*/
24348static const char statMutex[] = {
24349 0, /* SQLITE_STATUS_MEMORY_USED */
24350 1, /* SQLITE_STATUS_PAGECACHE_USED */
24351 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
24352 0, /* SQLITE_STATUS_SCRATCH_USED */
24353 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
24354 0, /* SQLITE_STATUS_MALLOC_SIZE */
24355 0, /* SQLITE_STATUS_PARSER_STACK */
24356 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
24357 0, /* SQLITE_STATUS_SCRATCH_SIZE */
24358 0, /* SQLITE_STATUS_MALLOC_COUNT */
24359};
24360
24361
24362/* The "wsdStat" macro will resolve to the status information
24363** state vector. If writable static data is unsupported on the target,
24364** we have to locate the state vector at run-time. In the more common
24365** case where writable static data is supported, wsdStat can refer directly
24366** to the "sqlite3Stat" state vector declared above.
24367*/
24368#ifdef SQLITE_OMIT_WSD
24369# define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)sqlite3Stat
24370# define wsdStatsqlite3Stat x[0]
24371#else
24372# define wsdStatInit
24373# define wsdStatsqlite3Stat sqlite3Stat
24374#endif
24375
24376/*
24377** Return the current value of a status parameter. The caller must
24378** be holding the appropriate mutex.
24379*/
24380SQLITE_PRIVATEstatic sqlite3_int64 sqlite3StatusValue(int op){
24381 wsdStatInit;
24382 assert( op>=0 && op<ArraySize(wsdStat.nowValue) )((void) (0));
24383 assert( op>=0 && op<ArraySize(statMutex) )((void) (0));
24384 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()((void) (0))
24385 : sqlite3MallocMutex()) )((void) (0));
24386 return wsdStatsqlite3Stat.nowValue[op];
24387}
24388
24389/*
24390** Add N to the value of a status record. The caller must hold the
24391** appropriate mutex. (Locking is checked by assert()).
24392**
24393** The StatusUp() routine can accept positive or negative values for N.
24394** The value of N is added to the current status value and the high-water
24395** mark is adjusted if necessary.
24396**
24397** The StatusDown() routine lowers the current value by N. The highwater
24398** mark is unchanged. N must be non-negative for StatusDown().
24399*/
24400SQLITE_PRIVATEstatic void sqlite3StatusUp(int op, int N){
24401 wsdStatInit;
24402 assert( op>=0 && op<ArraySize(wsdStat.nowValue) )((void) (0));
24403 assert( op>=0 && op<ArraySize(statMutex) )((void) (0));
24404 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()((void) (0))
24405 : sqlite3MallocMutex()) )((void) (0));
24406 wsdStatsqlite3Stat.nowValue[op] += N;
24407 if( wsdStatsqlite3Stat.nowValue[op]>wsdStatsqlite3Stat.mxValue[op] ){
24408 wsdStatsqlite3Stat.mxValue[op] = wsdStatsqlite3Stat.nowValue[op];
24409 }
24410}
24411SQLITE_PRIVATEstatic void sqlite3StatusDown(int op, int N){
24412 wsdStatInit;
24413 assert( N>=0 )((void) (0));
24414 assert( op>=0 && op<ArraySize(statMutex) )((void) (0));
24415 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()((void) (0))
24416 : sqlite3MallocMutex()) )((void) (0));
24417 assert( op>=0 && op<ArraySize(wsdStat.nowValue) )((void) (0));
24418 wsdStatsqlite3Stat.nowValue[op] -= N;
24419}
24420
24421/*
24422** Adjust the highwater mark if necessary.
24423** The caller must hold the appropriate mutex.
24424*/
24425SQLITE_PRIVATEstatic void sqlite3StatusHighwater(int op, int X){
24426 sqlite3StatValueType newValue;
24427 wsdStatInit;
24428 assert( X>=0 )((void) (0));
24429 newValue = (sqlite3StatValueType)X;
24430 assert( op>=0 && op<ArraySize(wsdStat.nowValue) )((void) (0));
24431 assert( op>=0 && op<ArraySize(statMutex) )((void) (0));
24432 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()((void) (0))
24433 : sqlite3MallocMutex()) )((void) (0));
24434 assert( op==SQLITE_STATUS_MALLOC_SIZE((void) (0))
24435 || op==SQLITE_STATUS_PAGECACHE_SIZE((void) (0))
24436 || op==SQLITE_STATUS_PARSER_STACK )((void) (0));
24437 if( newValue>wsdStatsqlite3Stat.mxValue[op] ){
24438 wsdStatsqlite3Stat.mxValue[op] = newValue;
24439 }
24440}
24441
24442/*
24443** Query status information.
24444*/
24445SQLITE_API int sqlite3_status64(
24446 int op,
24447 sqlite3_int64 *pCurrent,
24448 sqlite3_int64 *pHighwater,
24449 int resetFlag
24450){
24451 sqlite3_mutex *pMutex;
24452 wsdStatInit;
24453 if( op<0 || op>=ArraySize(wsdStat.nowValue)((int)(sizeof(sqlite3Stat.nowValue)/sizeof(sqlite3Stat.nowValue
[0])))
){
24454 return SQLITE_MISUSE_BKPTsqlite3MisuseError(24454);
24455 }
24456#ifdef SQLITE_ENABLE_API_ARMOR1
24457 if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPTsqlite3MisuseError(24457);
24458#endif
24459 pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
24460 sqlite3_mutex_enter(pMutex);
24461 *pCurrent = wsdStatsqlite3Stat.nowValue[op];
24462 *pHighwater = wsdStatsqlite3Stat.mxValue[op];
24463 if( resetFlag ){
24464 wsdStatsqlite3Stat.mxValue[op] = wsdStatsqlite3Stat.nowValue[op];
24465 }
24466 sqlite3_mutex_leave(pMutex);
24467 (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
24468 return SQLITE_OK0;
24469}
24470SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
24471 sqlite3_int64 iCur = 0, iHwtr = 0;
24472 int rc;
24473#ifdef SQLITE_ENABLE_API_ARMOR1
24474 if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPTsqlite3MisuseError(24474);
24475#endif
24476 rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
24477 if( rc==0 ){
24478 *pCurrent = (int)iCur;
24479 *pHighwater = (int)iHwtr;
24480 }
24481 return rc;
24482}
24483
24484/*
24485** Return the number of LookasideSlot elements on the linked list
24486*/
24487static u32 countLookasideSlots(LookasideSlot *p){
24488 u32 cnt = 0;
24489 while( p ){
24490 p = p->pNext;
24491 cnt++;
24492 }
24493 return cnt;
24494}
24495
24496/*
24497** Count the number of slots of lookaside memory that are outstanding
24498*/
24499SQLITE_PRIVATEstatic int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
24500 u32 nInit = countLookasideSlots(db->lookaside.pInit);
24501 u32 nFree = countLookasideSlots(db->lookaside.pFree);
24502#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
24503 nInit += countLookasideSlots(db->lookaside.pSmallInit);
24504 nFree += countLookasideSlots(db->lookaside.pSmallFree);
24505#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
24506 assert( db->lookaside.nSlot >= nInit+nFree )((void) (0));
24507 if( pHighwater ) *pHighwater = (int)(db->lookaside.nSlot - nInit);
24508 return (int)(db->lookaside.nSlot - (nInit+nFree));
24509}
24510
24511/*
24512** Query status information for a single database connection
24513*/
24514SQLITE_API int sqlite3_db_status(
24515 sqlite3 *db, /* The database connection whose status is desired */
24516 int op, /* Status verb */
24517 int *pCurrent, /* Write current value here */
24518 int *pHighwater, /* Write high-water mark here */
24519 int resetFlag /* Reset high-water mark if true */
24520){
24521 int rc = SQLITE_OK0; /* Return code */
24522#ifdef SQLITE_ENABLE_API_ARMOR1
24523 if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
24524 return SQLITE_MISUSE_BKPTsqlite3MisuseError(24524);
24525 }
24526#endif
24527 sqlite3_mutex_enter(db->mutex);
24528 switch( op ){
24529 case SQLITE_DBSTATUS_LOOKASIDE_USED0: {
24530 *pCurrent = sqlite3LookasideUsed(db, pHighwater);
24531 if( resetFlag ){
24532 LookasideSlot *p = db->lookaside.pFree;
24533 if( p ){
24534 while( p->pNext ) p = p->pNext;
24535 p->pNext = db->lookaside.pInit;
24536 db->lookaside.pInit = db->lookaside.pFree;
24537 db->lookaside.pFree = 0;
24538 }
24539#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
24540 p = db->lookaside.pSmallFree;
24541 if( p ){
24542 while( p->pNext ) p = p->pNext;
24543 p->pNext = db->lookaside.pSmallInit;
24544 db->lookaside.pSmallInit = db->lookaside.pSmallFree;
24545 db->lookaside.pSmallFree = 0;
24546 }
24547#endif
24548 }
24549 break;
24550 }
24551
24552 case SQLITE_DBSTATUS_LOOKASIDE_HIT4:
24553 case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE5:
24554 case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL6: {
24555 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
24556 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
24557 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
24558 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 )((void) (0));
24559 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 )((void) (0));
24560 *pCurrent = 0;
24561 *pHighwater = (int)db->lookaside.anStat[op-SQLITE_DBSTATUS_LOOKASIDE_HIT4];
24562 if( resetFlag ){
24563 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT4] = 0;
24564 }
24565 break;
24566 }
24567
24568 /*
24569 ** Return an approximation for the amount of memory currently used
24570 ** by all pagers associated with the given database connection. The
24571 ** highwater mark is meaningless and is returned as zero.
24572 */
24573 case SQLITE_DBSTATUS_CACHE_USED_SHARED11:
24574 case SQLITE_DBSTATUS_CACHE_USED1: {
24575 int totalUsed = 0;
24576 int i;
24577 sqlite3BtreeEnterAll(db);
24578 for(i=0; i<db->nDb; i++){
24579 Btree *pBt = db->aDb[i].pBt;
24580 if( pBt ){
24581 Pager *pPager = sqlite3BtreePager(pBt);
24582 int nByte = sqlite3PagerMemUsed(pPager);
24583 if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED11 ){
24584 nByte = nByte / sqlite3BtreeConnectionCount(pBt);
24585 }
24586 totalUsed += nByte;
24587 }
24588 }
24589 sqlite3BtreeLeaveAll(db);
24590 *pCurrent = totalUsed;
24591 *pHighwater = 0;
24592 break;
24593 }
24594
24595 /*
24596 ** *pCurrent gets an accurate estimate of the amount of memory used
24597 ** to store the schema for all databases (main, temp, and any ATTACHed
24598 ** databases. *pHighwater is set to zero.
24599 */
24600 case SQLITE_DBSTATUS_SCHEMA_USED2: {
24601 int i; /* Used to iterate through schemas */
24602 int nByte = 0; /* Used to accumulate return value */
24603
24604 sqlite3BtreeEnterAll(db);
24605 db->pnBytesFreed = &nByte;
24606 assert( db->lookaside.pEnd==db->lookaside.pTrueEnd )((void) (0));
24607 db->lookaside.pEnd = db->lookaside.pStart;
24608 for(i=0; i<db->nDb; i++){
24609 Schema *pSchema = db->aDb[i].pSchema;
24610 if( ALWAYS(pSchema!=0)(pSchema!=0) ){
24611 HashElem *p;
24612
24613 nByte += sqlite3GlobalConfigsqlite3Config.m.xRoundup(sizeof(HashElem)) * (
24614 pSchema->tblHash.count
24615 + pSchema->trigHash.count
24616 + pSchema->idxHash.count
24617 + pSchema->fkeyHash.count
24618 );
24619 nByte += sqlite3_msize(pSchema->tblHash.ht);
24620 nByte += sqlite3_msize(pSchema->trigHash.ht);
24621 nByte += sqlite3_msize(pSchema->idxHash.ht);
24622 nByte += sqlite3_msize(pSchema->fkeyHash.ht);
24623
24624 for(p=sqliteHashFirst(&pSchema->trigHash)((&pSchema->trigHash)->first); p; p=sqliteHashNext(p)((p)->next)){
24625 sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p)((p)->data));
24626 }
24627 for(p=sqliteHashFirst(&pSchema->tblHash)((&pSchema->tblHash)->first); p; p=sqliteHashNext(p)((p)->next)){
24628 sqlite3DeleteTable(db, (Table *)sqliteHashData(p)((p)->data));
24629 }
24630 }
24631 }
24632 db->pnBytesFreed = 0;
24633 db->lookaside.pEnd = db->lookaside.pTrueEnd;
24634 sqlite3BtreeLeaveAll(db);
24635
24636 *pHighwater = 0;
24637 *pCurrent = nByte;
24638 break;
24639 }
24640
24641 /*
24642 ** *pCurrent gets an accurate estimate of the amount of memory used
24643 ** to store all prepared statements.
24644 ** *pHighwater is set to zero.
24645 */
24646 case SQLITE_DBSTATUS_STMT_USED3: {
24647 struct Vdbe *pVdbe; /* Used to iterate through VMs */
24648 int nByte = 0; /* Used to accumulate return value */
24649
24650 db->pnBytesFreed = &nByte;
24651 assert( db->lookaside.pEnd==db->lookaside.pTrueEnd )((void) (0));
24652 db->lookaside.pEnd = db->lookaside.pStart;
24653 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pVNext){
24654 sqlite3VdbeDelete(pVdbe);
24655 }
24656 db->lookaside.pEnd = db->lookaside.pTrueEnd;
24657 db->pnBytesFreed = 0;
24658
24659 *pHighwater = 0; /* IMP: R-64479-57858 */
24660 *pCurrent = nByte;
24661
24662 break;
24663 }
24664
24665 /*
24666 ** Set *pCurrent to the total cache hits or misses encountered by all
24667 ** pagers the database handle is connected to. *pHighwater is always set
24668 ** to zero.
24669 */
24670 case SQLITE_DBSTATUS_CACHE_SPILL12:
24671 op = SQLITE_DBSTATUS_CACHE_WRITE9+1;
24672 /* no break */ deliberate_fall_through__attribute__((fallthrough));
24673 case SQLITE_DBSTATUS_CACHE_HIT7:
24674 case SQLITE_DBSTATUS_CACHE_MISS8:
24675 case SQLITE_DBSTATUS_CACHE_WRITE9:{
24676 int i;
24677 u64 nRet = 0;
24678 assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 )((void) (0));
24679 assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 )((void) (0));
24680
24681 for(i=0; i<db->nDb; i++){
24682 if( db->aDb[i].pBt ){
24683 Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
24684 sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
24685 }
24686 }
24687 *pHighwater = 0; /* IMP: R-42420-56072 */
24688 /* IMP: R-54100-20147 */
24689 /* IMP: R-29431-39229 */
24690 *pCurrent = (int)nRet & 0x7fffffff;
24691 break;
24692 }
24693
24694 /* Set *pCurrent to non-zero if there are unresolved deferred foreign
24695 ** key constraints. Set *pCurrent to zero if all foreign key constraints
24696 ** have been satisfied. The *pHighwater is always set to zero.
24697 */
24698 case SQLITE_DBSTATUS_DEFERRED_FKS10: {
24699 *pHighwater = 0; /* IMP: R-11967-56545 */
24700 *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
24701 break;
24702 }
24703
24704 default: {
24705 rc = SQLITE_ERROR1;
24706 }
24707 }
24708 sqlite3_mutex_leave(db->mutex);
24709 return rc;
24710}
24711
24712/************** End of status.c **********************************************/
24713/************** Begin file date.c ********************************************/
24714/*
24715** 2003 October 31
24716**
24717** The author disclaims copyright to this source code. In place of
24718** a legal notice, here is a blessing:
24719**
24720** May you do good and not evil.
24721** May you find forgiveness for yourself and forgive others.
24722** May you share freely, never taking more than you give.
24723**
24724*************************************************************************
24725** This file contains the C functions that implement date and time
24726** functions for SQLite.
24727**
24728** There is only one exported symbol in this file - the function
24729** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
24730** All other code has file scope.
24731**
24732** SQLite processes all times and dates as julian day numbers. The
24733** dates and times are stored as the number of days since noon
24734** in Greenwich on November 24, 4714 B.C. according to the Gregorian
24735** calendar system.
24736**
24737** 1970-01-01 00:00:00 is JD 2440587.5
24738** 2000-01-01 00:00:00 is JD 2451544.5
24739**
24740** This implementation requires years to be expressed as a 4-digit number
24741** which means that only dates between 0000-01-01 and 9999-12-31 can
24742** be represented, even though julian day numbers allow a much wider
24743** range of dates.
24744**
24745** The Gregorian calendar system is used for all dates and times,
24746** even those that predate the Gregorian calendar. Historians usually
24747** use the julian calendar for dates prior to 1582-10-15 and for some
24748** dates afterwards, depending on locale. Beware of this difference.
24749**
24750** The conversion algorithms are implemented based on descriptions
24751** in the following text:
24752**
24753** Jean Meeus
24754** Astronomical Algorithms, 2nd Edition, 1998
24755** ISBN 0-943396-61-1
24756** Willmann-Bell, Inc
24757** Richmond, Virginia (USA)
24758*/
24759/* #include "sqliteInt.h" */
24760/* #include <stdlib.h> */
24761/* #include <assert.h> */
24762#include <time.h>
24763
24764#ifndef SQLITE_OMIT_DATETIME_FUNCS
24765
24766/*
24767** The MSVC CRT on Windows CE may not have a localtime() function.
24768** So declare a substitute. The substitute function itself is
24769** defined in "os_win.c".
24770*/
24771#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
24772 (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
24773struct tm *__cdecl localtime(const time_t *);
24774#endif
24775
24776/*
24777** A structure for holding a single date and time.
24778*/
24779typedef struct DateTime DateTime;
24780struct DateTime {
24781 sqlite3_int64 iJD; /* The julian day number times 86400000 */
24782 int Y, M, D; /* Year, month, and day */
24783 int h, m; /* Hour and minutes */
24784 int tz; /* Timezone offset in minutes */
24785 double s; /* Seconds */
24786 char validJD; /* True (1) if iJD is valid */
24787 char validYMD; /* True (1) if Y,M,D are valid */
24788 char validHMS; /* True (1) if h,m,s are valid */
24789 char nFloor; /* Days to implement "floor" */
24790 unsigned rawS : 1; /* Raw numeric value stored in s */
24791 unsigned isError : 1; /* An overflow has occurred */
24792 unsigned useSubsec : 1; /* Display subsecond precision */
24793 unsigned isUtc : 1; /* Time is known to be UTC */
24794 unsigned isLocal : 1; /* Time is known to be localtime */
24795};
24796
24797
24798/*
24799** Convert zDate into one or more integers according to the conversion
24800** specifier zFormat.
24801**
24802** zFormat[] contains 4 characters for each integer converted, except for
24803** the last integer which is specified by three characters. The meaning
24804** of a four-character format specifiers ABCD is:
24805**
24806** A: number of digits to convert. Always "2" or "4".
24807** B: minimum value. Always "0" or "1".
24808** C: maximum value, decoded as:
24809** a: 12
24810** b: 14
24811** c: 24
24812** d: 31
24813** e: 59
24814** f: 9999
24815** D: the separator character, or \000 to indicate this is the
24816** last number to convert.
24817**
24818** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
24819** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
24820** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
24821** the 2-digit day which is the last integer in the set.
24822**
24823** The function returns the number of successful conversions.
24824*/
24825static int getDigits(const char *zDate, const char *zFormat, ...){
24826 /* The aMx[] array translates the 3rd character of each format
24827 ** spec into a max size: a b c d e f */
24828 static const u16 aMx[] = { 12, 14, 24, 31, 59, 14712 };
24829 va_list ap;
24830 int cnt = 0;
24831 char nextC;
24832 va_start(ap, zFormat)__builtin_va_start(ap, zFormat);
24833 do{
24834 char N = zFormat[0] - '0';
24835 char min = zFormat[1] - '0';
24836 int val = 0;
24837 u16 max;
24838
24839 assert( zFormat[2]>='a' && zFormat[2]<='f' )((void) (0));
24840 max = aMx[zFormat[2] - 'a'];
24841 nextC = zFormat[3];
24842 val = 0;
24843 while( N-- ){
24844 if( !sqlite3Isdigit(*zDate)(sqlite3CtypeMap[(unsigned char)(*zDate)]&0x04) ){
24845 goto end_getDigits;
24846 }
24847 val = val*10 + *zDate - '0';
24848 zDate++;
24849 }
24850 if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
24851 goto end_getDigits;
24852 }
24853 *va_arg(ap,int*)__builtin_va_arg(ap, int*) = val;
24854 zDate++;
24855 cnt++;
24856 zFormat += 4;
24857 }while( nextC );
24858end_getDigits:
24859 va_end(ap)__builtin_va_end(ap);
24860 return cnt;
24861}
24862
24863/*
24864** Parse a timezone extension on the end of a date-time.
24865** The extension is of the form:
24866**
24867** (+/-)HH:MM
24868**
24869** Or the "zulu" notation:
24870**
24871** Z
24872**
24873** If the parse is successful, write the number of minutes
24874** of change in p->tz and return 0. If a parser error occurs,
24875** return non-zero.
24876**
24877** A missing specifier is not considered an error.
24878*/
24879static int parseTimezone(const char *zDate, DateTime *p){
24880 int sgn = 0;
24881 int nHr, nMn;
24882 int c;
24883 while( sqlite3Isspace(*zDate)(sqlite3CtypeMap[(unsigned char)(*zDate)]&0x01) ){ zDate++; }
24884 p->tz = 0;
24885 c = *zDate;
24886 if( c=='-' ){
24887 sgn = -1;
24888 }else if( c=='+' ){
24889 sgn = +1;
24890 }else if( c=='Z' || c=='z' ){
24891 zDate++;
24892 p->isLocal = 0;
24893 p->isUtc = 1;
24894 goto zulu_time;
24895 }else{
24896 return c!=0;
24897 }
24898 zDate++;
24899 if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
24900 return 1;
24901 }
24902 zDate += 5;
24903 p->tz = sgn*(nMn + nHr*60);
24904zulu_time:
24905 while( sqlite3Isspace(*zDate)(sqlite3CtypeMap[(unsigned char)(*zDate)]&0x01) ){ zDate++; }
24906 return *zDate!=0;
24907}
24908
24909/*
24910** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
24911** The HH, MM, and SS must each be exactly 2 digits. The
24912** fractional seconds FFFF can be one or more digits.
24913**
24914** Return 1 if there is a parsing error and 0 on success.
24915*/
24916static int parseHhMmSs(const char *zDate, DateTime *p){
24917 int h, m, s;
24918 double ms = 0.0;
24919 if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
24920 return 1;
24921 }
24922 zDate += 5;
24923 if( *zDate==':' ){
24924 zDate++;
24925 if( getDigits(zDate, "20e", &s)!=1 ){
24926 return 1;
24927 }
24928 zDate += 2;
24929 if( *zDate=='.' && sqlite3Isdigit(zDate[1])(sqlite3CtypeMap[(unsigned char)(zDate[1])]&0x04) ){
24930 double rScale = 1.0;
24931 zDate++;
24932 while( sqlite3Isdigit(*zDate)(sqlite3CtypeMap[(unsigned char)(*zDate)]&0x04) ){
24933 ms = ms*10.0 + *zDate - '0';
24934 rScale *= 10.0;
24935 zDate++;
24936 }
24937 ms /= rScale;
24938 /* Truncate to avoid problems with sub-milliseconds
24939 ** rounding. https://sqlite.org/forum/forumpost/766a2c9231 */
24940 if( ms>0.999 ) ms = 0.999;
24941 }
24942 }else{
24943 s = 0;
24944 }
24945 p->validJD = 0;
24946 p->rawS = 0;
24947 p->validHMS = 1;
24948 p->h = h;
24949 p->m = m;
24950 p->s = s + ms;
24951 if( parseTimezone(zDate, p) ) return 1;
24952 return 0;
24953}
24954
24955/*
24956** Put the DateTime object into its error state.
24957*/
24958static void datetimeError(DateTime *p){
24959 memset(p, 0, sizeof(*p));
24960 p->isError = 1;
24961}
24962
24963/*
24964** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
24965** that the YYYY-MM-DD is according to the Gregorian calendar.
24966**
24967** Reference: Meeus page 61
24968*/
24969static void computeJD(DateTime *p){
24970 int Y, M, D, A, B, X1, X2;
24971
24972 if( p->validJD ) return;
24973 if( p->validYMD ){
24974 Y = p->Y;
24975 M = p->M;
24976 D = p->D;
24977 }else{
24978 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
24979 M = 1;
24980 D = 1;
24981 }
24982 if( Y<-4713 || Y>9999 || p->rawS ){
24983 datetimeError(p);
24984 return;
24985 }
24986 if( M<=2 ){
24987 Y--;
24988 M += 12;
24989 }
24990 A = (Y+4800)/100;
24991 B = 38 - A + (A/4);
24992 X1 = 36525*(Y+4716)/100;
24993 X2 = 306001*(M+1)/10000;
24994 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
24995 p->validJD = 1;
24996 if( p->validHMS ){
24997 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000 + 0.5);
24998 if( p->tz ){
24999 p->iJD -= p->tz*60000;
25000 p->validYMD = 0;
25001 p->validHMS = 0;
25002 p->tz = 0;
25003 p->isUtc = 1;
25004 p->isLocal = 0;
25005 }
25006 }
25007}
25008
25009/*
25010** Given the YYYY-MM-DD information current in p, determine if there
25011** is day-of-month overflow and set nFloor to the number of days that
25012** would need to be subtracted from the date in order to bring the
25013** date back to the end of the month.
25014*/
25015static void computeFloor(DateTime *p){
25016 assert( p->validYMD || p->isError )((void) (0));
25017 assert( p->D>=0 && p->D<=31 )((void) (0));
25018 assert( p->M>=0 && p->M<=12 )((void) (0));
25019 if( p->D<=28 ){
25020 p->nFloor = 0;
25021 }else if( (1<<p->M) & 0x15aa ){
25022 p->nFloor = 0;
25023 }else if( p->M!=2 ){
25024 p->nFloor = (p->D==31);
25025 }else if( p->Y%4!=0 || (p->Y%100==0 && p->Y%400!=0) ){
25026 p->nFloor = p->D - 28;
25027 }else{
25028 p->nFloor = p->D - 29;
25029 }
25030}
25031
25032/*
25033** Parse dates of the form
25034**
25035** YYYY-MM-DD HH:MM:SS.FFF
25036** YYYY-MM-DD HH:MM:SS
25037** YYYY-MM-DD HH:MM
25038** YYYY-MM-DD
25039**
25040** Write the result into the DateTime structure and return 0
25041** on success and 1 if the input string is not a well-formed
25042** date.
25043*/
25044static int parseYyyyMmDd(const char *zDate, DateTime *p){
25045 int Y, M, D, neg;
25046
25047 if( zDate[0]=='-' ){
25048 zDate++;
25049 neg = 1;
25050 }else{
25051 neg = 0;
25052 }
25053 if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
25054 return 1;
25055 }
25056 zDate += 10;
25057 while( sqlite3Isspace(*zDate)(sqlite3CtypeMap[(unsigned char)(*zDate)]&0x01) || 'T'==*(u8*)zDate ){ zDate++; }
25058 if( parseHhMmSs(zDate, p)==0 ){
25059 /* We got the time */
25060 }else if( *zDate==0 ){
25061 p->validHMS = 0;
25062 }else{
25063 return 1;
25064 }
25065 p->validJD = 0;
25066 p->validYMD = 1;
25067 p->Y = neg ? -Y : Y;
25068 p->M = M;
25069 p->D = D;
25070 computeFloor(p);
25071 if( p->tz ){
25072 computeJD(p);
25073 }
25074 return 0;
25075}
25076
25077
25078static void clearYMD_HMS_TZ(DateTime *p); /* Forward declaration */
25079
25080/*
25081** Set the time to the current time reported by the VFS.
25082**
25083** Return the number of errors.
25084*/
25085static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
25086 p->iJD = sqlite3StmtCurrentTime(context);
25087 if( p->iJD>0 ){
25088 p->validJD = 1;
25089 p->isUtc = 1;
25090 p->isLocal = 0;
25091 clearYMD_HMS_TZ(p);
25092 return 0;
25093 }else{
25094 return 1;
25095 }
25096}
25097
25098/*
25099** Input "r" is a numeric quantity which might be a julian day number,
25100** or the number of seconds since 1970. If the value if r is within
25101** range of a julian day number, install it as such and set validJD.
25102** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
25103*/
25104static void setRawDateNumber(DateTime *p, double r){
25105 p->s = r;
25106 p->rawS = 1;
25107 if( r>=0.0 && r<5373484.5 ){
25108 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
25109 p->validJD = 1;
25110 }
25111}
25112
25113/*
25114** Attempt to parse the given string into a julian day number. Return
25115** the number of errors.
25116**
25117** The following are acceptable forms for the input string:
25118**
25119** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
25120** DDDD.DD
25121** now
25122**
25123** In the first form, the +/-HH:MM is always optional. The fractional
25124** seconds extension (the ".FFF") is optional. The seconds portion
25125** (":SS.FFF") is option. The year and date can be omitted as long
25126** as there is a time string. The time string can be omitted as long
25127** as there is a year and date.
25128*/
25129static int parseDateOrTime(
25130 sqlite3_context *context,
25131 const char *zDate,
25132 DateTime *p
25133){
25134 double r;
25135 if( parseYyyyMmDd(zDate,p)==0 ){
25136 return 0;
25137 }else if( parseHhMmSs(zDate, p)==0 ){
25138 return 0;
25139 }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
25140 return setDateTimeToCurrent(context, p);
25141 }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF81)>0 ){
25142 setRawDateNumber(p, r);
25143 return 0;
25144 }else if( (sqlite3StrICmp(zDate,"subsec")==0
25145 || sqlite3StrICmp(zDate,"subsecond")==0)
25146 && sqlite3NotPureFunc(context) ){
25147 p->useSubsec = 1;
25148 return setDateTimeToCurrent(context, p);
25149 }
25150 return 1;
25151}
25152
25153/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
25154** Multiplying this by 86400000 gives 464269060799999 as the maximum value
25155** for DateTime.iJD.
25156**
25157** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
25158** such a large integer literal, so we have to encode it.
25159*/
25160#define INT_464269060799999((((i64)0x1a640)<<32)|0x1072fdff) ((((i64)0x1a640)<<32)|0x1072fdff)
25161
25162/*
25163** Return TRUE if the given julian day number is within range.
25164**
25165** The input is the JulianDay times 86400000.
25166*/
25167static int validJulianDay(sqlite3_int64 iJD){
25168 return iJD>=0 && iJD<=INT_464269060799999((((i64)0x1a640)<<32)|0x1072fdff);
25169}
25170
25171/*
25172** Compute the Year, Month, and Day from the julian day number.
25173*/
25174static void computeYMD(DateTime *p){
25175 int Z, alpha, A, B, C, D, E, X1;
25176 if( p->validYMD ) return;
25177 if( !p->validJD ){
25178 p->Y = 2000;
25179 p->M = 1;
25180 p->D = 1;
25181 }else if( !validJulianDay(p->iJD) ){
25182 datetimeError(p);
25183 return;
25184 }else{
25185 Z = (int)((p->iJD + 43200000)/86400000);
25186 alpha = (int)((Z + 32044.75)/36524.25) - 52;
25187 A = Z + 1 + alpha - ((alpha+100)/4) + 25;
25188 B = A + 1524;
25189 C = (int)((B - 122.1)/365.25);
25190 D = (36525*(C&32767))/100;
25191 E = (int)((B-D)/30.6001);
25192 X1 = (int)(30.6001*E);
25193 p->D = B - D - X1;
25194 p->M = E<14 ? E-1 : E-13;
25195 p->Y = p->M>2 ? C - 4716 : C - 4715;
25196 }
25197 p->validYMD = 1;
25198}
25199
25200/*
25201** Compute the Hour, Minute, and Seconds from the julian day number.
25202*/
25203static void computeHMS(DateTime *p){
25204 int day_ms, day_min; /* milliseconds, minutes into the day */
25205 if( p->validHMS ) return;
25206 computeJD(p);
25207 day_ms = (int)((p->iJD + 43200000) % 86400000);
25208 p->s = (day_ms % 60000)/1000.0;
25209 day_min = day_ms/60000;
25210 p->m = day_min % 60;
25211 p->h = day_min / 60;
25212 p->rawS = 0;
25213 p->validHMS = 1;
25214}
25215
25216/*
25217** Compute both YMD and HMS
25218*/
25219static void computeYMD_HMS(DateTime *p){
25220 computeYMD(p);
25221 computeHMS(p);
25222}
25223
25224/*
25225** Clear the YMD and HMS and the TZ
25226*/
25227static void clearYMD_HMS_TZ(DateTime *p){
25228 p->validYMD = 0;
25229 p->validHMS = 0;
25230 p->tz = 0;
25231}
25232
25233#ifndef SQLITE_OMIT_LOCALTIME
25234/*
25235** On recent Windows platforms, the localtime_s() function is available
25236** as part of the "Secure CRT". It is essentially equivalent to
25237** localtime_r() available under most POSIX platforms, except that the
25238** order of the parameters is reversed.
25239**
25240** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
25241**
25242** If the user has not indicated to use localtime_r() or localtime_s()
25243** already, check for an MSVC build environment that provides
25244** localtime_s().
25245*/
25246#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
25247 && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
25248#undef HAVE_LOCALTIME_S
25249#define HAVE_LOCALTIME_S 1
25250#endif
25251
25252/*
25253** The following routine implements the rough equivalent of localtime_r()
25254** using whatever operating-system specific localtime facility that
25255** is available. This routine returns 0 on success and
25256** non-zero on any kind of error.
25257**
25258** If the sqlite3GlobalConfig.bLocaltimeFault variable is non-zero then this
25259** routine will always fail. If bLocaltimeFault is nonzero and
25260** sqlite3GlobalConfig.xAltLocaltime is not NULL, then xAltLocaltime() is
25261** invoked in place of the OS-defined localtime() function.
25262**
25263** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
25264** library function localtime_r() is used to assist in the calculation of
25265** local time.
25266*/
25267static int osLocaltime(time_t *t, struct tm *pTm){
25268 int rc;
25269#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
25270 struct tm *pX;
25271#if SQLITE_THREADSAFE2>0
25272 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN2);
25273#endif
25274 sqlite3_mutex_enter(mutex);
25275 pX = localtime(t);
25276#ifndef SQLITE_UNTESTABLE
25277 if( sqlite3GlobalConfigsqlite3Config.bLocaltimeFault ){
25278 if( sqlite3GlobalConfigsqlite3Config.xAltLocaltime!=0
25279 && 0==sqlite3GlobalConfigsqlite3Config.xAltLocaltime((const void*)t,(void*)pTm)
25280 ){
25281 pX = pTm;
25282 }else{
25283 pX = 0;
25284 }
25285 }
25286#endif
25287 if( pX ) *pTm = *pX;
25288#if SQLITE_THREADSAFE2>0
25289 sqlite3_mutex_leave(mutex);
25290#endif
25291 rc = pX==0;
25292#else
25293#ifndef SQLITE_UNTESTABLE
25294 if( sqlite3GlobalConfigsqlite3Config.bLocaltimeFault ){
25295 if( sqlite3GlobalConfigsqlite3Config.xAltLocaltime!=0 ){
25296 return sqlite3GlobalConfigsqlite3Config.xAltLocaltime((const void*)t,(void*)pTm);
25297 }else{
25298 return 1;
25299 }
25300 }
25301#endif
25302#if HAVE_LOCALTIME_R
25303 rc = localtime_r(t, pTm)==0;
25304#else
25305 rc = localtime_s(pTm, t);
25306#endif /* HAVE_LOCALTIME_R */
25307#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
25308 return rc;
25309}
25310#endif /* SQLITE_OMIT_LOCALTIME */
25311
25312
25313#ifndef SQLITE_OMIT_LOCALTIME
25314/*
25315** Assuming the input DateTime is UTC, move it to its localtime equivalent.
25316*/
25317static int toLocaltime(
25318 DateTime *p, /* Date at which to calculate offset */
25319 sqlite3_context *pCtx /* Write error here if one occurs */
25320){
25321 time_t t;
25322 struct tm sLocal;
25323 int iYearDiff;
25324
25325 /* Initialize the contents of sLocal to avoid a compiler warning. */
25326 memset(&sLocal, 0, sizeof(sLocal));
25327
25328 computeJD(p);
25329 if( p->iJD<2108667600*(i64)100000 /* 1970-01-01 */
25330 || p->iJD>2130141456*(i64)100000 /* 2038-01-18 */
25331 ){
25332 /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
25333 ** works for years between 1970 and 2037. For dates outside this range,
25334 ** SQLite attempts to map the year into an equivalent year within this
25335 ** range, do the calculation, then map the year back.
25336 */
25337 DateTime x = *p;
25338 computeYMD_HMS(&x);
25339 iYearDiff = (2000 + x.Y%4) - x.Y;
25340 x.Y += iYearDiff;
25341 x.validJD = 0;
25342 computeJD(&x);
25343 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
25344 }else{
25345 iYearDiff = 0;
25346 t = (time_t)(p->iJD/1000 - 21086676*(i64)10000);
25347 }
25348 if( osLocaltime(&t, &sLocal) ){
25349 sqlite3_result_error(pCtx, "local time unavailable", -1);
25350 return SQLITE_ERROR1;
25351 }
25352 p->Y = sLocal.tm_year + 1900 - iYearDiff;
25353 p->M = sLocal.tm_mon + 1;
25354 p->D = sLocal.tm_mday;
25355 p->h = sLocal.tm_hour;
25356 p->m = sLocal.tm_min;
25357 p->s = sLocal.tm_sec + (p->iJD%1000)*0.001;
25358 p->validYMD = 1;
25359 p->validHMS = 1;
25360 p->validJD = 0;
25361 p->rawS = 0;
25362 p->tz = 0;
25363 p->isError = 0;
25364 return SQLITE_OK0;
25365}
25366#endif /* SQLITE_OMIT_LOCALTIME */
25367
25368/*
25369** The following table defines various date transformations of the form
25370**
25371** 'NNN days'
25372**
25373** Where NNN is an arbitrary floating-point number and "days" can be one
25374** of several units of time.
25375*/
25376static const struct {
25377 u8 nName; /* Length of the name */
25378 char zName[7]; /* Name of the transformation */
25379 float rLimit; /* Maximum NNN value for this transform */
25380 float rXform; /* Constant used for this transform */
25381} aXformType[] = {
25382 /* 0 */ { 6, "second", 4.6427e+14, 1.0 },
25383 /* 1 */ { 6, "minute", 7.7379e+12, 60.0 },
25384 /* 2 */ { 4, "hour", 1.2897e+11, 3600.0 },
25385 /* 3 */ { 3, "day", 5373485.0, 86400.0 },
25386 /* 4 */ { 5, "month", 176546.0, 2592000.0 },
25387 /* 5 */ { 4, "year", 14713.0, 31536000.0 },
25388};
25389
25390/*
25391** If the DateTime p is raw number, try to figure out if it is
25392** a julian day number of a unix timestamp. Set the p value
25393** appropriately.
25394*/
25395static void autoAdjustDate(DateTime *p){
25396 if( !p->rawS || p->validJD ){
25397 p->rawS = 0;
25398 }else if( p->s>=-21086676*(i64)10000 /* -4713-11-24 12:00:00 */
25399 && p->s<=(25340230*(i64)10000)+799 /* 9999-12-31 23:59:59 */
25400 ){
25401 double r = p->s*1000.0 + 210866760000000.0;
25402 clearYMD_HMS_TZ(p);
25403 p->iJD = (sqlite3_int64)(r + 0.5);
25404 p->validJD = 1;
25405 p->rawS = 0;
25406 }
25407}
25408
25409/*
25410** Process a modifier to a date-time stamp. The modifiers are
25411** as follows:
25412**
25413** NNN days
25414** NNN hours
25415** NNN minutes
25416** NNN.NNNN seconds
25417** NNN months
25418** NNN years
25419** +/-YYYY-MM-DD HH:MM:SS.SSS
25420** ceiling
25421** floor
25422** start of month
25423** start of year
25424** start of week
25425** start of day
25426** weekday N
25427** unixepoch
25428** auto
25429** localtime
25430** utc
25431** subsec
25432** subsecond
25433**
25434** Return 0 on success and 1 if there is any kind of error. If the error
25435** is in a system call (i.e. localtime()), then an error message is written
25436** to context pCtx. If the error is an unrecognized modifier, no error is
25437** written to pCtx.
25438*/
25439static int parseModifier(
25440 sqlite3_context *pCtx, /* Function context */
25441 const char *z, /* The text of the modifier */
25442 int n, /* Length of zMod in bytes */
25443 DateTime *p, /* The date/time value to be modified */
25444 int idx /* Parameter index of the modifier */
25445){
25446 int rc = 1;
25447 double r;
25448 switch(sqlite3UpperToLower[(u8)z[0]] ){
25449 case 'a': {
25450 /*
25451 ** auto
25452 **
25453 ** If rawS is available, then interpret as a julian day number, or
25454 ** a unix timestamp, depending on its magnitude.
25455 */
25456 if( sqlite3_stricmp(z, "auto")==0 ){
25457 if( idx>1 ) return 1; /* IMP: R-33611-57934 */
25458 autoAdjustDate(p);
25459 rc = 0;
25460 }
25461 break;
25462 }
25463 case 'c': {
25464 /*
25465 ** ceiling
25466 **
25467 ** Resolve day-of-month overflow by rolling forward into the next
25468 ** month. As this is the default action, this modifier is really
25469 ** a no-op that is only included for symmetry. See "floor".
25470 */
25471 if( sqlite3_stricmp(z, "ceiling")==0 ){
25472 computeJD(p);
25473 clearYMD_HMS_TZ(p);
25474 rc = 0;
25475 p->nFloor = 0;
25476 }
25477 break;
25478 }
25479 case 'f': {
25480 /*
25481 ** floor
25482 **
25483 ** Resolve day-of-month overflow by rolling back to the end of the
25484 ** previous month.
25485 */
25486 if( sqlite3_stricmp(z, "floor")==0 ){
25487 computeJD(p);
25488 p->iJD -= p->nFloor*86400000;
25489 clearYMD_HMS_TZ(p);
25490 rc = 0;
25491 }
25492 break;
25493 }
25494 case 'j': {
25495 /*
25496 ** julianday
25497 **
25498 ** Always interpret the prior number as a julian-day value. If this
25499 ** is not the first modifier, or if the prior argument is not a numeric
25500 ** value in the allowed range of julian day numbers understood by
25501 ** SQLite (0..5373484.5) then the result will be NULL.
25502 */
25503 if( sqlite3_stricmp(z, "julianday")==0 ){
25504 if( idx>1 ) return 1; /* IMP: R-31176-64601 */
25505 if( p->validJD && p->rawS ){
25506 rc = 0;
25507 p->rawS = 0;
25508 }
25509 }
25510 break;
25511 }
25512#ifndef SQLITE_OMIT_LOCALTIME
25513 case 'l': {
25514 /* localtime
25515 **
25516 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
25517 ** show local time.
25518 */
25519 if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
25520 rc = p->isLocal ? SQLITE_OK0 : toLocaltime(p, pCtx);
25521 p->isUtc = 0;
25522 p->isLocal = 1;
25523 }
25524 break;
25525 }
25526#endif
25527 case 'u': {
25528 /*
25529 ** unixepoch
25530 **
25531 ** Treat the current value of p->s as the number of
25532 ** seconds since 1970. Convert to a real julian day number.
25533 */
25534 if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
25535 if( idx>1 ) return 1; /* IMP: R-49255-55373 */
25536 r = p->s*1000.0 + 210866760000000.0;
25537 if( r>=0.0 && r<464269060800000.0 ){
25538 clearYMD_HMS_TZ(p);
25539 p->iJD = (sqlite3_int64)(r + 0.5);
25540 p->validJD = 1;
25541 p->rawS = 0;
25542 rc = 0;
25543 }
25544 }
25545#ifndef SQLITE_OMIT_LOCALTIME
25546 else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
25547 if( p->isUtc==0 ){
25548 i64 iOrigJD; /* Original localtime */
25549 i64 iGuess; /* Guess at the corresponding utc time */
25550 int cnt = 0; /* Safety to prevent infinite loop */
25551 i64 iErr; /* Guess is off by this much */
25552
25553 computeJD(p);
25554 iGuess = iOrigJD = p->iJD;
25555 iErr = 0;
25556 do{
25557 DateTime new;
25558 memset(&new, 0, sizeof(new));
25559 iGuess -= iErr;
25560 new.iJD = iGuess;
25561 new.validJD = 1;
25562 rc = toLocaltime(&new, pCtx);
25563 if( rc ) return rc;
25564 computeJD(&new);
25565 iErr = new.iJD - iOrigJD;
25566 }while( iErr && cnt++<3 );
25567 memset(p, 0, sizeof(*p));
25568 p->iJD = iGuess;
25569 p->validJD = 1;
25570 p->isUtc = 1;
25571 p->isLocal = 0;
25572 }
25573 rc = SQLITE_OK0;
25574 }
25575#endif
25576 break;
25577 }
25578 case 'w': {
25579 /*
25580 ** weekday N
25581 **
25582 ** Move the date to the same time on the next occurrence of
25583 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
25584 ** date is already on the appropriate weekday, this is a no-op.
25585 */
25586 if( sqlite3_strnicmp(z, "weekday ", 8)==0
25587 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF81)>0
25588 && r>=0.0 && r<7.0 && (n=(int)r)==r ){
25589 sqlite3_int64 Z;
25590 computeYMD_HMS(p);
25591 p->tz = 0;
25592 p->validJD = 0;
25593 computeJD(p);
25594 Z = ((p->iJD + 129600000)/86400000) % 7;
25595 if( Z>n ) Z -= 7;
25596 p->iJD += (n - Z)*86400000;
25597 clearYMD_HMS_TZ(p);
25598 rc = 0;
25599 }
25600 break;
25601 }
25602 case 's': {
25603 /*
25604 ** start of TTTTT
25605 **
25606 ** Move the date backwards to the beginning of the current day,
25607 ** or month or year.
25608 **
25609 ** subsecond
25610 ** subsec
25611 **
25612 ** Show subsecond precision in the output of datetime() and
25613 ** unixepoch() and strftime('%s').
25614 */
25615 if( sqlite3_strnicmp(z, "start of ", 9)!=0 ){
25616 if( sqlite3_stricmp(z, "subsec")==0
25617 || sqlite3_stricmp(z, "subsecond")==0
25618 ){
25619 p->useSubsec = 1;
25620 rc = 0;
25621 }
25622 break;
25623 }
25624 if( !p->validJD && !p->validYMD && !p->validHMS ) break;
25625 z += 9;
25626 computeYMD(p);
25627 p->validHMS = 1;
25628 p->h = p->m = 0;
25629 p->s = 0.0;
25630 p->rawS = 0;
25631 p->tz = 0;
25632 p->validJD = 0;
25633 if( sqlite3_stricmp(z,"month")==0 ){
25634 p->D = 1;
25635 rc = 0;
25636 }else if( sqlite3_stricmp(z,"year")==0 ){
25637 p->M = 1;
25638 p->D = 1;
25639 rc = 0;
25640 }else if( sqlite3_stricmp(z,"day")==0 ){
25641 rc = 0;
25642 }
25643 break;
25644 }
25645 case '+':
25646 case '-':
25647 case '0':
25648 case '1':
25649 case '2':
25650 case '3':
25651 case '4':
25652 case '5':
25653 case '6':
25654 case '7':
25655 case '8':
25656 case '9': {
25657 double rRounder;
25658 int i;
25659 int Y,M,D,h,m,x;
25660 const char *z2 = z;
25661 char z0 = z[0];
25662 for(n=1; z[n]; n++){
25663 if( z[n]==':' ) break;
25664 if( sqlite3Isspace(z[n])(sqlite3CtypeMap[(unsigned char)(z[n])]&0x01) ) break;
25665 if( z[n]=='-' ){
25666 if( n==5 && getDigits(&z[1], "40f", &Y)==1 ) break;
25667 if( n==6 && getDigits(&z[1], "50f", &Y)==1 ) break;
25668 }
25669 }
25670 if( sqlite3AtoF(z, &r, n, SQLITE_UTF81)<=0 ){
25671 assert( rc==1 )((void) (0));
25672 break;
25673 }
25674 if( z[n]=='-' ){
25675 /* A modifier of the form (+|-)YYYY-MM-DD adds or subtracts the
25676 ** specified number of years, months, and days. MM is limited to
25677 ** the range 0-11 and DD is limited to 0-30.
25678 */
25679 if( z0!='+' && z0!='-' ) break; /* Must start with +/- */
25680 if( n==5 ){
25681 if( getDigits(&z[1], "40f-20a-20d", &Y, &M, &D)!=3 ) break;
25682 }else{
25683 assert( n==6 )((void) (0));
25684 if( getDigits(&z[1], "50f-20a-20d", &Y, &M, &D)!=3 ) break;
25685 z++;
25686 }
25687 if( M>=12 ) break; /* M range 0..11 */
25688 if( D>=31 ) break; /* D range 0..30 */
25689 computeYMD_HMS(p);
25690 p->validJD = 0;
25691 if( z0=='-' ){
25692 p->Y -= Y;
25693 p->M -= M;
25694 D = -D;
25695 }else{
25696 p->Y += Y;
25697 p->M += M;
25698 }
25699 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
25700 p->Y += x;
25701 p->M -= x*12;
25702 computeFloor(p);
25703 computeJD(p);
25704 p->validHMS = 0;
25705 p->validYMD = 0;
25706 p->iJD += (i64)D*86400000;
25707 if( z[11]==0 ){
25708 rc = 0;
25709 break;
25710 }
25711 if( sqlite3Isspace(z[11])(sqlite3CtypeMap[(unsigned char)(z[11])]&0x01)
25712 && getDigits(&z[12], "20c:20e", &h, &m)==2
25713 ){
25714 z2 = &z[12];
25715 n = 2;
25716 }else{
25717 break;
25718 }
25719 }
25720 if( z2[n]==':' ){
25721 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
25722 ** specified number of hours, minutes, seconds, and fractional seconds
25723 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
25724 ** omitted.
25725 */
25726
25727 DateTime tx;
25728 sqlite3_int64 day;
25729 if( !sqlite3Isdigit(*z2)(sqlite3CtypeMap[(unsigned char)(*z2)]&0x04) ) z2++;
25730 memset(&tx, 0, sizeof(tx));
25731 if( parseHhMmSs(z2, &tx) ) break;
25732 computeJD(&tx);
25733 tx.iJD -= 43200000;
25734 day = tx.iJD/86400000;
25735 tx.iJD -= day*86400000;
25736 if( z0=='-' ) tx.iJD = -tx.iJD;
25737 computeJD(p);
25738 clearYMD_HMS_TZ(p);
25739 p->iJD += tx.iJD;
25740 rc = 0;
25741 break;
25742 }
25743
25744 /* If control reaches this point, it means the transformation is
25745 ** one of the forms like "+NNN days". */
25746 z += n;
25747 while( sqlite3Isspace(*z)(sqlite3CtypeMap[(unsigned char)(*z)]&0x01) ) z++;
25748 n = sqlite3Strlen30(z);
25749 if( n<3 || n>10 ) break;
25750 if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
25751 computeJD(p);
25752 assert( rc==1 )((void) (0));
25753 rRounder = r<0 ? -0.5 : +0.5;
25754 p->nFloor = 0;
25755 for(i=0; i<ArraySize(aXformType)((int)(sizeof(aXformType)/sizeof(aXformType[0]))); i++){
25756 if( aXformType[i].nName==n
25757 && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
25758 && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
25759 ){
25760 switch( i ){
25761 case 4: { /* Special processing to add months */
25762 assert( strcmp(aXformType[4].zName,"month")==0 )((void) (0));
25763 computeYMD_HMS(p);
25764 p->M += (int)r;
25765 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
25766 p->Y += x;
25767 p->M -= x*12;
25768 computeFloor(p);
25769 p->validJD = 0;
25770 r -= (int)r;
25771 break;
25772 }
25773 case 5: { /* Special processing to add years */
25774 int y = (int)r;
25775 assert( strcmp(aXformType[5].zName,"year")==0 )((void) (0));
25776 computeYMD_HMS(p);
25777 assert( p->M>=0 && p->M<=12 )((void) (0));
25778 p->Y += y;
25779 computeFloor(p);
25780 p->validJD = 0;
25781 r -= (int)r;
25782 break;
25783 }
25784 }
25785 computeJD(p);
25786 p->iJD += (sqlite3_int64)(r*1000.0*aXformType[i].rXform + rRounder);
25787 rc = 0;
25788 break;
25789 }
25790 }
25791 clearYMD_HMS_TZ(p);
25792 break;
25793 }
25794 default: {
25795 break;
25796 }
25797 }
25798 return rc;
25799}
25800
25801/*
25802** Process time function arguments. argv[0] is a date-time stamp.
25803** argv[1] and following are modifiers. Parse them all and write
25804** the resulting time into the DateTime structure p. Return 0
25805** on success and 1 if there are any errors.
25806**
25807** If there are zero parameters (if even argv[0] is undefined)
25808** then assume a default value of "now" for argv[0].
25809*/
25810static int isDate(
25811 sqlite3_context *context,
25812 int argc,
25813 sqlite3_value **argv,
25814 DateTime *p
25815){
25816 int i, n;
25817 const unsigned char *z;
25818 int eType;
25819 memset(p, 0, sizeof(*p));
25820 if( argc==0 ){
25821 if( !sqlite3NotPureFunc(context) ) return 1;
25822 return setDateTimeToCurrent(context, p);
25823 }
25824 if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT2
25825 || eType==SQLITE_INTEGER1 ){
25826 setRawDateNumber(p, sqlite3_value_double(argv[0]));
25827 }else{
25828 z = sqlite3_value_text(argv[0]);
25829 if( !z || parseDateOrTime(context, (char*)z, p) ){
25830 return 1;
25831 }
25832 }
25833 for(i=1; i<argc; i++){
25834 z = sqlite3_value_text(argv[i]);
25835 n = sqlite3_value_bytes(argv[i]);
25836 if( z==0 || parseModifier(context, (char*)z, n, p, i) ) return 1;
25837 }
25838 computeJD(p);
25839 if( p->isError || !validJulianDay(p->iJD) ) return 1;
25840 if( argc==1 && p->validYMD && p->D>28 ){
25841 /* Make sure a YYYY-MM-DD is normalized.
25842 ** Example: 2023-02-31 -> 2023-03-03 */
25843 assert( p->validJD )((void) (0));
25844 p->validYMD = 0;
25845 }
25846 return 0;
25847}
25848
25849
25850/*
25851** The following routines implement the various date and time functions
25852** of SQLite.
25853*/
25854
25855/*
25856** julianday( TIMESTRING, MOD, MOD, ...)
25857**
25858** Return the julian day number of the date specified in the arguments
25859*/
25860static void juliandayFunc(
25861 sqlite3_context *context,
25862 int argc,
25863 sqlite3_value **argv
25864){
25865 DateTime x;
25866 if( isDate(context, argc, argv, &x)==0 ){
25867 computeJD(&x);
25868 sqlite3_result_double(context, x.iJD/86400000.0);
25869 }
25870}
25871
25872/*
25873** unixepoch( TIMESTRING, MOD, MOD, ...)
25874**
25875** Return the number of seconds (including fractional seconds) since
25876** the unix epoch of 1970-01-01 00:00:00 GMT.
25877*/
25878static void unixepochFunc(
25879 sqlite3_context *context,
25880 int argc,
25881 sqlite3_value **argv
25882){
25883 DateTime x;
25884 if( isDate(context, argc, argv, &x)==0 ){
25885 computeJD(&x);
25886 if( x.useSubsec ){
25887 sqlite3_result_double(context, (x.iJD - 21086676*(i64)10000000)/1000.0);
25888 }else{
25889 sqlite3_result_int64(context, x.iJD/1000 - 21086676*(i64)10000);
25890 }
25891 }
25892}
25893
25894/*
25895** datetime( TIMESTRING, MOD, MOD, ...)
25896**
25897** Return YYYY-MM-DD HH:MM:SS
25898*/
25899static void datetimeFunc(
25900 sqlite3_context *context,
25901 int argc,
25902 sqlite3_value **argv
25903){
25904 DateTime x;
25905 if( isDate(context, argc, argv, &x)==0 ){
25906 int Y, s, n;
25907 char zBuf[32];
25908 computeYMD_HMS(&x);
25909 Y = x.Y;
25910 if( Y<0 ) Y = -Y;
25911 zBuf[1] = '0' + (Y/1000)%10;
25912 zBuf[2] = '0' + (Y/100)%10;
25913 zBuf[3] = '0' + (Y/10)%10;
25914 zBuf[4] = '0' + (Y)%10;
25915 zBuf[5] = '-';
25916 zBuf[6] = '0' + (x.M/10)%10;
25917 zBuf[7] = '0' + (x.M)%10;
25918 zBuf[8] = '-';
25919 zBuf[9] = '0' + (x.D/10)%10;
25920 zBuf[10] = '0' + (x.D)%10;
25921 zBuf[11] = ' ';
25922 zBuf[12] = '0' + (x.h/10)%10;
25923 zBuf[13] = '0' + (x.h)%10;
25924 zBuf[14] = ':';
25925 zBuf[15] = '0' + (x.m/10)%10;
25926 zBuf[16] = '0' + (x.m)%10;
25927 zBuf[17] = ':';
25928 if( x.useSubsec ){
25929 s = (int)(1000.0*x.s + 0.5);
25930 zBuf[18] = '0' + (s/10000)%10;
25931 zBuf[19] = '0' + (s/1000)%10;
25932 zBuf[20] = '.';
25933 zBuf[21] = '0' + (s/100)%10;
25934 zBuf[22] = '0' + (s/10)%10;
25935 zBuf[23] = '0' + (s)%10;
25936 zBuf[24] = 0;
25937 n = 24;
25938 }else{
25939 s = (int)x.s;
25940 zBuf[18] = '0' + (s/10)%10;
25941 zBuf[19] = '0' + (s)%10;
25942 zBuf[20] = 0;
25943 n = 20;
25944 }
25945 if( x.Y<0 ){
25946 zBuf[0] = '-';
25947 sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT((sqlite3_destructor_type)-1));
25948 }else{
25949 sqlite3_result_text(context, &zBuf[1], n-1, SQLITE_TRANSIENT((sqlite3_destructor_type)-1));
25950 }
25951 }
25952}
25953
25954/*
25955** time( TIMESTRING, MOD, MOD, ...)
25956**
25957** Return HH:MM:SS
25958*/
25959static void timeFunc(
25960 sqlite3_context *context,
25961 int argc,
25962 sqlite3_value **argv
25963){
25964 DateTime x;
25965 if( isDate(context, argc, argv, &x)==0 ){
25966 int s, n;
25967 char zBuf[16];
25968 computeHMS(&x);
25969 zBuf[0] = '0' + (x.h/10)%10;
25970 zBuf[1] = '0' + (x.h)%10;
25971 zBuf[2] = ':';
25972 zBuf[3] = '0' + (x.m/10)%10;
25973 zBuf[4] = '0' + (x.m)%10;
25974 zBuf[5] = ':';
25975 if( x.useSubsec ){
25976 s = (int)(1000.0*x.s + 0.5);
25977 zBuf[6] = '0' + (s/10000)%10;
25978 zBuf[7] = '0' + (s/1000)%10;
25979 zBuf[8] = '.';
25980 zBuf[9] = '0' + (s/100)%10;
25981 zBuf[10] = '0' + (s/10)%10;
25982 zBuf[11] = '0' + (s)%10;
25983 zBuf[12] = 0;
25984 n = 12;
25985 }else{
25986 s = (int)x.s;
25987 zBuf[6] = '0' + (s/10)%10;
25988 zBuf[7] = '0' + (s)%10;
25989 zBuf[8] = 0;
25990 n = 8;
25991 }
25992 sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT((sqlite3_destructor_type)-1));
25993 }
25994}
25995
25996/*
25997** date( TIMESTRING, MOD, MOD, ...)
25998**
25999** Return YYYY-MM-DD
26000*/
26001static void dateFunc(
26002 sqlite3_context *context,
26003 int argc,
26004 sqlite3_value **argv
26005){
26006 DateTime x;
26007 if( isDate(context, argc, argv, &x)==0 ){
26008 int Y;
26009 char zBuf[16];
26010 computeYMD(&x);
26011 Y = x.Y;
26012 if( Y<0 ) Y = -Y;
26013 zBuf[1] = '0' + (Y/1000)%10;
26014 zBuf[2] = '0' + (Y/100)%10;
26015 zBuf[3] = '0' + (Y/10)%10;
26016 zBuf[4] = '0' + (Y)%10;
26017 zBuf[5] = '-';
26018 zBuf[6] = '0' + (x.M/10)%10;
26019 zBuf[7] = '0' + (x.M)%10;
26020 zBuf[8] = '-';
26021 zBuf[9] = '0' + (x.D/10)%10;
26022 zBuf[10] = '0' + (x.D)%10;
26023 zBuf[11] = 0;
26024 if( x.Y<0 ){
26025 zBuf[0] = '-';
26026 sqlite3_result_text(context, zBuf, 11, SQLITE_TRANSIENT((sqlite3_destructor_type)-1));
26027 }else{
26028 sqlite3_result_text(context, &zBuf[1], 10, SQLITE_TRANSIENT((sqlite3_destructor_type)-1));
26029 }
26030 }
26031}
26032
26033/*
26034** Compute the number of days after the most recent January 1.
26035**
26036** In other words, compute the zero-based day number for the
26037** current year:
26038**
26039** Jan01 = 0, Jan02 = 1, ..., Jan31 = 30, Feb01 = 31, ...
26040** Dec31 = 364 or 365.
26041*/
26042static int daysAfterJan01(DateTime *pDate){
26043 DateTime jan01 = *pDate;
26044 assert( jan01.validYMD )((void) (0));
26045 assert( jan01.validHMS )((void) (0));
26046 assert( pDate->validJD )((void) (0));
26047 jan01.validJD = 0;
26048 jan01.M = 1;
26049 jan01.D = 1;
26050 computeJD(&jan01);
26051 return (int)((pDate->iJD-jan01.iJD+43200000)/86400000);
26052}
26053
26054/*
26055** Return the number of days after the most recent Monday.
26056**
26057** In other words, return the day of the week according
26058** to this code:
26059**
26060** 0=Monday, 1=Tuesday, 2=Wednesday, ..., 6=Sunday.
26061*/
26062static int daysAfterMonday(DateTime *pDate){
26063 assert( pDate->validJD )((void) (0));
26064 return (int)((pDate->iJD+43200000)/86400000) % 7;
26065}
26066
26067/*
26068** Return the number of days after the most recent Sunday.
26069**
26070** In other words, return the day of the week according
26071** to this code:
26072**
26073** 0=Sunday, 1=Monday, 2=Tuesday, ..., 6=Saturday
26074*/
26075static int daysAfterSunday(DateTime *pDate){
26076 assert( pDate->validJD )((void) (0));
26077 return (int)((pDate->iJD+129600000)/86400000) % 7;
26078}
26079
26080/*
26081** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
26082**
26083** Return a string described by FORMAT. Conversions as follows:
26084**
26085** %d day of month 01-31
26086** %e day of month 1-31
26087** %f ** fractional seconds SS.SSS
26088** %F ISO date. YYYY-MM-DD
26089** %G ISO year corresponding to %V 0000-9999.
26090** %g 2-digit ISO year corresponding to %V 00-99
26091** %H hour 00-24
26092** %k hour 0-24 (leading zero converted to space)
26093** %I hour 01-12
26094** %j day of year 001-366
26095** %J ** julian day number
26096** %l hour 1-12 (leading zero converted to space)
26097** %m month 01-12
26098** %M minute 00-59
26099** %p "am" or "pm"
26100** %P "AM" or "PM"
26101** %R time as HH:MM
26102** %s seconds since 1970-01-01
26103** %S seconds 00-59
26104** %T time as HH:MM:SS
26105** %u day of week 1-7 Monday==1, Sunday==7
26106** %w day of week 0-6 Sunday==0, Monday==1
26107** %U week of year 00-53 (First Sunday is start of week 01)
26108** %V week of year 01-53 (First week containing Thursday is week 01)
26109** %W week of year 00-53 (First Monday is start of week 01)
26110** %Y year 0000-9999
26111** %% %
26112*/
26113static void strftimeFunc(
26114 sqlite3_context *context,
26115 int argc,
26116 sqlite3_value **argv
26117){
26118 DateTime x;
26119 size_t i,j;
26120 sqlite3 *db;
26121 const char *zFmt;
26122 sqlite3_str sRes;
26123
26124
26125 if( argc==0 ) return;
26126 zFmt = (const char*)sqlite3_value_text(argv[0]);
26127 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
26128 db = sqlite3_context_db_handle(context);
26129 sqlite3StrAccumInit(&sRes, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH0]);
26130
26131 computeJD(&x);
26132 computeYMD_HMS(&x);
26133 for(i=j=0; zFmt[i]; i++){
26134 char cf;
26135 if( zFmt[i]!='%' ) continue;
26136 if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j));
26137 i++;
26138 j = i + 1;
26139 cf = zFmt[i];
26140 switch( cf ){
26141 case 'd': /* Fall thru */
26142 case 'e': {
26143 sqlite3_str_appendf(&sRes, cf=='d' ? "%02d" : "%2d", x.D);
26144 break;
26145 }
26146 case 'f': { /* Fractional seconds. (Non-standard) */
26147 double s = x.s;
26148 if( NEVER(s>59.999)(s>59.999) ) s = 59.999;
26149 sqlite3_str_appendf(&sRes, "%06.3f", s);
26150 break;
26151 }
26152 case 'F': {
26153 sqlite3_str_appendf(&sRes, "%04d-%02d-%02d", x.Y, x.M, x.D);
26154 break;
26155 }
26156 case 'G': /* Fall thru */
26157 case 'g': {
26158 DateTime y = x;
26159 assert( y.validJD )((void) (0));
26160 /* Move y so that it is the Thursday in the same week as x */
26161 y.iJD += (3 - daysAfterMonday(&x))*86400000;
26162 y.validYMD = 0;
26163 computeYMD(&y);
26164 if( cf=='g' ){
26165 sqlite3_str_appendf(&sRes, "%02d", y.Y%100);
26166 }else{
26167 sqlite3_str_appendf(&sRes, "%04d", y.Y);
26168 }
26169 break;
26170 }
26171 case 'H':
26172 case 'k': {
26173 sqlite3_str_appendf(&sRes, cf=='H' ? "%02d" : "%2d", x.h);
26174 break;
26175 }
26176 case 'I': /* Fall thru */
26177 case 'l': {
26178 int h = x.h;
26179 if( h>12 ) h -= 12;
26180 if( h==0 ) h = 12;
26181 sqlite3_str_appendf(&sRes, cf=='I' ? "%02d" : "%2d", h);
26182 break;
26183 }
26184 case 'j': { /* Day of year. Jan01==1, Jan02==2, and so forth */
26185 sqlite3_str_appendf(&sRes,"%03d",daysAfterJan01(&x)+1);
26186 break;
26187 }
26188 case 'J': { /* Julian day number. (Non-standard) */
26189 sqlite3_str_appendf(&sRes,"%.16g",x.iJD/86400000.0);
26190 break;
26191 }
26192 case 'm': {
26193 sqlite3_str_appendf(&sRes,"%02d",x.M);
26194 break;
26195 }
26196 case 'M': {
26197 sqlite3_str_appendf(&sRes,"%02d",x.m);
26198 break;
26199 }
26200 case 'p': /* Fall thru */
26201 case 'P': {
26202 if( x.h>=12 ){
26203 sqlite3_str_append(&sRes, cf=='p' ? "PM" : "pm", 2);
26204 }else{
26205 sqlite3_str_append(&sRes, cf=='p' ? "AM" : "am", 2);
26206 }
26207 break;
26208 }
26209 case 'R': {
26210 sqlite3_str_appendf(&sRes, "%02d:%02d", x.h, x.m);
26211 break;
26212 }
26213 case 's': {
26214 if( x.useSubsec ){
26215 sqlite3_str_appendf(&sRes,"%.3f",
26216 (x.iJD - 21086676*(i64)10000000)/1000.0);
26217 }else{
26218 i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
26219 sqlite3_str_appendf(&sRes,"%lld",iS);
26220 }
26221 break;
26222 }
26223 case 'S': {
26224 sqlite3_str_appendf(&sRes,"%02d",(int)x.s);
26225 break;
26226 }
26227 case 'T': {
26228 sqlite3_str_appendf(&sRes,"%02d:%02d:%02d", x.h, x.m, (int)x.s);
26229 break;
26230 }
26231 case 'u': /* Day of week. 1 to 7. Monday==1, Sunday==7 */
26232 case 'w': { /* Day of week. 0 to 6. Sunday==0, Monday==1 */
26233 char c = (char)daysAfterSunday(&x) + '0';
26234 if( c=='0' && cf=='u' ) c = '7';
26235 sqlite3_str_appendchar(&sRes, 1, c);
26236 break;
26237 }
26238 case 'U': { /* Week num. 00-53. First Sun of the year is week 01 */
26239 sqlite3_str_appendf(&sRes,"%02d",
26240 (daysAfterJan01(&x)-daysAfterSunday(&x)+7)/7);
26241 break;
26242 }
26243 case 'V': { /* Week num. 01-53. First week with a Thur is week 01 */
26244 DateTime y = x;
26245 /* Adjust y so that is the Thursday in the same week as x */
26246 assert( y.validJD )((void) (0));
26247 y.iJD += (3 - daysAfterMonday(&x))*86400000;
26248 y.validYMD = 0;
26249 computeYMD(&y);
26250 sqlite3_str_appendf(&sRes,"%02d", daysAfterJan01(&y)/7+1);
26251 break;
26252 }
26253 case 'W': { /* Week num. 00-53. First Mon of the year is week 01 */
26254 sqlite3_str_appendf(&sRes,"%02d",
26255 (daysAfterJan01(&x)-daysAfterMonday(&x)+7)/7);
26256 break;
26257 }
26258 case 'Y': {
26259 sqlite3_str_appendf(&sRes,"%04d",x.Y);
26260 break;
26261 }
26262 case '%': {
26263 sqlite3_str_appendchar(&sRes, 1, '%');
26264 break;
26265 }
26266 default: {
26267 sqlite3_str_reset(&sRes);
26268 return;
26269 }
26270 }
26271 }
26272 if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j));
26273 sqlite3ResultStrAccum(context, &sRes);
26274}
26275
26276/*
26277** current_time()
26278**
26279** This function returns the same value as time('now').
26280*/
26281static void ctimeFunc(
26282 sqlite3_context *context,
26283 int NotUsed,
26284 sqlite3_value **NotUsed2
26285){
26286 UNUSED_PARAMETER2(NotUsed, NotUsed2)(void)(NotUsed),(void)(NotUsed2);
26287 timeFunc(context, 0, 0);
26288}
26289
26290/*
26291** current_date()
26292**
26293** This function returns the same value as date('now').
26294*/
26295static void cdateFunc(
26296 sqlite3_context *context,
26297 int NotUsed,
26298 sqlite3_value **NotUsed2
26299){
26300 UNUSED_PARAMETER2(NotUsed, NotUsed2)(void)(NotUsed),(void)(NotUsed2);
26301 dateFunc(context, 0, 0);
26302}
26303
26304/*
26305** timediff(DATE1, DATE2)
26306**
26307** Return the amount of time that must be added to DATE2 in order to
26308** convert it into DATE2. The time difference format is:
26309**
26310** +YYYY-MM-DD HH:MM:SS.SSS
26311**
26312** The initial "+" becomes "-" if DATE1 occurs before DATE2. For
26313** date/time values A and B, the following invariant should hold:
26314**
26315** datetime(A) == (datetime(B, timediff(A,B))
26316**
26317** Both DATE arguments must be either a julian day number, or an
26318** ISO-8601 string. The unix timestamps are not supported by this
26319** routine.
26320*/
26321static void timediffFunc(
26322 sqlite3_context *context,
26323 int NotUsed1,
26324 sqlite3_value **argv
26325){
26326 char sign;
26327 int Y, M;
26328 DateTime d1, d2;
26329 sqlite3_str sRes;
26330 UNUSED_PARAMETER(NotUsed1)(void)(NotUsed1);
26331 if( isDate(context, 1, &argv[0], &d1) ) return;
26332 if( isDate(context, 1, &argv[1], &d2) ) return;
26333 computeYMD_HMS(&d1);
26334 computeYMD_HMS(&d2);
26335 if( d1.iJD>=d2.iJD ){
26336 sign = '+';
26337 Y = d1.Y - d2.Y;
26338 if( Y ){
26339 d2.Y = d1.Y;
26340 d2.validJD = 0;
26341 computeJD(&d2);
26342 }
26343 M = d1.M - d2.M;
26344 if( M<0 ){
26345 Y--;
26346 M += 12;
26347 }
26348 if( M!=0 ){
26349 d2.M = d1.M;
26350 d2.validJD = 0;
26351 computeJD(&d2);
26352 }
26353 while( d1.iJD<d2.iJD ){
26354 M--;
26355 if( M<0 ){
26356 M = 11;
26357 Y--;
26358 }
26359 d2.M--;
26360 if( d2.M<1 ){
26361 d2.M = 12;
26362 d2.Y--;
26363 }
26364 d2.validJD = 0;
26365 computeJD(&d2);
26366 }
26367 d1.iJD -= d2.iJD;
26368 d1.iJD += (u64)1486995408 * (u64)100000;
26369 }else /* d1<d2 */{
26370 sign = '-';
26371 Y = d2.Y - d1.Y;
26372 if( Y ){
26373 d2.Y = d1.Y;
26374 d2.validJD = 0;
26375 computeJD(&d2);
26376 }
26377 M = d2.M - d1.M;
26378 if( M<0 ){
26379 Y--;
26380 M += 12;
26381 }
26382 if( M!=0 ){
26383 d2.M = d1.M;
26384 d2.validJD = 0;
26385 computeJD(&d2);
26386 }
26387 while( d1.iJD>d2.iJD ){
26388 M--;
26389 if( M<0 ){
26390 M = 11;
26391 Y--;
26392 }
26393 d2.M++;
26394 if( d2.M>12 ){
26395 d2.M = 1;
26396 d2.Y++;
26397 }
26398 d2.validJD = 0;
26399 computeJD(&d2);
26400 }
26401 d1.iJD = d2.iJD - d1.iJD;
26402 d1.iJD += (u64)1486995408 * (u64)100000;
26403 }
26404 clearYMD_HMS_TZ(&d1);
26405 computeYMD_HMS(&d1);
26406 sqlite3StrAccumInit(&sRes, 0, 0, 0, 100);
26407 sqlite3_str_appendf(&sRes, "%c%04d-%02d-%02d %02d:%02d:%06.3f",
26408 sign, Y, M, d1.D-1, d1.h, d1.m, d1.s);
26409 sqlite3ResultStrAccum(context, &sRes);
26410}
26411
26412
26413/*
26414** current_timestamp()
26415**
26416** This function returns the same value as datetime('now').
26417*/
26418static void ctimestampFunc(
26419 sqlite3_context *context,
26420 int NotUsed,
26421 sqlite3_value **NotUsed2
26422){
26423 UNUSED_PARAMETER2(NotUsed, NotUsed2)(void)(NotUsed),(void)(NotUsed2);
26424 datetimeFunc(context, 0, 0);
26425}
26426#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
26427
26428#ifdef SQLITE_OMIT_DATETIME_FUNCS
26429/*
26430** If the library is compiled to omit the full-scale date and time
26431** handling (to get a smaller binary), the following minimal version
26432** of the functions current_time(), current_date() and current_timestamp()
26433** are included instead. This is to support column declarations that
26434** include "DEFAULT CURRENT_TIME" etc.
26435**
26436** This function uses the C-library functions time(), gmtime()
26437** and strftime(). The format string to pass to strftime() is supplied
26438** as the user-data for the function.
26439*/
26440static void currentTimeFunc(
26441 sqlite3_context *context,
26442 int argc,
26443 sqlite3_value **argv
26444){
26445 time_t t;
26446 char *zFormat = (char *)sqlite3_user_data(context);
26447 sqlite3_int64 iT;
26448 struct tm *pTm;
26449 struct tm sNow;
26450 char zBuf[20];
26451
26452 UNUSED_PARAMETER(argc)(void)(argc);
26453 UNUSED_PARAMETER(argv)(void)(argv);
26454
26455 iT = sqlite3StmtCurrentTime(context);
26456 if( iT<=0 ) return;
26457 t = iT/1000 - 10000*(sqlite3_int64)21086676;
26458#if HAVE_GMTIME_R
26459 pTm = gmtime_r(&t, &sNow);
26460#else
26461 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN2));
26462 pTm = gmtime(&t);
26463 if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
26464 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN2));
26465#endif
26466 if( pTm ){
26467 strftime(zBuf, 20, zFormat, &sNow);
26468 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT((sqlite3_destructor_type)-1));
26469 }
26470}
26471#endif
26472
26473#if !defined(SQLITE_OMIT_DATETIME_FUNCS) && defined(SQLITE_DEBUG)
26474/*
26475** datedebug(...)
26476**
26477** This routine returns JSON that describes the internal DateTime object.
26478** Used for debugging and testing only. Subject to change.
26479*/
26480static void datedebugFunc(
26481 sqlite3_context *context,
26482 int argc,
26483 sqlite3_value **argv
26484){
26485 DateTime x;
26486 if( isDate(context, argc, argv, &x)==0 ){
26487 char *zJson;
26488 zJson = sqlite3_mprintf(
26489 "{iJD:%lld,Y:%d,M:%d,D:%d,h:%d,m:%d,tz:%d,"
26490 "s:%.3f,validJD:%d,validYMS:%d,validHMS:%d,"
26491 "nFloor:%d,rawS:%d,isError:%d,useSubsec:%d,"
26492 "isUtc:%d,isLocal:%d}",
26493 x.iJD, x.Y, x.M, x.D, x.h, x.m, x.tz,
26494 x.s, x.validJD, x.validYMD, x.validHMS,
26495 x.nFloor, x.rawS, x.isError, x.useSubsec,
26496 x.isUtc, x.isLocal);
26497 sqlite3_result_text(context, zJson, -1, sqlite3_free);
26498 }
26499}
26500#endif /* !SQLITE_OMIT_DATETIME_FUNCS && SQLITE_DEBUG */
26501
26502
26503/*
26504** This function registered all of the above C functions as SQL
26505** functions. This should be the only routine in this file with
26506** external linkage.
26507*/
26508SQLITE_PRIVATEstatic void sqlite3RegisterDateTimeFunctions(void){
26509 static FuncDef aDateTimeFuncs[] = {
26510#ifndef SQLITE_OMIT_DATETIME_FUNCS
26511 PURE_DATE(julianday, -1, 0, 0, juliandayFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0
, juliandayFunc, 0, 0, 0, "julianday", {0} }
,
26512 PURE_DATE(unixepoch, -1, 0, 0, unixepochFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0
, unixepochFunc, 0, 0, 0, "unixepoch", {0} }
,
26513 PURE_DATE(date, -1, 0, 0, dateFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0
, dateFunc, 0, 0, 0, "date", {0} }
,
26514 PURE_DATE(time, -1, 0, 0, timeFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0
, timeFunc, 0, 0, 0, "time", {0} }
,
26515 PURE_DATE(datetime, -1, 0, 0, datetimeFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0
, datetimeFunc, 0, 0, 0, "datetime", {0} }
,
26516 PURE_DATE(strftime, -1, 0, 0, strftimeFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0
, strftimeFunc, 0, 0, 0, "strftime", {0} }
,
26517 PURE_DATE(timediff, 2, 0, 0, timediffFunc ){2, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0
, timediffFunc, 0, 0, 0, "timediff", {0} }
,
26518#ifdef SQLITE_DEBUG
26519 PURE_DATE(datedebug, -1, 0, 0, datedebugFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0
, datedebugFunc, 0, 0, 0, "datedebug", {0} }
,
26520#endif
26521 DFUNCTION(current_time, 0, 0, 0, ctimeFunc ){0, 0x00800000|0x2000|1, 0, 0, ctimeFunc, 0, 0, 0, "current_time"
, {0} }
,
26522 DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc){0, 0x00800000|0x2000|1, 0, 0, ctimestampFunc, 0, 0, 0, "current_timestamp"
, {0} }
,
26523 DFUNCTION(current_date, 0, 0, 0, cdateFunc ){0, 0x00800000|0x2000|1, 0, 0, cdateFunc, 0, 0, 0, "current_date"
, {0} }
,
26524#else
26525 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc){0, 0x00800000| 0x2000|1|(0*0x0020), "%H:%M:%S", 0, currentTimeFunc
, 0, 0, 0, "current_time", }
,
26526 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc){0, 0x00800000| 0x2000|1|(0*0x0020), "%Y-%m-%d", 0, currentTimeFunc
, 0, 0, 0, "current_date", }
,
26527 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc){0, 0x00800000| 0x2000|1|(0*0x0020), "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc
, 0, 0, 0, "current_timestamp", }
,
26528#endif
26529 };
26530 sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs)((int)(sizeof(aDateTimeFuncs)/sizeof(aDateTimeFuncs[0]))));
26531}
26532
26533/************** End of date.c ************************************************/
26534/************** Begin file os.c **********************************************/
26535/*
26536** 2005 November 29
26537**
26538** The author disclaims copyright to this source code. In place of
26539** a legal notice, here is a blessing:
26540**
26541** May you do good and not evil.
26542** May you find forgiveness for yourself and forgive others.
26543** May you share freely, never taking more than you give.
26544**
26545******************************************************************************
26546**
26547** This file contains OS interface code that is common to all
26548** architectures.
26549*/
26550/* #include "sqliteInt.h" */
26551
26552/*
26553** If we compile with the SQLITE_TEST macro set, then the following block
26554** of code will give us the ability to simulate a disk I/O error. This
26555** is used for testing the I/O recovery logic.
26556*/
26557#if defined(SQLITE_TEST)
26558SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
26559SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
26560SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
26561SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
26562SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
26563SQLITE_API int sqlite3_diskfull_pending = 0;
26564SQLITE_API int sqlite3_diskfull = 0;
26565#endif /* defined(SQLITE_TEST) */
26566
26567/*
26568** When testing, also keep a count of the number of open files.
26569*/
26570#if defined(SQLITE_TEST)
26571SQLITE_API int sqlite3_open_file_count = 0;
26572#endif /* defined(SQLITE_TEST) */
26573
26574/*
26575** The default SQLite sqlite3_vfs implementations do not allocate
26576** memory (actually, os_unix.c allocates a small amount of memory
26577** from within OsOpen()), but some third-party implementations may.
26578** So we test the effects of a malloc() failing and the sqlite3OsXXX()
26579** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
26580**
26581** The following functions are instrumented for malloc() failure
26582** testing:
26583**
26584** sqlite3OsRead()
26585** sqlite3OsWrite()
26586** sqlite3OsSync()
26587** sqlite3OsFileSize()
26588** sqlite3OsLock()
26589** sqlite3OsCheckReservedLock()
26590** sqlite3OsFileControl()
26591** sqlite3OsShmMap()
26592** sqlite3OsOpen()
26593** sqlite3OsDelete()
26594** sqlite3OsAccess()
26595** sqlite3OsFullPathname()
26596**
26597*/
26598#if defined(SQLITE_TEST)
26599SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
26600 #define DO_OS_MALLOC_TEST(x) \
26601 if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
26602 void *pTstAlloc = sqlite3Malloc(10); \
26603 if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); \
26604 sqlite3_free(pTstAlloc); \
26605 }
26606#else
26607 #define DO_OS_MALLOC_TEST(x)
26608#endif
26609
26610/*
26611** The following routines are convenience wrappers around methods
26612** of the sqlite3_file object. This is mostly just syntactic sugar. All
26613** of this would be completely automatic if SQLite were coded using
26614** C++ instead of plain old C.
26615*/
26616SQLITE_PRIVATEstatic void sqlite3OsClose(sqlite3_file *pId){
26617 if( pId->pMethods ){
26618 pId->pMethods->xClose(pId);
26619 pId->pMethods = 0;
26620 }
26621}
26622SQLITE_PRIVATEstatic int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
26623 DO_OS_MALLOC_TEST(id);
26624 return id->pMethods->xRead(id, pBuf, amt, offset);
26625}
26626SQLITE_PRIVATEstatic int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
26627 DO_OS_MALLOC_TEST(id);
26628 return id->pMethods->xWrite(id, pBuf, amt, offset);
26629}
26630SQLITE_PRIVATEstatic int sqlite3OsTruncate(sqlite3_file *id, i64 size){
26631 return id->pMethods->xTruncate(id, size);
26632}
26633SQLITE_PRIVATEstatic int sqlite3OsSync(sqlite3_file *id, int flags){
26634 DO_OS_MALLOC_TEST(id);
26635 return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK0;
26636}
26637SQLITE_PRIVATEstatic int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
26638 DO_OS_MALLOC_TEST(id);
26639 return id->pMethods->xFileSize(id, pSize);
26640}
26641SQLITE_PRIVATEstatic int sqlite3OsLock(sqlite3_file *id, int lockType){
26642 DO_OS_MALLOC_TEST(id);
26643 assert( lockType>=SQLITE_LOCK_SHARED && lockType<=SQLITE_LOCK_EXCLUSIVE )((void) (0));
26644 return id->pMethods->xLock(id, lockType);
26645}
26646SQLITE_PRIVATEstatic int sqlite3OsUnlock(sqlite3_file *id, int lockType){
26647 assert( lockType==SQLITE_LOCK_NONE || lockType==SQLITE_LOCK_SHARED )((void) (0));
26648 return id->pMethods->xUnlock(id, lockType);
26649}
26650SQLITE_PRIVATEstatic int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
26651 DO_OS_MALLOC_TEST(id);
26652 return id->pMethods->xCheckReservedLock(id, pResOut);
26653}
26654
26655/*
26656** Use sqlite3OsFileControl() when we are doing something that might fail
26657** and we need to know about the failures. Use sqlite3OsFileControlHint()
26658** when simply tossing information over the wall to the VFS and we do not
26659** really care if the VFS receives and understands the information since it
26660** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
26661** routine has no return value since the return value would be meaningless.
26662*/
26663SQLITE_PRIVATEstatic int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
26664 if( id->pMethods==0 ) return SQLITE_NOTFOUND12;
26665#ifdef SQLITE_TEST
26666 if( op!=SQLITE_FCNTL_COMMIT_PHASETWO22
26667 && op!=SQLITE_FCNTL_LOCK_TIMEOUT34
26668 && op!=SQLITE_FCNTL_CKPT_DONE37
26669 && op!=SQLITE_FCNTL_CKPT_START39
26670 ){
26671 /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
26672 ** is using a regular VFS, it is called after the corresponding
26673 ** transaction has been committed. Injecting a fault at this point
26674 ** confuses the test scripts - the COMMIT command returns SQLITE_NOMEM
26675 ** but the transaction is committed anyway.
26676 **
26677 ** The core must call OsFileControl() though, not OsFileControlHint(),
26678 ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
26679 ** means the commit really has failed and an error should be returned
26680 ** to the user.
26681 **
26682 ** The CKPT_DONE and CKPT_START file-controls are write-only signals
26683 ** to the cksumvfs. Their return code is meaningless and is ignored
26684 ** by the SQLite core, so there is no point in simulating OOMs for them.
26685 */
26686 DO_OS_MALLOC_TEST(id);
26687 }
26688#endif
26689 return id->pMethods->xFileControl(id, op, pArg);
26690}
26691SQLITE_PRIVATEstatic void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
26692 if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
26693}
26694
26695SQLITE_PRIVATEstatic int sqlite3OsSectorSize(sqlite3_file *id){
26696 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
26697 return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE4096);
26698}
26699SQLITE_PRIVATEstatic int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
26700 if( NEVER(id->pMethods==0)(id->pMethods==0) ) return 0;
26701 return id->pMethods->xDeviceCharacteristics(id);
26702}
26703#ifndef SQLITE_OMIT_WAL
26704SQLITE_PRIVATEstatic int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
26705 return id->pMethods->xShmLock(id, offset, n, flags);
26706}
26707SQLITE_PRIVATEstatic void sqlite3OsShmBarrier(sqlite3_file *id){
26708 id->pMethods->xShmBarrier(id);
26709}
26710SQLITE_PRIVATEstatic int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
26711 return id->pMethods->xShmUnmap(id, deleteFlag);
26712}
26713SQLITE_PRIVATEstatic int sqlite3OsShmMap(
26714 sqlite3_file *id, /* Database file handle */
26715 int iPage,
26716 int pgsz,
26717 int bExtend, /* True to extend file if necessary */
26718 void volatile **pp /* OUT: Pointer to mapping */
26719){
26720 DO_OS_MALLOC_TEST(id);
26721 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
26722}
26723#endif /* SQLITE_OMIT_WAL */
26724
26725#if SQLITE_MAX_MMAP_SIZE20971520>0
26726/* The real implementation of xFetch and xUnfetch */
26727SQLITE_PRIVATEstatic int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
26728 DO_OS_MALLOC_TEST(id);
26729 return id->pMethods->xFetch(id, iOff, iAmt, pp);
26730}
26731SQLITE_PRIVATEstatic int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
26732 return id->pMethods->xUnfetch(id, iOff, p);
26733}
26734#else
26735/* No-op stubs to use when memory-mapped I/O is disabled */
26736SQLITE_PRIVATEstatic int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
26737 *pp = 0;
26738 return SQLITE_OK0;
26739}
26740SQLITE_PRIVATEstatic int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
26741 return SQLITE_OK0;
26742}
26743#endif
26744
26745/*
26746** The next group of routines are convenience wrappers around the
26747** VFS methods.
26748*/
26749SQLI