sqlite3.c

8.8 MB · showing the first 1 MB · raw

1/******************************************************************************2** This file is an amalgamation of many separate C source files from SQLite3** version 3.49.1.  By combining all the individual C code files into this4** single large file, the entire code can be compiled as a single translation5** unit.  This allows many compilers to do optimizations that would not be6** possible if the files were compiled separately.  Performance improvements7** of 5% or more are commonly seen when SQLite is compiled as a single8** translation unit.9**10** This file is all you need to compile SQLite.  To use SQLite in other11** programs, you need this file and the "sqlite3.h" header file that defines12** the programming interface to the SQLite library.  (If you do not have13** the "sqlite3.h" header file at hand, you will find a copy embedded within14** the text of this file.  Search for "Begin file sqlite3.h" to find the start15** of the embedded sqlite3.h header file.) Additional code files may be needed16** if you want a wrapper to interface SQLite with your choice of programming17** language. The code for the "sqlite3" command-line shell is also in a18** separate file. This file contains only code for the core SQLite library.19**20** The content in this amalgamation comes from Fossil check-in21** 873d4e274b4988d260ba8354a9718324a1c2 with changes in files:22**23**    24*/25#ifndef SQLITE_AMALGAMATION26#define SQLITE_CORE 127#define SQLITE_AMALGAMATION 128#ifndef SQLITE_PRIVATE29# define SQLITE_PRIVATE static30#endif31/************** Begin file sqliteInt.h ***************************************/32/*33** 2001 September 1534**35** The author disclaims copyright to this source code.  In place of36** 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_H47#define SQLITEINT_H4849/* Special Comments:50**51** Some comments have special meaning to the tools that measure test52** coverage:53**54**    NO_TEST                     - The branches on this line are not55**                                  measured by branch coverage.  This is56**                                  used on lines of code that actually57**                                  implement parts of coverage testing.58**59**    OPTIMIZATION-IF-TRUE        - This branch is allowed to always be false60**                                  and the correct answer is still obtained,61**                                  though perhaps more slowly.62**63**    OPTIMIZATION-IF-FALSE       - This branch is allowed to always be true64**                                  and the correct answer is still obtained,65**                                  though perhaps more slowly.66**67**    PREVENTS-HARMLESS-OVERREAD  - This branch prevents a buffer overread68**                                  that would be harmless and undetectable69**                                  if it did occur.70**71** In all cases, the special comment must be enclosed in the usual72** slash-asterisk...asterisk-slash comment marks, with no spaces between the73** asterisks and the comment text.74*/7576/*77** Make sure the Tcl calling convention macro is defined.  This macro is78** only used by test code and Tcl integration code.79*/80#ifndef SQLITE_TCLAPI81#  define SQLITE_TCLAPI82#endif8384/*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 spurious87** compiler warnings due to subsequent content in this file and other files88** 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 1294**95** The author disclaims copyright to this source code.  In place of96** 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_H107#define SQLITE_MSVC_H108109#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) */126127#if defined(_MSC_VER) && !defined(_WIN64)128#undef SQLITE_4_BYTE_ALIGNED_MALLOC129#define SQLITE_4_BYTE_ALIGNED_MALLOC130#endif /* defined(_MSC_VER) && !defined(_WIN64) */131132#if !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800133#define HAVE_LOG2 0134#endif /* !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800 */135136#endif /* SQLITE_MSVC_H */137138/************** End of msvc.h ************************************************/139/************** Continuing where we left off in sqliteInt.h ******************/140141/*142** Special setup for VxWorks143*/144/************** Include vxworks.h in the middle of sqliteInt.h ***************/145/************** Begin file vxworks.h *****************************************/146/*147** 2015-03-02148**149** The author disclaims copyright to this source code.  In place of150** 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 VxWorks159*/160#if defined(__RTP__) || defined(_WRS_KERNEL)161/* This is VxWorks.  Set up things specially for that OS162*/163#include <vxWorks.h>164#include <pthread.h>  /* amalgamator: dontcache */165#define OS_VXWORKS 1166#define SQLITE_OS_OTHER 0167#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1168#define SQLITE_OMIT_LOAD_EXTENSION 1169#define SQLITE_ENABLE_LOCKING_STYLE 0170#define HAVE_UTIME 1171#else172/* This is not VxWorks. */173#define OS_VXWORKS 0174#define HAVE_FCHOWN 1175#define HAVE_READLINK 1176#define HAVE_LSTAT 1177#endif /* defined(_WRS_KERNEL) */178179/************** End of vxworks.h *********************************************/180/************** Continuing where we left off in sqliteInt.h ******************/181182/*183** These #defines should enable >2GB file support on POSIX if the184** underlying operating system supports it.  If the OS lacks185** 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 any188** system #includes.  Hence, this block of code must be the very first189** code in all source files.190**191** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch192** on the compiler command line.  This is necessary if you are compiling193** on a recent machine (ex: Red Hat 7.2) but you want your code to work194** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2195** without this option, LFS is enable.  But LFS does not exist in the kernel196** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary197** portability you should omit LFS.198**199** The previous paragraph was written in 2005.  (This paragraph is written200** on 2008-11-28.) These days, all Linux kernels support large files, so201** you should probably leave LFS enabled.  But some embedded platforms might202** 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_LFS207# define _LARGE_FILE       1208# ifndef _FILE_OFFSET_BITS209#   define _FILE_OFFSET_BITS 64210# endif211# define _LARGEFILE_SOURCE 1212#endif213214/* The GCC_VERSION and MSVC_VERSION macros are used to215** conditionally include optimizations for each of these compilers.  A216** value of 0 means that compiler is not being used.  The217** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific218** optimizations, and hence set all compiler macros to 0219**220** There was once also a CLANG_VERSION macro.  However, we learn that the221** version numbers in clang are for "marketing" only and are inconsistent222** and unreliable.  Fortunately, all versions of clang also recognize the223** 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 even225** when compiling with clang.226*/227#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)228# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)229#else230# define GCC_VERSION 0231#endif232#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)233# define MSVC_VERSION _MSC_VER234#else235# define MSVC_VERSION 0236#endif237238/*239** Some C99 functions in "math.h" are only present for MSVC when its version240** is associated with Visual Studio 2013 or higher.241*/242#ifndef SQLITE_HAVE_C99_MATH_FUNCS243# if MSVC_VERSION==0 || MSVC_VERSION>=1800244#  define SQLITE_HAVE_C99_MATH_FUNCS (1)245# else246#  define SQLITE_HAVE_C99_MATH_FUNCS (0)247# endif248#endif249250/* Needed for various definitions... */251#if defined(__GNUC__) && !defined(_GNU_SOURCE)252# define _GNU_SOURCE253#endif254255#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)256# define _BSD_SOURCE257#endif258259/*260** Macro to disable warnings about missing "break" at the end of a "case".261*/262#if defined(__has_attribute)263#  if __has_attribute(fallthrough)264#    define deliberate_fall_through __attribute__((fallthrough));265#  endif266#endif267#if !defined(deliberate_fall_through)268#  define deliberate_fall_through269#endif270271/*272** For MinGW, check to see if we can include the header file containing its273** version information, among other things.  Normally, this internal MinGW274** header file would [only] be included automatically by other MinGW header275** files; however, the contained version information is now required by this276** header file to work around binary compatibility issues (see below) and277** this is the only known way to reliably obtain it.  This entire #if block278** would be completely unnecessary if there was any other way of detecting279** MinGW via their preprocessor (e.g. if they customized their GCC to define280** some MinGW-specific macros).  When compiling for MinGW, either the281** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be282** defined; otherwise, detection of conditions specific to MinGW will be283** disabled.284*/285#if defined(_HAVE_MINGW_H)286# include "mingw.h"287#elif defined(_HAVE__MINGW_H)288# include "_mingw.h"289#endif290291/*292** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T293** define is required to maintain binary compatibility with the MSVC runtime294** 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_T301#endif302303/* Optionally #include a user-defined header, whereby compilation options304** may be set prior to where they take effect, but after platform setup.305** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include306** file.307*/308#ifdef SQLITE_CUSTOM_INCLUDE309# define INC_STRINGIFY_(f) #f310# define INC_STRINGIFY(f) INC_STRINGIFY_(f)311# include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE)312#endif313314/* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear315** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for316** MinGW.317*/318/************** Include sqlite3.h in the middle of sqliteInt.h ***************/319/************** Begin file sqlite3.h *****************************************/320/*321** 2001-09-15322**323** The author disclaims copyright to this source code.  In place of324** 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 library332** presents to client programs.  If a C-function, structure, datatype,333** or constant definition does not appear in this file, then it is334** not a published API of SQLite, is subject to change without335** notice, and should not be referenced by programs that use SQLite.336**337** Some of the definitions that are in this file are marked as338** "experimental".  Experimental interfaces are normally new339** features recently added to SQLite.  We do not anticipate changes340** to experimental interfaces but reserve the right to make minor changes341** if experience from use "in the wild" suggest such changes are prudent.342**343** The official C-language API documentation for SQLite is derived344** from comments in this file.  This file is the authoritative source345** 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 inserting349** the version number) and changes its name to "sqlite3.h" as350** part of the build process.351*/352#ifndef SQLITE3_H353#define SQLITE3_H354#include <stdarg.h>     /* Needed for the definition of va_list */355356/*357** Make sure we can call this stuff from C++.358*/359#if 0360extern "C" {361#endif362363364/*365** Facilitate override of interface linkage and calling conventions.366** Be aware that these macros may not be used within this particular367** translation of the amalgamation and its associated header file.368**369** The SQLITE_EXTERN and SQLITE_API macros are used to instruct the370** compiler that the target identifier should have external linkage.371**372** The SQLITE_CDECL macro is used to set the calling convention for373** public functions that accept a variable number of arguments.374**375** The SQLITE_APICALL macro is used to set the calling convention for376** 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 for381** function pointers.382**383** The SQLITE_SYSAPI macro is used to set the calling convention for384** functions provided by the operating system.385**386** Currently, the SQLITE_CDECL, SQLITE_APICALL, SQLITE_CALLBACK, and387** SQLITE_SYSAPI macros are used only when building for environments388** that require non-default calling conventions.389*/390#ifndef SQLITE_EXTERN391# define SQLITE_EXTERN extern392#endif393#ifndef SQLITE_API394# define SQLITE_API395#endif396#ifndef SQLITE_CDECL397# define SQLITE_CDECL398#endif399#ifndef SQLITE_APICALL400# define SQLITE_APICALL401#endif402#ifndef SQLITE_STDCALL403# define SQLITE_STDCALL SQLITE_APICALL404#endif405#ifndef SQLITE_CALLBACK406# define SQLITE_CALLBACK407#endif408#ifndef SQLITE_SYSAPI409# define SQLITE_SYSAPI410#endif411412/*413** These no-op macros are used in front of interfaces to mark those414** interfaces as either deprecated or experimental.  New applications415** should not use deprecated interfaces - they are supported for backwards416** compatibility only.  Application writers should be aware that417** experimental interfaces are subject to change in point releases.418**419** These macros used to resolve to various kinds of compiler magic that420** would generate warning messages when they were used.  But that421** compiler magic ended up generating such a flurry of bug reports422** that we have taken it all out and gone back to using simple423** noop macros.424*/425#define SQLITE_DEPRECATED426#define SQLITE_EXPERIMENTAL427428/*429** Ensure these symbols were not defined by some previous header file.430*/431#ifdef SQLITE_VERSION432# undef SQLITE_VERSION433#endif434#ifdef SQLITE_VERSION_NUMBER435# undef SQLITE_VERSION_NUMBER436#endif437438/*439** CAPI3REF: Compile-Time Library Version Numbers440**441** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header442** evaluates to a string literal that is the SQLite version in the443** format "X.Y.Z" where X is the major version number (always 3 for444** 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 integer446** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same447** numbers used in [SQLITE_VERSION].)^448** The SQLITE_VERSION_NUMBER for any given release of SQLite will also449** be larger than the release from which it is derived.  Either Y will450** be held constant and Z will be incremented or else Y will be incremented451** 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 the455** <a href="http://www.fossil-scm.org/">Fossil configuration management456** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to457** a string which identifies a particular check-in of SQLite458** within its configuration management system.  ^The SQLITE_SOURCE_ID459** string contains the date and time of the check-in (UTC) and a SHA1460** or SHA3-256 hash of the entire source tree.  If the source code has461** been edited in any way since it was last checked in, then the last462** 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.49.1"469#define SQLITE_VERSION_NUMBER 3049001470#define SQLITE_SOURCE_ID      "2025-02-18 13:38:58 873d4e274b4988d260ba8354a9718324a1c26187a4ab4c1cc0227c03d0f10e70"471472/*473** CAPI3REF: Run-Time Library Version Numbers474** KEYWORDS: sqlite3_version sqlite3_sourceid475**476** These interfaces provide the same information as the [SQLITE_VERSION],477** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros478** but are associated with the library instead of the header file.  ^(Cautious479** programmers might include assert() statements in their application to480** verify that values returned by these interfaces match the macros in481** the header, and thus ensure that the application is482** 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 the492** to the sqlite3_version[] string constant.  The sqlite3_libversion()493** function is provided for use in DLLs since DLL users usually do not have494** direct access to string constants within the DLL.  ^The495** sqlite3_libversion_number() function returns an integer equal to496** [SQLITE_VERSION_NUMBER].  ^(The sqlite3_sourceid() function returns497** a pointer to a string constant whose value is the same as the498** [SQLITE_SOURCE_ID] C preprocessor macro.  Except if SQLite is built499** using an edited copy of [the amalgamation], then the last four characters500** 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;505SQLITE_API const char *sqlite3_libversion(void);506SQLITE_API const char *sqlite3_sourceid(void);507SQLITE_API int sqlite3_libversion_number(void);508509/*510** CAPI3REF: Run-Time Library Compilation Options Diagnostics511**512** ^The sqlite3_compileoption_used() function returns 0 or 1513** indicating whether the specified option was defined at514** compile time.  ^The SQLITE_ prefix may be omitted from the515** option name passed to sqlite3_compileoption_used().516**517** ^The sqlite3_compileoption_get() function allows iterating518** over the list of options that were defined at compile time by519** 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 by522** sqlite3_compileoption_get().523**524** ^Support for the diagnostic functions sqlite3_compileoption_used()525** and sqlite3_compileoption_get() may be omitted by specifying the526** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.527**528** See also: SQL functions [sqlite_compileoption_used()] and529** [sqlite_compileoption_get()] and the [compile_options pragma].530*/531#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS532SQLITE_API int sqlite3_compileoption_used(const char *zOptName);533SQLITE_API const char *sqlite3_compileoption_get(int N);534#else535# define sqlite3_compileoption_used(X) 0536# define sqlite3_compileoption_get(X)  ((void*)0)537#endif538539/*540** CAPI3REF: Test To See If The Library Is Threadsafe541**542** ^The sqlite3_threadsafe() function returns zero if and only if543** SQLite was compiled with mutexing code omitted due to the544** [SQLITE_THREADSAFE] compile-time option being set to 0.545**546** SQLite can be compiled with or without mutexes.  When547** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes548** are enabled and SQLite is threadsafe.  When the549** [SQLITE_THREADSAFE] macro is 0,550** the mutexes are omitted.  Without the mutexes, it is not safe551** 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 disable555** 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 the559** version of SQLite that it is linking against was compiled with560** the desired setting of the [SQLITE_THREADSAFE] macro.561**562** This interface only reports on the compile-time mutex setting563** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with564** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but565** 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 the568** sqlite3_threadsafe() function shows only the compile-time setting of569** thread safety, not any run-time changes to that setting made by570** 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);576577/*578** CAPI3REF: Database Connection Handle579** KEYWORDS: {database connection} {database connections}580**581** Each open SQLite database is represented by a pointer to an instance of582** the opaque structure named "sqlite3".  It is useful to think of an sqlite3583** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and584** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]585** and [sqlite3_close_v2()] are its destructors.  There are many other586** interfaces (such as587** [sqlite3_prepare_v2()], [sqlite3_create_function()], and588** [sqlite3_busy_timeout()] to name but three) that are methods on an589** sqlite3 object.590*/591typedef struct sqlite3 sqlite3;592593/*594** CAPI3REF: 64-Bit Integer Types595** KEYWORDS: sqlite_int64 sqlite_uint64596**597** Because there is no cross-platform way to specify 64-bit integer types598** 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 backwards602** compatibility only.603**604** ^The sqlite3_int64 and sqlite_int64 types can store integer values605** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The606** sqlite3_uint64 and sqlite_uint64 types can store integer values607** between 0 and +18446744073709551615 inclusive.608*/609#ifdef SQLITE_INT64_TYPE610  typedef SQLITE_INT64_TYPE sqlite_int64;611# ifdef SQLITE_UINT64_TYPE612    typedef SQLITE_UINT64_TYPE sqlite_uint64;613# else614    typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;615# endif616#elif defined(_MSC_VER) || defined(__BORLANDC__)617  typedef __int64 sqlite_int64;618  typedef unsigned __int64 sqlite_uint64;619#else620  typedef long long int sqlite_int64;621  typedef unsigned long long int sqlite_uint64;622#endif623typedef sqlite_int64 sqlite3_int64;624typedef sqlite_uint64 sqlite3_uint64;625626/*627** If compiling for a processor that lacks floating point support,628** substitute integer for floating-point.629*/630#ifdef SQLITE_OMIT_FLOATING_POINT631# define double sqlite3_int64632#endif633634/*635** CAPI3REF: Closing A Database Connection636** DESTRUCTOR: sqlite3637**638** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors639** for the [sqlite3] object.640** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if641** the [sqlite3] object is successfully destroyed and all associated642** resources are deallocated.643**644** Ideally, applications should [sqlite3_finalize | finalize] all645** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and646** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated647** with the [sqlite3] object prior to attempting to close the object.648** ^If the database connection is associated with unfinalized prepared649** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then650** sqlite3_close() will leave the database connection open and return651** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared652** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,653** it returns [SQLITE_OK] regardless, but instead of deallocating the database654** connection immediately, it marks the database connection as an unusable655** "zombie" and makes arrangements to automatically deallocate the database656** connection after all prepared statements are finalized, all BLOB handles657** are closed, and all backups have finished. The sqlite3_close_v2() interface658** is intended for use with host languages that are garbage collected, and659** 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 NULL666** pointer or an [sqlite3] object pointer obtained667** from [sqlite3_open()], [sqlite3_open16()], or668** [sqlite3_open_v2()], and not previously closed.669** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer670** argument is a harmless no-op.671*/672SQLITE_API int sqlite3_close(sqlite3*);673SQLITE_API int sqlite3_close_v2(sqlite3*);674675/*676** The type for a callback function.677** This is legacy and deprecated.  It is included for historical678** compatibility and is not documented.679*/680typedef int (*sqlite3_callback)(void*,int,char**, char**);681682/*683** CAPI3REF: One-Step Query Execution Interface684** METHOD: sqlite3685**686** The sqlite3_exec() interface is a convenience wrapper around687** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],688** that allows an application to run multiple statements of SQL689** 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 1st694** argument.  ^If the callback function of the 3rd argument to695** sqlite3_exec() is not NULL, then it is invoked for each result row696** coming out of the evaluated SQL statements.  ^The 4th argument to697** sqlite3_exec() is relayed through to the 1st argument of each698** callback invocation.  ^If the callback pointer to sqlite3_exec()699** is NULL, then no callback is ever invoked and result rows are700** ignored.701**702** ^If an error occurs while evaluating the SQL statements passed into703** sqlite3_exec(), then execution of the current statement stops and704** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()705** is not NULL then any error message is written into memory obtained706** 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 of709** sqlite3_exec() after the error message string is no longer needed.710** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors711** occur, then sqlite3_exec() sets the pointer in its 5th parameter to712** 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 and716** without running any subsequent SQL statements.717**718** ^The 2nd argument to the sqlite3_exec() callback function is the719** 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 from721** [sqlite3_column_text()], one for each column.  ^If an element of a722** result row is NULL then the corresponding string pointer for the723** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the724** sqlite3_exec() callback is an array of pointers to strings where each725** entry represents the name of corresponding result column as obtained726** from [sqlite3_column_name()].727**728** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer729** to an empty string, or a pointer that contains only whitespace and/or730** SQL comments, then no SQL statements are evaluated and the database731** 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 by739**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.740** <li> The application must not modify the SQL statement text passed into741**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.742** <li> The application must not dereference the arrays or string pointers743**       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);753754/*755** CAPI3REF: Result Codes756** KEYWORDS: {result code definitions}757**758** Many SQLite functions return an integer result code from the set shown759** 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_OK           0   /* Successful result */766/* beginning-of-error-codes */767#define SQLITE_ERROR        1   /* Generic error */768#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */769#define SQLITE_PERM         3   /* Access permission denied */770#define SQLITE_ABORT        4   /* Callback routine requested an abort */771#define SQLITE_BUSY         5   /* The database file is locked */772#define SQLITE_LOCKED       6   /* A table in the database is locked */773#define SQLITE_NOMEM        7   /* A malloc() failed */774#define SQLITE_READONLY     8   /* Attempt to write a readonly database */775#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/776#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */777#define SQLITE_CORRUPT     11   /* The database disk image is malformed */778#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */779#define SQLITE_FULL        13   /* Insertion failed because database is full */780#define SQLITE_CANTOPEN    14   /* Unable to open the database file */781#define SQLITE_PROTOCOL    15   /* Database lock protocol error */782#define SQLITE_EMPTY       16   /* Internal use only */783#define SQLITE_SCHEMA      17   /* The database schema changed */784#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */785#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */786#define SQLITE_MISMATCH    20   /* Data type mismatch */787#define SQLITE_MISUSE      21   /* Library used incorrectly */788#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */789#define SQLITE_AUTH        23   /* Authorization denied */790#define SQLITE_FORMAT      24   /* Not used */791#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */792#define SQLITE_NOTADB      26   /* File opened that is not a database file */793#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */794#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */795#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */796#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */797/* end-of-error-codes */798799/*800** CAPI3REF: Extended Result Codes801** KEYWORDS: {extended result code definitions}802**803** In its default configuration, SQLite API routines return one of 30 integer804** [result codes].  However, experience has shown that many of805** these result codes are too coarse-grained.  They do not provide as806** much information about problems as programmers might like.  In an effort to807** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]808** and later) include809** support for additional result codes that provide more detailed information810** about errors. These [extended result codes] are enabled or disabled811** on a per database connection basis using the812** [sqlite3_extended_result_codes()] API.  Or, the extended code for813** the most recent error can be obtained using814** [sqlite3_extended_errcode()].815*/816#define SQLITE_ERROR_MISSING_COLLSEQ   (SQLITE_ERROR | (1<<8))817#define SQLITE_ERROR_RETRY             (SQLITE_ERROR | (2<<8))818#define SQLITE_ERROR_SNAPSHOT          (SQLITE_ERROR | (3<<8))819#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))820#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))821#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))822#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))823#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))824#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))825#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))826#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))827#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))828#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))829#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))830#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))831#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))832#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))833#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))834#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))835#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))836#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))837#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))838#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))839#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))840#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))841#define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))842#define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))843#define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))844#define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))845#define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))846#define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))847#define SQLITE_IOERR_BEGIN_ATOMIC      (SQLITE_IOERR | (29<<8))848#define SQLITE_IOERR_COMMIT_ATOMIC     (SQLITE_IOERR | (30<<8))849#define SQLITE_IOERR_ROLLBACK_ATOMIC   (SQLITE_IOERR | (31<<8))850#define SQLITE_IOERR_DATA              (SQLITE_IOERR | (32<<8))851#define SQLITE_IOERR_CORRUPTFS         (SQLITE_IOERR | (33<<8))852#define SQLITE_IOERR_IN_PAGE           (SQLITE_IOERR | (34<<8))853#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))854#define SQLITE_LOCKED_VTAB             (SQLITE_LOCKED |  (2<<8))855#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))856#define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))857#define SQLITE_BUSY_TIMEOUT            (SQLITE_BUSY   |  (3<<8))858#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))859#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))860#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))861#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))862#define SQLITE_CANTOPEN_DIRTYWAL       (SQLITE_CANTOPEN | (5<<8)) /* Not Used */863#define SQLITE_CANTOPEN_SYMLINK        (SQLITE_CANTOPEN | (6<<8))864#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))865#define SQLITE_CORRUPT_SEQUENCE        (SQLITE_CORRUPT | (2<<8))866#define SQLITE_CORRUPT_INDEX           (SQLITE_CORRUPT | (3<<8))867#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))868#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))869#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))870#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))871#define SQLITE_READONLY_CANTINIT       (SQLITE_READONLY | (5<<8))872#define SQLITE_READONLY_DIRECTORY      (SQLITE_READONLY | (6<<8))873#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))874#define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))875#define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))876#define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))877#define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))878#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))879#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))880#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))881#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))882#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))883#define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))884#define SQLITE_CONSTRAINT_PINNED       (SQLITE_CONSTRAINT |(11<<8))885#define SQLITE_CONSTRAINT_DATATYPE     (SQLITE_CONSTRAINT |(12<<8))886#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))887#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))888#define SQLITE_NOTICE_RBU              (SQLITE_NOTICE | (3<<8))889#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))890#define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))891#define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))892#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8)) /* internal use only */893894/*895** CAPI3REF: Flags For File Open Operations896**897** These bit values are intended for use in the898** 3rd parameter to the [sqlite3_open_v2()] interface and899** in the 4th parameter to the [sqlite3_vfs.xOpen] method.900**901** Only those flags marked as "Ok for sqlite3_open_v2()" may be902** 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 is905** 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 into909** [sqlite3_open_v2()] does *not* cause the underlying database file910** to be opened using O_EXCL.  Passing SQLITE_OPEN_EXCLUSIVE into911** [sqlite3_open_v2()] has historically be a no-op and might become an912** error in future versions of SQLite.913*/914#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */915#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */916#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */917#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */918#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */919#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */920#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */921#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */922#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */923#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */924#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */925#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */926#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */927#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */928#define SQLITE_OPEN_SUPER_JOURNAL    0x00004000  /* VFS only */929#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */930#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */931#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */932#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */933#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */934#define SQLITE_OPEN_NOFOLLOW         0x01000000  /* Ok for sqlite3_open_v2() */935#define SQLITE_OPEN_EXRESCODE        0x02000000  /* Extended result codes */936937/* Reserved:                         0x00F00000 */938/* Legacy compatibility: */939#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */940941942/*943** CAPI3REF: Device Characteristics944**945** The xDeviceCharacteristics method of the [sqlite3_io_methods]946** object returns an integer which is a vector of these947** bit values expressing I/O characteristics of the mass storage948** device that holds the file that the [sqlite3_io_methods]949** refers to.950**951** The SQLITE_IOCAP_ATOMIC property means that all writes of952** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values953** mean that writes of blocks that are nnn bytes in size and954** are aligned to an address which is an integer multiple of955** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means956** that when data is appended to a file, the data is appended957** first then the size of the file is extended, never the other958** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that959** information is written to disk in the same order as calls960** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that961** after reboot following a crash or power loss, the only bytes in a962** file that were written at the application level might have changed963** and that adjacent bytes, even bytes within the same sector are964** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN965** flag indicates that a file cannot be deleted when open.  The966** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on967** read-only media and cannot be changed even by processes with968** elevated privileges.969**970** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying971** filesystem supports doing multiple write operations atomically when those972** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and973** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].974**975** The SQLITE_IOCAP_SUBPAGE_READ property means that it is ok to read976** from the database file in amounts that are not a multiple of the977** page size and that do not begin at a page boundary.  Without this978** property, SQLite is careful to only do full-page reads and write979** on aligned pages, with the one exception that it will do a sub-page980** read of the first page to access the database header.981*/982#define SQLITE_IOCAP_ATOMIC                 0x00000001983#define SQLITE_IOCAP_ATOMIC512              0x00000002984#define SQLITE_IOCAP_ATOMIC1K               0x00000004985#define SQLITE_IOCAP_ATOMIC2K               0x00000008986#define SQLITE_IOCAP_ATOMIC4K               0x00000010987#define SQLITE_IOCAP_ATOMIC8K               0x00000020988#define SQLITE_IOCAP_ATOMIC16K              0x00000040989#define SQLITE_IOCAP_ATOMIC32K              0x00000080990#define SQLITE_IOCAP_ATOMIC64K              0x00000100991#define SQLITE_IOCAP_SAFE_APPEND            0x00000200992#define SQLITE_IOCAP_SEQUENTIAL             0x00000400993#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800994#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000995#define SQLITE_IOCAP_IMMUTABLE              0x00002000996#define SQLITE_IOCAP_BATCH_ATOMIC           0x00004000997#define SQLITE_IOCAP_SUBPAGE_READ           0x00008000998999/*1000** CAPI3REF: File Locking Levels1001**1002** SQLite uses one of these integer values as the second1003** argument to calls it makes to the xLock() and xUnlock() methods1004** of an [sqlite3_io_methods] object.  These values are ordered from1005** lest restrictive to most restrictive.1006**1007** The argument to xLock() is always SHARED or higher.  The argument to1008** xUnlock is either SHARED or NONE.1009*/1010#define SQLITE_LOCK_NONE          0       /* xUnlock() only */1011#define SQLITE_LOCK_SHARED        1       /* xLock() or xUnlock() */1012#define SQLITE_LOCK_RESERVED      2       /* xLock() only */1013#define SQLITE_LOCK_PENDING       3       /* xLock() only */1014#define SQLITE_LOCK_EXCLUSIVE     4       /* xLock() only */10151016/*1017** CAPI3REF: Synchronization Type Flags1018**1019** When SQLite invokes the xSync() method of an1020** [sqlite3_io_methods] object it uses a combination of1021** these integer values as the second argument.1022**1023** When the SQLITE_SYNC_DATAONLY flag is used, it means that the1024** sync operation only needs to flush data to mass storage.  Inode1025** information need not be flushed. If the lower four bits of the flag1026** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.1027** If the lower four bits equal SQLITE_SYNC_FULL, that means1028** to use Mac OS X style fullsync instead of fsync().1029**1030** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags1031** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL1032** settings.  The [synchronous pragma] determines when calls to the1033** xSync VFS method occur and applies uniformly across all platforms.1034** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how1035** energetic or rigorous or forceful the sync operations are and1036** only make a difference on Mac OSX for the default SQLite code.1037** (Third-party VFS implementations might also make the distinction1038** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the1039** operating systems natively supported by SQLite, only Mac OSX1040** cares about the difference.)1041*/1042#define SQLITE_SYNC_NORMAL        0x000021043#define SQLITE_SYNC_FULL          0x000031044#define SQLITE_SYNC_DATAONLY      0x0001010451046/*1047** CAPI3REF: OS Interface Open File Handle1048**1049** An [sqlite3_file] object represents an open file in the1050** [sqlite3_vfs | OS interface layer].  Individual OS interface1051** implementations will1052** want to subclass this object by appending additional fields1053** for their own use.  The pMethods entry is a pointer to an1054** [sqlite3_io_methods] object that defines methods for performing1055** 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};10611062/*1063** CAPI3REF: OS Interface File Virtual Methods Object1064**1065** Every file opened by the [sqlite3_vfs.xOpen] method populates an1066** [sqlite3_file] object (or, more commonly, a subclass of the1067** [sqlite3_file] object) with a pointer to an instance of this object.1068** This object defines the methods used to perform various operations1069** against the open file represented by the [sqlite3_file] object.1070**1071** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element1072** to a non-NULL pointer, then the sqlite3_io_methods.xClose method1073** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The1074** 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 element1076** to NULL.1077**1078** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or1079** [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 file1082** and not its inode needs to be synced.1083**1084** The integer values to xLock() and xUnlock() are one of1085** <ul>1086** <li> [SQLITE_LOCK_NONE],1087** <li> [SQLITE_LOCK_SHARED],1088** <li> [SQLITE_LOCK_RESERVED],1089** <li> [SQLITE_LOCK_PENDING], or1090** <li> [SQLITE_LOCK_EXCLUSIVE].1091** </ul>1092** xLock() upgrades the database file lock.  In other words, xLock() moves the1093** database file lock in the direction NONE toward EXCLUSIVE. The argument to1094** xLock() is always one of SHARED, RESERVED, PENDING, or EXCLUSIVE, never1095** SQLITE_LOCK_NONE.  If the database file lock is already at or above the1096** 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 call1099** 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 output1103** pointer parameter, true if such a lock exists and false otherwise.1104**1105** The xFileControl() method is a generic interface that allows custom1106** VFS implementations to directly control an open file using the1107** [sqlite3_file_control()] interface.  The second "op" argument is an1108** integer opcode.  The third argument is a generic pointer intended to1109** point to a structure that may contain arguments or space in which to1110** write return values.  Potential uses for xFileControl() might be1111** functions to enable blocking locks with timeouts, to change the1112** locking strategy (for example to use dot-file locks), to inquire1113** about the status of a lock, or to break stale locks.  The SQLite1114** 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 opcodes1117** greater than 100 to avoid conflicts.  VFS implementations should1118** return [SQLITE_NOTFOUND] for file control opcodes that they do not1119** recognize.1120**1121** The xSectorSize() method returns the sector size of the1122** device that underlies the file.  The sector size is the1123** minimum write that can be performed without disturbing1124** other bytes in the file.  The xDeviceCharacteristics()1125** method returns a bit vector describing behaviors of the1126** 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 of1148** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values1149** mean that writes of blocks that are nnn bytes in size and1150** are aligned to an address which is an integer multiple of1151** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means1152** that when data is appended to a file, the data is appended1153** first then the size of the file is extended, never the other1154** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that1155** information is written to disk in the same order as calls1156** to xWrite().1157**1158** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill1159** in the unread portions of the buffer with zeros.  A VFS that1160** fails to zero-fill short reads might seem to work.  However,1161** failure to zero-fill short reads will eventually lead to1162** 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};11901191/*1192** CAPI3REF: Standard File Control Opcodes1193** KEYWORDS: {file control opcodes} {file control opcode}1194**1195** These integer constants are opcodes for the xFileControl method1196** 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.  This1202** opcode causes the xFileControl method to write the current state of1203** 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 VFS1210** layer a hint of how large the database file will grow to be during the1211** current transaction.  This hint is not guaranteed to be accurate but it1212** is often close.  The underlying VFS might choose to preallocate database1213** file space based on this hint in order to help writes to the database1214** file run faster.1215**1216** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]1217** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that1218** implements [sqlite3_deserialize()] to set an upper bound on the size1219** 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 the1221** current limit.  Otherwise the limit is set to the larger of the value1222** of the integer pointed to and the current database size.  The integer1223** 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 VFS1227** extends and truncates the database file in chunks of a size specified1228** by the user. The fourth argument to [sqlite3_file_control()] should1229** point to an integer (type int) containing the new chunk-size to use1230** for the nominated database. Allocating database file space in large1231** chunks (say 1MB at a time), may reduce file-system fragmentation and1232** improve performance on some systems.1233**1234** <li>[[SQLITE_FCNTL_FILE_POINTER]]1235** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer1236** to the [sqlite3_file] object associated with a particular database1237** 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 pointer1241** to the [sqlite3_file] object associated with the journal file (either1242** the [rollback journal] or the [write-ahead log]) for a particular database1243** 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 and1250** sent to the VFS immediately before the xSync method is invoked on a1251** database file descriptor. Or, if the xSync method is not invoked1252** because the user has configured SQLite with1253** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place1254** of the xSync method. In most cases, the pointer argument passed with1255** this file-control is NULL. However, if the database file is being synced1256** as part of a multi-database commit, the argument points to a nul-terminated1257** string containing the transactions super-journal file name. VFSes that1258** do not need this signal should silently ignore this opcode. Applications1259** should not call [sqlite3_file_control()] with this opcode as doing so may1260** 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 SQLite1264** and sent to the VFS after a transaction has been committed immediately1265** but before the database is unlocked. VFSes that do not need this signal1266** should silently ignore this opcode. Applications should not call1267** [sqlite3_file_control()] with this opcode as doing so may disrupt the1268** 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 automatic1272** retry counts and intervals for certain disk I/O operations for the1273** windows [VFS] in order to provide robustness in the presence of1274** 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 delay1276** of 25 milliseconds before the first retry and with the delay increasing1277** by an additional 25 milliseconds with each subsequent retry.  This1278** opcode allows these two values (10 retries and 25 milliseconds of delay)1279** to be adjusted.  The values are changed for all database connections1280** within the same process.  The argument is a pointer to an array of two1281** integers where the first integer is the new retry count and the second1282** integer is the delay.  If either integer is negative, then the setting1283** is not changed but instead the prior value of that setting is written1284** into the array entry, allowing the current retry settings to be1285** 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 the1289** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary1290** write ahead log ([WAL file]) and shared memory1291** files used for transaction control1292** are automatically deleted when the latest connection to the database1293** closes.  Setting persistent WAL mode causes those files to persist after1294** close.  Persisting the files is useful when other processes that do not1295** have write permission on the directory containing the database file want1296** to read the database file, as the WAL and shared memory files must exist1297** in order for the database to be readable.  The fourth parameter to1298** [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 persistent1300** WAL mode.  If the integer is -1, then it is overwritten with the current1301** WAL persistence setting.1302**1303** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]1304** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the1305** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting1306** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the1307** xDeviceCharacteristics methods. The fourth parameter to1308** [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-damage1310** mode.  If the integer is -1, then it is overwritten with the current1311** zero-damage mode setting.1312**1313** <li>[[SQLITE_FCNTL_OVERWRITE]]1314** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening1315** a write transaction to indicate that, unless it is rolled back for some1316** reason, the entire database file will be overwritten by the current1317** 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 of1321** all [VFSes] in the VFS stack.  The names are of all VFS shims and the1322** final bottom-level VFS are written into memory obtained from1323** [sqlite3_malloc()] and the result is stored in the char* variable1324** that the fourth parameter of [sqlite3_file_control()] points to.1325** The caller is responsible for freeing the memory when done.  As with1326** all file-control actions, there is no guarantee that this will actually1327** do anything.  Callers should initialize the char* variable to a NULL1328** pointer in case this file-control is not implemented.  This file-control1329** 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-level1333** [VFSes] currently in use.  ^(The argument X in1334** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be1335** of type "[sqlite3_vfs] **".  This opcodes will set *X1336** to a pointer to the top-level VFS.)^1337** ^When there are multiple VFS shims in the stack, this opcode finds the1338** 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 corresponding1343** to the database file to which the pragma statement refers. ^The argument1344** to the [SQLITE_FCNTL_PRAGMA] file control is an array of1345** pointers to strings (char**) in which the second element of the array1346** is the name of the pragma and the third element is the argument to the1347** pragma or NULL if the pragma has no argument.  ^The handler for an1348** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element1349** 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 or1351** the error message if the pragma fails. ^If the1352** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal1353** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]1354** file control returns [SQLITE_OK], then the parser assumes that the1355** VFS has handled the PRAGMA itself and the parser generates a no-op1356** prepared statement if result string is NULL, or that returns a copy1357** of the result string if the string is non-NULL.1358** ^If the [SQLITE_FCNTL_PRAGMA] file control returns1359** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means1360** that the VFS encountered an error while handling the [PRAGMA] and the1361** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]1362** file control occurs at the beginning of pragma statement analysis and so1363** 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 handle1368** shortly after it is opened in order to provide a custom VFS with access1369** to the connection's busy-handler callback. The argument is of type (void**)1370** - an array of two (void *) values. The first (void *) actually points1371** to a function of type (int (*)(void *)). In order to invoke the connection's1372** busy-handler, this function should be invoked with the second (void *) in1373** the array as the only argument. If it returns non-zero, then the operation1374** should be retried. If it returns zero, the custom VFS should abandon the1375** current operation.1376**1377** <li>[[SQLITE_FCNTL_TEMPFILENAME]]1378** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control1379** to have SQLite generate a1380** temporary filename using the same algorithm that is followed to generate1381** temporary filenames for TEMP tables and other internal uses.  The1382** argument should be a char** which will be filled with the filename1383** written into memory obtained from [sqlite3_malloc()].  The caller should1384** 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 the1388** 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 that1390** is an advisory maximum number of bytes in the file to memory map.  The1391** pointer is overwritten with the old value.  The limit is not changed if1392** the value originally pointed to is negative, and so the current limit1393** can be queried by passing in a pointer to a negative number.  This1394** 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 information1398** 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 the1401** SQLite stack may generate instances of this file control if1402** 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 a1406** pointer to an integer and it writes a boolean into that integer depending1407** on whether or not the file has been renamed, moved, or deleted since it1408** was first opened.1409**1410** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]1411** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the1412** underlying native file handle associated with a file handle.  This file1413** control interprets its argument as a pointer to a native file handle and1414** 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.  This1418** opcode causes the xFileControl method to swap the file handle with the one1419** pointed to by the pArg argument.  This capability is used during testing1420** 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 descriptor1424** or file handle for the [sqlite3_file] object such that it will no longer1425** 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 might1429** be advantageous to block on the next WAL lock if the lock is not immediately1430** available.  The WAL subsystem issues this signal during rare1431** 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 other1436** 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 by1440** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for1441** this opcode.1442**1443** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]1444** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then1445** the file descriptor is placed in "batch write mode", which1446** means all subsequent write operations will be deferred and done1447** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].  Systems1448** that do not support batch atomic writes will return SQLITE_NOTFOUND.1449** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to1450** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or1451** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make1452** no VFS interface calls on the same [sqlite3_file] file descriptor1453** except for calls to the xWrite method and the xFileControl method1454** with [SQLITE_FCNTL_SIZE_HINT].1455**1456** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]1457** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write1458** operations since the previous successful call to1459** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.1460** This file control returns [SQLITE_OK] if and only if the writes were1461** all performed successfully and have been committed to persistent storage.1462** ^Regardless of whether or not it is successful, this file control takes1463** the file descriptor out of batch write mode so that all subsequent1464** write operations are independent.1465** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without1466** 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 write1470** operations since the previous successful call to1471** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.1472** ^This file control takes the file descriptor out of batch write mode1473** so that all subsequent write operations are independent.1474** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without1475** 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 VFS1479** to block for up to M milliseconds before failing when attempting to1480** 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 contains1482** the value that M is to be set to. Before returning, the 32-bit signed1483** integer is overwritten with the previous value of M.1484**1485** <li>[[SQLITE_FCNTL_DATA_VERSION]]1486** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to1487** a database file.  The argument is a pointer to a 32-bit unsigned integer.1488** The "data version" for the pager is written into the pointer.  The1489** "data version" changes whenever any change occurs to the corresponding1490** database file, either through SQL statements on the same database1491** connection or through transactions committed by separate database1492** connections possibly in other processes. The [sqlite3_total_changes()]1493** interface can be used to find if any database on the connection has changed,1494** but that interface responds to changes on TEMP as well as MAIN and does1495** not provide a mechanism to detect changes to MAIN only.  Also, the1496** [sqlite3_total_changes()] interface responds to internal changes only and1497** omits changes made by other database connections.  The1498** [PRAGMA data_version] command provides a mechanism to detect changes to1499** a single attached database that occur due to other database connections,1500** but omits changes implemented by the database connection on which it is1501** called.  This file control is the only mechanism to detect changes that1502** happen either internally or externally and that are associated with1503** a particular attached database.1504**1505** <li>[[SQLITE_FCNTL_CKPT_START]]1506** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint1507** in wal mode before the client starts to copy pages from the wal1508** file to the database file.1509**1510** <li>[[SQLITE_FCNTL_CKPT_DONE]]1511** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint1512** in wal mode after the client has finished copying pages from the wal1513** file to the database file, but before the *-shm file is updated to1514** record the fact that the pages have been checkpointed.1515**1516** <li>[[SQLITE_FCNTL_EXTERNAL_READER]]1517** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect1518** whether or not there is a database client in another process with a wal-mode1519** transaction open on the database or not. It is only available on unix.The1520** (void*) argument passed with this file-control should be a pointer to a1521** value of type (int). The integer value is set to 1 if the database is a wal1522** mode database and there exists at least one client in another process that1523** currently has an SQL transaction open on the database. It is set to 0 if1524** the database is not a wal-mode db, or if there is no such connection in any1525** other process. This opcode cannot be used to detect transactions opened1526** by clients within the current process, only within other processes.1527**1528** <li>[[SQLITE_FCNTL_CKSM_FILE]]1529** The [SQLITE_FCNTL_CKSM_FILE] opcode is for use internally by the1530** [checksum VFS shim] only.1531**1532** <li>[[SQLITE_FCNTL_RESET_CACHE]]1533** If there is currently no transaction open on the database, and the1534** database is not a temp db, then the [SQLITE_FCNTL_RESET_CACHE] file-control1535** purges the contents of the in-memory page cache. If there is an open1536** transaction, or if the db is a temp-db, this opcode is a no-op, not an error.1537** </ul>1538*/1539#define SQLITE_FCNTL_LOCKSTATE               11540#define SQLITE_FCNTL_GET_LOCKPROXYFILE       21541#define SQLITE_FCNTL_SET_LOCKPROXYFILE       31542#define SQLITE_FCNTL_LAST_ERRNO              41543#define SQLITE_FCNTL_SIZE_HINT               51544#define SQLITE_FCNTL_CHUNK_SIZE              61545#define SQLITE_FCNTL_FILE_POINTER            71546#define SQLITE_FCNTL_SYNC_OMITTED            81547#define SQLITE_FCNTL_WIN32_AV_RETRY          91548#define SQLITE_FCNTL_PERSIST_WAL            101549#define SQLITE_FCNTL_OVERWRITE              111550#define SQLITE_FCNTL_VFSNAME                121551#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    131552#define SQLITE_FCNTL_PRAGMA                 141553#define SQLITE_FCNTL_BUSYHANDLER            151554#define SQLITE_FCNTL_TEMPFILENAME           161555#define SQLITE_FCNTL_MMAP_SIZE              181556#define SQLITE_FCNTL_TRACE                  191557#define SQLITE_FCNTL_HAS_MOVED              201558#define SQLITE_FCNTL_SYNC                   211559#define SQLITE_FCNTL_COMMIT_PHASETWO        221560#define SQLITE_FCNTL_WIN32_SET_HANDLE       231561#define SQLITE_FCNTL_WAL_BLOCK              241562#define SQLITE_FCNTL_ZIPVFS                 251563#define SQLITE_FCNTL_RBU                    261564#define SQLITE_FCNTL_VFS_POINTER            271565#define SQLITE_FCNTL_JOURNAL_POINTER        281566#define SQLITE_FCNTL_WIN32_GET_HANDLE       291567#define SQLITE_FCNTL_PDB                    301568#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE     311569#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE    321570#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE  331571#define SQLITE_FCNTL_LOCK_TIMEOUT           341572#define SQLITE_FCNTL_DATA_VERSION           351573#define SQLITE_FCNTL_SIZE_LIMIT             361574#define SQLITE_FCNTL_CKPT_DONE              371575#define SQLITE_FCNTL_RESERVE_BYTES          381576#define SQLITE_FCNTL_CKPT_START             391577#define SQLITE_FCNTL_EXTERNAL_READER        401578#define SQLITE_FCNTL_CKSM_FILE              411579#define SQLITE_FCNTL_RESET_CACHE            421580#define SQLITE_FCNTL_NULL_IO                4315811582/* deprecated names */1583#define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE1584#define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE1585#define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO158615871588/*1589** CAPI3REF: Mutex Handle1590**1591** The mutex module within SQLite defines [sqlite3_mutex] to be an1592** abstract type for a mutex object.  The SQLite core never looks1593** at the internal representation of an [sqlite3_mutex].  It only1594** deals with pointers to the [sqlite3_mutex] object.1595**1596** Mutexes are created using [sqlite3_mutex_alloc()].1597*/1598typedef struct sqlite3_mutex sqlite3_mutex;15991600/*1601** CAPI3REF: Loadable Extension Thunk1602**1603** A pointer to the opaque sqlite3_api_routines structure is passed as1604** the third parameter to entry points of [loadable extensions].  This1605** structure must be typedefed in order to work around compiler warnings1606** on some platforms.1607*/1608typedef struct sqlite3_api_routines sqlite3_api_routines;16091610/*1611** CAPI3REF: File Name1612**1613** Type [sqlite3_filename] is used by SQLite to pass filenames to the1614** xOpen method of a [VFS]. It may be cast to (const char*) and treated1615** as a normal, nul-terminated, UTF-8 buffer containing the filename, but1616** may also be passed to special APIs such as:1617**1618** <ul>1619** <li>  sqlite3_filename_database()1620** <li>  sqlite3_filename_journal()1621** <li>  sqlite3_filename_wal()1622** <li>  sqlite3_uri_parameter()1623** <li>  sqlite3_uri_boolean()1624** <li>  sqlite3_uri_int64()1625** <li>  sqlite3_uri_key()1626** </ul>1627*/1628typedef const char *sqlite3_filename;16291630/*1631** CAPI3REF: OS Interface Object1632**1633** An instance of the sqlite3_vfs object defines the interface between1634** the SQLite core and the underlying operating system.  The "vfs"1635** in the name of the object stands for "virtual file system".  See1636** the [VFS | VFS documentation] for further information.1637**1638** The VFS interface is sometimes extended by adding new methods onto1639** the end.  Each time such an extension occurs, the iVersion field1640** is incremented.  The iVersion value started out as 1 in1641** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 21642** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased1643** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6].  Additional fields1644** may be appended to the sqlite3_vfs object and the iVersion value1645** may increase again in future versions of SQLite.1646** Note that due to an oversight, the structure1647** of the sqlite3_vfs object changed in the transition from1648** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]1649** and yet the iVersion field was not increased.1650**1651** The szOsFile field is the size of the subclassed [sqlite3_file]1652** structure used by this VFS.  mxPathname is the maximum length of1653** a pathname in this VFS.1654**1655** Registered sqlite3_vfs objects are kept on a linked list formed by1656** the pNext pointer.  The [sqlite3_vfs_register()]1657** and [sqlite3_vfs_unregister()] interfaces manage this list1658** in a thread-safe way.  The [sqlite3_vfs_find()] interface1659** searches the list.  Neither the application code nor the VFS1660** implementation should use the pNext pointer.1661**1662** The pNext field is the only field in the sqlite3_vfs1663** structure that SQLite will ever modify.  SQLite will only access1664** or modify this field while holding a particular static mutex.1665** The application should never modify anything within the sqlite3_vfs1666** object once the object has been registered.1667**1668** The zName field holds the name of the VFS module.  The name must1669** be unique across all VFS modules.1670**1671** [[sqlite3_vfs.xOpen]]1672** ^SQLite guarantees that the zFilename parameter to xOpen1673** is either a NULL pointer or string obtained1674** from xFullPathname() with an optional suffix added.1675** ^If a suffix is added to the zFilename parameter, it will1676** consist of a single "-" character followed by no more than1677** 11 alphanumeric and/or "-" characters.1678** ^SQLite further guarantees that1679** the string will be valid and unchanged until xClose() is1680** called. Because of the previous sentence,1681** the [sqlite3_file] can safely store a pointer to the1682** filename if it needs to remember the filename for some reason.1683** If the zFilename parameter to xOpen is a NULL pointer then xOpen1684** must invent its own temporary name for the file.  ^Whenever the1685** xFilename parameter is NULL it will also be the case that the1686** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].1687**1688** The flags argument to xOpen() includes all bits set in1689** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]1690** or [sqlite3_open16()] is used, then flags includes at least1691** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].1692** If xOpen() opens a file read-only then it sets *pOutFlags to1693** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.1694**1695** ^(SQLite will also add one of the following flags to the xOpen()1696** call, depending on the object being opened:1697**1698** <ul>1699** <li>  [SQLITE_OPEN_MAIN_DB]1700** <li>  [SQLITE_OPEN_MAIN_JOURNAL]1701** <li>  [SQLITE_OPEN_TEMP_DB]1702** <li>  [SQLITE_OPEN_TEMP_JOURNAL]1703** <li>  [SQLITE_OPEN_TRANSIENT_DB]1704** <li>  [SQLITE_OPEN_SUBJOURNAL]1705** <li>  [SQLITE_OPEN_SUPER_JOURNAL]1706** <li>  [SQLITE_OPEN_WAL]1707** </ul>)^1708**1709** The file I/O implementation can use the object type flags to1710** change the way it deals with files.  For example, an application1711** that does not care about crash recovery or rollback might make1712** the open of a journal file a no-op.  Writes to this journal would1713** also be no-ops, and any attempt to read the journal would return1714** SQLITE_IOERR.  Or the implementation might recognize that a database1715** file will be doing page-aligned sector reads and writes in a random1716** order and set up its I/O subsystem accordingly.1717**1718** SQLite might also add one of the following flags to the xOpen method:1719**1720** <ul>1721** <li> [SQLITE_OPEN_DELETEONCLOSE]1722** <li> [SQLITE_OPEN_EXCLUSIVE]1723** </ul>1724**1725** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be1726** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]1727** will be set for TEMP databases and their journals, transient1728** databases, and subjournals.1729**1730** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction1731** with the [SQLITE_OPEN_CREATE] flag, which are both directly1732** analogous to the O_EXCL and O_CREAT flags of the POSIX open()1733** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the1734** SQLITE_OPEN_CREATE, is used to indicate that file should always1735** be created, and that it is an error if it already exists.1736** It is <i>not</i> used to indicate the file should be opened1737** for exclusive access.1738**1739** ^At least szOsFile bytes of memory are allocated by SQLite1740** to hold the [sqlite3_file] structure passed as the third1741** argument to xOpen.  The xOpen method does not have to1742** allocate the structure; it should just fill it in.  Note that1743** the xOpen method must set the sqlite3_file.pMethods to either1744** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do1745** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods1746** element will be valid after xOpen returns regardless of the success1747** or failure of the xOpen call.1748**1749** [[sqlite3_vfs.xAccess]]1750** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]1751** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to1752** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]1753** to test whether a file is at least readable.  The SQLITE_ACCESS_READ1754** flag is never actually used and is not implemented in the built-in1755** VFSes of SQLite.  The file is named by the second argument and can be a1756** directory. The xAccess method returns [SQLITE_OK] on success or some1757** non-zero error code if there is an I/O error or if the name of1758** the file given in the second argument is illegal.  If SQLITE_OK1759** is returned, then non-zero or zero is written into *pResOut to indicate1760** whether or not the file is accessible.1761**1762** ^SQLite will always allocate at least mxPathname+1 bytes for the1763** output buffer xFullPathname.  The exact size of the output buffer1764** is also passed as a parameter to both  methods. If the output buffer1765** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is1766** handled as a fatal error by SQLite, vfs implementations should endeavor1767** to prevent this by setting mxPathname to a sufficiently large value.1768**1769** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()1770** interfaces are not strictly a part of the filesystem, but they are1771** included in the VFS structure for completeness.1772** The xRandomness() function attempts to return nBytes bytes1773** of good-quality randomness into zOut.  The return value is1774** the actual number of bytes of randomness obtained.1775** The xSleep() method causes the calling thread to sleep for at1776** least the number of microseconds given.  ^The xCurrentTime()1777** method returns a Julian Day Number for the current date and time as1778** a floating point value.1779** ^The xCurrentTimeInt64() method returns, as an integer, the Julian1780** Day Number multiplied by 86400000 (the number of milliseconds in1781** a 24-hour day).1782** ^SQLite will use the xCurrentTimeInt64() method to get the current1783** date and time if that method is available (if iVersion is 2 or1784** greater and the function pointer is not NULL) and will fall back1785** to xCurrentTime() if xCurrentTimeInt64() is unavailable.1786**1787** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces1788** are not used by the SQLite core.  These optional interfaces are provided1789** by some VFSes to facilitate testing of the VFS code. By overriding1790** system calls with functions under its control, a test program can1791** simulate faults and error conditions that would otherwise be difficult1792** or impossible to induce.  The set of system calls that can be overridden1793** varies from one VFS to another, and from one version of the same VFS to the1794** next.  Applications that use these interfaces must be prepared for any1795** or all of these interfaces to be NULL or for their behavior to change1796** from one release to the next.  Applications must not attempt to access1797** any of these methods if the iVersion of the VFS is less than 3.1798*/1799typedef struct sqlite3_vfs sqlite3_vfs;1800typedef void (*sqlite3_syscall_ptr)(void);1801struct sqlite3_vfs {1802  int iVersion;            /* Structure version number (currently 3) */1803  int szOsFile;            /* Size of subclassed sqlite3_file */1804  int mxPathname;          /* Maximum file pathname length */1805  sqlite3_vfs *pNext;      /* Next registered VFS */1806  const char *zName;       /* Name of this virtual file system */1807  void *pAppData;          /* Pointer to application-specific data */1808  int (*xOpen)(sqlite3_vfs*, sqlite3_filename zName, sqlite3_file*,1809               int flags, int *pOutFlags);1810  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);1811  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);1812  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);1813  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);1814  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);1815  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);1816  void (*xDlClose)(sqlite3_vfs*, void*);1817  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);1818  int (*xSleep)(sqlite3_vfs*, int microseconds);1819  int (*xCurrentTime)(sqlite3_vfs*, double*);1820  int (*xGetLastError)(sqlite3_vfs*, int, char *);1821  /*1822  ** The methods above are in version 1 of the sqlite_vfs object1823  ** definition.  Those that follow are added in version 2 or later1824  */1825  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);1826  /*1827  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.1828  ** Those below are for version 3 and greater.1829  */1830  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);1831  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);1832  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);1833  /*1834  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.1835  ** New fields may be appended in future versions.  The iVersion1836  ** value will increment whenever this happens.1837  */1838};18391840/*1841** CAPI3REF: Flags for the xAccess VFS method1842**1843** These integer constants can be used as the third parameter to1844** the xAccess method of an [sqlite3_vfs] object.  They determine1845** what kind of permissions the xAccess method is looking for.1846** With SQLITE_ACCESS_EXISTS, the xAccess method1847** simply checks whether the file exists.1848** With SQLITE_ACCESS_READWRITE, the xAccess method1849** checks whether the named directory is both readable and writable1850** (in other words, if files can be added, removed, and renamed within1851** the directory).1852** The SQLITE_ACCESS_READWRITE constant is currently used only by the1853** [temp_store_directory pragma], though this could change in a future1854** release of SQLite.1855** With SQLITE_ACCESS_READ, the xAccess method1856** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is1857** currently unused, though it might be used in a future release of1858** SQLite.1859*/1860#define SQLITE_ACCESS_EXISTS    01861#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */1862#define SQLITE_ACCESS_READ      2   /* Unused */18631864/*1865** CAPI3REF: Flags for the xShmLock VFS method1866**1867** These integer constants define the various locking operations1868** allowed by the xShmLock method of [sqlite3_io_methods].  The1869** following are the only legal combinations of flags to the1870** xShmLock method:1871**1872** <ul>1873** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED1874** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE1875** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED1876** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE1877** </ul>1878**1879** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as1880** was given on the corresponding lock.1881**1882** The xShmLock method can transition between unlocked and SHARED or1883** between unlocked and EXCLUSIVE.  It cannot transition between SHARED1884** and EXCLUSIVE.1885*/1886#define SQLITE_SHM_UNLOCK       11887#define SQLITE_SHM_LOCK         21888#define SQLITE_SHM_SHARED       41889#define SQLITE_SHM_EXCLUSIVE    818901891/*1892** CAPI3REF: Maximum xShmLock index1893**1894** The xShmLock method on [sqlite3_io_methods] may use values1895** between 0 and this upper bound as its "offset" argument.1896** The SQLite core will never attempt to acquire or release a1897** lock outside of this range1898*/1899#define SQLITE_SHM_NLOCK        8190019011902/*1903** CAPI3REF: Initialize The SQLite Library1904**1905** ^The sqlite3_initialize() routine initializes the1906** SQLite library.  ^The sqlite3_shutdown() routine1907** deallocates any resources that were allocated by sqlite3_initialize().1908** These routines are designed to aid in process initialization and1909** shutdown on embedded systems.  Workstation applications using1910** SQLite normally do not need to invoke either of these routines.1911**1912** A call to sqlite3_initialize() is an "effective" call if it is1913** the first time sqlite3_initialize() is invoked during the lifetime of1914** the process, or if it is the first time sqlite3_initialize() is invoked1915** following a call to sqlite3_shutdown().  ^(Only an effective call1916** of sqlite3_initialize() does any initialization.  All other calls1917** are harmless no-ops.)^1918**1919** A call to sqlite3_shutdown() is an "effective" call if it is the first1920** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only1921** an effective call to sqlite3_shutdown() does any deinitialization.1922** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^1923**1924** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()1925** is not.  The sqlite3_shutdown() interface must only be called from a1926** single thread.  All open [database connections] must be closed and all1927** other SQLite resources must be deallocated prior to invoking1928** sqlite3_shutdown().1929**1930** Among other things, ^sqlite3_initialize() will invoke1931** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()1932** will invoke sqlite3_os_end().1933**1934** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.1935** ^If for some reason, sqlite3_initialize() is unable to initialize1936** the library (perhaps it is unable to allocate a needed resource such1937** as a mutex) it returns an [error code] other than [SQLITE_OK].1938**1939** ^The sqlite3_initialize() routine is called internally by many other1940** SQLite interfaces so that an application usually does not need to1941** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]1942** calls sqlite3_initialize() so the SQLite library will be automatically1943** initialized when [sqlite3_open()] is called if it has not be initialized1944** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]1945** compile-time option, then the automatic calls to sqlite3_initialize()1946** are omitted and the application must call sqlite3_initialize() directly1947** prior to using any other SQLite interface.  For maximum portability,1948** it is recommended that applications always invoke sqlite3_initialize()1949** directly prior to using any other SQLite interface.  Future releases1950** of SQLite may require this.  In other words, the behavior exhibited1951** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the1952** default behavior in some future release of SQLite.1953**1954** The sqlite3_os_init() routine does operating-system specific1955** initialization of the SQLite library.  The sqlite3_os_end()1956** routine undoes the effect of sqlite3_os_init().  Typical tasks1957** performed by these routines include allocation or deallocation1958** of static resources, initialization of global variables,1959** setting up a default [sqlite3_vfs] module, or setting up1960** a default configuration using [sqlite3_config()].1961**1962** The application should never invoke either sqlite3_os_init()1963** or sqlite3_os_end() directly.  The application should only invoke1964** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()1965** interface is called automatically by sqlite3_initialize() and1966** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate1967** implementations for sqlite3_os_init() and sqlite3_os_end()1968** are built into SQLite when it is compiled for Unix, Windows, or OS/2.1969** When [custom builds | built for other platforms]1970** (using the [SQLITE_OS_OTHER=1] compile-time1971** option) the application must supply a suitable implementation for1972** sqlite3_os_init() and sqlite3_os_end().  An application-supplied1973** implementation of sqlite3_os_init() or sqlite3_os_end()1974** must return [SQLITE_OK] on success and some other [error code] upon1975** failure.1976*/1977SQLITE_API int sqlite3_initialize(void);1978SQLITE_API int sqlite3_shutdown(void);1979SQLITE_API int sqlite3_os_init(void);1980SQLITE_API int sqlite3_os_end(void);19811982/*1983** CAPI3REF: Configuring The SQLite Library1984**1985** The sqlite3_config() interface is used to make global configuration1986** changes to SQLite in order to tune SQLite to the specific needs of1987** the application.  The default configuration is recommended for most1988** applications and so this routine is usually not necessary.  It is1989** provided to support rare applications with unusual needs.1990**1991** <b>The sqlite3_config() interface is not threadsafe. The application1992** must ensure that no other SQLite interfaces are invoked by other1993** threads while sqlite3_config() is running.</b>1994**1995** The first argument to sqlite3_config() is an integer1996** [configuration option] that determines1997** what property of SQLite is to be configured.  Subsequent arguments1998** vary depending on the [configuration option]1999** in the first argument.2000**2001** For most configuration options, the sqlite3_config() interface2002** may only be invoked prior to library initialization using2003** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].2004** The exceptional configuration options that may be invoked at any time2005** are called "anytime configuration options".2006** ^If sqlite3_config() is called after [sqlite3_initialize()] and before2007** [sqlite3_shutdown()] with a first argument that is not an anytime2008** configuration option, then the sqlite3_config() call will return SQLITE_MISUSE.2009** Note, however, that ^sqlite3_config() can be called as part of the2010** implementation of an application-defined [sqlite3_os_init()].2011**2012** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].2013** ^If the option is unknown or SQLite is unable to set the option2014** then this routine returns a non-zero [error code].2015*/2016SQLITE_API int sqlite3_config(int, ...);20172018/*2019** CAPI3REF: Configure database connections2020** METHOD: sqlite32021**2022** The sqlite3_db_config() interface is used to make configuration2023** changes to a [database connection].  The interface is similar to2024** [sqlite3_config()] except that the changes apply to a single2025** [database connection] (specified in the first argument).2026**2027** The second argument to sqlite3_db_config(D,V,...)  is the2028** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code2029** that indicates what aspect of the [database connection] is being configured.2030** Subsequent arguments vary depending on the configuration verb.2031**2032** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if2033** the call is considered successful.2034*/2035SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);20362037/*2038** CAPI3REF: Memory Allocation Routines2039**2040** An instance of this object defines the interface between SQLite2041** and low-level memory allocation routines.2042**2043** This object is used in only one place in the SQLite interface.2044** A pointer to an instance of this object is the argument to2045** [sqlite3_config()] when the configuration option is2046** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].2047** By creating an instance of this object2048** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])2049** during configuration, an application can specify an alternative2050** memory allocation subsystem for SQLite to use for all of its2051** dynamic memory needs.2052**2053** Note that SQLite comes with several [built-in memory allocators]2054** that are perfectly adequate for the overwhelming majority of applications2055** and that this object is only useful to a tiny minority of applications2056** with specialized memory allocation requirements.  This object is2057** also used during testing of SQLite in order to specify an alternative2058** memory allocator that simulates memory out-of-memory conditions in2059** order to verify that SQLite recovers gracefully from such2060** conditions.2061**2062** The xMalloc, xRealloc, and xFree methods must work like the2063** malloc(), realloc() and free() functions from the standard C library.2064** ^SQLite guarantees that the second argument to2065** xRealloc is always a value returned by a prior call to xRoundup.2066**2067** xSize should return the allocated size of a memory allocation2068** previously obtained from xMalloc or xRealloc.  The allocated size2069** is always at least as big as the requested size but may be larger.2070**2071** The xRoundup method returns what would be the allocated size of2072** a memory allocation given a particular requested size.  Most memory2073** allocators round up memory allocations at least to the next multiple2074** of 8.  Some allocators round up to a larger multiple or to a power of 2.2075** Every memory allocation request coming in through [sqlite3_malloc()]2076** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,2077** that causes the corresponding memory allocation to fail.2078**2079** The xInit method initializes the memory allocator.  For example,2080** it might allocate any required mutexes or initialize internal data2081** structures.  The xShutdown method is invoked (indirectly) by2082** [sqlite3_shutdown()] and should deallocate any resources acquired2083** by xInit.  The pAppData pointer is used as the only parameter to2084** xInit and xShutdown.2085**2086** SQLite holds the [SQLITE_MUTEX_STATIC_MAIN] mutex when it invokes2087** the xInit method, so the xInit method need not be threadsafe.  The2088** xShutdown method is only called from [sqlite3_shutdown()] so it does2089** not need to be threadsafe either.  For all other methods, SQLite2090** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the2091** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which2092** it is by default) and so the methods are automatically serialized.2093** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other2094** methods must be threadsafe or else make their own arrangements for2095** serialization.2096**2097** SQLite will never invoke xInit() more than once without an intervening2098** call to xShutdown().2099*/2100typedef struct sqlite3_mem_methods sqlite3_mem_methods;2101struct sqlite3_mem_methods {2102  void *(*xMalloc)(int);         /* Memory allocation function */2103  void (*xFree)(void*);          /* Free a prior allocation */2104  void *(*xRealloc)(void*,int);  /* Resize an allocation */2105  int (*xSize)(void*);           /* Return the size of an allocation */2106  int (*xRoundup)(int);          /* Round up request size to allocation size */2107  int (*xInit)(void*);           /* Initialize the memory allocator */2108  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */2109  void *pAppData;                /* Argument to xInit() and xShutdown() */2110};21112112/*2113** CAPI3REF: Configuration Options2114** KEYWORDS: {configuration option}2115**2116** These constants are the available integer configuration options that2117** can be passed as the first argument to the [sqlite3_config()] interface.2118**2119** Most of the configuration options for sqlite3_config()2120** will only work if invoked prior to [sqlite3_initialize()] or after2121** [sqlite3_shutdown()].  The few exceptions to this rule are called2122** "anytime configuration options".2123** ^Calling [sqlite3_config()] with a first argument that is not an2124** anytime configuration option in between calls to [sqlite3_initialize()] and2125** [sqlite3_shutdown()] is a no-op that returns SQLITE_MISUSE.2126**2127** The set of anytime configuration options can change (by insertions2128** and/or deletions) from one release of SQLite to the next.2129** As of SQLite version 3.42.0, the complete set of anytime configuration2130** options is:2131** <ul>2132** <li> SQLITE_CONFIG_LOG2133** <li> SQLITE_CONFIG_PCACHE_HDRSZ2134** </ul>2135**2136** New configuration options may be added in future releases of SQLite.2137** Existing configuration options might be discontinued.  Applications2138** should check the return code from [sqlite3_config()] to make sure that2139** the call worked.  The [sqlite3_config()] interface will return a2140** non-zero [error code] if a discontinued or unsupported configuration option2141** is invoked.2142**2143** <dl>2144** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>2145** <dd>There are no arguments to this option.  ^This option sets the2146** [threading mode] to Single-thread.  In other words, it disables2147** all mutexing and puts SQLite into a mode where it can only be used2148** by a single thread.   ^If SQLite is compiled with2149** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then2150** it is not possible to change the [threading mode] from its default2151** value of Single-thread and so [sqlite3_config()] will return2152** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD2153** configuration option.</dd>2154**2155** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>2156** <dd>There are no arguments to this option.  ^This option sets the2157** [threading mode] to Multi-thread.  In other words, it disables2158** mutexing on [database connection] and [prepared statement] objects.2159** The application is responsible for serializing access to2160** [database connections] and [prepared statements].  But other mutexes2161** are enabled so that SQLite will be safe to use in a multi-threaded2162** environment as long as no two threads attempt to use the same2163** [database connection] at the same time.  ^If SQLite is compiled with2164** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then2165** it is not possible to set the Multi-thread [threading mode] and2166** [sqlite3_config()] will return [SQLITE_ERROR] if called with the2167** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>2168**2169** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>2170** <dd>There are no arguments to this option.  ^This option sets the2171** [threading mode] to Serialized. In other words, this option enables2172** all mutexes including the recursive2173** mutexes on [database connection] and [prepared statement] objects.2174** In this mode (which is the default when SQLite is compiled with2175** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access2176** to [database connections] and [prepared statements] so that the2177** application is free to use the same [database connection] or the2178** same [prepared statement] in different threads at the same time.2179** ^If SQLite is compiled with2180** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then2181** it is not possible to set the Serialized [threading mode] and2182** [sqlite3_config()] will return [SQLITE_ERROR] if called with the2183** SQLITE_CONFIG_SERIALIZED configuration option.</dd>2184**2185** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>2186** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is2187** a pointer to an instance of the [sqlite3_mem_methods] structure.2188** The argument specifies2189** alternative low-level memory allocation routines to be used in place of2190** the memory allocation routines built into SQLite.)^ ^SQLite makes2191** its own private copy of the content of the [sqlite3_mem_methods] structure2192** before the [sqlite3_config()] call returns.</dd>2193**2194** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>2195** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which2196** is a pointer to an instance of the [sqlite3_mem_methods] structure.2197** The [sqlite3_mem_methods]2198** structure is filled with the currently defined memory allocation routines.)^2199** This option can be used to overload the default memory allocation2200** routines with a wrapper that simulations memory allocation failure or2201** tracks memory usage, for example. </dd>2202**2203** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>2204** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of2205** type int, interpreted as a boolean, which if true provides a hint to2206** SQLite that it should avoid large memory allocations if possible.2207** SQLite will run faster if it is free to make large memory allocations,2208** but some application might prefer to run slower in exchange for2209** guarantees about memory fragmentation that are possible if large2210** allocations are avoided.  This hint is normally off.2211** </dd>2212**2213** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>2214** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,2215** interpreted as a boolean, which enables or disables the collection of2216** memory allocation statistics. ^(When memory allocation statistics are2217** disabled, the following SQLite interfaces become non-operational:2218**   <ul>2219**   <li> [sqlite3_hard_heap_limit64()]2220**   <li> [sqlite3_memory_used()]2221**   <li> [sqlite3_memory_highwater()]2222**   <li> [sqlite3_soft_heap_limit64()]2223**   <li> [sqlite3_status64()]2224**   </ul>)^2225** ^Memory allocation statistics are enabled by default unless SQLite is2226** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory2227** allocation statistics are disabled by default.2228** </dd>2229**2230** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>2231** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.2232** </dd>2233**2234** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>2235** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool2236** that SQLite can use for the database page cache with the default page2237** cache implementation.2238** This configuration option is a no-op if an application-defined page2239** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].2240** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to2241** 8-byte aligned memory (pMem), the size of each page cache line (sz),2242** and the number of cache lines (N).2243** The sz argument should be the size of the largest database page2244** (a power of two between 512 and 65536) plus some extra bytes for each2245** page header.  ^The number of extra bytes needed by the page header2246** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].2247** ^It is harmless, apart from the wasted memory,2248** for the sz parameter to be larger than necessary.  The pMem2249** argument must be either a NULL pointer or a pointer to an 8-byte2250** aligned block of memory of at least sz*N bytes, otherwise2251** subsequent behavior is undefined.2252** ^When pMem is not NULL, SQLite will strive to use the memory provided2253** to satisfy page cache needs, falling back to [sqlite3_malloc()] if2254** a page cache line is larger than sz bytes or if all of the pMem buffer2255** is exhausted.2256** ^If pMem is NULL and N is non-zero, then each database connection2257** does an initial bulk allocation for page cache memory2258** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or2259** of -1024*N bytes if N is negative, . ^If additional2260** page cache memory is needed beyond what is provided by the initial2261** allocation, then SQLite goes to [sqlite3_malloc()] separately for each2262** additional cache line. </dd>2263**2264** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>2265** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer2266** that SQLite will use for all of its dynamic memory allocation needs2267** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].2268** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled2269** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns2270** [SQLITE_ERROR] if invoked otherwise.2271** ^There are three arguments to SQLITE_CONFIG_HEAP:2272** An 8-byte aligned pointer to the memory,2273** the number of bytes in the memory buffer, and the minimum allocation size.2274** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts2275** to using its default memory allocator (the system malloc() implementation),2276** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the2277** memory pointer is not NULL then the alternative memory2278** allocator is engaged to handle all of SQLites memory allocation needs.2279** The first pointer (the memory pointer) must be aligned to an 8-byte2280** boundary or subsequent behavior of SQLite will be undefined.2281** The minimum allocation size is capped at 2**12. Reasonable values2282** for the minimum allocation size are 2**5 through 2**8.</dd>2283**2284** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>2285** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a2286** pointer to an instance of the [sqlite3_mutex_methods] structure.2287** The argument specifies alternative low-level mutex routines to be used2288** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of2289** the content of the [sqlite3_mutex_methods] structure before the call to2290** [sqlite3_config()] returns. ^If SQLite is compiled with2291** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then2292** the entire mutexing subsystem is omitted from the build and hence calls to2293** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will2294** return [SQLITE_ERROR].</dd>2295**2296** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>2297** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which2298** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The2299** [sqlite3_mutex_methods]2300** structure is filled with the currently defined mutex routines.)^2301** This option can be used to overload the default mutex allocation2302** routines with a wrapper used to track mutex usage for performance2303** profiling or testing, for example.   ^If SQLite is compiled with2304** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then2305** the entire mutexing subsystem is omitted from the build and hence calls to2306** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will2307** return [SQLITE_ERROR].</dd>2308**2309** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>2310** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine2311** the default size of lookaside memory on each [database connection].2312** The first argument is the2313** size of each lookaside buffer slot and the second is the number of2314** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE2315** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]2316** option to [sqlite3_db_config()] can be used to change the lookaside2317** configuration on individual connections.)^ </dd>2318**2319** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>2320** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is2321** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies2322** the interface to a custom page cache implementation.)^2323** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>2324**2325** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>2326** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which2327** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of2328** the current page cache implementation into that object.)^ </dd>2329**2330** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>2331** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite2332** global [error log].2333** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a2334** function with a call signature of void(*)(void*,int,const char*),2335** and a pointer to void. ^If the function pointer is not NULL, it is2336** invoked by [sqlite3_log()] to process each logging event.  ^If the2337** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.2338** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is2339** passed through as the first parameter to the application-defined logger2340** function whenever that function is invoked.  ^The second parameter to2341** the logger function is a copy of the first parameter to the corresponding2342** [sqlite3_log()] call and is intended to be a [result code] or an2343** [extended result code].  ^The third parameter passed to the logger is2344** log message after formatting via [sqlite3_snprintf()].2345** The SQLite logging interface is not reentrant; the logger function2346** supplied by the application must not invoke any SQLite interface.2347** In a multi-threaded application, the application-defined logger2348** function must be threadsafe. </dd>2349**2350** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI2351** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.2352** If non-zero, then URI handling is globally enabled. If the parameter is zero,2353** then URI handling is globally disabled.)^ ^If URI handling is globally2354** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],2355** [sqlite3_open16()] or2356** specified as part of [ATTACH] commands are interpreted as URIs, regardless2357** of whether or not the [SQLITE_OPEN_URI] flag is set when the database2358** connection is opened. ^If it is globally disabled, filenames are2359** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the2360** database connection is opened. ^(By default, URI handling is globally2361** disabled. The default value may be changed by compiling with the2362** [SQLITE_USE_URI] symbol defined.)^2363**2364** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN2365** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer2366** argument which is interpreted as a boolean in order to enable or disable2367** the use of covering indices for full table scans in the query optimizer.2368** ^The default setting is determined2369** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"2370** if that compile-time option is omitted.2371** The ability to disable the use of covering indices for full table scans2372** is because some incorrectly coded legacy applications might malfunction2373** when the optimization is enabled.  Providing the ability to2374** disable the optimization allows the older, buggy application code to work2375** without change even with newer versions of SQLite.2376**2377** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]2378** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE2379** <dd> These options are obsolete and should not be used by new code.2380** They are retained for backwards compatibility but are now no-ops.2381** </dd>2382**2383** [[SQLITE_CONFIG_SQLLOG]]2384** <dt>SQLITE_CONFIG_SQLLOG2385** <dd>This option is only available if sqlite is compiled with the2386** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should2387** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).2388** The second should be of type (void*). The callback is invoked by the library2389** in three separate circumstances, identified by the value passed as the2390** fourth parameter. If the fourth parameter is 0, then the database connection2391** passed as the second argument has just been opened. The third argument2392** points to a buffer containing the name of the main database file. If the2393** fourth parameter is 1, then the SQL statement that the third parameter2394** points to has just been executed. Or, if the fourth parameter is 2, then2395** the connection being passed as the second parameter is being closed. The2396** third parameter is passed NULL In this case.  An example of using this2397** configuration option can be seen in the "test_sqllog.c" source file in2398** the canonical SQLite source tree.</dd>2399**2400** [[SQLITE_CONFIG_MMAP_SIZE]]2401** <dt>SQLITE_CONFIG_MMAP_SIZE2402** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values2403** that are the default mmap size limit (the default setting for2404** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.2405** ^The default setting can be overridden by each database connection using2406** either the [PRAGMA mmap_size] command, or by using the2407** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size2408** will be silently truncated if necessary so that it does not exceed the2409** compile-time maximum mmap size set by the2410** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^2411** ^If either argument to this option is negative, then that argument is2412** changed to its compile-time default.2413**2414** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]2415** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE2416** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is2417** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro2418** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value2419** that specifies the maximum size of the created heap.2420**2421** [[SQLITE_CONFIG_PCACHE_HDRSZ]]2422** <dt>SQLITE_CONFIG_PCACHE_HDRSZ2423** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which2424** is a pointer to an integer and writes into that integer the number of extra2425** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].2426** The amount of extra space required can change depending on the compiler,2427** target platform, and SQLite version.2428**2429** [[SQLITE_CONFIG_PMASZ]]2430** <dt>SQLITE_CONFIG_PMASZ2431** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which2432** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded2433** sorter to that integer.  The default minimum PMA Size is set by the2434** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched2435** to help with sort operations when multithreaded sorting2436** is enabled (using the [PRAGMA threads] command) and the amount of content2437** to be sorted exceeds the page size times the minimum of the2438** [PRAGMA cache_size] setting and this value.2439**2440** [[SQLITE_CONFIG_STMTJRNL_SPILL]]2441** <dt>SQLITE_CONFIG_STMTJRNL_SPILL2442** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which2443** becomes the [statement journal] spill-to-disk threshold.2444** [Statement journals] are held in memory until their size (in bytes)2445** exceeds this threshold, at which point they are written to disk.2446** Or if the threshold is -1, statement journals are always held2447** exclusively in memory.2448** Since many statement journals never become large, setting the spill2449** threshold to a value such as 64KiB can greatly reduce the amount of2450** I/O required to support statement rollback.2451** The default value for this setting is controlled by the2452** [SQLITE_STMTJRNL_SPILL] compile-time option.2453**2454** [[SQLITE_CONFIG_SORTERREF_SIZE]]2455** <dt>SQLITE_CONFIG_SORTERREF_SIZE2456** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter2457** of type (int) - the new value of the sorter-reference size threshold.2458** Usually, when SQLite uses an external sort to order records according2459** to an ORDER BY clause, all fields required by the caller are present in the2460** sorted records. However, if SQLite determines based on the declared type2461** of a table column that its values are likely to be very large - larger2462** than the configured sorter-reference size threshold - then a reference2463** is stored in each sorted record and the required column values loaded2464** from the database as records are returned in sorted order. The default2465** value for this option is to never use this optimization. Specifying a2466** negative value for this option restores the default behavior.2467** This option is only available if SQLite is compiled with the2468** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.2469**2470** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]2471** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE2472** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter2473** [sqlite3_int64] parameter which is the default maximum size for an in-memory2474** database created using [sqlite3_deserialize()].  This default maximum2475** size can be adjusted up or down for individual databases using the2476** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control].  If this2477** configuration setting is never used, then the default maximum is determined2478** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option.  If that2479** compile-time option is not set, then the default maximum is 1073741824.2480**2481** [[SQLITE_CONFIG_ROWID_IN_VIEW]]2482** <dt>SQLITE_CONFIG_ROWID_IN_VIEW2483** <dd>The SQLITE_CONFIG_ROWID_IN_VIEW option enables or disables the ability2484** for VIEWs to have a ROWID.  The capability can only be enabled if SQLite is2485** compiled with -DSQLITE_ALLOW_ROWID_IN_VIEW, in which case the capability2486** defaults to on.  This configuration option queries the current setting or2487** changes the setting to off or on.  The argument is a pointer to an integer.2488** If that integer initially holds a value of 1, then the ability for VIEWs to2489** have ROWIDs is activated.  If the integer initially holds zero, then the2490** ability is deactivated.  Any other initial value for the integer leaves the2491** setting unchanged.  After changes, if any, the integer is written with2492** a 1 or 0, if the ability for VIEWs to have ROWIDs is on or off.  If SQLite2493** is compiled without -DSQLITE_ALLOW_ROWID_IN_VIEW (which is the usual and2494** recommended case) then the integer is always filled with zero, regardless2495** if its initial value.2496** </dl>2497*/2498#define SQLITE_CONFIG_SINGLETHREAD         1  /* nil */2499#define SQLITE_CONFIG_MULTITHREAD          2  /* nil */2500#define SQLITE_CONFIG_SERIALIZED           3  /* nil */2501#define SQLITE_CONFIG_MALLOC               4  /* sqlite3_mem_methods* */2502#define SQLITE_CONFIG_GETMALLOC            5  /* sqlite3_mem_methods* */2503#define SQLITE_CONFIG_SCRATCH              6  /* No longer used */2504#define SQLITE_CONFIG_PAGECACHE            7  /* void*, int sz, int N */2505#define SQLITE_CONFIG_HEAP                 8  /* void*, int nByte, int min */2506#define SQLITE_CONFIG_MEMSTATUS            9  /* boolean */2507#define SQLITE_CONFIG_MUTEX               10  /* sqlite3_mutex_methods* */2508#define SQLITE_CONFIG_GETMUTEX            11  /* sqlite3_mutex_methods* */2509/* previously SQLITE_CONFIG_CHUNKALLOC    12 which is now unused. */2510#define SQLITE_CONFIG_LOOKASIDE           13  /* int int */2511#define SQLITE_CONFIG_PCACHE              14  /* no-op */2512#define SQLITE_CONFIG_GETPCACHE           15  /* no-op */2513#define SQLITE_CONFIG_LOG                 16  /* xFunc, void* */2514#define SQLITE_CONFIG_URI                 17  /* int */2515#define SQLITE_CONFIG_PCACHE2             18  /* sqlite3_pcache_methods2* */2516#define SQLITE_CONFIG_GETPCACHE2          19  /* sqlite3_pcache_methods2* */2517#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */2518#define SQLITE_CONFIG_SQLLOG              21  /* xSqllog, void* */2519#define SQLITE_CONFIG_MMAP_SIZE           22  /* sqlite3_int64, sqlite3_int64 */2520#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */2521#define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */2522#define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */2523#define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */2524#define SQLITE_CONFIG_SMALL_MALLOC        27  /* boolean */2525#define SQLITE_CONFIG_SORTERREF_SIZE      28  /* int nByte */2526#define SQLITE_CONFIG_MEMDB_MAXSIZE       29  /* sqlite3_int64 */2527#define SQLITE_CONFIG_ROWID_IN_VIEW       30  /* int* */25282529/*2530** CAPI3REF: Database Connection Configuration Options2531**2532** These constants are the available integer configuration options that2533** can be passed as the second parameter to the [sqlite3_db_config()] interface.2534**2535** The [sqlite3_db_config()] interface is a var-args functions.  It takes a2536** variable number of parameters, though always at least two.  The number of2537** parameters passed into sqlite3_db_config() depends on which of these2538** constants is given as the second parameter.  This documentation page2539** refers to parameters beyond the second as "arguments".  Thus, when this2540** page says "the N-th argument" it means "the N-th parameter past the2541** configuration option" or "the (N+2)-th parameter to sqlite3_db_config()".2542**2543** New configuration options may be added in future releases of SQLite.2544** Existing configuration options might be discontinued.  Applications2545** should check the return code from [sqlite3_db_config()] to make sure that2546** the call worked.  ^The [sqlite3_db_config()] interface will return a2547** non-zero [error code] if a discontinued or unsupported configuration option2548** is invoked.2549**2550** <dl>2551** [[SQLITE_DBCONFIG_LOOKASIDE]]2552** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>2553** <dd> The SQLITE_DBCONFIG_LOOKASIDE option is used to adjust the2554** configuration of the lookaside memory allocator within a database2555** connection.2556** The arguments to the SQLITE_DBCONFIG_LOOKASIDE option are <i>not</i>2557** in the [DBCONFIG arguments|usual format].2558** The SQLITE_DBCONFIG_LOOKASIDE option takes three arguments, not two,2559** so that a call to [sqlite3_db_config()] that uses SQLITE_DBCONFIG_LOOKASIDE2560** should have a total of five parameters.2561** ^The first argument (the third parameter to [sqlite3_db_config()] is a2562** pointer to a memory buffer to use for lookaside memory.2563** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb2564** may be NULL in which case SQLite will allocate the2565** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the2566** size of each lookaside buffer slot.  ^The third argument is the number of2567** slots.  The size of the buffer in the first argument must be greater than2568** or equal to the product of the second and third arguments.  The buffer2569** must be aligned to an 8-byte boundary.  ^If the second argument to2570** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally2571** rounded down to the next smaller multiple of 8.  ^(The lookaside memory2572** configuration for a database connection can only be changed when that2573** connection is not currently using lookaside memory, or in other words2574** when the "current value" returned by2575** [sqlite3_db_status](D,[SQLITE_DBSTATUS_LOOKASIDE_USED],...) is zero.2576** Any attempt to change the lookaside memory configuration when lookaside2577** memory is in use leaves the configuration unchanged and returns2578** [SQLITE_BUSY].)^</dd>2579**2580** [[SQLITE_DBCONFIG_ENABLE_FKEY]]2581** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>2582** <dd> ^This option is used to enable or disable the enforcement of2583** [foreign key constraints].  This is the same setting that is2584** enabled or disabled by the [PRAGMA foreign_keys] statement.2585** The first argument is an integer which is 0 to disable FK enforcement,2586** positive to enable FK enforcement or negative to leave FK enforcement2587** unchanged.  The second parameter is a pointer to an integer into which2588** is written 0 or 1 to indicate whether FK enforcement is off or on2589** following this call.  The second parameter may be a NULL pointer, in2590** which case the FK enforcement setting is not reported back. </dd>2591**2592** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]2593** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>2594** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].2595** There should be two additional arguments.2596** The first argument is an integer which is 0 to disable triggers,2597** positive to enable triggers or negative to leave the setting unchanged.2598** The second parameter is a pointer to an integer into which2599** is written 0 or 1 to indicate whether triggers are disabled or enabled2600** following this call.  The second parameter may be a NULL pointer, in2601** which case the trigger setting is not reported back.2602**2603** <p>Originally this option disabled all triggers.  ^(However, since2604** SQLite version 3.35.0, TEMP triggers are still allowed even if2605** this option is off.  So, in other words, this option now only disables2606** triggers in the main database schema or in the schemas of [ATTACH]-ed2607** databases.)^ </dd>2608**2609** [[SQLITE_DBCONFIG_ENABLE_VIEW]]2610** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt>2611** <dd> ^This option is used to enable or disable [CREATE VIEW | views].2612** There must be two additional arguments.2613** The first argument is an integer which is 0 to disable views,2614** positive to enable views or negative to leave the setting unchanged.2615** The second parameter is a pointer to an integer into which2616** is written 0 or 1 to indicate whether views are disabled or enabled2617** following this call.  The second parameter may be a NULL pointer, in2618** which case the view setting is not reported back.2619**2620** <p>Originally this option disabled all views.  ^(However, since2621** SQLite version 3.35.0, TEMP views are still allowed even if2622** this option is off.  So, in other words, this option now only disables2623** views in the main database schema or in the schemas of ATTACH-ed2624** databases.)^ </dd>2625**2626** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]2627** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>2628** <dd> ^This option is used to enable or disable the2629** [fts3_tokenizer()] function which is part of the2630** [FTS3] full-text search engine extension.2631** There must be two additional arguments.2632** The first argument is an integer which is 0 to disable fts3_tokenizer() or2633** positive to enable fts3_tokenizer() or negative to leave the setting2634** unchanged.2635** The second parameter is a pointer to an integer into which2636** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled2637** following this call.  The second parameter may be a NULL pointer, in2638** which case the new setting is not reported back. </dd>2639**2640** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]2641** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>2642** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]2643** interface independently of the [load_extension()] SQL function.2644** The [sqlite3_enable_load_extension()] API enables or disables both the2645** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].2646** There must be two additional arguments.2647** When the first argument to this interface is 1, then only the C-API is2648** enabled and the SQL function remains disabled.  If the first argument to2649** this interface is 0, then both the C-API and the SQL function are disabled.2650** If the first argument is -1, then no changes are made to state of either the2651** C-API or the SQL function.2652** The second parameter is a pointer to an integer into which2653** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface2654** is disabled or enabled following this call.  The second parameter may2655** be a NULL pointer, in which case the new setting is not reported back.2656** </dd>2657**2658** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>2659** <dd> ^This option is used to change the name of the "main" database2660** schema.  This option does not follow the2661** [DBCONFIG arguments|usual SQLITE_DBCONFIG argument format].2662** This option takes exactly one additional argument so that the2663** [sqlite3_db_config()] call has a total of three parameters.  The2664** extra argument must be a pointer to a constant UTF8 string which2665** will become the new schema name in place of "main".  ^SQLite does2666** not make a copy of the new main schema name string, so the application2667** must ensure that the argument passed into SQLITE_DBCONFIG MAINDBNAME2668** is unchanged until after the database connection closes.2669** </dd>2670**2671** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]2672** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>2673** <dd> Usually, when a database in [WAL mode] is closed or detached from a2674** database handle, SQLite checks if if there are other connections to the2675** same database, and if there are no other database connection (if the2676** connection being closed is the last open connection to the database),2677** then SQLite performs a [checkpoint] before closing the connection and2678** deletes the WAL file.  The SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE option can2679** be used to override that behavior. The first argument passed to this2680** operation (the third parameter to [sqlite3_db_config()]) is an integer2681** which is positive to disable checkpoints-on-close, or zero (the default)2682** to enable them, and negative to leave the setting unchanged.2683** The second argument (the fourth parameter) is a pointer to an integer2684** into which is written 0 or 1 to indicate whether checkpoints-on-close2685** have been disabled - 0 if they are not disabled, 1 if they are.2686** </dd>2687**2688** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>2689** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates2690** the [query planner stability guarantee] (QPSG).  When the QPSG is active,2691** a single SQL query statement will always use the same algorithm regardless2692** of values of [bound parameters].)^ The QPSG disables some query optimizations2693** that look at the values of bound parameters, which can make some queries2694** slower.  But the QPSG has the advantage of more predictable behavior.  With2695** the QPSG active, SQLite will always use the same query plan in the field as2696** was used during testing in the lab.2697** The first argument to this setting is an integer which is 0 to disable2698** the QPSG, positive to enable QPSG, or negative to leave the setting2699** unchanged. The second parameter is a pointer to an integer into which2700** is written 0 or 1 to indicate whether the QPSG is disabled or enabled2701** following this call.2702** </dd>2703**2704** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>2705** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not2706** include output for any operations performed by trigger programs. This2707** option is used to set or clear (the default) a flag that governs this2708** behavior. The first parameter passed to this operation is an integer -2709** positive to enable output for trigger programs, or zero to disable it,2710** or negative to leave the setting unchanged.2711** The second parameter is a pointer to an integer into which is written2712** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if2713** it is not disabled, 1 if it is.2714** </dd>2715**2716** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>2717** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run2718** [VACUUM] in order to reset a database back to an empty database2719** with no schema and no content. The following process works even for2720** a badly corrupted database file:2721** <ol>2722** <li> If the database connection is newly opened, make sure it has read the2723**      database schema by preparing then discarding some query against the2724**      database, or calling sqlite3_table_column_metadata(), ignoring any2725**      errors.  This step is only necessary if the application desires to keep2726**      the database in WAL mode after the reset if it was in WAL mode before2727**      the reset.2728** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);2729** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);2730** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);2731** </ol>2732** Because resetting a database is destructive and irreversible, the2733** process requires the use of this obscure API and multiple steps to2734** help ensure that it does not happen by accident. Because this2735** feature must be capable of resetting corrupt databases, and2736** shutting down virtual tables may require access to that corrupt2737** storage, the library must abandon any installed virtual tables2738** without calling their xDestroy() methods.2739**2740** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>2741** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the2742** "defensive" flag for a database connection.  When the defensive2743** flag is enabled, language features that allow ordinary SQL to2744** deliberately corrupt the database file are disabled.  The disabled2745** features include but are not limited to the following:2746** <ul>2747** <li> The [PRAGMA writable_schema=ON] statement.2748** <li> The [PRAGMA journal_mode=OFF] statement.2749** <li> The [PRAGMA schema_version=N] statement.2750** <li> Writes to the [sqlite_dbpage] virtual table.2751** <li> Direct writes to [shadow tables].2752** </ul>2753** </dd>2754**2755** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt>2756** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the2757** "writable_schema" flag. This has the same effect and is logically equivalent2758** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].2759** The first argument to this setting is an integer which is 0 to disable2760** the writable_schema, positive to enable writable_schema, or negative to2761** leave the setting unchanged. The second parameter is a pointer to an2762** integer into which is written 0 or 1 to indicate whether the writable_schema2763** is enabled or disabled following this call.2764** </dd>2765**2766** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]2767** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt>2768** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates2769** the legacy behavior of the [ALTER TABLE RENAME] command such it2770** behaves as it did prior to [version 3.24.0] (2018-06-04).  See the2771** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for2772** additional information. This feature can also be turned on and off2773** using the [PRAGMA legacy_alter_table] statement.2774** </dd>2775**2776** [[SQLITE_DBCONFIG_DQS_DML]]2777** <dt>SQLITE_DBCONFIG_DQS_DML</dt>2778** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates2779** the legacy [double-quoted string literal] misfeature for DML statements2780** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The2781** default value of this setting is determined by the [-DSQLITE_DQS]2782** compile-time option.2783** </dd>2784**2785** [[SQLITE_DBCONFIG_DQS_DDL]]2786** <dt>SQLITE_DBCONFIG_DQS_DDL</dt>2787** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates2788** the legacy [double-quoted string literal] misfeature for DDL statements,2789** such as CREATE TABLE and CREATE INDEX. The2790** default value of this setting is determined by the [-DSQLITE_DQS]2791** compile-time option.2792** </dd>2793**2794** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]2795** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</dt>2796** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to2797** assume that database schemas are untainted by malicious content.2798** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite2799** takes additional defensive steps to protect the application from harm2800** including:2801** <ul>2802** <li> Prohibit the use of SQL functions inside triggers, views,2803** CHECK constraints, DEFAULT clauses, expression indexes,2804** partial indexes, or generated columns2805** unless those functions are tagged with [SQLITE_INNOCUOUS].2806** <li> Prohibit the use of virtual tables inside of triggers or views2807** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].2808** </ul>2809** This setting defaults to "on" for legacy compatibility, however2810** all applications are advised to turn it off if possible. This setting2811** can also be controlled using the [PRAGMA trusted_schema] statement.2812** </dd>2813**2814** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]2815** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</dt>2816** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates2817** the legacy file format flag.  When activated, this flag causes all newly2818** created database file to have a schema format version number (the 4-byte2819** integer found at offset 44 into the database header) of 1.  This in turn2820** means that the resulting database file will be readable and writable by2821** any SQLite version back to 3.0.0 ([dateof:3.0.0]).  Without this setting,2822** newly created databases are generally not understandable by SQLite versions2823** prior to 3.3.0 ([dateof:3.3.0]).  As these words are written, there2824** is now scarcely any need to generate database files that are compatible2825** all the way back to version 3.0.0, and so this setting is of little2826** practical use, but is provided so that SQLite can continue to claim the2827** ability to generate new database files that are compatible with  version2828** 3.0.0.2829** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,2830** the [VACUUM] command will fail with an obscure error when attempting to2831** process a table with generated columns and a descending index.  This is2832** not considered a bug since SQLite versions 3.3.0 and earlier do not support2833** either generated columns or descending indexes.2834** </dd>2835**2836** [[SQLITE_DBCONFIG_STMT_SCANSTATUS]]2837** <dt>SQLITE_DBCONFIG_STMT_SCANSTATUS</dt>2838** <dd>The SQLITE_DBCONFIG_STMT_SCANSTATUS option is only useful in2839** SQLITE_ENABLE_STMT_SCANSTATUS builds. In this case, it sets or clears2840** a flag that enables collection of the sqlite3_stmt_scanstatus_v2()2841** statistics. For statistics to be collected, the flag must be set on2842** the database handle both when the SQL statement is prepared and when it2843** is stepped. The flag is set (collection of statistics is enabled)2844** by default. <p>This option takes two arguments: an integer and a pointer to2845** an integer..  The first argument is 1, 0, or -1 to enable, disable, or2846** leave unchanged the statement scanstatus option.  If the second argument2847** is not NULL, then the value of the statement scanstatus setting after2848** processing the first argument is written into the integer that the second2849** argument points to.2850** </dd>2851**2852** [[SQLITE_DBCONFIG_REVERSE_SCANORDER]]2853** <dt>SQLITE_DBCONFIG_REVERSE_SCANORDER</dt>2854** <dd>The SQLITE_DBCONFIG_REVERSE_SCANORDER option changes the default order2855** in which tables and indexes are scanned so that the scans start at the end2856** and work toward the beginning rather than starting at the beginning and2857** working toward the end. Setting SQLITE_DBCONFIG_REVERSE_SCANORDER is the2858** same as setting [PRAGMA reverse_unordered_selects]. <p>This option takes2859** two arguments which are an integer and a pointer to an integer.  The first2860** argument is 1, 0, or -1 to enable, disable, or leave unchanged the2861** reverse scan order flag, respectively.  If the second argument is not NULL,2862** then 0 or 1 is written into the integer that the second argument points to2863** depending on if the reverse scan order flag is set after processing the2864** first argument.2865** </dd>2866**2867** [[SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE]]2868** <dt>SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE</dt>2869** <dd>The SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE option enables or disables2870** the ability of the [ATTACH DATABASE] SQL command to create a new database2871** file if the database filed named in the ATTACH command does not already2872** exist.  This ability of ATTACH to create a new database is enabled by2873** default.  Applications can disable or reenable the ability for ATTACH to2874** create new database files using this DBCONFIG option.<p>2875** This option takes two arguments which are an integer and a pointer2876** to an integer.  The first argument is 1, 0, or -1 to enable, disable, or2877** leave unchanged the attach-create flag, respectively.  If the second2878** argument is not NULL, then 0 or 1 is written into the integer that the2879** second argument points to depending on if the attach-create flag is set2880** after processing the first argument.2881** </dd>2882**2883** [[SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE]]2884** <dt>SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE</dt>2885** <dd>The SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE option enables or disables the2886** ability of the [ATTACH DATABASE] SQL command to open a database for writing.2887** This capability is enabled by default.  Applications can disable or2888** reenable this capability using the current DBCONFIG option.  If the2889** the this capability is disabled, the [ATTACH] command will still work,2890** but the database will be opened read-only.  If this option is disabled,2891** then the ability to create a new database using [ATTACH] is also disabled,2892** regardless of the value of the [SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE]2893** option.<p>2894** This option takes two arguments which are an integer and a pointer2895** to an integer.  The first argument is 1, 0, or -1 to enable, disable, or2896** leave unchanged the ability to ATTACH another database for writing,2897** respectively.  If the second argument is not NULL, then 0 or 1 is written2898** into the integer to which the second argument points, depending on whether2899** the ability to ATTACH a read/write database is enabled or disabled2900** after processing the first argument.2901** </dd>2902**2903** [[SQLITE_DBCONFIG_ENABLE_COMMENTS]]2904** <dt>SQLITE_DBCONFIG_ENABLE_COMMENTS</dt>2905** <dd>The SQLITE_DBCONFIG_ENABLE_COMMENTS option enables or disables the2906** ability to include comments in SQL text.  Comments are enabled by default.2907** An application can disable or reenable comments in SQL text using this2908** DBCONFIG option.<p>2909** This option takes two arguments which are an integer and a pointer2910** to an integer.  The first argument is 1, 0, or -1 to enable, disable, or2911** leave unchanged the ability to use comments in SQL text,2912** respectively.  If the second argument is not NULL, then 0 or 1 is written2913** into the integer that the second argument points to depending on if2914** comments are allowed in SQL text after processing the first argument.2915** </dd>2916**2917** </dl>2918**2919** [[DBCONFIG arguments]] <h3>Arguments To SQLITE_DBCONFIG Options</h3>2920**2921** <p>Most of the SQLITE_DBCONFIG options take two arguments, so that the2922** overall call to [sqlite3_db_config()] has a total of four parameters.2923** The first argument (the third parameter to sqlite3_db_config()) is a integer.2924** The second argument is a pointer to an integer.  If the first argument is 1,2925** then the option becomes enabled.  If the first integer argument is 0, then the2926** option is disabled.  If the first argument is -1, then the option setting2927** is unchanged.  The second argument, the pointer to an integer, may be NULL.2928** If the second argument is not NULL, then a value of 0 or 1 is written into2929** the integer to which the second argument points, depending on whether the2930** setting is disabled or enabled after applying any changes specified by2931** the first argument.2932**2933** <p>While most SQLITE_DBCONFIG options use the argument format2934** described in the previous paragraph, the [SQLITE_DBCONFIG_MAINDBNAME]2935** and [SQLITE_DBCONFIG_LOOKASIDE] options are different.  See the2936** documentation of those exceptional options for details.2937*/2938#define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */2939#define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */2940#define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */2941#define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */2942#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */2943#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */2944#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */2945#define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */2946#define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */2947#define SQLITE_DBCONFIG_RESET_DATABASE        1009 /* int int* */2948#define SQLITE_DBCONFIG_DEFENSIVE             1010 /* int int* */2949#define SQLITE_DBCONFIG_WRITABLE_SCHEMA       1011 /* int int* */2950#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    1012 /* int int* */2951#define SQLITE_DBCONFIG_DQS_DML               1013 /* int int* */2952#define SQLITE_DBCONFIG_DQS_DDL               1014 /* int int* */2953#define SQLITE_DBCONFIG_ENABLE_VIEW           1015 /* int int* */2954#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    1016 /* int int* */2955#define SQLITE_DBCONFIG_TRUSTED_SCHEMA        1017 /* int int* */2956#define SQLITE_DBCONFIG_STMT_SCANSTATUS       1018 /* int int* */2957#define SQLITE_DBCONFIG_REVERSE_SCANORDER     1019 /* int int* */2958#define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE  1020 /* int int* */2959#define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE   1021 /* int int* */2960#define SQLITE_DBCONFIG_ENABLE_COMMENTS       1022 /* int int* */2961#define SQLITE_DBCONFIG_MAX                   1022 /* Largest DBCONFIG */29622963/*2964** CAPI3REF: Enable Or Disable Extended Result Codes2965** METHOD: sqlite32966**2967** ^The sqlite3_extended_result_codes() routine enables or disables the2968** [extended result codes] feature of SQLite. ^The extended result2969** codes are disabled by default for historical compatibility.2970*/2971SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);29722973/*2974** CAPI3REF: Last Insert Rowid2975** METHOD: sqlite32976**2977** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)2978** has a unique 64-bit signed2979** integer key called the [ROWID | "rowid"]. ^The rowid is always available2980** as an undeclared column named ROWID, OID, or _ROWID_ as long as those2981** names are not also used by explicitly declared columns. ^If2982** the table has a column of type [INTEGER PRIMARY KEY] then that column2983** is another alias for the rowid.2984**2985** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of2986** the most recent successful [INSERT] into a rowid table or [virtual table]2987** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not2988** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred2989** on the database connection D, then sqlite3_last_insert_rowid(D) returns2990** zero.2991**2992** As well as being set automatically as rows are inserted into database2993** tables, the value returned by this function may be set explicitly by2994** [sqlite3_set_last_insert_rowid()]2995**2996** Some virtual table implementations may INSERT rows into rowid tables as2997** part of committing a transaction (e.g. to flush data accumulated in memory2998** to disk). In this case subsequent calls to this function return the rowid2999** associated with these internal INSERT operations, which leads to3000** unintuitive results. Virtual table implementations that do write to rowid3001** tables in this way can avoid this problem by restoring the original3002** rowid value using [sqlite3_set_last_insert_rowid()] before returning3003** control to the user.3004**3005** ^(If an [INSERT] occurs within a trigger then this routine will3006** return the [rowid] of the inserted row as long as the trigger is3007** running. Once the trigger program ends, the value returned3008** by this routine reverts to what it was before the trigger was fired.)^3009**3010** ^An [INSERT] that fails due to a constraint violation is not a3011** successful [INSERT] and does not change the value returned by this3012** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,3013** and INSERT OR ABORT make no changes to the return value of this3014** routine when their insertion fails.  ^(When INSERT OR REPLACE3015** encounters a constraint violation, it does not fail.  The3016** INSERT continues to completion after deleting rows that caused3017** the constraint problem so INSERT OR REPLACE will always change3018** the return value of this interface.)^3019**3020** ^For the purposes of this routine, an [INSERT] is considered to3021** be successful even if it is subsequently rolled back.3022**3023** This function is accessible to SQL statements via the3024** [last_insert_rowid() SQL function].3025**3026** If a separate thread performs a new [INSERT] on the same3027** database connection while the [sqlite3_last_insert_rowid()]3028** function is running and thus changes the last insert [rowid],3029** then the value returned by [sqlite3_last_insert_rowid()] is3030** unpredictable and might not equal either the old or the new3031** last insert [rowid].3032*/3033SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);30343035/*3036** CAPI3REF: Set the Last Insert Rowid value.3037** METHOD: sqlite33038**3039** The sqlite3_set_last_insert_rowid(D, R) method allows the application to3040** set the value returned by calling sqlite3_last_insert_rowid(D) to R3041** without inserting a row into the database.3042*/3043SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);30443045/*3046** CAPI3REF: Count The Number Of Rows Modified3047** METHOD: sqlite33048**3049** ^These functions return the number of rows modified, inserted or3050** deleted by the most recently completed INSERT, UPDATE or DELETE3051** statement on the database connection specified by the only parameter.3052** The two functions are identical except for the type of the return value3053** and that if the number of rows modified by the most recent INSERT, UPDATE,3054** or DELETE is greater than the maximum value supported by type "int", then3055** the return value of sqlite3_changes() is undefined. ^Executing any other3056** type of SQL statement does not modify the value returned by these functions.3057** For the purposes of this interface, a CREATE TABLE AS SELECT statement3058** does not count as an INSERT, UPDATE or DELETE statement and hence the rows3059** added to the new table by the CREATE TABLE AS SELECT statement are not3060** counted.3061**3062** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are3063** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],3064** [foreign key actions] or [REPLACE] constraint resolution are not counted.3065**3066** Changes to a view that are intercepted by3067** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value3068** returned by sqlite3_changes() immediately after an INSERT, UPDATE or3069** DELETE statement run on a view is always zero. Only changes made to real3070** tables are counted.3071**3072** Things are more complicated if the sqlite3_changes() function is3073** executed while a trigger program is running. This may happen if the3074** program uses the [changes() SQL function], or if some other callback3075** function invokes sqlite3_changes() directly. Essentially:3076**3077** <ul>3078**   <li> ^(Before entering a trigger program the value returned by3079**        sqlite3_changes() function is saved. After the trigger program3080**        has finished, the original value is restored.)^3081**3082**   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE3083**        statement sets the value returned by sqlite3_changes()3084**        upon completion as normal. Of course, this value will not include3085**        any changes performed by sub-triggers, as the sqlite3_changes()3086**        value will be saved and restored after each sub-trigger has run.)^3087** </ul>3088**3089** ^This means that if the changes() SQL function (or similar) is used3090** by the first INSERT, UPDATE or DELETE statement within a trigger, it3091** returns the value as set when the calling statement began executing.3092** ^If it is used by the second or subsequent such statement within a trigger3093** program, the value returned reflects the number of rows modified by the3094** previous INSERT, UPDATE or DELETE statement within the same trigger.3095**3096** If a separate thread makes changes on the same database connection3097** while [sqlite3_changes()] is running then the value returned3098** is unpredictable and not meaningful.3099**3100** See also:3101** <ul>3102** <li> the [sqlite3_total_changes()] interface3103** <li> the [count_changes pragma]3104** <li> the [changes() SQL function]3105** <li> the [data_version pragma]3106** </ul>3107*/3108SQLITE_API int sqlite3_changes(sqlite3*);3109SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3*);31103111/*3112** CAPI3REF: Total Number Of Rows Modified3113** METHOD: sqlite33114**3115** ^These functions return the total number of rows inserted, modified or3116** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed3117** since the database connection was opened, including those executed as3118** part of trigger programs. The two functions are identical except for the3119** type of the return value and that if the number of rows modified by the3120** connection exceeds the maximum value supported by type "int", then3121** the return value of sqlite3_total_changes() is undefined. ^Executing3122** any other type of SQL statement does not affect the value returned by3123** sqlite3_total_changes().3124**3125** ^Changes made as part of [foreign key actions] are included in the3126** count, but those made as part of REPLACE constraint resolution are3127** not. ^Changes to a view that are intercepted by INSTEAD OF triggers3128** are not counted.3129**3130** The [sqlite3_total_changes(D)] interface only reports the number3131** of rows that changed due to SQL statement run against database3132** connection D.  Any changes by other database connections are ignored.3133** To detect changes against a database file from other database3134** connections use the [PRAGMA data_version] command or the3135** [SQLITE_FCNTL_DATA_VERSION] [file control].3136**3137** If a separate thread makes changes on the same database connection3138** while [sqlite3_total_changes()] is running then the value3139** returned is unpredictable and not meaningful.3140**3141** See also:3142** <ul>3143** <li> the [sqlite3_changes()] interface3144** <li> the [count_changes pragma]3145** <li> the [changes() SQL function]3146** <li> the [data_version pragma]3147** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]3148** </ul>3149*/3150SQLITE_API int sqlite3_total_changes(sqlite3*);3151SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3*);31523153/*3154** CAPI3REF: Interrupt A Long-Running Query3155** METHOD: sqlite33156**3157** ^This function causes any pending database operation to abort and3158** return at its earliest opportunity. This routine is typically3159** called in response to a user action such as pressing "Cancel"3160** or Ctrl-C where the user wants a long query operation to halt3161** immediately.3162**3163** ^It is safe to call this routine from a thread different from the3164** thread that is currently running the database operation.  But it3165** is not safe to call this routine with a [database connection] that3166** is closed or might close before sqlite3_interrupt() returns.3167**3168** ^If an SQL operation is very nearly finished at the time when3169** sqlite3_interrupt() is called, then it might not have an opportunity3170** to be interrupted and might continue to completion.3171**3172** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].3173** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE3174** that is inside an explicit transaction, then the entire transaction3175** will be rolled back automatically.3176**3177** ^The sqlite3_interrupt(D) call is in effect until all currently running3178** SQL statements on [database connection] D complete.  ^Any new SQL statements3179** that are started after the sqlite3_interrupt() call and before the3180** running statement count reaches zero are interrupted as if they had been3181** running prior to the sqlite3_interrupt() call.  ^New SQL statements3182** that are started after the running statement count reaches zero are3183** not effected by the sqlite3_interrupt().3184** ^A call to sqlite3_interrupt(D) that occurs when there are no running3185** SQL statements is a no-op and has no effect on SQL statements3186** that are started after the sqlite3_interrupt() call returns.3187**3188** ^The [sqlite3_is_interrupted(D)] interface can be used to determine whether3189** or not an interrupt is currently in effect for [database connection] D.3190** It returns 1 if an interrupt is currently in effect, or 0 otherwise.3191*/3192SQLITE_API void sqlite3_interrupt(sqlite3*);3193SQLITE_API int sqlite3_is_interrupted(sqlite3*);31943195/*3196** CAPI3REF: Determine If An SQL Statement Is Complete3197**3198** These routines are useful during command-line input to determine if the3199** currently entered text seems to form a complete SQL statement or3200** if additional input is needed before sending the text into3201** SQLite for parsing.  ^These routines return 1 if the input string3202** appears to be a complete SQL statement.  ^A statement is judged to be3203** complete if it ends with a semicolon token and is not a prefix of a3204** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within3205** string literals or quoted identifier names or comments are not3206** independent tokens (they are part of the token in which they are3207** embedded) and thus do not count as a statement terminator.  ^Whitespace3208** and comments that follow the final semicolon are ignored.3209**3210** ^These routines return 0 if the statement is incomplete.  ^If a3211** memory allocation fails, then SQLITE_NOMEM is returned.3212**3213** ^These routines do not parse the SQL statements thus3214** will not detect syntactically incorrect SQL.3215**3216** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior3217** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked3218** automatically by sqlite3_complete16().  If that initialization fails,3219** then the return value from sqlite3_complete16() will be non-zero3220** regardless of whether or not the input SQL is complete.)^3221**3222** The input to [sqlite3_complete()] must be a zero-terminated3223** UTF-8 string.3224**3225** The input to [sqlite3_complete16()] must be a zero-terminated3226** UTF-16 string in native byte order.3227*/3228SQLITE_API int sqlite3_complete(const char *sql);3229SQLITE_API int sqlite3_complete16(const void *sql);32303231/*3232** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors3233** KEYWORDS: {busy-handler callback} {busy handler}3234** METHOD: sqlite33235**3236** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X3237** that might be invoked with argument P whenever3238** an attempt is made to access a database table associated with3239** [database connection] D when another thread3240** or process has the table locked.3241** The sqlite3_busy_handler() interface is used to implement3242** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].3243**3244** ^If the busy callback is NULL, then [SQLITE_BUSY]3245** is returned immediately upon encountering the lock.  ^If the busy callback3246** is not NULL, then the callback might be invoked with two arguments.3247**3248** ^The first argument to the busy handler is a copy of the void* pointer which3249** is the third argument to sqlite3_busy_handler().  ^The second argument to3250** the busy handler callback is the number of times that the busy handler has3251** been invoked previously for the same locking event.  ^If the3252** busy callback returns 0, then no additional attempts are made to3253** access the database and [SQLITE_BUSY] is returned3254** to the application.3255** ^If the callback returns non-zero, then another attempt3256** is made to access the database and the cycle repeats.3257**3258** The presence of a busy handler does not guarantee that it will be invoked3259** when there is lock contention. ^If SQLite determines that invoking the busy3260** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]3261** to the application instead of invoking the3262** busy handler.3263** Consider a scenario where one process is holding a read lock that3264** it is trying to promote to a reserved lock and3265** a second process is holding a reserved lock that it is trying3266** to promote to an exclusive lock.  The first process cannot proceed3267** because it is blocked by the second and the second process cannot3268** proceed because it is blocked by the first.  If both processes3269** invoke the busy handlers, neither will make any progress.  Therefore,3270** SQLite returns [SQLITE_BUSY] for the first process, hoping that this3271** will induce the first process to release its read lock and allow3272** the second process to proceed.3273**3274** ^The default busy callback is NULL.3275**3276** ^(There can only be a single busy handler defined for each3277** [database connection].  Setting a new busy handler clears any3278** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]3279** or evaluating [PRAGMA busy_timeout=N] will change the3280** busy handler and thus clear any previously set busy handler.3281**3282** The busy callback should not take any actions which modify the3283** database connection that invoked the busy handler.  In other words,3284** the busy handler is not reentrant.  Any such actions3285** result in undefined behavior.3286**3287** A busy handler must not close the database connection3288** or [prepared statement] that invoked the busy handler.3289*/3290SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);32913292/*3293** CAPI3REF: Set A Busy Timeout3294** METHOD: sqlite33295**3296** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps3297** for a specified amount of time when a table is locked.  ^The handler3298** will sleep multiple times until at least "ms" milliseconds of sleeping3299** have accumulated.  ^After at least "ms" milliseconds of sleeping,3300** the handler returns 0 which causes [sqlite3_step()] to return3301** [SQLITE_BUSY].3302**3303** ^Calling this routine with an argument less than or equal to zero3304** turns off all busy handlers.3305**3306** ^(There can only be a single busy handler for a particular3307** [database connection] at any given moment.  If another busy handler3308** was defined  (using [sqlite3_busy_handler()]) prior to calling3309** this routine, that other busy handler is cleared.)^3310**3311** See also:  [PRAGMA busy_timeout]3312*/3313SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);33143315/*3316** CAPI3REF: Convenience Routines For Running Queries3317** METHOD: sqlite33318**3319** This is a legacy interface that is preserved for backwards compatibility.3320** Use of this interface is not recommended.3321**3322** Definition: A <b>result table</b> is memory data structure created by the3323** [sqlite3_get_table()] interface.  A result table records the3324** complete query results from one or more queries.3325**3326** The table conceptually has a number of rows and columns.  But3327** these numbers are not part of the result table itself.  These3328** numbers are obtained separately.  Let N be the number of rows3329** and M be the number of columns.3330**3331** A result table is an array of pointers to zero-terminated UTF-8 strings.3332** There are (N+1)*M elements in the array.  The first M pointers point3333** to zero-terminated strings that  contain the names of the columns.3334** The remaining entries all point to query results.  NULL values result3335** in NULL pointers.  All other values are in their UTF-8 zero-terminated3336** string representation as returned by [sqlite3_column_text()].3337**3338** A result table might consist of one or more memory allocations.3339** It is not safe to pass a result table directly to [sqlite3_free()].3340** A result table should be deallocated using [sqlite3_free_table()].3341**3342** ^(As an example of the result table format, suppose a query result3343** is as follows:3344**3345** <blockquote><pre>3346**        Name        | Age3347**        -----------------------3348**        Alice       | 433349**        Bob         | 283350**        Cindy       | 213351** </pre></blockquote>3352**3353** There are two columns (M==2) and three rows (N==3).  Thus the3354** result table has 8 entries.  Suppose the result table is stored3355** in an array named azResult.  Then azResult holds this content:3356**3357** <blockquote><pre>3358**        azResult&#91;0] = "Name";3359**        azResult&#91;1] = "Age";3360**        azResult&#91;2] = "Alice";3361**        azResult&#91;3] = "43";3362**        azResult&#91;4] = "Bob";3363**        azResult&#91;5] = "28";3364**        azResult&#91;6] = "Cindy";3365**        azResult&#91;7] = "21";3366** </pre></blockquote>)^3367**3368** ^The sqlite3_get_table() function evaluates one or more3369** semicolon-separated SQL statements in the zero-terminated UTF-83370** string of its 2nd parameter and returns a result table to the3371** pointer given in its 3rd parameter.3372**3373** After the application has finished with the result from sqlite3_get_table(),3374** it must pass the result table pointer to sqlite3_free_table() in order to3375** release the memory that was malloced.  Because of the way the3376** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling3377** function must not try to call [sqlite3_free()] directly.  Only3378** [sqlite3_free_table()] is able to release the memory properly and safely.3379**3380** The sqlite3_get_table() interface is implemented as a wrapper around3381** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access3382** to any internal data structures of SQLite.  It uses only the public3383** interface defined here.  As a consequence, errors that occur in the3384** wrapper layer outside of the internal [sqlite3_exec()] call are not3385** reflected in subsequent calls to [sqlite3_errcode()] or3386** [sqlite3_errmsg()].3387*/3388SQLITE_API int sqlite3_get_table(3389  sqlite3 *db,          /* An open database */3390  const char *zSql,     /* SQL to be evaluated */3391  char ***pazResult,    /* Results of the query */3392  int *pnRow,           /* Number of result rows written here */3393  int *pnColumn,        /* Number of result columns written here */3394  char **pzErrmsg       /* Error msg written here */3395);3396SQLITE_API void sqlite3_free_table(char **result);33973398/*3399** CAPI3REF: Formatted String Printing Functions3400**3401** These routines are work-alikes of the "printf()" family of functions3402** from the standard C library.3403** These routines understand most of the common formatting options from3404** the standard library printf()3405** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).3406** See the [built-in printf()] documentation for details.3407**3408** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their3409** results into memory obtained from [sqlite3_malloc64()].3410** The strings returned by these two routines should be3411** released by [sqlite3_free()].  ^Both routines return a3412** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough3413** memory to hold the resulting string.3414**3415** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from3416** the standard C library.  The result is written into the3417** buffer supplied as the second parameter whose size is given by3418** the first parameter. Note that the order of the3419** first two parameters is reversed from snprintf().)^  This is an3420** historical accident that cannot be fixed without breaking3421** backwards compatibility.  ^(Note also that sqlite3_snprintf()3422** returns a pointer to its buffer instead of the number of3423** characters actually written into the buffer.)^  We admit that3424** the number of characters written would be a more useful return3425** value but we cannot change the implementation of sqlite3_snprintf()3426** now without breaking compatibility.3427**3428** ^As long as the buffer size is greater than zero, sqlite3_snprintf()3429** guarantees that the buffer is always zero-terminated.  ^The first3430** parameter "n" is the total size of the buffer, including space for3431** the zero terminator.  So the longest string that can be completely3432** written will be n-1 characters.3433**3434** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().3435**3436** See also:  [built-in printf()], [printf() SQL function]3437*/3438SQLITE_API char *sqlite3_mprintf(const char*,...);3439SQLITE_API char *sqlite3_vmprintf(const char*, va_list);3440SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);3441SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);34423443/*3444** CAPI3REF: Memory Allocation Subsystem3445**3446** The SQLite core uses these three routines for all of its own3447** internal memory allocation needs. "Core" in the previous sentence3448** does not include operating-system specific [VFS] implementation.  The3449** Windows VFS uses native malloc() and free() for some operations.3450**3451** ^The sqlite3_malloc() routine returns a pointer to a block3452** of memory at least N bytes in length, where N is the parameter.3453** ^If sqlite3_malloc() is unable to obtain sufficient free3454** memory, it returns a NULL pointer.  ^If the parameter N to3455** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns3456** a NULL pointer.3457**3458** ^The sqlite3_malloc64(N) routine works just like3459** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead3460** of a signed 32-bit integer.3461**3462** ^Calling sqlite3_free() with a pointer previously returned3463** by sqlite3_malloc() or sqlite3_realloc() releases that memory so3464** that it might be reused.  ^The sqlite3_free() routine is3465** a no-op if is called with a NULL pointer.  Passing a NULL pointer3466** to sqlite3_free() is harmless.  After being freed, memory3467** should neither be read nor written.  Even reading previously freed3468** memory might result in a segmentation fault or other severe error.3469** Memory corruption, a segmentation fault, or other severe error3470** might result if sqlite3_free() is called with a non-NULL pointer that3471** was not obtained from sqlite3_malloc() or sqlite3_realloc().3472**3473** ^The sqlite3_realloc(X,N) interface attempts to resize a3474** prior memory allocation X to be at least N bytes.3475** ^If the X parameter to sqlite3_realloc(X,N)3476** is a NULL pointer then its behavior is identical to calling3477** sqlite3_malloc(N).3478** ^If the N parameter to sqlite3_realloc(X,N) is zero or3479** negative then the behavior is exactly the same as calling3480** sqlite3_free(X).3481** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation3482** of at least N bytes in size or NULL if insufficient memory is available.3483** ^If M is the size of the prior allocation, then min(N,M) bytes3484** of the prior allocation are copied into the beginning of buffer returned3485** by sqlite3_realloc(X,N) and the prior allocation is freed.3486** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the3487** prior allocation is not freed.3488**3489** ^The sqlite3_realloc64(X,N) interfaces works the same as3490** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead3491** of a 32-bit signed integer.3492**3493** ^If X is a memory allocation previously obtained from sqlite3_malloc(),3494** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then3495** sqlite3_msize(X) returns the size of that memory allocation in bytes.3496** ^The value returned by sqlite3_msize(X) might be larger than the number3497** of bytes requested when X was allocated.  ^If X is a NULL pointer then3498** sqlite3_msize(X) returns zero.  If X points to something that is not3499** the beginning of memory allocation, or if it points to a formerly3500** valid memory allocation that has now been freed, then the behavior3501** of sqlite3_msize(X) is undefined and possibly harmful.3502**3503** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),3504** sqlite3_malloc64(), and sqlite3_realloc64()3505** is always aligned to at least an 8 byte boundary, or to a3506** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time3507** option is used.3508**3509** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]3510** must be either NULL or else pointers obtained from a prior3511** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have3512** not yet been released.3513**3514** The application must not read or write any part of3515** a block of memory after it has been released using3516** [sqlite3_free()] or [sqlite3_realloc()].3517*/3518SQLITE_API void *sqlite3_malloc(int);3519SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);3520SQLITE_API void *sqlite3_realloc(void*, int);3521SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);3522SQLITE_API void sqlite3_free(void*);3523SQLITE_API sqlite3_uint64 sqlite3_msize(void*);35243525/*3526** CAPI3REF: Memory Allocator Statistics3527**3528** SQLite provides these two interfaces for reporting on the status3529** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]3530** routines, which form the built-in memory allocation subsystem.3531**3532** ^The [sqlite3_memory_used()] routine returns the number of bytes3533** of memory currently outstanding (malloced but not freed).3534** ^The [sqlite3_memory_highwater()] routine returns the maximum3535** value of [sqlite3_memory_used()] since the high-water mark3536** was last reset.  ^The values returned by [sqlite3_memory_used()] and3537** [sqlite3_memory_highwater()] include any overhead3538** added by SQLite in its implementation of [sqlite3_malloc()],3539** but not overhead added by the any underlying system library3540** routines that [sqlite3_malloc()] may call.3541**3542** ^The memory high-water mark is reset to the current value of3543** [sqlite3_memory_used()] if and only if the parameter to3544** [sqlite3_memory_highwater()] is true.  ^The value returned3545** by [sqlite3_memory_highwater(1)] is the high-water mark3546** prior to the reset.3547*/3548SQLITE_API sqlite3_int64 sqlite3_memory_used(void);3549SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);35503551/*3552** CAPI3REF: Pseudo-Random Number Generator3553**3554** SQLite contains a high-quality pseudo-random number generator (PRNG) used to3555** select random [ROWID | ROWIDs] when inserting new records into a table that3556** already uses the largest possible [ROWID].  The PRNG is also used for3557** the built-in random() and randomblob() SQL functions.  This interface allows3558** applications to access the same PRNG for other purposes.3559**3560** ^A call to this routine stores N bytes of randomness into buffer P.3561** ^The P parameter can be a NULL pointer.3562**3563** ^If this routine has not been previously called or if the previous3564** call had N less than one or a NULL pointer for P, then the PRNG is3565** seeded using randomness obtained from the xRandomness method of3566** the default [sqlite3_vfs] object.3567** ^If the previous call to this routine had an N of 1 or more and a3568** non-NULL P then the pseudo-randomness is generated3569** internally and without recourse to the [sqlite3_vfs] xRandomness3570** method.3571*/3572SQLITE_API void sqlite3_randomness(int N, void *P);35733574/*3575** CAPI3REF: Compile-Time Authorization Callbacks3576** METHOD: sqlite33577** KEYWORDS: {authorizer callback}3578**3579** ^This routine registers an authorizer callback with a particular3580** [database connection], supplied in the first argument.3581** ^The authorizer callback is invoked as SQL statements are being compiled3582** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],3583** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],3584** and [sqlite3_prepare16_v3()].  ^At various3585** points during the compilation process, as logic is being created3586** to perform various actions, the authorizer callback is invoked to3587** see if those actions are allowed.  ^The authorizer callback should3588** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the3589** specific action but allow the SQL statement to continue to be3590** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be3591** rejected with an error.  ^If the authorizer callback returns3592** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]3593** then the [sqlite3_prepare_v2()] or equivalent call that triggered3594** the authorizer will fail with an error message.3595**3596** When the callback returns [SQLITE_OK], that means the operation3597** requested is ok.  ^When the callback returns [SQLITE_DENY], the3598** [sqlite3_prepare_v2()] or equivalent call that triggered the3599** authorizer will fail with an error message explaining that3600** access is denied.3601**3602** ^The first parameter to the authorizer callback is a copy of the third3603** parameter to the sqlite3_set_authorizer() interface. ^The second parameter3604** to the callback is an integer [SQLITE_COPY | action code] that specifies3605** the particular action to be authorized. ^The third through sixth parameters3606** to the callback are either NULL pointers or zero-terminated strings3607** that contain additional details about the action to be authorized.3608** Applications must always be prepared to encounter a NULL pointer in any3609** of the third through the sixth parameters of the authorization callback.3610**3611** ^If the action code is [SQLITE_READ]3612** and the callback returns [SQLITE_IGNORE] then the3613** [prepared statement] statement is constructed to substitute3614** a NULL value in place of the table column that would have3615** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]3616** return can be used to deny an untrusted user access to individual3617** columns of a table.3618** ^When a table is referenced by a [SELECT] but no column values are3619** extracted from that table (for example in a query like3620** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback3621** is invoked once for that table with a column name that is an empty string.3622** ^If the action code is [SQLITE_DELETE] and the callback returns3623** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the3624** [truncate optimization] is disabled and all rows are deleted individually.3625**3626** An authorizer is used when [sqlite3_prepare | preparing]3627** SQL statements from an untrusted source, to ensure that the SQL statements3628** do not try to access data they are not allowed to see, or that they do not3629** try to execute malicious statements that damage the database.  For3630** example, an application may allow a user to enter arbitrary3631** SQL queries for evaluation by a database.  But the application does3632** not want the user to be able to make arbitrary changes to the3633** database.  An authorizer could then be put in place while the3634** user-entered SQL is being [sqlite3_prepare | prepared] that3635** disallows everything except [SELECT] statements.3636**3637** Applications that need to process SQL from untrusted sources3638** might also consider lowering resource limits using [sqlite3_limit()]3639** and limiting database size using the [max_page_count] [PRAGMA]3640** in addition to using an authorizer.3641**3642** ^(Only a single authorizer can be in place on a database connection3643** at a time.  Each call to sqlite3_set_authorizer overrides the3644** previous call.)^  ^Disable the authorizer by installing a NULL callback.3645** The authorizer is disabled by default.3646**3647** The authorizer callback must not do anything that will modify3648** the database connection that invoked the authorizer callback.3649** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their3650** database connections for the meaning of "modify" in this paragraph.3651**3652** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the3653** statement might be re-prepared during [sqlite3_step()] due to a3654** schema change.  Hence, the application should ensure that the3655** correct authorizer callback remains in place during the [sqlite3_step()].3656**3657** ^Note that the authorizer callback is invoked only during3658** [sqlite3_prepare()] or its variants.  Authorization is not3659** performed during statement evaluation in [sqlite3_step()], unless3660** as stated in the previous paragraph, sqlite3_step() invokes3661** sqlite3_prepare_v2() to reprepare a statement after a schema change.3662*/3663SQLITE_API int sqlite3_set_authorizer(3664  sqlite3*,3665  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),3666  void *pUserData3667);36683669/*3670** CAPI3REF: Authorizer Return Codes3671**3672** The [sqlite3_set_authorizer | authorizer callback function] must3673** return either [SQLITE_OK] or one of these two constants in order3674** to signal SQLite whether or not the action is permitted.  See the3675** [sqlite3_set_authorizer | authorizer documentation] for additional3676** information.3677**3678** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]3679** returned from the [sqlite3_vtab_on_conflict()] interface.3680*/3681#define SQLITE_DENY   1   /* Abort the SQL statement with an error */3682#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */36833684/*3685** CAPI3REF: Authorizer Action Codes3686**3687** The [sqlite3_set_authorizer()] interface registers a callback function3688** that is invoked to authorize certain SQL statement actions.  The3689** second parameter to the callback is an integer code that specifies3690** what action is being authorized.  These are the integer action codes that3691** the authorizer callback may be passed.3692**3693** These action code values signify what kind of operation is to be3694** authorized.  The 3rd and 4th parameters to the authorization3695** callback function will be parameters or NULL depending on which of these3696** codes is used as the second parameter.  ^(The 5th parameter to the3697** authorizer callback is the name of the database ("main", "temp",3698** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback3699** is the name of the inner-most trigger or view that is responsible for3700** the access attempt or NULL if this access attempt is directly from3701** top-level SQL code.3702*/3703/******************************************* 3rd ************ 4th ***********/3704#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */3705#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */3706#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */3707#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */3708#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */3709#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */3710#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */3711#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */3712#define SQLITE_DELETE                9   /* Table Name      NULL            */3713#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */3714#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */3715#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */3716#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */3717#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */3718#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */3719#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */3720#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */3721#define SQLITE_INSERT               18   /* Table Name      NULL            */3722#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */3723#define SQLITE_READ                 20   /* Table Name      Column Name     */3724#define SQLITE_SELECT               21   /* NULL            NULL            */3725#define SQLITE_TRANSACTION          22   /* Operation       NULL            */3726#define SQLITE_UPDATE               23   /* Table Name      Column Name     */3727#define SQLITE_ATTACH               24   /* Filename        NULL            */3728#define SQLITE_DETACH               25   /* Database Name   NULL            */3729#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */3730#define SQLITE_REINDEX              27   /* Index Name      NULL            */3731#define SQLITE_ANALYZE              28   /* Table Name      NULL            */3732#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */3733#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */3734#define SQLITE_FUNCTION             31   /* NULL            Function Name   */3735#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */3736#define SQLITE_COPY                  0   /* No longer used */3737#define SQLITE_RECURSIVE            33   /* NULL            NULL            */37383739/*3740** CAPI3REF: Deprecated Tracing And Profiling Functions3741** DEPRECATED3742**3743** These routines are deprecated. Use the [sqlite3_trace_v2()] interface3744** instead of the routines described here.3745**3746** These routines register callback functions that can be used for3747** tracing and profiling the execution of SQL statements.3748**3749** ^The callback function registered by sqlite3_trace() is invoked at3750** various times when an SQL statement is being run by [sqlite3_step()].3751** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the3752** SQL statement text as the statement first begins executing.3753** ^(Additional sqlite3_trace() callbacks might occur3754** as each triggered subprogram is entered.  The callbacks for triggers3755** contain a UTF-8 SQL comment that identifies the trigger.)^3756**3757** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit3758** the length of [bound parameter] expansion in the output of sqlite3_trace().3759**3760** ^The callback function registered by sqlite3_profile() is invoked3761** as each SQL statement finishes.  ^The profile callback contains3762** the original statement text and an estimate of wall-clock time3763** of how long that statement took to run.  ^The profile callback3764** time is in units of nanoseconds, however the current implementation3765** is only capable of millisecond resolution so the six least significant3766** digits in the time are meaningless.  Future versions of SQLite3767** might provide greater resolution on the profiler callback.  Invoking3768** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the3769** profile callback.3770*/3771SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,3772   void(*xTrace)(void*,const char*), void*);3773SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,3774   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);37753776/*3777** CAPI3REF: SQL Trace Event Codes3778** KEYWORDS: SQLITE_TRACE3779**3780** These constants identify classes of events that can be monitored3781** using the [sqlite3_trace_v2()] tracing logic.  The M argument3782** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of3783** the following constants.  ^The first argument to the trace callback3784** is one of the following constants.3785**3786** New tracing constants may be added in future releases.3787**3788** ^A trace callback has four arguments: xCallback(T,C,P,X).3789** ^The T argument is one of the integer type codes above.3790** ^The C argument is a copy of the context pointer passed in as the3791** fourth argument to [sqlite3_trace_v2()].3792** The P and X arguments are pointers whose meanings depend on T.3793**3794** <dl>3795** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>3796** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement3797** first begins running and possibly at other times during the3798** execution of the prepared statement, such as at the start of each3799** trigger subprogram. ^The P argument is a pointer to the3800** [prepared statement]. ^The X argument is a pointer to a string which3801** is the unexpanded SQL text of the prepared statement or an SQL comment3802** that indicates the invocation of a trigger.  ^The callback can compute3803** the same text that would have been returned by the legacy [sqlite3_trace()]3804** interface by using the X argument when X begins with "--" and invoking3805** [sqlite3_expanded_sql(P)] otherwise.3806**3807** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>3808** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same3809** information as is provided by the [sqlite3_profile()] callback.3810** ^The P argument is a pointer to the [prepared statement] and the3811** X argument points to a 64-bit integer which is approximately3812** the number of nanoseconds that the prepared statement took to run.3813** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.3814**3815** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>3816** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared3817** statement generates a single row of result.3818** ^The P argument is a pointer to the [prepared statement] and the3819** X argument is unused.3820**3821** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>3822** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database3823** connection closes.3824** ^The P argument is a pointer to the [database connection] object3825** and the X argument is unused.3826** </dl>3827*/3828#define SQLITE_TRACE_STMT       0x013829#define SQLITE_TRACE_PROFILE    0x023830#define SQLITE_TRACE_ROW        0x043831#define SQLITE_TRACE_CLOSE      0x0838323833/*3834** CAPI3REF: SQL Trace Hook3835** METHOD: sqlite33836**3837** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback3838** function X against [database connection] D, using property mask M3839** and context pointer P.  ^If the X callback is3840** NULL or if the M mask is zero, then tracing is disabled.  The3841** M argument should be the bitwise OR-ed combination of3842** zero or more [SQLITE_TRACE] constants.3843**3844** ^Each call to either sqlite3_trace(D,X,P) or sqlite3_trace_v2(D,M,X,P)3845** overrides (cancels) all prior calls to sqlite3_trace(D,X,P) or3846** sqlite3_trace_v2(D,M,X,P) for the [database connection] D.  Each3847** database connection may have at most one trace callback.3848**3849** ^The X callback is invoked whenever any of the events identified by3850** mask M occur.  ^The integer return value from the callback is currently3851** ignored, though this may change in future releases.  Callback3852** implementations should return zero to ensure future compatibility.3853**3854** ^A trace callback is invoked with four arguments: callback(T,C,P,X).3855** ^The T argument is one of the [SQLITE_TRACE]3856** constants to indicate why the callback was invoked.3857** ^The C argument is a copy of the context pointer.3858** The P and X arguments are pointers whose meanings depend on T.3859**3860** The sqlite3_trace_v2() interface is intended to replace the legacy3861** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which3862** are deprecated.3863*/3864SQLITE_API int sqlite3_trace_v2(3865  sqlite3*,3866  unsigned uMask,3867  int(*xCallback)(unsigned,void*,void*,void*),3868  void *pCtx3869);38703871/*3872** CAPI3REF: Query Progress Callbacks3873** METHOD: sqlite33874**3875** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback3876** function X to be invoked periodically during long running calls to3877** [sqlite3_step()] and [sqlite3_prepare()] and similar for3878** database connection D.  An example use for this3879** interface is to keep a GUI updated during a large query.3880**3881** ^The parameter P is passed through as the only parameter to the3882** callback function X.  ^The parameter N is the approximate number of3883** [virtual machine instructions] that are evaluated between successive3884** invocations of the callback X.  ^If N is less than one then the progress3885** handler is disabled.3886**3887** ^Only a single progress handler may be defined at one time per3888** [database connection]; setting a new progress handler cancels the3889** old one.  ^Setting parameter X to NULL disables the progress handler.3890** ^The progress handler is also disabled by setting N to a value less3891** than 1.3892**3893** ^If the progress callback returns non-zero, the operation is3894** interrupted.  This feature can be used to implement a3895** "Cancel" button on a GUI progress dialog box.3896**3897** The progress handler callback must not do anything that will modify3898** the database connection that invoked the progress handler.3899** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their3900** database connections for the meaning of "modify" in this paragraph.3901**3902** The progress handler callback would originally only be invoked from the3903** bytecode engine.  It still might be invoked during [sqlite3_prepare()]3904** and similar because those routines might force a reparse of the schema3905** which involves running the bytecode engine.  However, beginning with3906** SQLite version 3.41.0, the progress handler callback might also be3907** invoked directly from [sqlite3_prepare()] while analyzing and generating3908** code for complex queries.3909*/3910SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);39113912/*3913** CAPI3REF: Opening A New Database Connection3914** CONSTRUCTOR: sqlite33915**3916** ^These routines open an SQLite database file as specified by the3917** filename argument. ^The filename argument is interpreted as UTF-8 for3918** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte3919** order for sqlite3_open16(). ^(A [database connection] handle is usually3920** returned in *ppDb, even if an error occurs.  The only exception is that3921** if SQLite is unable to allocate memory to hold the [sqlite3] object,3922** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]3923** object.)^ ^(If the database is opened (and/or created) successfully, then3924** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The3925** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain3926** an English language description of the error following a failure of any3927** of the sqlite3_open() routines.3928**3929** ^The default encoding will be UTF-8 for databases created using3930** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases3931** created using sqlite3_open16() will be UTF-16 in the native byte order.3932**3933** Whether or not an error occurs when it is opened, resources3934** associated with the [database connection] handle should be released by3935** passing it to [sqlite3_close()] when it is no longer required.3936**3937** The sqlite3_open_v2() interface works like sqlite3_open()3938** except that it accepts two additional parameters for additional control3939** over the new database connection.  ^(The flags parameter to3940** sqlite3_open_v2() must include, at a minimum, one of the following3941** three flag combinations:)^3942**3943** <dl>3944** ^(<dt>[SQLITE_OPEN_READONLY]</dt>3945** <dd>The database is opened in read-only mode.  If the database does3946** not already exist, an error is returned.</dd>)^3947**3948** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>3949** <dd>The database is opened for reading and writing if possible, or3950** reading only if the file is write protected by the operating3951** system.  In either case the database must already exist, otherwise3952** an error is returned.  For historical reasons, if opening in3953** read-write mode fails due to OS-level permissions, an attempt is3954** made to open it in read-only mode. [sqlite3_db_readonly()] can be3955** used to determine whether the database is actually3956** read-write.</dd>)^3957**3958** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>3959** <dd>The database is opened for reading and writing, and is created if3960** it does not already exist. This is the behavior that is always used for3961** sqlite3_open() and sqlite3_open16().</dd>)^3962** </dl>3963**3964** In addition to the required flags, the following optional flags are3965** also supported:3966**3967** <dl>3968** ^(<dt>[SQLITE_OPEN_URI]</dt>3969** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^3970**3971** ^(<dt>[SQLITE_OPEN_MEMORY]</dt>3972** <dd>The database will be opened as an in-memory database.  The database3973** is named by the "filename" argument for the purposes of cache-sharing,3974** if shared cache mode is enabled, but the "filename" is otherwise ignored.3975** </dd>)^3976**3977** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt>3978** <dd>The new database connection will use the "multi-thread"3979** [threading mode].)^  This means that separate threads are allowed3980** to use SQLite at the same time, as long as each thread is using3981** a different [database connection].3982**3983** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt>3984** <dd>The new database connection will use the "serialized"3985** [threading mode].)^  This means the multiple threads can safely3986** attempt to use the same database connection at the same time.3987** (Mutexes will block any actual concurrency, but in this mode3988** there is no harm in trying.)3989**3990** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>3991** <dd>The database is opened [shared cache] enabled, overriding3992** the default shared cache setting provided by3993** [sqlite3_enable_shared_cache()].)^3994** The [use of shared cache mode is discouraged] and hence shared cache3995** capabilities may be omitted from many builds of SQLite.  In such cases,3996** this option is a no-op.3997**3998** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>3999** <dd>The database is opened [shared cache] disabled, overriding4000** the default shared cache setting provided by4001** [sqlite3_enable_shared_cache()].)^4002**4003** [[OPEN_EXRESCODE]] ^(<dt>[SQLITE_OPEN_EXRESCODE]</dt>4004** <dd>The database connection comes up in "extended result code mode".4005** In other words, the database behaves as if4006** [sqlite3_extended_result_codes(db,1)] were called on the database4007** connection as soon as the connection is created. In addition to setting4008** the extended result code mode, this flag also causes [sqlite3_open_v2()]4009** to return an extended result code.</dd>4010**4011** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>4012** <dd>The database filename is not allowed to contain a symbolic link</dd>4013** </dl>)^4014**4015** If the 3rd parameter to sqlite3_open_v2() is not one of the4016** required combinations shown above optionally combined with other4017** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]4018** then the behavior is undefined.  Historic versions of SQLite4019** have silently ignored surplus bits in the flags parameter to4020** sqlite3_open_v2(), however that behavior might not be carried through4021** into future versions of SQLite and so applications should not rely4022** upon it.  Note in particular that the SQLITE_OPEN_EXCLUSIVE flag is a no-op4023** for sqlite3_open_v2().  The SQLITE_OPEN_EXCLUSIVE does *not* cause4024** the open to fail if the database already exists.  The SQLITE_OPEN_EXCLUSIVE4025** flag is intended for use by the [sqlite3_vfs|VFS interface] only, and not4026** by sqlite3_open_v2().4027**4028** ^The fourth parameter to sqlite3_open_v2() is the name of the4029** [sqlite3_vfs] object that defines the operating system interface that4030** the new database connection should use.  ^If the fourth parameter is4031** a NULL pointer then the default [sqlite3_vfs] object is used.4032**4033** ^If the filename is ":memory:", then a private, temporary in-memory database4034** is created for the connection.  ^This in-memory database will vanish when4035** the database connection is closed.  Future versions of SQLite might4036** make use of additional special filenames that begin with the ":" character.4037** It is recommended that when a database filename actually does begin with4038** a ":" character you should prefix the filename with a pathname such as4039** "./" to avoid ambiguity.4040**4041** ^If the filename is an empty string, then a private, temporary4042** on-disk database will be created.  ^This private database will be4043** automatically deleted as soon as the database connection is closed.4044**4045** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>4046**4047** ^If [URI filename] interpretation is enabled, and the filename argument4048** begins with "file:", then the filename is interpreted as a URI. ^URI4049** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is4050** set in the third argument to sqlite3_open_v2(), or if it has4051** been enabled globally using the [SQLITE_CONFIG_URI] option with the4052** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.4053** URI filename interpretation is turned off4054** by default, but future releases of SQLite might enable URI filename4055** interpretation by default.  See "[URI filenames]" for additional4056** information.4057**4058** URI filenames are parsed according to RFC 3986. ^If the URI contains an4059** authority, then it must be either an empty string or the string4060** "localhost". ^If the authority is not an empty string or "localhost", an4061** error is returned to the caller. ^The fragment component of a URI, if4062** present, is ignored.4063**4064** ^SQLite uses the path component of the URI as the name of the disk file4065** which contains the database. ^If the path begins with a '/' character,4066** then it is interpreted as an absolute path. ^If the path does not begin4067** with a '/' (meaning that the authority section is omitted from the URI)4068** then the path is interpreted as a relative path.4069** ^(On windows, the first component of an absolute path4070** is a drive specification (e.g. "C:").)^4071**4072** [[core URI query parameters]]4073** The query component of a URI may contain parameters that are interpreted4074** either by SQLite itself, or by a [VFS | custom VFS implementation].4075** SQLite and its built-in [VFSes] interpret the4076** following query parameters:4077**4078** <ul>4079**   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of4080**     a VFS object that provides the operating system interface that should4081**     be used to access the database file on disk. ^If this option is set to4082**     an empty string the default VFS object is used. ^Specifying an unknown4083**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is4084**     present, then the VFS specified by the option takes precedence over4085**     the value passed as the fourth parameter to sqlite3_open_v2().4086**4087**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",4088**     "rwc", or "memory". Attempting to set it to any other value is4089**     an error)^.4090**     ^If "ro" is specified, then the database is opened for read-only4091**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the4092**     third argument to sqlite3_open_v2(). ^If the mode option is set to4093**     "rw", then the database is opened for read-write (but not create)4094**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had4095**     been set. ^Value "rwc" is equivalent to setting both4096**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is4097**     set to "memory" then a pure [in-memory database] that never reads4098**     or writes from disk is used. ^It is an error to specify a value for4099**     the mode parameter that is less restrictive than that specified by4100**     the flags passed in the third parameter to sqlite3_open_v2().4101**4102**   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or4103**     "private". ^Setting it to "shared" is equivalent to setting the4104**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to4105**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is4106**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.4107**     ^If sqlite3_open_v2() is used and the "cache" parameter is present in4108**     a URI filename, its value overrides any behavior requested by setting4109**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.4110**4111**  <li> <b>psow</b>: ^The psow parameter indicates whether or not the4112**     [powersafe overwrite] property does or does not apply to the4113**     storage media on which the database file resides.4114**4115**  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter4116**     which if set disables file locking in rollback journal modes.  This4117**     is useful for accessing a database on a filesystem that does not4118**     support locking.  Caution:  Database corruption might result if two4119**     or more processes write to the same database and any one of those4120**     processes uses nolock=1.4121**4122**  <li> <b>immutable</b>: ^The immutable parameter is a boolean query4123**     parameter that indicates that the database file is stored on4124**     read-only media.  ^When immutable is set, SQLite assumes that the4125**     database file cannot be changed, even by a process with higher4126**     privilege, and so the database is opened read-only and all locking4127**     and change detection is disabled.  Caution: Setting the immutable4128**     property on a database file that does in fact change can result4129**     in incorrect query results and/or [SQLITE_CORRUPT] errors.4130**     See also: [SQLITE_IOCAP_IMMUTABLE].4131**4132** </ul>4133**4134** ^Specifying an unknown parameter in the query component of a URI is not an4135** error.  Future versions of SQLite might understand additional query4136** parameters.  See "[query parameters with special meaning to SQLite]" for4137** additional information.4138**4139** [[URI filename examples]] <h3>URI filename examples</h3>4140**4141** <table border="1" align=center cellpadding=5>4142** <tr><th> URI filenames <th> Results4143** <tr><td> file:data.db <td>4144**          Open the file "data.db" in the current directory.4145** <tr><td> file:/home/fred/data.db<br>4146**          file:///home/fred/data.db <br>4147**          file://localhost/home/fred/data.db <br> <td>4148**          Open the database file "/home/fred/data.db".4149** <tr><td> file://darkstar/home/fred/data.db <td>4150**          An error. "darkstar" is not a recognized authority.4151** <tr><td style="white-space:nowrap">4152**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db4153**     <td> Windows only: Open the file "data.db" on fred's desktop on drive4154**          C:. Note that the %20 escaping in this example is not strictly4155**          necessary - space characters can be used literally4156**          in URI filenames.4157** <tr><td> file:data.db?mode=ro&cache=private <td>4158**          Open file "data.db" in the current directory for read-only access.4159**          Regardless of whether or not shared-cache mode is enabled by4160**          default, use a private cache.4161** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>4162**          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"4163**          that uses dot-files in place of posix advisory locking.4164** <tr><td> file:data.db?mode=readonly <td>4165**          An error. "readonly" is not a valid option for the "mode" parameter.4166**          Use "ro" instead:  "file:data.db?mode=ro".4167** </table>4168**4169** ^URI hexadecimal escape sequences (%HH) are supported within the path and4170** query components of a URI. A hexadecimal escape sequence consists of a4171** percent sign - "%" - followed by exactly two hexadecimal digits4172** specifying an octet value. ^Before the path or query components of a4173** URI filename are interpreted, they are encoded using UTF-8 and all4174** hexadecimal escape sequences replaced by a single byte containing the4175** corresponding octet. If this process generates an invalid UTF-8 encoding,4176** the results are undefined.4177**4178** <b>Note to Windows users:</b>  The encoding used for the filename argument4179** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever4180** codepage is currently defined.  Filenames containing international4181** characters must be converted to UTF-8 prior to passing them into4182** sqlite3_open() or sqlite3_open_v2().4183**4184** <b>Note to Windows Runtime users:</b>  The temporary directory must be set4185** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various4186** features that require the use of temporary files may fail.4187**4188** See also: [sqlite3_temp_directory]4189*/4190SQLITE_API int sqlite3_open(4191  const char *filename,   /* Database filename (UTF-8) */4192  sqlite3 **ppDb          /* OUT: SQLite db handle */4193);4194SQLITE_API int sqlite3_open16(4195  const void *filename,   /* Database filename (UTF-16) */4196  sqlite3 **ppDb          /* OUT: SQLite db handle */4197);4198SQLITE_API int sqlite3_open_v2(4199  const char *filename,   /* Database filename (UTF-8) */4200  sqlite3 **ppDb,         /* OUT: SQLite db handle */4201  int flags,              /* Flags */4202  const char *zVfs        /* Name of VFS module to use */4203);42044205/*4206** CAPI3REF: Obtain Values For URI Parameters4207**4208** These are utility routines, useful to [VFS|custom VFS implementations],4209** that check if a database file was a URI that contained a specific query4210** parameter, and if so obtains the value of that query parameter.4211**4212** The first parameter to these interfaces (hereafter referred to4213** as F) must be one of:4214** <ul>4215** <li> A database filename pointer created by the SQLite core and4216** passed into the xOpen() method of a VFS implementation, or4217** <li> A filename obtained from [sqlite3_db_filename()], or4218** <li> A new filename constructed using [sqlite3_create_filename()].4219** </ul>4220** If the F parameter is not one of the above, then the behavior is4221** undefined and probably undesirable.  Older versions of SQLite were4222** more tolerant of invalid F parameters than newer versions.4223**4224** If F is a suitable filename (as described in the previous paragraph)4225** and if P is the name of the query parameter, then4226** sqlite3_uri_parameter(F,P) returns the value of the P4227** parameter if it exists or a NULL pointer if P does not appear as a4228** query parameter on F.  If P is a query parameter of F and it4229** has no explicit value, then sqlite3_uri_parameter(F,P) returns4230** a pointer to an empty string.4231**4232** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean4233** parameter and returns true (1) or false (0) according to the value4234** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the4235** value of query parameter P is one of "yes", "true", or "on" in any4236** case or if the value begins with a non-zero number.  The4237** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of4238** query parameter P is one of "no", "false", or "off" in any case or4239** if the value begins with a numeric zero.  If P is not a query4240** parameter on F or if the value of P does not match any of the4241** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).4242**4243** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a4244** 64-bit signed integer and returns that integer, or D if P does not4245** exist.  If the value of P is something other than an integer, then4246** zero is returned.4247**4248** The sqlite3_uri_key(F,N) returns a pointer to the name (not4249** the value) of the N-th query parameter for filename F, or a NULL4250** pointer if N is less than zero or greater than the number of query4251** parameters minus 1.  The N value is zero-based so N should be 0 to obtain4252** the name of the first query parameter, 1 for the second parameter, and4253** so forth.4254**4255** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and4256** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and4257** is not a database file pathname pointer that the SQLite core passed4258** into the xOpen VFS method, then the behavior of this routine is undefined4259** and probably undesirable.4260**4261** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F4262** parameter can also be the name of a rollback journal file or WAL file4263** in addition to the main database file.  Prior to version 3.31.0, these4264** routines would only work if F was the name of the main database file.4265** When the F parameter is the name of the rollback journal or WAL file,4266** it has access to all the same query parameters as were found on the4267** main database file.4268**4269** See the [URI filename] documentation for additional information.4270*/4271SQLITE_API const char *sqlite3_uri_parameter(sqlite3_filename z, const char *zParam);4272SQLITE_API int sqlite3_uri_boolean(sqlite3_filename z, const char *zParam, int bDefault);4273SQLITE_API sqlite3_int64 sqlite3_uri_int64(sqlite3_filename, const char*, sqlite3_int64);4274SQLITE_API const char *sqlite3_uri_key(sqlite3_filename z, int N);42754276/*4277** CAPI3REF:  Translate filenames4278**4279** These routines are available to [VFS|custom VFS implementations] for4280** translating filenames between the main database file, the journal file,4281** and the WAL file.4282**4283** If F is the name of an sqlite database file, journal file, or WAL file4284** passed by the SQLite core into the VFS, then sqlite3_filename_database(F)4285** returns the name of the corresponding database file.4286**4287** If F is the name of an sqlite database file, journal file, or WAL file4288** passed by the SQLite core into the VFS, or if F is a database filename4289** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F)4290** returns the name of the corresponding rollback journal file.4291**4292** If F is the name of an sqlite database file, journal file, or WAL file4293** that was passed by the SQLite core into the VFS, or if F is a database4294** filename obtained from [sqlite3_db_filename()], then4295** sqlite3_filename_wal(F) returns the name of the corresponding4296** WAL file.4297**4298** In all of the above, if F is not the name of a database, journal or WAL4299** filename passed into the VFS from the SQLite core and F is not the4300** return value from [sqlite3_db_filename()], then the result is4301** undefined and is likely a memory access violation.4302*/4303SQLITE_API const char *sqlite3_filename_database(sqlite3_filename);4304SQLITE_API const char *sqlite3_filename_journal(sqlite3_filename);4305SQLITE_API const char *sqlite3_filename_wal(sqlite3_filename);43064307/*4308** CAPI3REF:  Database File Corresponding To A Journal4309**4310** ^If X is the name of a rollback or WAL-mode journal file that is4311** passed into the xOpen method of [sqlite3_vfs], then4312** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file]4313** object that represents the main database file.4314**4315** This routine is intended for use in custom [VFS] implementations4316** only.  It is not a general-purpose interface.4317** The argument sqlite3_file_object(X) must be a filename pointer that4318** has been passed into [sqlite3_vfs].xOpen method where the4319** flags parameter to xOpen contains one of the bits4320** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL].  Any other use4321** of this routine results in undefined and probably undesirable4322** behavior.4323*/4324SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);43254326/*4327** CAPI3REF: Create and Destroy VFS Filenames4328**4329** These interfaces are provided for use by [VFS shim] implementations and4330** are not useful outside of that context.4331**4332** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of4333** database filename D with corresponding journal file J and WAL file W and4334** with N URI parameters key/values pairs in the array P.  The result from4335** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that4336** is safe to pass to routines like:4337** <ul>4338** <li> [sqlite3_uri_parameter()],4339** <li> [sqlite3_uri_boolean()],4340** <li> [sqlite3_uri_int64()],4341** <li> [sqlite3_uri_key()],4342** <li> [sqlite3_filename_database()],4343** <li> [sqlite3_filename_journal()], or4344** <li> [sqlite3_filename_wal()].4345** </ul>4346** If a memory allocation error occurs, sqlite3_create_filename() might4347** return a NULL pointer.  The memory obtained from sqlite3_create_filename(X)4348** must be released by a corresponding call to sqlite3_free_filename(Y).4349**4350** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array4351** of 2*N pointers to strings.  Each pair of pointers in this array corresponds4352** to a key and value for a query parameter.  The P parameter may be a NULL4353** pointer if N is zero.  None of the 2*N pointers in the P array may be4354** NULL pointers and key pointers should not be empty strings.4355** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may4356** be NULL pointers, though they can be empty strings.4357**4358** The sqlite3_free_filename(Y) routine releases a memory allocation4359** previously obtained from sqlite3_create_filename().  Invoking4360** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.4361**4362** If the Y parameter to sqlite3_free_filename(Y) is anything other4363** than a NULL pointer or a pointer previously acquired from4364** sqlite3_create_filename(), then bad things such as heap4365** corruption or segfaults may occur. The value Y should not be4366** used again after sqlite3_free_filename(Y) has been called.  This means4367** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y,4368** then the corresponding [sqlite3_module.xClose() method should also be4369** invoked prior to calling sqlite3_free_filename(Y).4370*/4371SQLITE_API sqlite3_filename sqlite3_create_filename(4372  const char *zDatabase,4373  const char *zJournal,4374  const char *zWal,4375  int nParam,4376  const char **azParam4377);4378SQLITE_API void sqlite3_free_filename(sqlite3_filename);43794380/*4381** CAPI3REF: Error Codes And Messages4382** METHOD: sqlite34383**4384** ^If the most recent sqlite3_* API call associated with4385** [database connection] D failed, then the sqlite3_errcode(D) interface4386** returns the numeric [result code] or [extended result code] for that4387** API call.4388** ^The sqlite3_extended_errcode()4389** interface is the same except that it always returns the4390** [extended result code] even when extended result codes are4391** disabled.4392**4393** The values returned by sqlite3_errcode() and/or4394** sqlite3_extended_errcode() might change with each API call.4395** Except, there are some interfaces that are guaranteed to never4396** change the value of the error code.  The error-code preserving4397** interfaces include the following:4398**4399** <ul>4400** <li> sqlite3_errcode()4401** <li> sqlite3_extended_errcode()4402** <li> sqlite3_errmsg()4403** <li> sqlite3_errmsg16()4404** <li> sqlite3_error_offset()4405** </ul>4406**4407** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language4408** text that describes the error, as either UTF-8 or UTF-16 respectively,4409** or NULL if no error message is available.4410** (See how SQLite handles [invalid UTF] for exceptions to this rule.)4411** ^(Memory to hold the error message string is managed internally.4412** The application does not need to worry about freeing the result.4413** However, the error string might be overwritten or deallocated by4414** subsequent calls to other SQLite interface functions.)^4415**4416** ^The sqlite3_errstr(E) interface returns the English-language text4417** that describes the [result code] E, as UTF-8, or NULL if E is not an4418** result code for which a text error message is available.4419** ^(Memory to hold the error message string is managed internally4420** and must not be freed by the application)^.4421**4422** ^If the most recent error references a specific token in the input4423** SQL, the sqlite3_error_offset() interface returns the byte offset4424** of the start of that token.  ^The byte offset returned by4425** sqlite3_error_offset() assumes that the input SQL is UTF8.4426** ^If the most recent error does not reference a specific token in the input4427** SQL, then the sqlite3_error_offset() function returns -1.4428**4429** When the serialized [threading mode] is in use, it might be the4430** case that a second error occurs on a separate thread in between4431** the time of the first error and the call to these interfaces.4432** When that happens, the second error will be reported since these4433** interfaces always report the most recent result.  To avoid4434** this, each thread can obtain exclusive use of the [database connection] D4435** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning4436** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after4437** all calls to the interfaces listed here are completed.4438**4439** If an interface fails with SQLITE_MISUSE, that means the interface4440** was invoked incorrectly by the application.  In that case, the4441** error code and message may or may not be set.4442*/4443SQLITE_API int sqlite3_errcode(sqlite3 *db);4444SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);4445SQLITE_API const char *sqlite3_errmsg(sqlite3*);4446SQLITE_API const void *sqlite3_errmsg16(sqlite3*);4447SQLITE_API const char *sqlite3_errstr(int);4448SQLITE_API int sqlite3_error_offset(sqlite3 *db);44494450/*4451** CAPI3REF: Prepared Statement Object4452** KEYWORDS: {prepared statement} {prepared statements}4453**4454** An instance of this object represents a single SQL statement that4455** has been compiled into binary form and is ready to be evaluated.4456**4457** Think of each SQL statement as a separate computer program.  The4458** original SQL text is source code.  A prepared statement object4459** is the compiled object code.  All SQL must be converted into a4460** prepared statement before it can be run.4461**4462** The life-cycle of a prepared statement object usually goes like this:4463**4464** <ol>4465** <li> Create the prepared statement object using [sqlite3_prepare_v2()].4466** <li> Bind values to [parameters] using the sqlite3_bind_*()4467**      interfaces.4468** <li> Run the SQL by calling [sqlite3_step()] one or more times.4469** <li> Reset the prepared statement using [sqlite3_reset()] then go back4470**      to step 2.  Do this zero or more times.4471** <li> Destroy the object using [sqlite3_finalize()].4472** </ol>4473*/4474typedef struct sqlite3_stmt sqlite3_stmt;44754476/*4477** CAPI3REF: Run-time Limits4478** METHOD: sqlite34479**4480** ^(This interface allows the size of various constructs to be limited4481** on a connection by connection basis.  The first parameter is the4482** [database connection] whose limit is to be set or queried.  The4483** second parameter is one of the [limit categories] that define a4484** class of constructs to be size limited.  The third parameter is the4485** new limit for that construct.)^4486**4487** ^If the new limit is a negative number, the limit is unchanged.4488** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a4489** [limits | hard upper bound]4490** set at compile-time by a C preprocessor macro called4491** [limits | SQLITE_MAX_<i>NAME</i>].4492** (The "_LIMIT_" in the name is changed to "_MAX_".))^4493** ^Attempts to increase a limit above its hard upper bound are4494** silently truncated to the hard upper bound.4495**4496** ^Regardless of whether or not the limit was changed, the4497** [sqlite3_limit()] interface returns the prior value of the limit.4498** ^Hence, to find the current value of a limit without changing it,4499** simply invoke this interface with the third parameter set to -1.4500**4501** Run-time limits are intended for use in applications that manage4502** both their own internal database and also databases that are controlled4503** by untrusted external sources.  An example application might be a4504** web browser that has its own databases for storing history and4505** separate databases controlled by JavaScript applications downloaded4506** off the Internet.  The internal databases can be given the4507** large, default limits.  Databases managed by external sources can4508** be given much smaller limits designed to prevent a denial of service4509** attack.  Developers might also want to use the [sqlite3_set_authorizer()]4510** interface to further control untrusted SQL.  The size of the database4511** created by an untrusted script can be contained using the4512** [max_page_count] [PRAGMA].4513**4514** New run-time limit categories may be added in future releases.4515*/4516SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);45174518/*4519** CAPI3REF: Run-Time Limit Categories4520** KEYWORDS: {limit category} {*limit categories}4521**4522** These constants define various performance limits4523** that can be lowered at run-time using [sqlite3_limit()].4524** The synopsis of the meanings of the various limits is shown below.4525** Additional information is available at [limits | Limits in SQLite].4526**4527** <dl>4528** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>4529** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^4530**4531** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>4532** <dd>The maximum length of an SQL statement, in bytes.</dd>)^4533**4534** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>4535** <dd>The maximum number of columns in a table definition or in the4536** result set of a [SELECT] or the maximum number of columns in an index4537** or in an ORDER BY or GROUP BY clause.</dd>)^4538**4539** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>4540** <dd>The maximum depth of the parse tree on any expression.</dd>)^4541**4542** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>4543** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^4544**4545** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>4546** <dd>The maximum number of instructions in a virtual machine program4547** used to implement an SQL statement.  If [sqlite3_prepare_v2()] or4548** the equivalent tries to allocate space for more than this many opcodes4549** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^4550**4551** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>4552** <dd>The maximum number of arguments on a function.</dd>)^4553**4554** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>4555** <dd>The maximum number of [ATTACH | attached databases].)^</dd>4556**4557** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]4558** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>4559** <dd>The maximum length of the pattern argument to the [LIKE] or4560** [GLOB] operators.</dd>)^4561**4562** [[SQLITE_LIMIT_VARIABLE_NUMBER]]4563** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>4564** <dd>The maximum index number of any [parameter] in an SQL statement.)^4565**4566** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>4567** <dd>The maximum depth of recursion for triggers.</dd>)^4568**4569** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>4570** <dd>The maximum number of auxiliary worker threads that a single4571** [prepared statement] may start.</dd>)^4572** </dl>4573*/4574#define SQLITE_LIMIT_LENGTH                    04575#define SQLITE_LIMIT_SQL_LENGTH                14576#define SQLITE_LIMIT_COLUMN                    24577#define SQLITE_LIMIT_EXPR_DEPTH                34578#define SQLITE_LIMIT_COMPOUND_SELECT           44579#define SQLITE_LIMIT_VDBE_OP                   54580#define SQLITE_LIMIT_FUNCTION_ARG              64581#define SQLITE_LIMIT_ATTACHED                  74582#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       84583#define SQLITE_LIMIT_VARIABLE_NUMBER           94584#define SQLITE_LIMIT_TRIGGER_DEPTH            104585#define SQLITE_LIMIT_WORKER_THREADS           1145864587/*4588** CAPI3REF: Prepare Flags4589**4590** These constants define various flags that can be passed into4591** "prepFlags" parameter of the [sqlite3_prepare_v3()] and4592** [sqlite3_prepare16_v3()] interfaces.4593**4594** New flags may be added in future releases of SQLite.4595**4596** <dl>4597** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>4598** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner4599** that the prepared statement will be retained for a long time and4600** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]4601** and [sqlite3_prepare16_v3()] assume that the prepared statement will4602** be used just once or at most a few times and then destroyed using4603** [sqlite3_finalize()] relatively soon. The current implementation acts4604** on this hint by avoiding the use of [lookaside memory] so as not to4605** deplete the limited store of lookaside memory. Future versions of4606** SQLite may act on this hint differently.4607**4608** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt>4609** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used4610** to be required for any prepared statement that wanted to use the4611** [sqlite3_normalized_sql()] interface.  However, the4612** [sqlite3_normalized_sql()] interface is now available to all4613** prepared statements, regardless of whether or not they use this4614** flag.4615**4616** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt>4617** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler4618** to return an error (error code SQLITE_ERROR) if the statement uses4619** any virtual tables.4620**4621** [[SQLITE_PREPARE_DONT_LOG]] <dt>SQLITE_PREPARE_DONT_LOG</dt>4622** <dd>The SQLITE_PREPARE_DONT_LOG flag prevents SQL compiler4623** errors from being sent to the error log defined by4624** [SQLITE_CONFIG_LOG].  This can be used, for example, to do test4625** compiles to see if some SQL syntax is well-formed, without generating4626** messages on the global error log when it is not.  If the test compile4627** fails, the sqlite3_prepare_v3() call returns the same error indications4628** with or without this flag; it just omits the call to [sqlite3_log()] that4629** logs the error.4630** </dl>4631*/4632#define SQLITE_PREPARE_PERSISTENT              0x014633#define SQLITE_PREPARE_NORMALIZE               0x024634#define SQLITE_PREPARE_NO_VTAB                 0x044635#define SQLITE_PREPARE_DONT_LOG                0x1046364637/*4638** CAPI3REF: Compiling An SQL Statement4639** KEYWORDS: {SQL statement compiler}4640** METHOD: sqlite34641** CONSTRUCTOR: sqlite3_stmt4642**4643** To execute an SQL statement, it must first be compiled into a byte-code4644** program using one of these routines.  Or, in other words, these routines4645** are constructors for the [prepared statement] object.4646**4647** The preferred routine to use is [sqlite3_prepare_v2()].  The4648** [sqlite3_prepare()] interface is legacy and should be avoided.4649** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used4650** for special purposes.4651**4652** The use of the UTF-8 interfaces is preferred, as SQLite currently4653** does all parsing using UTF-8.  The UTF-16 interfaces are provided4654** as a convenience.  The UTF-16 interfaces work by converting the4655** input text into UTF-8, then invoking the corresponding UTF-8 interface.4656**4657** The first argument, "db", is a [database connection] obtained from a4658** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or4659** [sqlite3_open16()].  The database connection must not have been closed.4660**4661** The second argument, "zSql", is the statement to be compiled, encoded4662** as either UTF-8 or UTF-16.  The sqlite3_prepare(), sqlite3_prepare_v2(),4663** and sqlite3_prepare_v3()4664** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),4665** and sqlite3_prepare16_v3() use UTF-16.4666**4667** ^If the nByte argument is negative, then zSql is read up to the4668** first zero terminator. ^If nByte is positive, then it is the maximum4669** number of bytes read from zSql.  When nByte is positive, zSql is read4670** up to the first zero terminator or until the nByte bytes have been read,4671** whichever comes first.  ^If nByte is zero, then no prepared4672** statement is generated.4673** If the caller knows that the supplied string is nul-terminated, then4674** there is a small performance advantage to passing an nByte parameter that4675** is the number of bytes in the input string <i>including</i>4676** the nul-terminator.4677** Note that nByte measure the length of the input in bytes, not4678** characters, even for the UTF-16 interfaces.4679**4680** ^If pzTail is not NULL then *pzTail is made to point to the first byte4681** past the end of the first SQL statement in zSql.  These routines only4682** compile the first statement in zSql, so *pzTail is left pointing to4683** what remains uncompiled.4684**4685** ^*ppStmt is left pointing to a compiled [prepared statement] that can be4686** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set4687** to NULL.  ^If the input text contains no SQL (if the input is an empty4688** string or a comment) then *ppStmt is set to NULL.4689** The calling procedure is responsible for deleting the compiled4690** SQL statement using [sqlite3_finalize()] after it has finished with it.4691** ppStmt may not be NULL.4692**4693** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];4694** otherwise an [error code] is returned.4695**4696** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),4697** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.4698** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())4699** are retained for backwards compatibility, but their use is discouraged.4700** ^In the "vX" interfaces, the prepared statement4701** that is returned (the [sqlite3_stmt] object) contains a copy of the4702** original SQL text. This causes the [sqlite3_step()] interface to4703** behave differently in three ways:4704**4705** <ol>4706** <li>4707** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it4708** always used to do, [sqlite3_step()] will automatically recompile the SQL4709** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]4710** retries will occur before sqlite3_step() gives up and returns an error.4711** </li>4712**4713** <li>4714** ^When an error occurs, [sqlite3_step()] will return one of the detailed4715** [error codes] or [extended error codes].  ^The legacy behavior was that4716** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code4717** and the application would have to make a second call to [sqlite3_reset()]4718** in order to find the underlying cause of the problem. With the "v2" prepare4719** interfaces, the underlying reason for the error is returned immediately.4720** </li>4721**4722** <li>4723** ^If the specific value bound to a [parameter | host parameter] in the4724** WHERE clause might influence the choice of query plan for a statement,4725** then the statement will be automatically recompiled, as if there had been4726** a schema change, on the first [sqlite3_step()] call following any change4727** to the [sqlite3_bind_text | bindings] of that [parameter].4728** ^The specific value of a WHERE-clause [parameter] might influence the4729** choice of query plan if the parameter is the left-hand side of a [LIKE]4730** or [GLOB] operator or if the parameter is compared to an indexed column4731** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.4732** </li>4733** </ol>4734**4735** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having4736** the extra prepFlags parameter, which is a bit array consisting of zero or4737** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags.  ^The4738** sqlite3_prepare_v2() interface works exactly the same as4739** sqlite3_prepare_v3() with a zero prepFlags parameter.4740*/4741SQLITE_API int sqlite3_prepare(4742  sqlite3 *db,            /* Database handle */4743  const char *zSql,       /* SQL statement, UTF-8 encoded */4744  int nByte,              /* Maximum length of zSql in bytes. */4745  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */4746  const char **pzTail     /* OUT: Pointer to unused portion of zSql */4747);4748SQLITE_API int sqlite3_prepare_v2(4749  sqlite3 *db,            /* Database handle */4750  const char *zSql,       /* SQL statement, UTF-8 encoded */4751  int nByte,              /* Maximum length of zSql in bytes. */4752  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */4753  const char **pzTail     /* OUT: Pointer to unused portion of zSql */4754);4755SQLITE_API int sqlite3_prepare_v3(4756  sqlite3 *db,            /* Database handle */4757  const char *zSql,       /* SQL statement, UTF-8 encoded */4758  int nByte,              /* Maximum length of zSql in bytes. */4759  unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */4760  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */4761  const char **pzTail     /* OUT: Pointer to unused portion of zSql */4762);4763SQLITE_API int sqlite3_prepare16(4764  sqlite3 *db,            /* Database handle */4765  const void *zSql,       /* SQL statement, UTF-16 encoded */4766  int nByte,              /* Maximum length of zSql in bytes. */4767  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */4768  const void **pzTail     /* OUT: Pointer to unused portion of zSql */4769);4770SQLITE_API int sqlite3_prepare16_v2(4771  sqlite3 *db,            /* Database handle */4772  const void *zSql,       /* SQL statement, UTF-16 encoded */4773  int nByte,              /* Maximum length of zSql in bytes. */4774  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */4775  const void **pzTail     /* OUT: Pointer to unused portion of zSql */4776);4777SQLITE_API int sqlite3_prepare16_v3(4778  sqlite3 *db,            /* Database handle */4779  const void *zSql,       /* SQL statement, UTF-16 encoded */4780  int nByte,              /* Maximum length of zSql in bytes. */4781  unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */4782  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */4783  const void **pzTail     /* OUT: Pointer to unused portion of zSql */4784);47854786/*4787** CAPI3REF: Retrieving Statement SQL4788** METHOD: sqlite3_stmt4789**4790** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-84791** SQL text used to create [prepared statement] P if P was4792** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],4793** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].4794** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-84795** string containing the SQL text of prepared statement P with4796** [bound parameters] expanded.4797** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-84798** string containing the normalized SQL text of prepared statement P.  The4799** semantics used to normalize a SQL statement are unspecified and subject4800** to change.  At a minimum, literal values will be replaced with suitable4801** placeholders.4802**4803** ^(For example, if a prepared statement is created using the SQL4804** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 23454805** and parameter :xyz is unbound, then sqlite3_sql() will return4806** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()4807** will return "SELECT 2345,NULL".)^4808**4809** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory4810** is available to hold the result, or if the result would exceed the4811** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].4812**4813** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of4814** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time4815** option causes sqlite3_expanded_sql() to always return NULL.4816**4817** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)4818** are managed by SQLite and are automatically freed when the prepared4819** statement is finalized.4820** ^The string returned by sqlite3_expanded_sql(P), on the other hand,4821** is obtained from [sqlite3_malloc()] and must be freed by the application4822** by passing it to [sqlite3_free()].4823**4824** ^The sqlite3_normalized_sql() interface is only available if4825** the [SQLITE_ENABLE_NORMALIZE] compile-time option is defined.4826*/4827SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);4828SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);4829#ifdef SQLITE_ENABLE_NORMALIZE4830SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);4831#endif48324833/*4834** CAPI3REF: Determine If An SQL Statement Writes The Database4835** METHOD: sqlite3_stmt4836**4837** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if4838** and only if the [prepared statement] X makes no direct changes to4839** the content of the database file.4840**4841** Note that [application-defined SQL functions] or4842** [virtual tables] might change the database indirectly as a side effect.4843** ^(For example, if an application defines a function "eval()" that4844** calls [sqlite3_exec()], then the following SQL statement would4845** change the database file through side-effects:4846**4847** <blockquote><pre>4848**    SELECT eval('DELETE FROM t1') FROM t2;4849** </pre></blockquote>4850**4851** But because the [SELECT] statement does not change the database file4852** directly, sqlite3_stmt_readonly() would still return true.)^4853**4854** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],4855** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,4856** since the statements themselves do not actually modify the database but4857** rather they control the timing of when other statements modify the4858** database.  ^The [ATTACH] and [DETACH] statements also cause4859** sqlite3_stmt_readonly() to return true since, while those statements4860** change the configuration of a database connection, they do not make4861** changes to the content of the database files on disk.4862** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since4863** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and4864** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so4865** sqlite3_stmt_readonly() returns false for those commands.4866**4867** ^This routine returns false if there is any possibility that the4868** statement might change the database file.  ^A false return does4869** not guarantee that the statement will change the database file.4870** ^For example, an UPDATE statement might have a WHERE clause that4871** makes it a no-op, but the sqlite3_stmt_readonly() result would still4872** be false.  ^Similarly, a CREATE TABLE IF NOT EXISTS statement is a4873** read-only no-op if the table already exists, but4874** sqlite3_stmt_readonly() still returns false for such a statement.4875**4876** ^If prepared statement X is an [EXPLAIN] or [EXPLAIN QUERY PLAN]4877** statement, then sqlite3_stmt_readonly(X) returns the same value as4878** if the EXPLAIN or EXPLAIN QUERY PLAN prefix were omitted.4879*/4880SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);48814882/*4883** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement4884** METHOD: sqlite3_stmt4885**4886** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the4887** prepared statement S is an EXPLAIN statement, or 2 if the4888** statement S is an EXPLAIN QUERY PLAN.4889** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is4890** an ordinary statement or a NULL pointer.4891*/4892SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);48934894/*4895** CAPI3REF: Change The EXPLAIN Setting For A Prepared Statement4896** METHOD: sqlite3_stmt4897**4898** The sqlite3_stmt_explain(S,E) interface changes the EXPLAIN4899** setting for [prepared statement] S.  If E is zero, then S becomes4900** a normal prepared statement.  If E is 1, then S behaves as if4901** its SQL text began with "[EXPLAIN]".  If E is 2, then S behaves as if4902** its SQL text began with "[EXPLAIN QUERY PLAN]".4903**4904** Calling sqlite3_stmt_explain(S,E) might cause S to be reprepared.4905** SQLite tries to avoid a reprepare, but a reprepare might be necessary4906** on the first transition into EXPLAIN or EXPLAIN QUERY PLAN mode.4907**4908** Because of the potential need to reprepare, a call to4909** sqlite3_stmt_explain(S,E) will fail with SQLITE_ERROR if S cannot be4910** reprepared because it was created using [sqlite3_prepare()] instead of4911** the newer [sqlite3_prepare_v2()] or [sqlite3_prepare_v3()] interfaces and4912** hence has no saved SQL text with which to reprepare.4913**4914** Changing the explain setting for a prepared statement does not change4915** the original SQL text for the statement.  Hence, if the SQL text originally4916** began with EXPLAIN or EXPLAIN QUERY PLAN, but sqlite3_stmt_explain(S,0)4917** is called to convert the statement into an ordinary statement, the EXPLAIN4918** or EXPLAIN QUERY PLAN keywords will still appear in the sqlite3_sql(S)4919** output, even though the statement now acts like a normal SQL statement.4920**4921** This routine returns SQLITE_OK if the explain mode is successfully4922** changed, or an error code if the explain mode could not be changed.4923** The explain mode cannot be changed while a statement is active.4924** Hence, it is good practice to call [sqlite3_reset(S)]4925** immediately prior to calling sqlite3_stmt_explain(S,E).4926*/4927SQLITE_API int sqlite3_stmt_explain(sqlite3_stmt *pStmt, int eMode);49284929/*4930** CAPI3REF: Determine If A Prepared Statement Has Been Reset4931** METHOD: sqlite3_stmt4932**4933** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the4934** [prepared statement] S has been stepped at least once using4935** [sqlite3_step(S)] but has neither run to completion (returned4936** [SQLITE_DONE] from [sqlite3_step(S)]) nor4937** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)4938** interface returns false if S is a NULL pointer.  If S is not a4939** NULL pointer and is not a pointer to a valid [prepared statement]4940** object, then the behavior is undefined and probably undesirable.4941**4942** This interface can be used in combination [sqlite3_next_stmt()]4943** to locate all prepared statements associated with a database4944** connection that are in need of being reset.  This can be used,4945** for example, in diagnostic routines to search for prepared4946** statements that are holding a transaction open.4947*/4948SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);49494950/*4951** CAPI3REF: Dynamically Typed Value Object4952** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}4953**4954** SQLite uses the sqlite3_value object to represent all values4955** that can be stored in a database table. SQLite uses dynamic typing4956** for the values it stores.  ^Values stored in sqlite3_value objects4957** can be integers, floating point values, strings, BLOBs, or NULL.4958**4959** An sqlite3_value object may be either "protected" or "unprotected".4960** Some interfaces require a protected sqlite3_value.  Other interfaces4961** will accept either a protected or an unprotected sqlite3_value.4962** Every interface that accepts sqlite3_value arguments specifies4963** whether or not it requires a protected sqlite3_value.  The4964** [sqlite3_value_dup()] interface can be used to construct a new4965** protected sqlite3_value from an unprotected sqlite3_value.4966**4967** The terms "protected" and "unprotected" refer to whether or not4968** a mutex is held.  An internal mutex is held for a protected4969** sqlite3_value object but no mutex is held for an unprotected4970** sqlite3_value object.  If SQLite is compiled to be single-threaded4971** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)4972** or if SQLite is run in one of reduced mutex modes4973** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]4974** then there is no distinction between protected and unprotected4975** sqlite3_value objects and they can be used interchangeably.  However,4976** for maximum code portability it is recommended that applications4977** still make the distinction between protected and unprotected4978** sqlite3_value objects even when not strictly required.4979**4980** ^The sqlite3_value objects that are passed as parameters into the4981** implementation of [application-defined SQL functions] are protected.4982** ^The sqlite3_value objects returned by [sqlite3_vtab_rhs_value()]4983** are protected.4984** ^The sqlite3_value object returned by4985** [sqlite3_column_value()] is unprotected.4986** Unprotected sqlite3_value objects may only be used as arguments4987** to [sqlite3_result_value()], [sqlite3_bind_value()], and4988** [sqlite3_value_dup()].4989** The [sqlite3_value_blob | sqlite3_value_type()] family of4990** interfaces require protected sqlite3_value objects.4991*/4992typedef struct sqlite3_value sqlite3_value;49934994/*4995** CAPI3REF: SQL Function Context Object4996**4997** The context in which an SQL function executes is stored in an4998** sqlite3_context object.  ^A pointer to an sqlite3_context object4999** is always first parameter to [application-defined SQL functions].5000** The application-defined SQL function implementation will pass this5001** pointer through into calls to [sqlite3_result_int | sqlite3_result()],5002** [sqlite3_aggregate_context()], [sqlite3_user_data()],5003** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],5004** and/or [sqlite3_set_auxdata()].5005*/5006typedef struct sqlite3_context sqlite3_context;50075008/*5009** CAPI3REF: Binding Values To Prepared Statements5010** KEYWORDS: {host parameter} {host parameters} {host parameter name}5011** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}5012** METHOD: sqlite3_stmt5013**5014** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,5015** literals may be replaced by a [parameter] that matches one of following5016** templates:5017**5018** <ul>5019** <li>  ?5020** <li>  ?NNN5021** <li>  :VVV5022** <li>  @VVV5023** <li>  $VVV5024** </ul>5025**5026** In the templates above, NNN represents an integer literal,5027** and VVV represents an alphanumeric identifier.)^  ^The values of these5028** parameters (also called "host parameter names" or "SQL parameters")5029** can be set using the sqlite3_bind_*() routines defined here.5030**5031** ^The first argument to the sqlite3_bind_*() routines is always5032** a pointer to the [sqlite3_stmt] object returned from5033** [sqlite3_prepare_v2()] or its variants.5034**5035** ^The second argument is the index of the SQL parameter to be set.5036** ^The leftmost SQL parameter has an index of 1.  ^When the same named5037** SQL parameter is used more than once, second and subsequent5038** occurrences have the same index as the first occurrence.5039** ^The index for named parameters can be looked up using the5040** [sqlite3_bind_parameter_index()] API if desired.  ^The index5041** for "?NNN" parameters is the value of NNN.5042** ^The NNN value must be between 1 and the [sqlite3_limit()]5043** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766).5044**5045** ^The third argument is the value to bind to the parameter.5046** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()5047** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter5048** is ignored and the end result is the same as sqlite3_bind_null().5049** ^If the third parameter to sqlite3_bind_text() is not NULL, then5050** it should be a pointer to well-formed UTF8 text.5051** ^If the third parameter to sqlite3_bind_text16() is not NULL, then5052** it should be a pointer to well-formed UTF16 text.5053** ^If the third parameter to sqlite3_bind_text64() is not NULL, then5054** it should be a pointer to a well-formed unicode string that is5055** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF165056** otherwise.5057**5058** [[byte-order determination rules]] ^The byte-order of5059** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)5060** found in first character, which is removed, or in the absence of a BOM5061** the byte order is the native byte order of the host5062** machine for sqlite3_bind_text16() or the byte order specified in5063** the 6th parameter for sqlite3_bind_text64().)^5064** ^If UTF16 input text contains invalid unicode5065** characters, then SQLite might change those invalid characters5066** into the unicode replacement character: U+FFFD.5067**5068** ^(In those routines that have a fourth argument, its value is the5069** number of bytes in the parameter.  To be clear: the value is the5070** number of <u>bytes</u> in the value, not the number of characters.)^5071** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()5072** is negative, then the length of the string is5073** the number of bytes up to the first zero terminator.5074** If the fourth parameter to sqlite3_bind_blob() is negative, then5075** the behavior is undefined.5076** If a non-negative fourth parameter is provided to sqlite3_bind_text()5077** or sqlite3_bind_text16() or sqlite3_bind_text64() then5078** that parameter must be the byte offset5079** where the NUL terminator would occur assuming the string were NUL5080** terminated.  If any NUL characters occurs at byte offsets less than5081** the value of the fourth parameter then the resulting string value will5082** contain embedded NULs.  The result of expressions involving strings5083** with embedded NULs is undefined.5084**5085** ^The fifth argument to the BLOB and string binding interfaces controls5086** or indicates the lifetime of the object referenced by the third parameter.5087** These three options exist:5088** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished5089** with it may be passed. ^It is called to dispose of the BLOB or string even5090** if the call to the bind API fails, except the destructor is not called if5091** the third parameter is a NULL pointer or the fourth parameter is negative.5092** ^ (2) The special constant, [SQLITE_STATIC], may be passed to indicate that5093** the application remains responsible for disposing of the object. ^In this5094** case, the object and the provided pointer to it must remain valid until5095** either the prepared statement is finalized or the same SQL parameter is5096** bound to something else, whichever occurs sooner.5097** ^ (3) The constant, [SQLITE_TRANSIENT], may be passed to indicate that the5098** object is to be copied prior to the return from sqlite3_bind_*(). ^The5099** object and pointer to it must remain valid until then. ^SQLite will then5100** manage the lifetime of its private copy.5101**5102** ^The sixth argument to sqlite3_bind_text64() must be one of5103** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]5104** to specify the encoding of the text in the third parameter.  If5105** the sixth argument to sqlite3_bind_text64() is not one of the5106** allowed values shown above, or if the text encoding is different5107** from the encoding specified by the sixth parameter, then the behavior5108** is undefined.5109**5110** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that5111** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory5112** (just an integer to hold its size) while it is being processed.5113** Zeroblobs are intended to serve as placeholders for BLOBs whose5114** content is later written using5115** [sqlite3_blob_open | incremental BLOB I/O] routines.5116** ^A negative value for the zeroblob results in a zero-length BLOB.5117**5118** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in5119** [prepared statement] S to have an SQL value of NULL, but to also be5120** associated with the pointer P of type T.  ^D is either a NULL pointer or5121** a pointer to a destructor function for P. ^SQLite will invoke the5122** destructor D with a single argument of P when it is finished using5123** P.  The T parameter should be a static string, preferably a string5124** literal. The sqlite3_bind_pointer() routine is part of the5125** [pointer passing interface] added for SQLite 3.20.0.5126**5127** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer5128** for the [prepared statement] or with a prepared statement for which5129** [sqlite3_step()] has been called more recently than [sqlite3_reset()],5130** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()5131** routine is passed a [prepared statement] that has been finalized, the5132** result is undefined and probably harmful.5133**5134** ^Bindings are not cleared by the [sqlite3_reset()] routine.5135** ^Unbound parameters are interpreted as NULL.5136**5137** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an5138** [error code] if anything goes wrong.5139** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB5140** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or5141** [SQLITE_MAX_LENGTH].5142** ^[SQLITE_RANGE] is returned if the parameter5143** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.5144**5145** See also: [sqlite3_bind_parameter_count()],5146** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].5147*/5148SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));5149SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,5150                        void(*)(void*));5151SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);5152SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);5153SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);5154SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);5155SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));5156SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));5157SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,5158                         void(*)(void*), unsigned char encoding);5159SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);5160SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));5161SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);5162SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);51635164/*5165** CAPI3REF: Number Of SQL Parameters5166** METHOD: sqlite3_stmt5167**5168** ^This routine can be used to find the number of [SQL parameters]5169** in a [prepared statement].  SQL parameters are tokens of the5170** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as5171** placeholders for values that are [sqlite3_bind_blob | bound]5172** to the parameters at a later time.5173**5174** ^(This routine actually returns the index of the largest (rightmost)5175** parameter. For all forms except ?NNN, this will correspond to the5176** number of unique parameters.  If parameters of the ?NNN form are used,5177** there may be gaps in the list.)^5178**5179** See also: [sqlite3_bind_blob|sqlite3_bind()],5180** [sqlite3_bind_parameter_name()], and5181** [sqlite3_bind_parameter_index()].5182*/5183SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);51845185/*5186** CAPI3REF: Name Of A Host Parameter5187** METHOD: sqlite3_stmt5188**5189** ^The sqlite3_bind_parameter_name(P,N) interface returns5190** the name of the N-th [SQL parameter] in the [prepared statement] P.5191** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"5192** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"5193** respectively.5194** In other words, the initial ":" or "$" or "@" or "?"5195** is included as part of the name.)^5196** ^Parameters of the form "?" without a following integer have no name5197** and are referred to as "nameless" or "anonymous parameters".5198**5199** ^The first host parameter has an index of 1, not 0.5200**5201** ^If the value N is out of range or if the N-th parameter is5202** nameless, then NULL is returned.  ^The returned string is5203** always in UTF-8 encoding even if the named parameter was5204** originally specified as UTF-16 in [sqlite3_prepare16()],5205** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].5206**5207** See also: [sqlite3_bind_blob|sqlite3_bind()],5208** [sqlite3_bind_parameter_count()], and5209** [sqlite3_bind_parameter_index()].5210*/5211SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);52125213/*5214** CAPI3REF: Index Of A Parameter With A Given Name5215** METHOD: sqlite3_stmt5216**5217** ^Return the index of an SQL parameter given its name.  ^The5218** index value returned is suitable for use as the second5219** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero5220** is returned if no matching parameter is found.  ^The parameter5221** name must be given in UTF-8 even if the original statement5222** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or5223** [sqlite3_prepare16_v3()].5224**5225** See also: [sqlite3_bind_blob|sqlite3_bind()],5226** [sqlite3_bind_parameter_count()], and5227** [sqlite3_bind_parameter_name()].5228*/5229SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);52305231/*5232** CAPI3REF: Reset All Bindings On A Prepared Statement5233** METHOD: sqlite3_stmt5234**5235** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset5236** the [sqlite3_bind_blob | bindings] on a [prepared statement].5237** ^Use this routine to reset all host parameters to NULL.5238*/5239SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);52405241/*5242** CAPI3REF: Number Of Columns In A Result Set5243** METHOD: sqlite3_stmt5244**5245** ^Return the number of columns in the result set returned by the5246** [prepared statement]. ^If this routine returns 0, that means the5247** [prepared statement] returns no data (for example an [UPDATE]).5248** ^However, just because this routine returns a positive number does not5249** mean that one or more rows of data will be returned.  ^A SELECT statement5250** will always have a positive sqlite3_column_count() but depending on the5251** WHERE clause constraints and the table content, it might return no rows.5252**5253** See also: [sqlite3_data_count()]5254*/5255SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);52565257/*5258** CAPI3REF: Column Names In A Result Set5259** METHOD: sqlite3_stmt5260**5261** ^These routines return the name assigned to a particular column5262** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()5263** interface returns a pointer to a zero-terminated UTF-8 string5264** and sqlite3_column_name16() returns a pointer to a zero-terminated5265** UTF-16 string.  ^The first parameter is the [prepared statement]5266** that implements the [SELECT] statement. ^The second parameter is the5267** column number.  ^The leftmost column is number 0.5268**5269** ^The returned string pointer is valid until either the [prepared statement]5270** is destroyed by [sqlite3_finalize()] or until the statement is automatically5271** reprepared by the first call to [sqlite3_step()] for a particular run5272** or until the next call to5273** sqlite3_column_name() or sqlite3_column_name16() on the same column.5274**5275** ^If sqlite3_malloc() fails during the processing of either routine5276** (for example during a conversion from UTF-8 to UTF-16) then a5277** NULL pointer is returned.5278**5279** ^The name of a result column is the value of the "AS" clause for5280** that column, if there is an AS clause.  If there is no AS clause5281** then the name of the column is unspecified and may change from5282** one release of SQLite to the next.5283*/5284SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);5285SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);52865287/*5288** CAPI3REF: Source Of Data In A Query Result5289** METHOD: sqlite3_stmt5290**5291** ^These routines provide a means to determine the database, table, and5292** table column that is the origin of a particular result column in5293** [SELECT] statement.5294** ^The name of the database or table or column can be returned as5295** either a UTF-8 or UTF-16 string.  ^The _database_ routines return5296** the database name, the _table_ routines return the table name, and5297** the origin_ routines return the column name.5298** ^The returned string is valid until the [prepared statement] is destroyed5299** using [sqlite3_finalize()] or until the statement is automatically5300** reprepared by the first call to [sqlite3_step()] for a particular run5301** or until the same information is requested5302** again in a different encoding.5303**5304** ^The names returned are the original un-aliased names of the5305** database, table, and column.5306**5307** ^The first argument to these interfaces is a [prepared statement].5308** ^These functions return information about the Nth result column returned by5309** the statement, where N is the second function argument.5310** ^The left-most column is column 0 for these routines.5311**5312** ^If the Nth column returned by the statement is an expression or5313** subquery and is not a column value, then all of these functions return5314** NULL.  ^These routines might also return NULL if a memory allocation error5315** occurs.  ^Otherwise, they return the name of the attached database, table,5316** or column that query result column was extracted from.5317**5318** ^As with all other SQLite APIs, those whose names end with "16" return5319** UTF-16 encoded strings and the other functions return UTF-8.5320**5321** ^These APIs are only available if the library was compiled with the5322** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.5323**5324** If two or more threads call one or more5325** [sqlite3_column_database_name | column metadata interfaces]5326** for the same [prepared statement] and result column5327** at the same time then the results are undefined.5328*/5329SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);5330SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);5331SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);5332SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);5333SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);5334SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);53355336/*5337** CAPI3REF: Declared Datatype Of A Query Result5338** METHOD: sqlite3_stmt5339**5340** ^(The first parameter is a [prepared statement].5341** If this statement is a [SELECT] statement and the Nth column of the5342** returned result set of that [SELECT] is a table column (not an5343** expression or subquery) then the declared type of the table5344** column is returned.)^  ^If the Nth column of the result set is an5345** expression or subquery, then a NULL pointer is returned.5346** ^The returned string is always UTF-8 encoded.5347**5348** ^(For example, given the database schema:5349**5350** CREATE TABLE t1(c1 VARIANT);5351**5352** and the following statement to be compiled:5353**5354** SELECT c1 + 1, c1 FROM t1;5355**5356** this routine would return the string "VARIANT" for the second result5357** column (i==1), and a NULL pointer for the first result column (i==0).)^5358**5359** ^SQLite uses dynamic run-time typing.  ^So just because a column5360** is declared to contain a particular type does not mean that the5361** data stored in that column is of the declared type.  SQLite is5362** strongly typed, but the typing is dynamic not static.  ^Type5363** is associated with individual values, not with the containers5364** used to hold those values.5365*/5366SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);5367SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);53685369/*5370** CAPI3REF: Evaluate An SQL Statement5371** METHOD: sqlite3_stmt5372**5373** After a [prepared statement] has been prepared using any of5374** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],5375** or [sqlite3_prepare16_v3()] or one of the legacy5376** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function5377** must be called one or more times to evaluate the statement.5378**5379** The details of the behavior of the sqlite3_step() interface depend5380** on whether the statement was prepared using the newer "vX" interfaces5381** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],5382** [sqlite3_prepare16_v2()] or the older legacy5383** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the5384** new "vX" interface is recommended for new applications but the legacy5385** interface will continue to be supported.5386**5387** ^In the legacy interface, the return value will be either [SQLITE_BUSY],5388** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].5389** ^With the "v2" interface, any of the other [result codes] or5390** [extended result codes] might be returned as well.5391**5392** ^[SQLITE_BUSY] means that the database engine was unable to acquire the5393** database locks it needs to do its job.  ^If the statement is a [COMMIT]5394** or occurs outside of an explicit transaction, then you can retry the5395** statement.  If the statement is not a [COMMIT] and occurs within an5396** explicit transaction then you should rollback the transaction before5397** continuing.5398**5399** ^[SQLITE_DONE] means that the statement has finished executing5400** successfully.  sqlite3_step() should not be called again on this virtual5401** machine without first calling [sqlite3_reset()] to reset the virtual5402** machine back to its initial state.5403**5404** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]5405** is returned each time a new row of data is ready for processing by the5406** caller. The values may be accessed using the [column access functions].5407** sqlite3_step() is called again to retrieve the next row of data.5408**5409** ^[SQLITE_ERROR] means that a run-time error (such as a constraint5410** violation) has occurred.  sqlite3_step() should not be called again on5411** the VM. More information may be found by calling [sqlite3_errmsg()].5412** ^With the legacy interface, a more specific error code (for example,5413** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)5414** can be obtained by calling [sqlite3_reset()] on the5415** [prepared statement].  ^In the "v2" interface,5416** the more specific error code is returned directly by sqlite3_step().5417**5418** [SQLITE_MISUSE] means that the this routine was called inappropriately.5419** Perhaps it was called on a [prepared statement] that has5420** already been [sqlite3_finalize | finalized] or on one that had5421** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could5422** be the case that the same database connection is being used by two or5423** more threads at the same moment in time.5424**5425** For all versions of SQLite up to and including 3.6.23.1, a call to5426** [sqlite3_reset()] was required after sqlite3_step() returned anything5427** other than [SQLITE_ROW] before any subsequent invocation of5428** sqlite3_step().  Failure to reset the prepared statement using5429** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from5430** sqlite3_step().  But after [version 3.6.23.1] ([dateof:3.6.23.1],5431** sqlite3_step() began5432** calling [sqlite3_reset()] automatically in this circumstance rather5433** than returning [SQLITE_MISUSE].  This is not considered a compatibility5434** break because any application that ever receives an SQLITE_MISUSE error5435** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option5436** can be used to restore the legacy behavior.5437**5438** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()5439** API always returns a generic error code, [SQLITE_ERROR], following any5440** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call5441** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the5442** specific [error codes] that better describes the error.5443** We admit that this is a goofy design.  The problem has been fixed5444** with the "v2" interface.  If you prepare all of your SQL statements5445** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]5446** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead5447** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,5448** then the more specific [error codes] are returned directly5449** by sqlite3_step().  The use of the "vX" interfaces is recommended.5450*/5451SQLITE_API int sqlite3_step(sqlite3_stmt*);54525453/*5454** CAPI3REF: Number of columns in a result set5455** METHOD: sqlite3_stmt5456**5457** ^The sqlite3_data_count(P) interface returns the number of columns in the5458** current row of the result set of [prepared statement] P.5459** ^If prepared statement P does not have results ready to return5460** (via calls to the [sqlite3_column_int | sqlite3_column()] family of5461** interfaces) then sqlite3_data_count(P) returns 0.5462** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.5463** ^The sqlite3_data_count(P) routine returns 0 if the previous call to5464** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)5465** will return non-zero if previous call to [sqlite3_step](P) returned5466** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]5467** where it always returns zero since each step of that multi-step5468** pragma returns 0 columns of data.5469**5470** See also: [sqlite3_column_count()]5471*/5472SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);54735474/*5475** CAPI3REF: Fundamental Datatypes5476** KEYWORDS: SQLITE_TEXT5477**5478** ^(Every value in SQLite has one of five fundamental datatypes:5479**5480** <ul>5481** <li> 64-bit signed integer5482** <li> 64-bit IEEE floating point number5483** <li> string5484** <li> BLOB5485** <li> NULL5486** </ul>)^5487**5488** These constants are codes for each of those types.5489**5490** Note that the SQLITE_TEXT constant was also used in SQLite version 25491** for a completely different meaning.  Software that links against both5492** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not5493** SQLITE_TEXT.5494*/5495#define SQLITE_INTEGER  15496#define SQLITE_FLOAT    25497#define SQLITE_BLOB     45498#define SQLITE_NULL     55499#ifdef SQLITE_TEXT5500# undef SQLITE_TEXT5501#else5502# define SQLITE_TEXT     35503#endif5504#define SQLITE3_TEXT     355055506/*5507** CAPI3REF: Result Values From A Query5508** KEYWORDS: {column access functions}5509** METHOD: sqlite3_stmt5510**5511** <b>Summary:</b>5512** <blockquote><table border=0 cellpadding=0 cellspacing=0>5513** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result5514** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result5515** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result5516** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result5517** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result5518** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result5519** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an5520** [sqlite3_value|unprotected sqlite3_value] object.5521** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;5522** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB5523** or a UTF-8 TEXT result in bytes5524** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>5525** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-165526** TEXT in bytes5527** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default5528** datatype of the result5529** </table></blockquote>5530**5531** <b>Details:</b>5532**5533** ^These routines return information about a single column of the current5534** result row of a query.  ^In every case the first argument is a pointer5535** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]5536** that was returned from [sqlite3_prepare_v2()] or one of its variants)5537** and the second argument is the index of the column for which information5538** should be returned. ^The leftmost column of the result set has the index 0.5539** ^The number of columns in the result can be determined using5540** [sqlite3_column_count()].5541**5542** If the SQL statement does not currently point to a valid row, or if the5543** column index is out of range, the result is undefined.5544** These routines may only be called when the most recent call to5545** [sqlite3_step()] has returned [SQLITE_ROW] and neither5546** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.5547** If any of these routines are called after [sqlite3_reset()] or5548** [sqlite3_finalize()] or after [sqlite3_step()] has returned5549** something other than [SQLITE_ROW], the results are undefined.5550** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]5551** are called from a different thread while any of these routines5552** are pending, then the results are undefined.5553**5554** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)5555** each return the value of a result column in a specific data format.  If5556** the result column is not initially in the requested format (for example,5557** if the query returns an integer but the sqlite3_column_text() interface5558** is used to extract the value) then an automatic type conversion is performed.5559**5560** ^The sqlite3_column_type() routine returns the5561** [SQLITE_INTEGER | datatype code] for the initial data type5562** of the result column.  ^The returned value is one of [SQLITE_INTEGER],5563** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].5564** The return value of sqlite3_column_type() can be used to decide which5565** of the first six interface should be used to extract the column value.5566** The value returned by sqlite3_column_type() is only meaningful if no5567** automatic type conversions have occurred for the value in question.5568** After a type conversion, the result of calling sqlite3_column_type()5569** is undefined, though harmless.  Future5570** versions of SQLite may change the behavior of sqlite3_column_type()5571** following a type conversion.5572**5573** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()5574** or sqlite3_column_bytes16() interfaces can be used to determine the size5575** of that BLOB or string.5576**5577** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()5578** routine returns the number of bytes in that BLOB or string.5579** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts5580** the string to UTF-8 and then returns the number of bytes.5581** ^If the result is a numeric value then sqlite3_column_bytes() uses5582** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns5583** the number of bytes in that string.5584** ^If the result is NULL, then sqlite3_column_bytes() returns zero.5585**5586** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()5587** routine returns the number of bytes in that BLOB or string.5588** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts5589** the string to UTF-16 and then returns the number of bytes.5590** ^If the result is a numeric value then sqlite3_column_bytes16() uses5591** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns5592** the number of bytes in that string.5593** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.5594**5595** ^The values returned by [sqlite3_column_bytes()] and5596** [sqlite3_column_bytes16()] do not include the zero terminators at the end5597** of the string.  ^For clarity: the values returned by5598** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of5599** bytes in the string, not the number of characters.5600**5601** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),5602** even empty strings, are always zero-terminated.  ^The return5603** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.5604**5605** ^Strings returned by sqlite3_column_text16() always have the endianness5606** which is native to the platform, regardless of the text encoding set5607** for the database.5608**5609** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an5610** [unprotected sqlite3_value] object.  In a multithreaded environment,5611** an unprotected sqlite3_value object may only be used safely with5612** [sqlite3_bind_value()] and [sqlite3_result_value()].5613** If the [unprotected sqlite3_value] object returned by5614** [sqlite3_column_value()] is used in any other way, including calls5615** to routines like [sqlite3_value_int()], [sqlite3_value_text()],5616** or [sqlite3_value_bytes()], the behavior is not threadsafe.5617** Hence, the sqlite3_column_value() interface5618** is normally only useful within the implementation of5619** [application-defined SQL functions] or [virtual tables], not within5620** top-level application code.5621**5622** These routines may attempt to convert the datatype of the result.5623** ^For example, if the internal representation is FLOAT and a text result5624** is requested, [sqlite3_snprintf()] is used internally to perform the5625** conversion automatically.  ^(The following table details the conversions5626** that are applied:5627**5628** <blockquote>5629** <table border="1">5630** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion5631**5632** <tr><td>  NULL    <td> INTEGER   <td> Result is 05633** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.05634** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer5635** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer5636** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float5637** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer5638** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT5639** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER5640** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float5641** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB5642** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER5643** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL5644** <tr><td>  TEXT    <td>   BLOB    <td> No change5645** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER5646** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL5647** <tr><td>  BLOB    <td>   TEXT    <td> [CAST] to TEXT, ensure zero terminator5648** </table>5649** </blockquote>)^5650**5651** Note that when type conversions occur, pointers returned by prior5652** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or5653** sqlite3_column_text16() may be invalidated.5654** Type conversions and pointer invalidations might occur5655** in the following cases:5656**5657** <ul>5658** <li> The initial content is a BLOB and sqlite3_column_text() or5659**      sqlite3_column_text16() is called.  A zero-terminator might5660**      need to be added to the string.</li>5661** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or5662**      sqlite3_column_text16() is called.  The content must be converted5663**      to UTF-16.</li>5664** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or5665**      sqlite3_column_text() is called.  The content must be converted5666**      to UTF-8.</li>5667** </ul>5668**5669** ^Conversions between UTF-16be and UTF-16le are always done in place and do5670** not invalidate a prior pointer, though of course the content of the buffer5671** that the prior pointer references will have been modified.  Other kinds5672** of conversion are done in place when it is possible, but sometimes they5673** are not possible and in those cases prior pointers are invalidated.5674**5675** The safest policy is to invoke these routines5676** in one of the following ways:5677**5678** <ul>5679**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>5680**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>5681**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>5682** </ul>5683**5684** In other words, you should call sqlite3_column_text(),5685** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result5686** into the desired format, then invoke sqlite3_column_bytes() or5687** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls5688** to sqlite3_column_text() or sqlite3_column_blob() with calls to5689** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()5690** with calls to sqlite3_column_bytes().5691**5692** ^The pointers returned are valid until a type conversion occurs as5693** described above, or until [sqlite3_step()] or [sqlite3_reset()] or5694** [sqlite3_finalize()] is called.  ^The memory space used to hold strings5695** and BLOBs is freed automatically.  Do not pass the pointers returned5696** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into5697** [sqlite3_free()].5698**5699** As long as the input parameters are correct, these routines will only5700** fail if an out-of-memory error occurs during a format conversion.5701** Only the following subset of interfaces are subject to out-of-memory5702** errors:5703**5704** <ul>5705** <li> sqlite3_column_blob()5706** <li> sqlite3_column_text()5707** <li> sqlite3_column_text16()5708** <li> sqlite3_column_bytes()5709** <li> sqlite3_column_bytes16()5710** </ul>5711**5712** If an out-of-memory error occurs, then the return value from these5713** routines is the same as if the column had contained an SQL NULL value.5714** Valid SQL NULL returns can be distinguished from out-of-memory errors5715** by invoking the [sqlite3_errcode()] immediately after the suspect5716** return value is obtained and before any5717** other SQLite interface is called on the same [database connection].5718*/5719SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);5720SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);5721SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);5722SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);5723SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);5724SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);5725SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);5726SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);5727SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);5728SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);57295730/*5731** CAPI3REF: Destroy A Prepared Statement Object5732** DESTRUCTOR: sqlite3_stmt5733**5734** ^The sqlite3_finalize() function is called to delete a [prepared statement].5735** ^If the most recent evaluation of the statement encountered no errors5736** or if the statement is never been evaluated, then sqlite3_finalize() returns5737** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then5738** sqlite3_finalize(S) returns the appropriate [error code] or5739** [extended error code].5740**5741** ^The sqlite3_finalize(S) routine can be called at any point during5742** the life cycle of [prepared statement] S:5743** before statement S is ever evaluated, after5744** one or more calls to [sqlite3_reset()], or after any call5745** to [sqlite3_step()] regardless of whether or not the statement has5746** completed execution.5747**5748** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.5749**5750** The application must finalize every [prepared statement] in order to avoid5751** resource leaks.  It is a grievous error for the application to try to use5752** a prepared statement after it has been finalized.  Any use of a prepared5753** statement after it has been finalized can result in undefined and5754** undesirable behavior such as segfaults and heap corruption.5755*/5756SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);57575758/*5759** CAPI3REF: Reset A Prepared Statement Object5760** METHOD: sqlite3_stmt5761**5762** The sqlite3_reset() function is called to reset a [prepared statement]5763** object back to its initial state, ready to be re-executed.5764** ^Any SQL statement variables that had values bound to them using5765** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.5766** Use [sqlite3_clear_bindings()] to reset the bindings.5767**5768** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S5769** back to the beginning of its program.5770**5771** ^The return code from [sqlite3_reset(S)] indicates whether or not5772** the previous evaluation of prepared statement S completed successfully.5773** ^If [sqlite3_step(S)] has never before been called on S or if5774** [sqlite3_step(S)] has not been called since the previous call5775** to [sqlite3_reset(S)], then [sqlite3_reset(S)] will return5776** [SQLITE_OK].5777**5778** ^If the most recent call to [sqlite3_step(S)] for the5779** [prepared statement] S indicated an error, then5780** [sqlite3_reset(S)] returns an appropriate [error code].5781** ^The [sqlite3_reset(S)] interface might also return an [error code]5782** if there were no prior errors but the process of resetting5783** the prepared statement caused a new error. ^For example, if an5784** [INSERT] statement with a [RETURNING] clause is only stepped one time,5785** that one call to [sqlite3_step(S)] might return SQLITE_ROW but5786** the overall statement might still fail and the [sqlite3_reset(S)] call5787** might return SQLITE_BUSY if locking constraints prevent the5788** database change from committing.  Therefore, it is important that5789** applications check the return code from [sqlite3_reset(S)] even if5790** no prior call to [sqlite3_step(S)] indicated a problem.5791**5792** ^The [sqlite3_reset(S)] interface does not change the values5793** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.5794*/5795SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);579657975798/*5799** CAPI3REF: Create Or Redefine SQL Functions5800** KEYWORDS: {function creation routines}5801** METHOD: sqlite35802**5803** ^These functions (collectively known as "function creation routines")5804** are used to add SQL functions or aggregates or to redefine the behavior5805** of existing SQL functions or aggregates. The only differences between5806** the three "sqlite3_create_function*" routines are the text encoding5807** expected for the second parameter (the name of the function being5808** created) and the presence or absence of a destructor callback for5809** the application data pointer. Function sqlite3_create_window_function()5810** is similar, but allows the user to supply the extra callback functions5811** needed by [aggregate window functions].5812**5813** ^The first parameter is the [database connection] to which the SQL5814** function is to be added.  ^If an application uses more than one database5815** connection then application-defined SQL functions must be added5816** to each database connection separately.5817**5818** ^The second parameter is the name of the SQL function to be created or5819** redefined.  ^The length of the name is limited to 255 bytes in a UTF-85820** representation, exclusive of the zero-terminator.  ^Note that the name5821** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.5822** ^Any attempt to create a function with a longer name5823** will result in [SQLITE_MISUSE] being returned.5824**5825** ^The third parameter (nArg)5826** is the number of arguments that the SQL function or5827** aggregate takes. ^If this parameter is -1, then the SQL function or5828** aggregate may take any number of arguments between 0 and the limit5829** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third5830** parameter is less than -1 or greater than 127 then the behavior is5831** undefined.5832**5833** ^The fourth parameter, eTextRep, specifies what5834** [SQLITE_UTF8 | text encoding] this SQL function prefers for5835** its parameters.  The application should set this parameter to5836** [SQLITE_UTF16LE] if the function implementation invokes5837** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the5838** implementation invokes [sqlite3_value_text16be()] on an input, or5839** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]5840** otherwise.  ^The same SQL function may be registered multiple times using5841** different preferred text encodings, with different implementations for5842** each encoding.5843** ^When multiple implementations of the same function are available, SQLite5844** will pick the one that involves the least amount of data conversion.5845**5846** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]5847** to signal that the function will always return the same result given5848** the same inputs within a single SQL statement.  Most SQL functions are5849** deterministic.  The built-in [random()] SQL function is an example of a5850** function that is not deterministic.  The SQLite query planner is able to5851** perform additional optimizations on deterministic functions, so use5852** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.5853**5854** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY]5855** flag, which if present prevents the function from being invoked from5856** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,5857** index expressions, or the WHERE clause of partial indexes.5858**5859** For best security, the [SQLITE_DIRECTONLY] flag is recommended for5860** all application-defined SQL functions that do not need to be5861** used inside of triggers, view, CHECK constraints, or other elements of5862** the database schema.  This flags is especially recommended for SQL5863** functions that have side effects or reveal internal application state.5864** Without this flag, an attacker might be able to modify the schema of5865** a database file to include invocations of the function with parameters5866** chosen by the attacker, which the application will then execute when5867** the database file is opened and read.5868**5869** ^(The fifth parameter is an arbitrary pointer.  The implementation of the5870** function can gain access to this pointer using [sqlite3_user_data()].)^5871**5872** ^The sixth, seventh and eighth parameters passed to the three5873** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are5874** pointers to C-language functions that implement the SQL function or5875** aggregate. ^A scalar SQL function requires an implementation of the xFunc5876** callback only; NULL pointers must be passed as the xStep and xFinal5877** parameters. ^An aggregate SQL function requires an implementation of xStep5878** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing5879** SQL function or aggregate, pass NULL pointers for all three function5880** callbacks.5881**5882** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue5883** and xInverse) passed to sqlite3_create_window_function are pointers to5884** C-language callbacks that implement the new function. xStep and xFinal5885** must both be non-NULL. xValue and xInverse may either both be NULL, in5886** which case a regular aggregate function is created, or must both be5887** non-NULL, in which case the new function may be used as either an aggregate5888** or aggregate window function. More details regarding the implementation5889** of aggregate window functions are5890** [user-defined window functions|available here].5891**5892** ^(If the final parameter to sqlite3_create_function_v2() or5893** sqlite3_create_window_function() is not NULL, then it is destructor for5894** the application data pointer. The destructor is invoked when the function5895** is deleted, either by being overloaded or when the database connection5896** closes.)^ ^The destructor is also invoked if the call to5897** sqlite3_create_function_v2() fails.  ^When the destructor callback is5898** invoked, it is passed a single argument which is a copy of the application5899** data pointer which was the fifth parameter to sqlite3_create_function_v2().5900**5901** ^It is permitted to register multiple implementations of the same5902** functions with the same name but with either differing numbers of5903** arguments or differing preferred text encodings.  ^SQLite will use5904** the implementation that most closely matches the way in which the5905** SQL function is used.  ^A function implementation with a non-negative5906** nArg parameter is a better match than a function implementation with5907** a negative nArg.  ^A function where the preferred text encoding5908** matches the database encoding is a better5909** match than a function where the encoding is different.5910** ^A function where the encoding difference is between UTF16le and UTF16be5911** is a closer match than a function where the encoding difference is5912** between UTF8 and UTF16.5913**5914** ^Built-in functions may be overloaded by new application-defined functions.5915**5916** ^An application-defined function is permitted to call other5917** SQLite interfaces.  However, such calls must not5918** close the database connection nor finalize or reset the prepared5919** statement in which the function is running.5920*/5921SQLITE_API int sqlite3_create_function(5922  sqlite3 *db,5923  const char *zFunctionName,5924  int nArg,5925  int eTextRep,5926  void *pApp,5927  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),5928  void (*xStep)(sqlite3_context*,int,sqlite3_value**),5929  void (*xFinal)(sqlite3_context*)5930);5931SQLITE_API int sqlite3_create_function16(5932  sqlite3 *db,5933  const void *zFunctionName,5934  int nArg,5935  int eTextRep,5936  void *pApp,5937  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),5938  void (*xStep)(sqlite3_context*,int,sqlite3_value**),5939  void (*xFinal)(sqlite3_context*)5940);5941SQLITE_API int sqlite3_create_function_v2(5942  sqlite3 *db,5943  const char *zFunctionName,5944  int nArg,5945  int eTextRep,5946  void *pApp,5947  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),5948  void (*xStep)(sqlite3_context*,int,sqlite3_value**),5949  void (*xFinal)(sqlite3_context*),5950  void(*xDestroy)(void*)5951);5952SQLITE_API int sqlite3_create_window_function(5953  sqlite3 *db,5954  const char *zFunctionName,5955  int nArg,5956  int eTextRep,5957  void *pApp,5958  void (*xStep)(sqlite3_context*,int,sqlite3_value**),5959  void (*xFinal)(sqlite3_context*),5960  void (*xValue)(sqlite3_context*),5961  void (*xInverse)(sqlite3_context*,int,sqlite3_value**),5962  void(*xDestroy)(void*)5963);59645965/*5966** CAPI3REF: Text Encodings5967**5968** These constant define integer codes that represent the various5969** text encodings supported by SQLite.5970*/5971#define SQLITE_UTF8           1    /* IMP: R-37514-35566 */5972#define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */5973#define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */5974#define SQLITE_UTF16          4    /* Use native byte order */5975#define SQLITE_ANY            5    /* Deprecated */5976#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */59775978/*5979** CAPI3REF: Function Flags5980**5981** These constants may be ORed together with the5982** [SQLITE_UTF8 | preferred text encoding] as the fourth argument5983** to [sqlite3_create_function()], [sqlite3_create_function16()], or5984** [sqlite3_create_function_v2()].5985**5986** <dl>5987** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd>5988** The SQLITE_DETERMINISTIC flag means that the new function always gives5989** the same output when the input parameters are the same.5990** The [abs|abs() function] is deterministic, for example, but5991** [randomblob|randomblob()] is not.  Functions must5992** be deterministic in order to be used in certain contexts such as5993** with the WHERE clause of [partial indexes] or in [generated columns].5994** SQLite might also optimize deterministic functions by factoring them5995** out of inner loops.5996** </dd>5997**5998** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd>5999** The SQLITE_DIRECTONLY flag means that the function may only be invoked6000** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in6001** schema structures such as [CHECK constraints], [DEFAULT clauses],6002** [expression indexes], [partial indexes], or [generated columns].6003** <p>6004** The SQLITE_DIRECTONLY flag is recommended for any6005** [application-defined SQL function]6006** that has side-effects or that could potentially leak sensitive information.6007** This will prevent attacks in which an application is tricked6008** into using a database file that has had its schema surreptitiously6009** modified to invoke the application-defined function in ways that are6010** harmful.6011** <p>6012** Some people say it is good practice to set SQLITE_DIRECTONLY on all6013** [application-defined SQL functions], regardless of whether or not they6014** are security sensitive, as doing so prevents those functions from being used6015** inside of the database schema, and thus ensures that the database6016** can be inspected and modified using generic tools (such as the [CLI])6017** that do not have access to the application-defined functions.6018** </dd>6019**6020** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd>6021** The SQLITE_INNOCUOUS flag means that the function is unlikely6022** to cause problems even if misused.  An innocuous function should have6023** no side effects and should not depend on any values other than its6024** input parameters. The [abs|abs() function] is an example of an6025** innocuous function.6026** The [load_extension() SQL function] is not innocuous because of its6027** side effects.6028** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not6029** exactly the same.  The [random|random() function] is an example of a6030** function that is innocuous but not deterministic.6031** <p>Some heightened security settings6032** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF])6033** disable the use of SQL functions inside views and triggers and in6034** schema structures such as [CHECK constraints], [DEFAULT clauses],6035** [expression indexes], [partial indexes], and [generated columns] unless6036** the function is tagged with SQLITE_INNOCUOUS.  Most built-in functions6037** are innocuous.  Developers are advised to avoid using the6038** SQLITE_INNOCUOUS flag for application-defined functions unless the6039** function has been carefully audited and found to be free of potentially6040** security-adverse side-effects and information-leaks.6041** </dd>6042**6043** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>6044** The SQLITE_SUBTYPE flag indicates to SQLite that a function might call6045** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.6046** This flag instructs SQLite to omit some corner-case optimizations that6047** might disrupt the operation of the [sqlite3_value_subtype()] function,6048** causing it to return zero rather than the correct subtype().6049** All SQL functions that invoke [sqlite3_value_subtype()] should have this6050** property.  If the SQLITE_SUBTYPE property is omitted, then the return6051** value from [sqlite3_value_subtype()] might sometimes be zero even though6052** a non-zero subtype was specified by the function argument expression.6053**6054** [[SQLITE_RESULT_SUBTYPE]] <dt>SQLITE_RESULT_SUBTYPE</dt><dd>6055** The SQLITE_RESULT_SUBTYPE flag indicates to SQLite that a function might call6056** [sqlite3_result_subtype()] to cause a sub-type to be associated with its6057** result.6058** Every function that invokes [sqlite3_result_subtype()] should have this6059** property.  If it does not, then the call to [sqlite3_result_subtype()]6060** might become a no-op if the function is used as term in an6061** [expression index].  On the other hand, SQL functions that never invoke6062** [sqlite3_result_subtype()] should avoid setting this property, as the6063** purpose of this property is to disable certain optimizations that are6064** incompatible with subtypes.6065**6066** [[SQLITE_SELFORDER1]] <dt>SQLITE_SELFORDER1</dt><dd>6067** The SQLITE_SELFORDER1 flag indicates that the function is an aggregate6068** that internally orders the values provided to the first argument.  The6069** ordered-set aggregate SQL notation with a single ORDER BY term can be6070** used to invoke this function.  If the ordered-set aggregate notation is6071** used on a function that lacks this flag, then an error is raised. Note6072** that the ordered-set aggregate syntax is only available if SQLite is6073** built using the -DSQLITE_ENABLE_ORDERED_SET_AGGREGATES compile-time option.6074** </dd>6075** </dl>6076*/6077#define SQLITE_DETERMINISTIC    0x0000008006078#define SQLITE_DIRECTONLY       0x0000800006079#define SQLITE_SUBTYPE          0x0001000006080#define SQLITE_INNOCUOUS        0x0002000006081#define SQLITE_RESULT_SUBTYPE   0x0010000006082#define SQLITE_SELFORDER1       0x00200000060836084/*6085** CAPI3REF: Deprecated Functions6086** DEPRECATED6087**6088** These functions are [deprecated].  In order to maintain6089** backwards compatibility with older code, these functions continue6090** to be supported.  However, new applications should avoid6091** the use of these functions.  To encourage programmers to avoid6092** these functions, we will not explain what they do.6093*/6094#ifndef SQLITE_OMIT_DEPRECATED6095SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);6096SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);6097SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);6098SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);6099SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);6100SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),6101                      void*,sqlite3_int64);6102#endif61036104/*6105** CAPI3REF: Obtaining SQL Values6106** METHOD: sqlite3_value6107**6108** <b>Summary:</b>6109** <blockquote><table border=0 cellpadding=0 cellspacing=0>6110** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value6111** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value6112** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value6113** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value6114** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value6115** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value6116** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in6117** the native byteorder6118** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value6119** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value6120** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;6121** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB6122** or a UTF-8 TEXT in bytes6123** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>6124** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-166125** TEXT in bytes6126** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default6127** datatype of the value6128** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>6129** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value6130** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>6131** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE6132** against a virtual table.6133** <tr><td><b>sqlite3_value_frombind&nbsp;&nbsp;</b>6134** <td>&rarr;&nbsp;&nbsp;<td>True if value originated from a [bound parameter]6135** </table></blockquote>6136**6137** <b>Details:</b>6138**6139** These routines extract type, size, and content information from6140** [protected sqlite3_value] objects.  Protected sqlite3_value objects6141** are used to pass parameter information into the functions that6142** implement [application-defined SQL functions] and [virtual tables].6143**6144** These routines work only with [protected sqlite3_value] objects.6145** Any attempt to use these routines on an [unprotected sqlite3_value]6146** is not threadsafe.6147**6148** ^These routines work just like the corresponding [column access functions]6149** except that these routines take a single [protected sqlite3_value] object6150** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.6151**6152** ^The sqlite3_value_text16() interface extracts a UTF-16 string6153** in the native byte-order of the host machine.  ^The6154** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces6155** extract UTF-16 strings as big-endian and little-endian respectively.6156**6157** ^If [sqlite3_value] object V was initialized6158** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]6159** and if X and Y are strings that compare equal according to strcmp(X,Y),6160** then sqlite3_value_pointer(V,Y) will return the pointer P.  ^Otherwise,6161** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()6162** routine is part of the [pointer passing interface] added for SQLite 3.20.0.6163**6164** ^(The sqlite3_value_type(V) interface returns the6165** [SQLITE_INTEGER | datatype code] for the initial datatype of the6166** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],6167** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^6168** Other interfaces might change the datatype for an sqlite3_value object.6169** For example, if the datatype is initially SQLITE_INTEGER and6170** sqlite3_value_text(V) is called to extract a text value for that6171** integer, then subsequent calls to sqlite3_value_type(V) might return6172** SQLITE_TEXT.  Whether or not a persistent internal datatype conversion6173** occurs is undefined and may change from one release of SQLite to the next.6174**6175** ^(The sqlite3_value_numeric_type() interface attempts to apply6176** numeric affinity to the value.  This means that an attempt is6177** made to convert the value to an integer or floating point.  If6178** such a conversion is possible without loss of information (in other6179** words, if the value is a string that looks like a number)6180** then the conversion is performed.  Otherwise no conversion occurs.6181** The [SQLITE_INTEGER | datatype] after conversion is returned.)^6182**6183** ^Within the [xUpdate] method of a [virtual table], the6184** sqlite3_value_nochange(X) interface returns true if and only if6185** the column corresponding to X is unchanged by the UPDATE operation6186** that the xUpdate method call was invoked to implement and if6187** and the prior [xColumn] method call that was invoked to extracted6188** the value for that column returned without setting a result (probably6189** because it queried [sqlite3_vtab_nochange()] and found that the column6190** was unchanging).  ^Within an [xUpdate] method, any value for which6191** sqlite3_value_nochange(X) is true will in all other respects appear6192** to be a NULL value.  If sqlite3_value_nochange(X) is invoked anywhere other6193** than within an [xUpdate] method call for an UPDATE statement, then6194** the return value is arbitrary and meaningless.6195**6196** ^The sqlite3_value_frombind(X) interface returns non-zero if the6197** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]6198** interfaces.  ^If X comes from an SQL literal value, or a table column,6199** or an expression, then sqlite3_value_frombind(X) returns zero.6200**6201** Please pay particular attention to the fact that the pointer returned6202** from [sqlite3_value_blob()], [sqlite3_value_text()], or6203** [sqlite3_value_text16()] can be invalidated by a subsequent call to6204** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],6205** or [sqlite3_value_text16()].6206**6207** These routines must be called from the same thread as6208** the SQL function that supplied the [sqlite3_value*] parameters.6209**6210** As long as the input parameter is correct, these routines can only6211** fail if an out-of-memory error occurs during a format conversion.6212** Only the following subset of interfaces are subject to out-of-memory6213** errors:6214**6215** <ul>6216** <li> sqlite3_value_blob()6217** <li> sqlite3_value_text()6218** <li> sqlite3_value_text16()6219** <li> sqlite3_value_text16le()6220** <li> sqlite3_value_text16be()6221** <li> sqlite3_value_bytes()6222** <li> sqlite3_value_bytes16()6223** </ul>6224**6225** If an out-of-memory error occurs, then the return value from these6226** routines is the same as if the column had contained an SQL NULL value.6227** Valid SQL NULL returns can be distinguished from out-of-memory errors6228** by invoking the [sqlite3_errcode()] immediately after the suspect6229** return value is obtained and before any6230** other SQLite interface is called on the same [database connection].6231*/6232SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);6233SQLITE_API double sqlite3_value_double(sqlite3_value*);6234SQLITE_API int sqlite3_value_int(sqlite3_value*);6235SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);6236SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);6237SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);6238SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);6239SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);6240SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);6241SQLITE_API int sqlite3_value_bytes(sqlite3_value*);6242SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);6243SQLITE_API int sqlite3_value_type(sqlite3_value*);6244SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);6245SQLITE_API int sqlite3_value_nochange(sqlite3_value*);6246SQLITE_API int sqlite3_value_frombind(sqlite3_value*);62476248/*6249** CAPI3REF: Report the internal text encoding state of an sqlite3_value object6250** METHOD: sqlite3_value6251**6252** ^(The sqlite3_value_encoding(X) interface returns one of [SQLITE_UTF8],6253** [SQLITE_UTF16BE], or [SQLITE_UTF16LE] according to the current text encoding6254** of the value X, assuming that X has type TEXT.)^  If sqlite3_value_type(X)6255** returns something other than SQLITE_TEXT, then the return value from6256** sqlite3_value_encoding(X) is meaningless.  ^Calls to6257** [sqlite3_value_text(X)], [sqlite3_value_text16(X)], [sqlite3_value_text16be(X)],6258** [sqlite3_value_text16le(X)], [sqlite3_value_bytes(X)], or6259** [sqlite3_value_bytes16(X)] might change the encoding of the value X and6260** thus change the return from subsequent calls to sqlite3_value_encoding(X).6261**6262** This routine is intended for used by applications that test and validate6263** the SQLite implementation.  This routine is inquiring about the opaque6264** internal state of an [sqlite3_value] object.  Ordinary applications should6265** not need to know what the internal state of an sqlite3_value object is and6266** hence should not need to use this interface.6267*/6268SQLITE_API int sqlite3_value_encoding(sqlite3_value*);62696270/*6271** CAPI3REF: Finding The Subtype Of SQL Values6272** METHOD: sqlite3_value6273**6274** The sqlite3_value_subtype(V) function returns the subtype for6275** an [application-defined SQL function] argument V.  The subtype6276** information can be used to pass a limited amount of context from6277** one SQL function to another.  Use the [sqlite3_result_subtype()]6278** routine to set the subtype for the return value of an SQL function.6279**6280** Every [application-defined SQL function] that invokes this interface6281** should include the [SQLITE_SUBTYPE] property in the text6282** encoding argument when the function is [sqlite3_create_function|registered].6283** If the [SQLITE_SUBTYPE] property is omitted, then sqlite3_value_subtype()6284** might return zero instead of the upstream subtype in some corner cases.6285*/6286SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);62876288/*6289** CAPI3REF: Copy And Free SQL Values6290** METHOD: sqlite3_value6291**6292** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]6293** object D and returns a pointer to that copy.  ^The [sqlite3_value] returned6294** is a [protected sqlite3_value] object even if the input is not.6295** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a6296** memory allocation fails. ^If V is a [pointer value], then the result6297** of sqlite3_value_dup(V) is a NULL value.6298**6299** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object6300** previously obtained from [sqlite3_value_dup()].  ^If V is a NULL pointer6301** then sqlite3_value_free(V) is a harmless no-op.6302*/6303SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);6304SQLITE_API void sqlite3_value_free(sqlite3_value*);63056306/*6307** CAPI3REF: Obtain Aggregate Function Context6308** METHOD: sqlite3_context6309**6310** Implementations of aggregate SQL functions use this6311** routine to allocate memory for storing their state.6312**6313** ^The first time the sqlite3_aggregate_context(C,N) routine is called6314** for a particular aggregate function, SQLite allocates6315** N bytes of memory, zeroes out that memory, and returns a pointer6316** to the new memory. ^On second and subsequent calls to6317** sqlite3_aggregate_context() for the same aggregate function instance,6318** the same buffer is returned.  Sqlite3_aggregate_context() is normally6319** called once for each invocation of the xStep callback and then one6320** last time when the xFinal callback is invoked.  ^(When no rows match6321** an aggregate query, the xStep() callback of the aggregate function6322** implementation is never called and xFinal() is called exactly once.6323** In those cases, sqlite3_aggregate_context() might be called for the6324** first time from within xFinal().)^6325**6326** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer6327** when first called if N is less than or equal to zero or if a memory6328** allocation error occurs.6329**6330** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is6331** determined by the N parameter on first successful call.  Changing the6332** value of N in any subsequent call to sqlite3_aggregate_context() within6333** the same aggregate function instance will not resize the memory6334** allocation.)^  Within the xFinal callback, it is customary to set6335** N=0 in calls to sqlite3_aggregate_context(C,N) so that no6336** pointless memory allocations occur.6337**6338** ^SQLite automatically frees the memory allocated by6339** sqlite3_aggregate_context() when the aggregate query concludes.6340**6341** The first parameter must be a copy of the6342** [sqlite3_context | SQL function context] that is the first parameter6343** to the xStep or xFinal callback routine that implements the aggregate6344** function.6345**6346** This routine must be called from the same thread in which6347** the aggregate SQL function is running.6348*/6349SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);63506351/*6352** CAPI3REF: User Data For Functions6353** METHOD: sqlite3_context6354**6355** ^The sqlite3_user_data() interface returns a copy of6356** the pointer that was the pUserData parameter (the 5th parameter)6357** of the [sqlite3_create_function()]6358** and [sqlite3_create_function16()] routines that originally6359** registered the application defined function.6360**6361** This routine must be called from the same thread in which6362** the application-defined function is running.6363*/6364SQLITE_API void *sqlite3_user_data(sqlite3_context*);63656366/*6367** CAPI3REF: Database Connection For Functions6368** METHOD: sqlite3_context6369**6370** ^The sqlite3_context_db_handle() interface returns a copy of6371** the pointer to the [database connection] (the 1st parameter)6372** of the [sqlite3_create_function()]6373** and [sqlite3_create_function16()] routines that originally6374** registered the application defined function.6375*/6376SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);63776378/*6379** CAPI3REF: Function Auxiliary Data6380** METHOD: sqlite3_context6381**6382** These functions may be used by (non-aggregate) SQL functions to6383** associate auxiliary data with argument values. If the same argument6384** value is passed to multiple invocations of the same SQL function during6385** query execution, under some circumstances the associated auxiliary data6386** might be preserved.  An example of where this might be useful is in a6387** regular-expression matching function. The compiled version of the regular6388** expression can be stored as auxiliary data associated with the pattern string.6389** Then as long as the pattern string remains the same,6390** the compiled regular expression can be reused on multiple6391** invocations of the same function.6392**6393** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the auxiliary data6394** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument6395** value to the application-defined function.  ^N is zero for the left-most6396** function argument.  ^If there is no auxiliary data6397** associated with the function argument, the sqlite3_get_auxdata(C,N) interface6398** returns a NULL pointer.6399**6400** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as auxiliary data for the6401** N-th argument of the application-defined function.  ^Subsequent6402** calls to sqlite3_get_auxdata(C,N) return P from the most recent6403** sqlite3_set_auxdata(C,N,P,X) call if the auxiliary data is still valid or6404** NULL if the auxiliary data has been discarded.6405** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,6406** SQLite will invoke the destructor function X with parameter P exactly6407** once, when the auxiliary data is discarded.6408** SQLite is free to discard the auxiliary data at any time, including: <ul>6409** <li> ^(when the corresponding function parameter changes)^, or6410** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the6411**      SQL statement)^, or6412** <li> ^(when sqlite3_set_auxdata() is invoked again on the same6413**       parameter)^, or6414** <li> ^(during the original sqlite3_set_auxdata() call when a memory6415**      allocation error occurs.)^6416** <li> ^(during the original sqlite3_set_auxdata() call if the function6417**      is evaluated during query planning instead of during query execution,6418**      as sometimes happens with [SQLITE_ENABLE_STAT4].)^ </ul>6419**6420** Note the last two bullets in particular.  The destructor X in6421** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the6422** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()6423** should be called near the end of the function implementation and the6424** function implementation should not make any use of P after6425** sqlite3_set_auxdata() has been called.  Furthermore, a call to6426** sqlite3_get_auxdata() that occurs immediately after a corresponding call6427** to sqlite3_set_auxdata() might still return NULL if an out-of-memory6428** condition occurred during the sqlite3_set_auxdata() call or if the6429** function is being evaluated during query planning rather than during6430** query execution.6431**6432** ^(In practice, auxiliary data is preserved between function calls for6433** function parameters that are compile-time constants, including literal6434** values and [parameters] and expressions composed from the same.)^6435**6436** The value of the N parameter to these interfaces should be non-negative.6437** Future enhancements may make use of negative N values to define new6438** kinds of function caching behavior.6439**6440** These routines must be called from the same thread in which6441** the SQL function is running.6442**6443** See also: [sqlite3_get_clientdata()] and [sqlite3_set_clientdata()].6444*/6445SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);6446SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));64476448/*6449** CAPI3REF: Database Connection Client Data6450** METHOD: sqlite36451**6452** These functions are used to associate one or more named pointers6453** with a [database connection].6454** A call to sqlite3_set_clientdata(D,N,P,X) causes the pointer P6455** to be attached to [database connection] D using name N.  Subsequent6456** calls to sqlite3_get_clientdata(D,N) will return a copy of pointer P6457** or a NULL pointer if there were no prior calls to6458** sqlite3_set_clientdata() with the same values of D and N.6459** Names are compared using strcmp() and are thus case sensitive.6460**6461** If P and X are both non-NULL, then the destructor X is invoked with6462** argument P on the first of the following occurrences:6463** <ul>6464** <li> An out-of-memory error occurs during the call to6465**      sqlite3_set_clientdata() which attempts to register pointer P.6466** <li> A subsequent call to sqlite3_set_clientdata(D,N,P,X) is made6467**      with the same D and N parameters.6468** <li> The database connection closes.  SQLite does not make any guarantees6469**      about the order in which destructors are called, only that all6470**      destructors will be called exactly once at some point during the6471**      database connection closing process.6472** </ul>6473**6474** SQLite does not do anything with client data other than invoke6475** destructors on the client data at the appropriate time.  The intended6476** use for client data is to provide a mechanism for wrapper libraries6477** to store additional information about an SQLite database connection.6478**6479** There is no limit (other than available memory) on the number of different6480** client data pointers (with different names) that can be attached to a6481** single database connection.  However, the implementation is optimized6482** for the case of having only one or two different client data names.6483** Applications and wrapper libraries are discouraged from using more than6484** one client data name each.6485**6486** There is no way to enumerate the client data pointers6487** associated with a database connection.  The N parameter can be thought6488** of as a secret key such that only code that knows the secret key is able6489** to access the associated data.6490**6491** Security Warning:  These interfaces should not be exposed in scripting6492** languages or in other circumstances where it might be possible for an6493** an attacker to invoke them.  Any agent that can invoke these interfaces6494** can probably also take control of the process.6495**6496** Database connection client data is only available for SQLite6497** version 3.44.0 ([dateof:3.44.0]) and later.6498**6499** See also: [sqlite3_set_auxdata()] and [sqlite3_get_auxdata()].6500*/6501SQLITE_API void *sqlite3_get_clientdata(sqlite3*,const char*);6502SQLITE_API int sqlite3_set_clientdata(sqlite3*, const char*, void*, void(*)(void*));65036504/*6505** CAPI3REF: Constants Defining Special Destructor Behavior6506**6507** These are special values for the destructor that is passed in as the6508** final argument to routines like [sqlite3_result_blob()].  ^If the destructor6509** argument is SQLITE_STATIC, it means that the content pointer is constant6510** and will never change.  It does not need to be destroyed.  ^The6511** SQLITE_TRANSIENT value means that the content will likely change in6512** the near future and that SQLite should make its own private copy of6513** the content before returning.6514**6515** The typedef is necessary to work around problems in certain6516** C++ compilers.6517*/6518typedef void (*sqlite3_destructor_type)(void*);6519#define SQLITE_STATIC      ((sqlite3_destructor_type)0)6520#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)65216522/*6523** CAPI3REF: Setting The Result Of An SQL Function6524** METHOD: sqlite3_context6525**6526** These routines are used by the xFunc or xFinal callbacks that6527** implement SQL functions and aggregates.  See6528** [sqlite3_create_function()] and [sqlite3_create_function16()]6529** for additional information.6530**6531** These functions work very much like the [parameter binding] family of6532** functions used to bind values to host parameters in prepared statements.6533** Refer to the [SQL parameter] documentation for additional information.6534**6535** ^The sqlite3_result_blob() interface sets the result from6536** an application-defined function to be the BLOB whose content is pointed6537** to by the second parameter and which is N bytes long where N is the6538** third parameter.6539**6540** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)6541** interfaces set the result of the application-defined function to be6542** a BLOB containing all zero bytes and N bytes in size.6543**6544** ^The sqlite3_result_double() interface sets the result from6545** an application-defined function to be a floating point value specified6546** by its 2nd argument.6547**6548** ^The sqlite3_result_error() and sqlite3_result_error16() functions6549** cause the implemented SQL function to throw an exception.6550** ^SQLite uses the string pointed to by the6551** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()6552** as the text of an error message.  ^SQLite interprets the error6553** message string from sqlite3_result_error() as UTF-8. ^SQLite6554** interprets the string from sqlite3_result_error16() as UTF-16 using6555** the same [byte-order determination rules] as [sqlite3_bind_text16()].6556** ^If the third parameter to sqlite3_result_error()6557** or sqlite3_result_error16() is negative then SQLite takes as the error6558** message all text up through the first zero character.6559** ^If the third parameter to sqlite3_result_error() or6560** sqlite3_result_error16() is non-negative then SQLite takes that many6561** bytes (not characters) from the 2nd parameter as the error message.6562** ^The sqlite3_result_error() and sqlite3_result_error16()6563** routines make a private copy of the error message text before6564** they return.  Hence, the calling function can deallocate or6565** modify the text after they return without harm.6566** ^The sqlite3_result_error_code() function changes the error code6567** returned by SQLite as a result of an error in a function.  ^By default,6568** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()6569** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.6570**6571** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an6572** error indicating that a string or BLOB is too long to represent.6573**6574** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an6575** error indicating that a memory allocation failed.6576**6577** ^The sqlite3_result_int() interface sets the return value6578** of the application-defined function to be the 32-bit signed integer6579** value given in the 2nd argument.6580** ^The sqlite3_result_int64() interface sets the return value6581** of the application-defined function to be the 64-bit signed integer6582** value given in the 2nd argument.6583**6584** ^The sqlite3_result_null() interface sets the return value6585** of the application-defined function to be NULL.6586**6587** ^The sqlite3_result_text(), sqlite3_result_text16(),6588** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces6589** set the return value of the application-defined function to be6590** a text string which is represented as UTF-8, UTF-16 native byte order,6591** UTF-16 little endian, or UTF-16 big endian, respectively.6592** ^The sqlite3_result_text64() interface sets the return value of an6593** application-defined function to be a text string in an encoding6594** specified by the fifth (and last) parameter, which must be one6595** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].6596** ^SQLite takes the text result from the application from6597** the 2nd parameter of the sqlite3_result_text* interfaces.6598** ^If the 3rd parameter to any of the sqlite3_result_text* interfaces6599** other than sqlite3_result_text64() is negative, then SQLite computes6600** the string length itself by searching the 2nd parameter for the first6601** zero character.6602** ^If the 3rd parameter to the sqlite3_result_text* interfaces6603** is non-negative, then as many bytes (not characters) of the text6604** pointed to by the 2nd parameter are taken as the application-defined6605** function result.  If the 3rd parameter is non-negative, then it6606** must be the byte offset into the string where the NUL terminator would6607** appear if the string where NUL terminated.  If any NUL characters occur6608** in the string at a byte offset that is less than the value of the 3rd6609** parameter, then the resulting string will contain embedded NULs and the6610** result of expressions operating on strings with embedded NULs is undefined.6611** ^If the 4th parameter to the sqlite3_result_text* interfaces6612** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that6613** function as the destructor on the text or BLOB result when it has6614** finished using that result.6615** ^If the 4th parameter to the sqlite3_result_text* interfaces or to6616** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite6617** assumes that the text or BLOB result is in constant space and does not6618** copy the content of the parameter nor call a destructor on the content6619** when it has finished using that result.6620** ^If the 4th parameter to the sqlite3_result_text* interfaces6621** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT6622** then SQLite makes a copy of the result into space obtained6623** from [sqlite3_malloc()] before it returns.6624**6625** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and6626** sqlite3_result_text16be() routines, and for sqlite3_result_text64()6627** when the encoding is not UTF8, if the input UTF16 begins with a6628** byte-order mark (BOM, U+FEFF) then the BOM is removed from the6629** string and the rest of the string is interpreted according to the6630** byte-order specified by the BOM.  ^The byte-order specified by6631** the BOM at the beginning of the text overrides the byte-order6632** specified by the interface procedure.  ^So, for example, if6633** sqlite3_result_text16le() is invoked with text that begins6634** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the6635** first two bytes of input are skipped and the remaining input6636** is interpreted as UTF16BE text.6637**6638** ^For UTF16 input text to the sqlite3_result_text16(),6639** sqlite3_result_text16be(), sqlite3_result_text16le(), and6640** sqlite3_result_text64() routines, if the text contains invalid6641** UTF16 characters, the invalid characters might be converted6642** into the unicode replacement character, U+FFFD.6643**6644** ^The sqlite3_result_value() interface sets the result of6645** the application-defined function to be a copy of the6646** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The6647** sqlite3_result_value() interface makes a copy of the [sqlite3_value]6648** so that the [sqlite3_value] specified in the parameter may change or6649** be deallocated after sqlite3_result_value() returns without harm.6650** ^A [protected sqlite3_value] object may always be used where an6651** [unprotected sqlite3_value] object is required, so either6652** kind of [sqlite3_value] object can be used with this interface.6653**6654** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an6655** SQL NULL value, just like [sqlite3_result_null(C)], except that it6656** also associates the host-language pointer P or type T with that6657** NULL value such that the pointer can be retrieved within an6658** [application-defined SQL function] using [sqlite3_value_pointer()].6659** ^If the D parameter is not NULL, then it is a pointer to a destructor6660** for the P parameter.  ^SQLite invokes D with P as its only argument6661** when SQLite is finished with P.  The T parameter should be a static6662** string and preferably a string literal. The sqlite3_result_pointer()6663** routine is part of the [pointer passing interface] added for SQLite 3.20.0.6664**6665** If these routines are called from within the different thread6666** than the one containing the application-defined function that received6667** the [sqlite3_context] pointer, the results are undefined.6668*/6669SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));6670SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,6671                           sqlite3_uint64,void(*)(void*));6672SQLITE_API void sqlite3_result_double(sqlite3_context*, double);6673SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);6674SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);6675SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);6676SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);6677SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);6678SQLITE_API void sqlite3_result_int(sqlite3_context*, int);6679SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);6680SQLITE_API void sqlite3_result_null(sqlite3_context*);6681SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));6682SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,6683                           void(*)(void*), unsigned char encoding);6684SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));6685SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));6686SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));6687SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);6688SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));6689SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);6690SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);669166926693/*6694** CAPI3REF: Setting The Subtype Of An SQL Function6695** METHOD: sqlite3_context6696**6697** The sqlite3_result_subtype(C,T) function causes the subtype of6698** the result from the [application-defined SQL function] with6699** [sqlite3_context] C to be the value T.  Only the lower 8 bits6700** of the subtype T are preserved in current versions of SQLite;6701** higher order bits are discarded.6702** The number of subtype bytes preserved by SQLite might increase6703** in future releases of SQLite.6704**6705** Every [application-defined SQL function] that invokes this interface6706** should include the [SQLITE_RESULT_SUBTYPE] property in its6707** text encoding argument when the SQL function is6708** [sqlite3_create_function|registered].  If the [SQLITE_RESULT_SUBTYPE]6709** property is omitted from the function that invokes sqlite3_result_subtype(),6710** then in some cases the sqlite3_result_subtype() might fail to set6711** the result subtype.6712**6713** If SQLite is compiled with -DSQLITE_STRICT_SUBTYPE=1, then any6714** SQL function that invokes the sqlite3_result_subtype() interface6715** and that does not have the SQLITE_RESULT_SUBTYPE property will raise6716** an error.  Future versions of SQLite might enable -DSQLITE_STRICT_SUBTYPE=16717** by default.6718*/6719SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);67206721/*6722** CAPI3REF: Define New Collating Sequences6723** METHOD: sqlite36724**6725** ^These functions add, remove, or modify a [collation] associated6726** with the [database connection] specified as the first argument.6727**6728** ^The name of the collation is a UTF-8 string6729** for sqlite3_create_collation() and sqlite3_create_collation_v2()6730** and a UTF-16 string in native byte order for sqlite3_create_collation16().6731** ^Collation names that compare equal according to [sqlite3_strnicmp()] are6732** considered to be the same name.6733**6734** ^(The third argument (eTextRep) must be one of the constants:6735** <ul>6736** <li> [SQLITE_UTF8],6737** <li> [SQLITE_UTF16LE],6738** <li> [SQLITE_UTF16BE],6739** <li> [SQLITE_UTF16], or6740** <li> [SQLITE_UTF16_ALIGNED].6741** </ul>)^6742** ^The eTextRep argument determines the encoding of strings passed6743** to the collating function callback, xCompare.6744** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep6745** force strings to be UTF16 with native byte order.6746** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin6747** on an even byte address.6748**6749** ^The fourth argument, pArg, is an application data pointer that is passed6750** through as the first argument to the collating function callback.6751**6752** ^The fifth argument, xCompare, is a pointer to the collating function.6753** ^Multiple collating functions can be registered using the same name but6754** with different eTextRep parameters and SQLite will use whichever6755** function requires the least amount of data transformation.6756** ^If the xCompare argument is NULL then the collating function is6757** deleted.  ^When all collating functions having the same name are deleted,6758** that collation is no longer usable.6759**6760** ^The collating function callback is invoked with a copy of the pArg6761** application data pointer and with two strings in the encoding specified6762** by the eTextRep argument.  The two integer parameters to the collating6763** function callback are the length of the two strings, in bytes. The collating6764** function must return an integer that is negative, zero, or positive6765** if the first string is less than, equal to, or greater than the second,6766** respectively.  A collating function must always return the same answer6767** given the same inputs.  If two or more collating functions are registered6768** to the same collation name (using different eTextRep values) then all6769** must give an equivalent answer when invoked with equivalent strings.6770** The collating function must obey the following properties for all6771** strings A, B, and C:6772**6773** <ol>6774** <li> If A==B then B==A.6775** <li> If A==B and B==C then A==C.6776** <li> If A&lt;B THEN B&gt;A.6777** <li> If A&lt;B and B&lt;C then A&lt;C.6778** </ol>6779**6780** If a collating function fails any of the above constraints and that6781** collating function is registered and used, then the behavior of SQLite6782** is undefined.6783**6784** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()6785** with the addition that the xDestroy callback is invoked on pArg when6786** the collating function is deleted.6787** ^Collating functions are deleted when they are overridden by later6788** calls to the collation creation functions or when the6789** [database connection] is closed using [sqlite3_close()].6790**6791** ^The xDestroy callback is <u>not</u> called if the6792** sqlite3_create_collation_v2() function fails.  Applications that invoke6793** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should6794** check the return code and dispose of the application data pointer6795** themselves rather than expecting SQLite to deal with it for them.6796** This is different from every other SQLite interface.  The inconsistency6797** is unfortunate but cannot be changed without breaking backwards6798** compatibility.6799**6800** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].6801*/6802SQLITE_API int sqlite3_create_collation(6803  sqlite3*,6804  const char *zName,6805  int eTextRep,6806  void *pArg,6807  int(*xCompare)(void*,int,const void*,int,const void*)6808);6809SQLITE_API int sqlite3_create_collation_v2(6810  sqlite3*,6811  const char *zName,6812  int eTextRep,6813  void *pArg,6814  int(*xCompare)(void*,int,const void*,int,const void*),6815  void(*xDestroy)(void*)6816);6817SQLITE_API int sqlite3_create_collation16(6818  sqlite3*,6819  const void *zName,6820  int eTextRep,6821  void *pArg,6822  int(*xCompare)(void*,int,const void*,int,const void*)6823);68246825/*6826** CAPI3REF: Collation Needed Callbacks6827** METHOD: sqlite36828**6829** ^To avoid having to register all collation sequences before a database6830** can be used, a single callback function may be registered with the6831** [database connection] to be invoked whenever an undefined collation6832** sequence is required.6833**6834** ^If the function is registered using the sqlite3_collation_needed() API,6835** then it is passed the names of undefined collation sequences as strings6836** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,6837** the names are passed as UTF-16 in machine native byte order.6838** ^A call to either function replaces the existing collation-needed callback.6839**6840** ^(When the callback is invoked, the first argument passed is a copy6841** of the second argument to sqlite3_collation_needed() or6842** sqlite3_collation_needed16().  The second argument is the database6843** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],6844** or [SQLITE_UTF16LE], indicating the most desirable form of the collation6845** sequence function required.  The fourth parameter is the name of the6846** required collation sequence.)^6847**6848** The callback function should register the desired collation using6849** [sqlite3_create_collation()], [sqlite3_create_collation16()], or6850** [sqlite3_create_collation_v2()].6851*/6852SQLITE_API int sqlite3_collation_needed(6853  sqlite3*,6854  void*,6855  void(*)(void*,sqlite3*,int eTextRep,const char*)6856);6857SQLITE_API int sqlite3_collation_needed16(6858  sqlite3*,6859  void*,6860  void(*)(void*,sqlite3*,int eTextRep,const void*)6861);68626863#ifdef SQLITE_ENABLE_CEROD6864/*6865** Specify the activation key for a CEROD database.  Unless6866** activated, none of the CEROD routines will work.6867*/6868SQLITE_API void sqlite3_activate_cerod(6869  const char *zPassPhrase        /* Activation phrase */6870);6871#endif68726873/*6874** CAPI3REF: Suspend Execution For A Short Time6875**6876** The sqlite3_sleep() function causes the current thread to suspend execution6877** for at least a number of milliseconds specified in its parameter.6878**6879** If the operating system does not support sleep requests with6880** millisecond time resolution, then the time will be rounded up to6881** the nearest second. The number of milliseconds of sleep actually6882** requested from the operating system is returned.6883**6884** ^SQLite implements this interface by calling the xSleep()6885** method of the default [sqlite3_vfs] object.  If the xSleep() method6886** of the default VFS is not implemented correctly, or not implemented at6887** all, then the behavior of sqlite3_sleep() may deviate from the description6888** in the previous paragraphs.6889**6890** If a negative argument is passed to sqlite3_sleep() the results vary by6891** VFS and operating system.  Some system treat a negative argument as an6892** instruction to sleep forever.  Others understand it to mean do not sleep6893** at all. ^In SQLite version 3.42.0 and later, a negative6894** argument passed into sqlite3_sleep() is changed to zero before it is relayed6895** down into the xSleep method of the VFS.6896*/6897SQLITE_API int sqlite3_sleep(int);68986899/*6900** CAPI3REF: Name Of The Folder Holding Temporary Files6901**6902** ^(If this global variable is made to point to a string which is6903** the name of a folder (a.k.a. directory), then all temporary files6904** created by SQLite when using a built-in [sqlite3_vfs | VFS]6905** will be placed in that directory.)^  ^If this variable6906** is a NULL pointer, then SQLite performs a search for an appropriate6907** temporary file directory.6908**6909** Applications are strongly discouraged from using this global variable.6910** It is required to set a temporary folder on Windows Runtime (WinRT).6911** But for all other platforms, it is highly recommended that applications6912** neither read nor write this variable.  This global variable is a relic6913** that exists for backwards compatibility of legacy applications and should6914** be avoided in new projects.6915**6916** It is not safe to read or modify this variable in more than one6917** thread at a time.  It is not safe to read or modify this variable6918** if a [database connection] is being used at the same time in a separate6919** thread.6920** It is intended that this variable be set once6921** as part of process initialization and before any SQLite interface6922** routines have been called and that this variable remain unchanged6923** thereafter.6924**6925** ^The [temp_store_directory pragma] may modify this variable and cause6926** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,6927** the [temp_store_directory pragma] always assumes that any string6928** that this variable points to is held in memory obtained from6929** [sqlite3_malloc] and the pragma may attempt to free that memory6930** using [sqlite3_free].6931** Hence, if this variable is modified directly, either it should be6932** made NULL or made to point to memory obtained from [sqlite3_malloc]6933** or else the use of the [temp_store_directory pragma] should be avoided.6934** Except when requested by the [temp_store_directory pragma], SQLite6935** does not free the memory that sqlite3_temp_directory points to.  If6936** the application wants that memory to be freed, it must do6937** so itself, taking care to only do so after all [database connection]6938** objects have been destroyed.6939**6940** <b>Note to Windows Runtime users:</b>  The temporary directory must be set6941** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various6942** features that require the use of temporary files may fail.  Here is an6943** example of how to do this using C++ with the Windows Runtime:6944**6945** <blockquote><pre>6946** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->6947** &nbsp;     TemporaryFolder->Path->Data();6948** char zPathBuf&#91;MAX_PATH + 1&#93;;6949** memset(zPathBuf, 0, sizeof(zPathBuf));6950** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),6951** &nbsp;     NULL, NULL);6952** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);6953** </pre></blockquote>6954*/6955SQLITE_API char *sqlite3_temp_directory;69566957/*6958** CAPI3REF: Name Of The Folder Holding Database Files6959**6960** ^(If this global variable is made to point to a string which is6961** the name of a folder (a.k.a. directory), then all database files6962** specified with a relative pathname and created or accessed by6963** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed6964** to be relative to that directory.)^ ^If this variable is a NULL6965** pointer, then SQLite assumes that all database files specified6966** with a relative pathname are relative to the current directory6967** for the process.  Only the windows VFS makes use of this global6968** variable; it is ignored by the unix VFS.6969**6970** Changing the value of this variable while a database connection is6971** open can result in a corrupt database.6972**6973** It is not safe to read or modify this variable in more than one6974** thread at a time.  It is not safe to read or modify this variable6975** if a [database connection] is being used at the same time in a separate6976** thread.6977** It is intended that this variable be set once6978** as part of process initialization and before any SQLite interface6979** routines have been called and that this variable remain unchanged6980** thereafter.6981**6982** ^The [data_store_directory pragma] may modify this variable and cause6983** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,6984** the [data_store_directory pragma] always assumes that any string6985** that this variable points to is held in memory obtained from6986** [sqlite3_malloc] and the pragma may attempt to free that memory6987** using [sqlite3_free].6988** Hence, if this variable is modified directly, either it should be6989** made NULL or made to point to memory obtained from [sqlite3_malloc]6990** or else the use of the [data_store_directory pragma] should be avoided.6991*/6992SQLITE_API char *sqlite3_data_directory;69936994/*6995** CAPI3REF: Win32 Specific Interface6996**6997** These interfaces are available only on Windows.  The6998** [sqlite3_win32_set_directory] interface is used to set the value associated6999** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to7000** zValue, depending on the value of the type parameter.  The zValue parameter7001** should be NULL to cause the previous value to be freed via [sqlite3_free];7002** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]7003** prior to being used.  The [sqlite3_win32_set_directory] interface returns7004** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,7005** or [SQLITE_NOMEM] if memory could not be allocated.  The value of the7006** [sqlite3_data_directory] variable is intended to act as a replacement for7007** the current directory on the sub-platforms of Win32 where that concept is7008** not present, e.g. WinRT and UWP.  The [sqlite3_win32_set_directory8] and7009** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the7010** sqlite3_win32_set_directory interface except the string parameter must be7011** UTF-8 or UTF-16, respectively.7012*/7013SQLITE_API int sqlite3_win32_set_directory(7014  unsigned long type, /* Identifier for directory being set or reset */7015  void *zValue        /* New value for directory being set or reset */7016);7017SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);7018SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);70197020/*7021** CAPI3REF: Win32 Directory Types7022**7023** These macros are only available on Windows.  They define the allowed values7024** for the type argument to the [sqlite3_win32_set_directory] interface.7025*/7026#define SQLITE_WIN32_DATA_DIRECTORY_TYPE  17027#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE  270287029/*7030** CAPI3REF: Test For Auto-Commit Mode7031** KEYWORDS: {autocommit mode}7032** METHOD: sqlite37033**7034** ^The sqlite3_get_autocommit() interface returns non-zero or7035** zero if the given database connection is or is not in autocommit mode,7036** respectively.  ^Autocommit mode is on by default.7037** ^Autocommit mode is disabled by a [BEGIN] statement.7038** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].7039**7040** If certain kinds of errors occur on a statement within a multi-statement7041** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],7042** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the7043** transaction might be rolled back automatically.  The only way to7044** find out whether SQLite automatically rolled back the transaction after7045** an error is to use this function.7046**7047** If another thread changes the autocommit status of the database7048** connection while this routine is running, then the return value7049** is undefined.7050*/7051SQLITE_API int sqlite3_get_autocommit(sqlite3*);70527053/*7054** CAPI3REF: Find The Database Handle Of A Prepared Statement7055** METHOD: sqlite3_stmt7056**7057** ^The sqlite3_db_handle interface returns the [database connection] handle7058** to which a [prepared statement] belongs.  ^The [database connection]7059** returned by sqlite3_db_handle is the same [database connection]7060** that was the first argument7061** to the [sqlite3_prepare_v2()] call (or its variants) that was used to7062** create the statement in the first place.7063*/7064SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);70657066/*7067** CAPI3REF: Return The Schema Name For A Database Connection7068** METHOD: sqlite37069**7070** ^The sqlite3_db_name(D,N) interface returns a pointer to the schema name7071** for the N-th database on database connection D, or a NULL pointer of N is7072** out of range.  An N value of 0 means the main database file.  An N of 1 is7073** the "temp" schema.  Larger values of N correspond to various ATTACH-ed7074** databases.7075**7076** Space to hold the string that is returned by sqlite3_db_name() is managed7077** by SQLite itself.  The string might be deallocated by any operation that7078** changes the schema, including [ATTACH] or [DETACH] or calls to7079** [sqlite3_serialize()] or [sqlite3_deserialize()], even operations that7080** occur on a different thread.  Applications that need to7081** remember the string long-term should make their own copy.  Applications that7082** are accessing the same database connection simultaneously on multiple7083** threads should mutex-protect calls to this API and should make their own7084** private copy of the result prior to releasing the mutex.7085*/7086SQLITE_API const char *sqlite3_db_name(sqlite3 *db, int N);70877088/*7089** CAPI3REF: Return The Filename For A Database Connection7090** METHOD: sqlite37091**7092** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename7093** associated with database N of connection D.7094** ^If there is no attached database N on the database7095** connection D, or if database N is a temporary or in-memory database, then7096** this function will return either a NULL pointer or an empty string.7097**7098** ^The string value returned by this routine is owned and managed by7099** the database connection.  ^The value will be valid until the database N7100** is [DETACH]-ed or until the database connection closes.7101**7102** ^The filename returned by this function is the output of the7103** xFullPathname method of the [VFS].  ^In other words, the filename7104** will be an absolute pathname, even if the filename used7105** to open the database originally was a URI or relative pathname.7106**7107** If the filename pointer returned by this routine is not NULL, then it7108** can be used as the filename input parameter to these routines:7109** <ul>7110** <li> [sqlite3_uri_parameter()]7111** <li> [sqlite3_uri_boolean()]7112** <li> [sqlite3_uri_int64()]7113** <li> [sqlite3_filename_database()]7114** <li> [sqlite3_filename_journal()]7115** <li> [sqlite3_filename_wal()]7116** </ul>7117*/7118SQLITE_API sqlite3_filename sqlite3_db_filename(sqlite3 *db, const char *zDbName);71197120/*7121** CAPI3REF: Determine if a database is read-only7122** METHOD: sqlite37123**7124** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N7125** of connection D is read-only, 0 if it is read/write, or -1 if N is not7126** the name of a database on connection D.7127*/7128SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);71297130/*7131** CAPI3REF: Determine the transaction state of a database7132** METHOD: sqlite37133**7134** ^The sqlite3_txn_state(D,S) interface returns the current7135** [transaction state] of schema S in database connection D.  ^If S is NULL,7136** then the highest transaction state of any schema on database connection D7137** is returned.  Transaction states are (in order of lowest to highest):7138** <ol>7139** <li value="0"> SQLITE_TXN_NONE7140** <li value="1"> SQLITE_TXN_READ7141** <li value="2"> SQLITE_TXN_WRITE7142** </ol>7143** ^If the S argument to sqlite3_txn_state(D,S) is not the name of7144** a valid schema, then -1 is returned.7145*/7146SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);71477148/*7149** CAPI3REF: Allowed return values from sqlite3_txn_state()7150** KEYWORDS: {transaction state}7151**7152** These constants define the current transaction state of a database file.7153** ^The [sqlite3_txn_state(D,S)] interface returns one of these7154** constants in order to describe the transaction state of schema S7155** in [database connection] D.7156**7157** <dl>7158** [[SQLITE_TXN_NONE]] <dt>SQLITE_TXN_NONE</dt>7159** <dd>The SQLITE_TXN_NONE state means that no transaction is currently7160** pending.</dd>7161**7162** [[SQLITE_TXN_READ]] <dt>SQLITE_TXN_READ</dt>7163** <dd>The SQLITE_TXN_READ state means that the database is currently7164** in a read transaction.  Content has been read from the database file7165** but nothing in the database file has changed.  The transaction state7166** will advanced to SQLITE_TXN_WRITE if any changes occur and there are7167** no other conflicting concurrent write transactions.  The transaction7168** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or7169** [COMMIT].</dd>7170**7171** [[SQLITE_TXN_WRITE]] <dt>SQLITE_TXN_WRITE</dt>7172** <dd>The SQLITE_TXN_WRITE state means that the database is currently7173** in a write transaction.  Content has been written to the database file7174** but has not yet committed.  The transaction state will change to7175** to SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd>7176*/7177#define SQLITE_TXN_NONE  07178#define SQLITE_TXN_READ  17179#define SQLITE_TXN_WRITE 271807181/*7182** CAPI3REF: Find the next prepared statement7183** METHOD: sqlite37184**7185** ^This interface returns a pointer to the next [prepared statement] after7186** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL7187** then this interface returns a pointer to the first prepared statement7188** associated with the database connection pDb.  ^If no prepared statement7189** satisfies the conditions of this routine, it returns NULL.7190**7191** The [database connection] pointer D in a call to7192** [sqlite3_next_stmt(D,S)] must refer to an open database7193** connection and in particular must not be a NULL pointer.7194*/7195SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);71967197/*7198** CAPI3REF: Commit And Rollback Notification Callbacks7199** METHOD: sqlite37200**7201** ^The sqlite3_commit_hook() interface registers a callback7202** function to be invoked whenever a transaction is [COMMIT | committed].7203** ^Any callback set by a previous call to sqlite3_commit_hook()7204** for the same database connection is overridden.7205** ^The sqlite3_rollback_hook() interface registers a callback7206** function to be invoked whenever a transaction is [ROLLBACK | rolled back].7207** ^Any callback set by a previous call to sqlite3_rollback_hook()7208** for the same database connection is overridden.7209** ^The pArg argument is passed through to the callback.7210** ^If the callback on a commit hook function returns non-zero,7211** then the commit is converted into a rollback.7212**7213** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions7214** return the P argument from the previous call of the same function7215** on the same [database connection] D, or NULL for7216** the first call for each function on D.7217**7218** The commit and rollback hook callbacks are not reentrant.7219** The callback implementation must not do anything that will modify7220** the database connection that invoked the callback.  Any actions7221** to modify the database connection must be deferred until after the7222** completion of the [sqlite3_step()] call that triggered the commit7223** or rollback hook in the first place.7224** Note that running any other SQL statements, including SELECT statements,7225** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify7226** the database connections for the meaning of "modify" in this paragraph.7227**7228** ^Registering a NULL function disables the callback.7229**7230** ^When the commit hook callback routine returns zero, the [COMMIT]7231** operation is allowed to continue normally.  ^If the commit hook7232** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].7233** ^The rollback hook is invoked on a rollback that results from a commit7234** hook returning non-zero, just as it would be with any other rollback.7235**7236** ^For the purposes of this API, a transaction is said to have been7237** rolled back if an explicit "ROLLBACK" statement is executed, or7238** an error or constraint causes an implicit rollback to occur.7239** ^The rollback callback is not invoked if a transaction is7240** automatically rolled back because the database connection is closed.7241**7242** See also the [sqlite3_update_hook()] interface.7243*/7244SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);7245SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);72467247/*7248** CAPI3REF: Autovacuum Compaction Amount Callback7249** METHOD: sqlite37250**7251** ^The sqlite3_autovacuum_pages(D,C,P,X) interface registers a callback7252** function C that is invoked prior to each autovacuum of the database7253** file.  ^The callback is passed a copy of the generic data pointer (P),7254** the schema-name of the attached database that is being autovacuumed,7255** the size of the database file in pages, the number of free pages,7256** and the number of bytes per page, respectively.  The callback should7257** return the number of free pages that should be removed by the7258** autovacuum.  ^If the callback returns zero, then no autovacuum happens.7259** ^If the value returned is greater than or equal to the number of7260** free pages, then a complete autovacuum happens.7261**7262** <p>^If there are multiple ATTACH-ed database files that are being7263** modified as part of a transaction commit, then the autovacuum pages7264** callback is invoked separately for each file.7265**7266** <p><b>The callback is not reentrant.</b> The callback function should7267** not attempt to invoke any other SQLite interface.  If it does, bad7268** things may happen, including segmentation faults and corrupt database7269** files.  The callback function should be a simple function that7270** does some arithmetic on its input parameters and returns a result.7271**7272** ^The X parameter to sqlite3_autovacuum_pages(D,C,P,X) is an optional7273** destructor for the P parameter.  ^If X is not NULL, then X(P) is7274** invoked whenever the database connection closes or when the callback7275** is overwritten by another invocation of sqlite3_autovacuum_pages().7276**7277** <p>^There is only one autovacuum pages callback per database connection.7278** ^Each call to the sqlite3_autovacuum_pages() interface overrides all7279** previous invocations for that database connection.  ^If the callback7280** argument (C) to sqlite3_autovacuum_pages(D,C,P,X) is a NULL pointer,7281** then the autovacuum steps callback is canceled.  The return value7282** from sqlite3_autovacuum_pages() is normally SQLITE_OK, but might7283** be some other error code if something goes wrong.  The current7284** implementation will only return SQLITE_OK or SQLITE_MISUSE, but other7285** return codes might be added in future releases.7286**7287** <p>If no autovacuum pages callback is specified (the usual case) or7288** a NULL pointer is provided for the callback,7289** then the default behavior is to vacuum all free pages.  So, in other7290** words, the default behavior is the same as if the callback function7291** were something like this:7292**7293** <blockquote><pre>7294** &nbsp;   unsigned int demonstration_autovac_pages_callback(7295** &nbsp;     void *pClientData,7296** &nbsp;     const char *zSchema,7297** &nbsp;     unsigned int nDbPage,7298** &nbsp;     unsigned int nFreePage,7299** &nbsp;     unsigned int nBytePerPage7300** &nbsp;   ){7301** &nbsp;     return nFreePage;7302** &nbsp;   }7303** </pre></blockquote>7304*/7305SQLITE_API int sqlite3_autovacuum_pages(7306  sqlite3 *db,7307  unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),7308  void*,7309  void(*)(void*)7310);731173127313/*7314** CAPI3REF: Data Change Notification Callbacks7315** METHOD: sqlite37316**7317** ^The sqlite3_update_hook() interface registers a callback function7318** with the [database connection] identified by the first argument7319** to be invoked whenever a row is updated, inserted or deleted in7320** a [rowid table].7321** ^Any callback set by a previous call to this function7322** for the same database connection is overridden.7323**7324** ^The second argument is a pointer to the function to invoke when a7325** row is updated, inserted or deleted in a rowid table.7326** ^The first argument to the callback is a copy of the third argument7327** to sqlite3_update_hook().7328** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],7329** or [SQLITE_UPDATE], depending on the operation that caused the callback7330** to be invoked.7331** ^The third and fourth arguments to the callback contain pointers to the7332** database and table name containing the affected row.7333** ^The final callback parameter is the [rowid] of the row.7334** ^In the case of an update, this is the [rowid] after the update takes place.7335**7336** ^(The update hook is not invoked when internal system tables are7337** modified (i.e. sqlite_sequence).)^7338** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.7339**7340** ^In the current implementation, the update hook7341** is not invoked when conflicting rows are deleted because of an7342** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook7343** invoked when rows are deleted using the [truncate optimization].7344** The exceptions defined in this paragraph might change in a future7345** release of SQLite.7346**7347** Whether the update hook is invoked before or after the7348** corresponding change is currently unspecified and may differ7349** depending on the type of change. Do not rely on the order of the7350** hook call with regards to the final result of the operation which7351** triggers the hook.7352**7353** The update hook implementation must not do anything that will modify7354** the database connection that invoked the update hook.  Any actions7355** to modify the database connection must be deferred until after the7356** completion of the [sqlite3_step()] call that triggered the update hook.7357** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their7358** database connections for the meaning of "modify" in this paragraph.7359**7360** ^The sqlite3_update_hook(D,C,P) function7361** returns the P argument from the previous call7362** on the same [database connection] D, or NULL for7363** the first call on D.7364**7365** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],7366** and [sqlite3_preupdate_hook()] interfaces.7367*/7368SQLITE_API void *sqlite3_update_hook(7369  sqlite3*,7370  void(*)(void *,int ,char const *,char const *,sqlite3_int64),7371  void*7372);73737374/*7375** CAPI3REF: Enable Or Disable Shared Pager Cache7376**7377** ^(This routine enables or disables the sharing of the database cache7378** and schema data structures between [database connection | connections]7379** to the same database. Sharing is enabled if the argument is true7380** and disabled if the argument is false.)^7381**7382** This interface is omitted if SQLite is compiled with7383** [-DSQLITE_OMIT_SHARED_CACHE].  The [-DSQLITE_OMIT_SHARED_CACHE]7384** compile-time option is recommended because the7385** [use of shared cache mode is discouraged].7386**7387** ^Cache sharing is enabled and disabled for an entire process.7388** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).7389** In prior versions of SQLite,7390** sharing was enabled or disabled for each thread separately.7391**7392** ^(The cache sharing mode set by this interface effects all subsequent7393** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].7394** Existing database connections continue to use the sharing mode7395** that was in effect at the time they were opened.)^7396**7397** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled7398** successfully.  An [error code] is returned otherwise.)^7399**7400** ^Shared cache is disabled by default. It is recommended that it stay7401** that way.  In other words, do not use this routine.  This interface7402** continues to be provided for historical compatibility, but its use is7403** discouraged.  Any use of shared cache is discouraged.  If shared cache7404** must be used, it is recommended that shared cache only be enabled for7405** individual database connections using the [sqlite3_open_v2()] interface7406** with the [SQLITE_OPEN_SHAREDCACHE] flag.7407**7408** Note: This method is disabled on MacOS X 10.7 and iOS version 5.07409** and will always return SQLITE_MISUSE. On those systems,7410** shared cache mode should be enabled per-database connection via7411** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].7412**7413** This interface is threadsafe on processors where writing a7414** 32-bit integer is atomic.7415**7416** See Also:  [SQLite Shared-Cache Mode]7417*/7418SQLITE_API int sqlite3_enable_shared_cache(int);74197420/*7421** CAPI3REF: Attempt To Free Heap Memory7422**7423** ^The sqlite3_release_memory() interface attempts to free N bytes7424** of heap memory by deallocating non-essential memory allocations7425** held by the database library.   Memory used to cache database7426** pages to improve performance is an example of non-essential memory.7427** ^sqlite3_release_memory() returns the number of bytes actually freed,7428** which might be more or less than the amount requested.7429** ^The sqlite3_release_memory() routine is a no-op returning zero7430** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].7431**7432** See also: [sqlite3_db_release_memory()]7433*/7434SQLITE_API int sqlite3_release_memory(int);74357436/*7437** CAPI3REF: Free Memory Used By A Database Connection7438** METHOD: sqlite37439**7440** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap7441** memory as possible from database connection D. Unlike the7442** [sqlite3_release_memory()] interface, this interface is in effect even7443** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is7444** omitted.7445**7446** See also: [sqlite3_release_memory()]7447*/7448SQLITE_API int sqlite3_db_release_memory(sqlite3*);74497450/*7451** CAPI3REF: Impose A Limit On Heap Size7452**7453** These interfaces impose limits on the amount of heap memory that will be7454** by all database connections within a single process.7455**7456** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the7457** soft limit on the amount of heap memory that may be allocated by SQLite.7458** ^SQLite strives to keep heap memory utilization below the soft heap7459** limit by reducing the number of pages held in the page cache7460** as heap memory usages approaches the limit.7461** ^The soft heap limit is "soft" because even though SQLite strives to stay7462** below the limit, it will exceed the limit rather than generate7463** an [SQLITE_NOMEM] error.  In other words, the soft heap limit7464** is advisory only.7465**7466** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of7467** N bytes on the amount of memory that will be allocated.  ^The7468** sqlite3_hard_heap_limit64(N) interface is similar to7469** sqlite3_soft_heap_limit64(N) except that memory allocations will fail7470** when the hard heap limit is reached.7471**7472** ^The return value from both sqlite3_soft_heap_limit64() and7473** sqlite3_hard_heap_limit64() is the size of7474** the heap limit prior to the call, or negative in the case of an7475** error.  ^If the argument N is negative7476** then no change is made to the heap limit.  Hence, the current7477** size of heap limits can be determined by invoking7478** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).7479**7480** ^Setting the heap limits to zero disables the heap limiter mechanism.7481**7482** ^The soft heap limit may not be greater than the hard heap limit.7483** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N)7484** is invoked with a value of N that is greater than the hard heap limit,7485** the soft heap limit is set to the value of the hard heap limit.7486** ^The soft heap limit is automatically enabled whenever the hard heap7487** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and7488** the soft heap limit is outside the range of 1..N, then the soft heap7489** limit is set to N.  ^Invoking sqlite3_soft_heap_limit64(0) when the7490** hard heap limit is enabled makes the soft heap limit equal to the7491** hard heap limit.7492**7493** The memory allocation limits can also be adjusted using7494** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit].7495**7496** ^(The heap limits are not enforced in the current implementation7497** if one or more of following conditions are true:7498**7499** <ul>7500** <li> The limit value is set to zero.7501** <li> Memory accounting is disabled using a combination of the7502**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and7503**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.7504** <li> An alternative page cache implementation is specified using7505**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).7506** <li> The page cache allocates from its own memory pool supplied7507**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than7508**      from the heap.7509** </ul>)^7510**7511** The circumstances under which SQLite will enforce the heap limits may7512** changes in future releases of SQLite.7513*/7514SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);7515SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);75167517/*7518** CAPI3REF: Deprecated Soft Heap Limit Interface7519** DEPRECATED7520**7521** This is a deprecated version of the [sqlite3_soft_heap_limit64()]7522** interface.  This routine is provided for historical compatibility7523** only.  All new applications should use the7524** [sqlite3_soft_heap_limit64()] interface rather than this one.7525*/7526SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);752775287529/*7530** CAPI3REF: Extract Metadata About A Column Of A Table7531** METHOD: sqlite37532**7533** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns7534** information about column C of table T in database D7535** on [database connection] X.)^  ^The sqlite3_table_column_metadata()7536** interface returns SQLITE_OK and fills in the non-NULL pointers in7537** the final five arguments with appropriate values if the specified7538** column exists.  ^The sqlite3_table_column_metadata() interface returns7539** SQLITE_ERROR if the specified column does not exist.7540** ^If the column-name parameter to sqlite3_table_column_metadata() is a7541** NULL pointer, then this routine simply checks for the existence of the7542** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it7543** does not.  If the table name parameter T in a call to7544** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is7545** undefined behavior.7546**7547** ^The column is identified by the second, third and fourth parameters to7548** this function. ^(The second parameter is either the name of the database7549** (i.e. "main", "temp", or an attached database) containing the specified7550** table or NULL.)^ ^If it is NULL, then all attached databases are searched7551** for the table using the same algorithm used by the database engine to7552** resolve unqualified table references.7553**7554** ^The third and fourth parameters to this function are the table and column7555** name of the desired column, respectively.7556**7557** ^Metadata is returned by writing to the memory locations passed as the 5th7558** and subsequent parameters to this function. ^Any of these arguments may be7559** NULL, in which case the corresponding element of metadata is omitted.7560**7561** ^(<blockquote>7562** <table border="1">7563** <tr><th> Parameter <th> Output<br>Type <th>  Description7564**7565** <tr><td> 5th <td> const char* <td> Data type7566** <tr><td> 6th <td> const char* <td> Name of default collation sequence7567** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint7568** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY7569** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]7570** </table>7571** </blockquote>)^7572**7573** ^The memory pointed to by the character pointers returned for the7574** declaration type and collation sequence is valid until the next7575** call to any SQLite API function.7576**7577** ^If the specified table is actually a view, an [error code] is returned.7578**7579** ^If the specified column is "rowid", "oid" or "_rowid_" and the table7580** is not a [WITHOUT ROWID] table and an7581** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output7582** parameters are set for the explicitly declared column. ^(If there is no7583** [INTEGER PRIMARY KEY] column, then the outputs7584** for the [rowid] are set as follows:7585**7586** <pre>7587**     data type: "INTEGER"7588**     collation sequence: "BINARY"7589**     not null: 07590**     primary key: 17591**     auto increment: 07592** </pre>)^7593**7594** ^This function causes all database schemas to be read from disk and7595** parsed, if that has not already been done, and returns an error if7596** any errors are encountered while loading the schema.7597*/7598SQLITE_API int sqlite3_table_column_metadata(7599  sqlite3 *db,                /* Connection handle */7600  const char *zDbName,        /* Database name or NULL */7601  const char *zTableName,     /* Table name */7602  const char *zColumnName,    /* Column name */7603  char const **pzDataType,    /* OUTPUT: Declared data type */7604  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */7605  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */7606  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */7607  int *pAutoinc               /* OUTPUT: True if column is auto-increment */7608);76097610/*7611** CAPI3REF: Load An Extension7612** METHOD: sqlite37613**7614** ^This interface loads an SQLite extension library from the named file.7615**7616** ^The sqlite3_load_extension() interface attempts to load an7617** [SQLite extension] library contained in the file zFile.  If7618** the file cannot be loaded directly, attempts are made to load7619** with various operating-system specific extensions added.7620** So for example, if "samplelib" cannot be loaded, then names like7621** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might7622** be tried also.7623**7624** ^The entry point is zProc.7625** ^(zProc may be 0, in which case SQLite will try to come up with an7626** entry point name on its own.  It first tries "sqlite3_extension_init".7627** If that does not work, it constructs a name "sqlite3_X_init" where the7628** X is consists of the lower-case equivalent of all ASCII alphabetic7629** characters in the filename from the last "/" to the first following7630** "." and omitting any initial "lib".)^7631** ^The sqlite3_load_extension() interface returns7632** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.7633** ^If an error occurs and pzErrMsg is not 0, then the7634** [sqlite3_load_extension()] interface shall attempt to7635** fill *pzErrMsg with error message text stored in memory7636** obtained from [sqlite3_malloc()]. The calling function7637** should free this memory by calling [sqlite3_free()].7638**7639** ^Extension loading must be enabled using7640** [sqlite3_enable_load_extension()] or7641** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)7642** prior to calling this API,7643** otherwise an error will be returned.7644**7645** <b>Security warning:</b> It is recommended that the7646** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this7647** interface.  The use of the [sqlite3_enable_load_extension()] interface7648** should be avoided.  This will keep the SQL function [load_extension()]7649** disabled and prevent SQL injections from giving attackers7650** access to extension loading capabilities.7651**7652** See also the [load_extension() SQL function].7653*/7654SQLITE_API int sqlite3_load_extension(7655  sqlite3 *db,          /* Load the extension into this database connection */7656  const char *zFile,    /* Name of the shared library containing extension */7657  const char *zProc,    /* Entry point.  Derived from zFile if 0 */7658  char **pzErrMsg       /* Put error message here if not 0 */7659);76607661/*7662** CAPI3REF: Enable Or Disable Extension Loading7663** METHOD: sqlite37664**7665** ^So as not to open security holes in older applications that are7666** unprepared to deal with [extension loading], and as a means of disabling7667** [extension loading] while evaluating user-entered SQL, the following API7668** is provided to turn the [sqlite3_load_extension()] mechanism on and off.7669**7670** ^Extension loading is off by default.7671** ^Call the sqlite3_enable_load_extension() routine with onoff==17672** to turn extension loading on and call it with onoff==0 to turn7673** it back off again.7674**7675** ^This interface enables or disables both the C-API7676** [sqlite3_load_extension()] and the SQL function [load_extension()].7677** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)7678** to enable or disable only the C-API.)^7679**7680** <b>Security warning:</b> It is recommended that extension loading7681** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method7682** rather than this interface, so the [load_extension()] SQL function7683** remains disabled. This will prevent SQL injections from giving attackers7684** access to extension loading capabilities.7685*/7686SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);76877688/*7689** CAPI3REF: Automatically Load Statically Linked Extensions7690**7691** ^This interface causes the xEntryPoint() function to be invoked for7692** each new [database connection] that is created.  The idea here is that7693** xEntryPoint() is the entry point for a statically linked [SQLite extension]7694** that is to be automatically loaded into all new database connections.7695**7696** ^(Even though the function prototype shows that xEntryPoint() takes7697** no arguments and returns void, SQLite invokes xEntryPoint() with three7698** arguments and expects an integer result as if the signature of the7699** entry point where as follows:7700**7701** <blockquote><pre>7702** &nbsp;  int xEntryPoint(7703** &nbsp;    sqlite3 *db,7704** &nbsp;    const char **pzErrMsg,7705** &nbsp;    const struct sqlite3_api_routines *pThunk7706** &nbsp;  );7707** </pre></blockquote>)^7708**7709** If the xEntryPoint routine encounters an error, it should make *pzErrMsg7710** point to an appropriate error message (obtained from [sqlite3_mprintf()])7711** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg7712** is NULL before calling the xEntryPoint().  ^SQLite will invoke7713** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any7714** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],7715** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.7716**7717** ^Calling sqlite3_auto_extension(X) with an entry point X that is already7718** on the list of automatic extensions is a harmless no-op. ^No entry point7719** will be called more than once for each database connection that is opened.7720**7721** See also: [sqlite3_reset_auto_extension()]7722** and [sqlite3_cancel_auto_extension()]7723*/7724SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));77257726/*7727** CAPI3REF: Cancel Automatic Extension Loading7728**7729** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the7730** initialization routine X that was registered using a prior call to7731** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]7732** routine returns 1 if initialization routine X was successfully7733** unregistered and it returns 0 if X was not on the list of initialization7734** routines.7735*/7736SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));77377738/*7739** CAPI3REF: Reset Automatic Extension Loading7740**7741** ^This interface disables all automatic extensions previously7742** registered using [sqlite3_auto_extension()].7743*/7744SQLITE_API void sqlite3_reset_auto_extension(void);77457746/*7747** Structures used by the virtual table interface7748*/7749typedef struct sqlite3_vtab sqlite3_vtab;7750typedef struct sqlite3_index_info sqlite3_index_info;7751typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;7752typedef struct sqlite3_module sqlite3_module;77537754/*7755** CAPI3REF: Virtual Table Object7756** KEYWORDS: sqlite3_module {virtual table module}7757**7758** This structure, sometimes called a "virtual table module",7759** defines the implementation of a [virtual table].7760** This structure consists mostly of methods for the module.7761**7762** ^A virtual table module is created by filling in a persistent7763** instance of this structure and passing a pointer to that instance7764** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].7765** ^The registration remains valid until it is replaced by a different7766** module or until the [database connection] closes.  The content7767** of this structure must not change while it is registered with7768** any database connection.7769*/7770struct sqlite3_module {7771  int iVersion;7772  int (*xCreate)(sqlite3*, void *pAux,7773               int argc, const char *const*argv,7774               sqlite3_vtab **ppVTab, char**);7775  int (*xConnect)(sqlite3*, void *pAux,7776               int argc, const char *const*argv,7777               sqlite3_vtab **ppVTab, char**);7778  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);7779  int (*xDisconnect)(sqlite3_vtab *pVTab);7780  int (*xDestroy)(sqlite3_vtab *pVTab);7781  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);7782  int (*xClose)(sqlite3_vtab_cursor*);7783  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,7784                int argc, sqlite3_value **argv);7785  int (*xNext)(sqlite3_vtab_cursor*);7786  int (*xEof)(sqlite3_vtab_cursor*);7787  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);7788  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);7789  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);7790  int (*xBegin)(sqlite3_vtab *pVTab);7791  int (*xSync)(sqlite3_vtab *pVTab);7792  int (*xCommit)(sqlite3_vtab *pVTab);7793  int (*xRollback)(sqlite3_vtab *pVTab);7794  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,7795                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),7796                       void **ppArg);7797  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);7798  /* The methods above are in version 1 of the sqlite_module object. Those7799  ** below are for version 2 and greater. */7800  int (*xSavepoint)(sqlite3_vtab *pVTab, int);7801  int (*xRelease)(sqlite3_vtab *pVTab, int);7802  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);7803  /* The methods above are in versions 1 and 2 of the sqlite_module object.7804  ** Those below are for version 3 and greater. */7805  int (*xShadowName)(const char*);7806  /* The methods above are in versions 1 through 3 of the sqlite_module object.7807  ** Those below are for version 4 and greater. */7808  int (*xIntegrity)(sqlite3_vtab *pVTab, const char *zSchema,7809                    const char *zTabName, int mFlags, char **pzErr);7810};78117812/*7813** CAPI3REF: Virtual Table Indexing Information7814** KEYWORDS: sqlite3_index_info7815**7816** The sqlite3_index_info structure and its substructures is used as part7817** of the [virtual table] interface to7818** pass information into and receive the reply from the [xBestIndex]7819** method of a [virtual table module].  The fields under **Inputs** are the7820** inputs to xBestIndex and are read-only.  xBestIndex inserts its7821** results into the **Outputs** fields.7822**7823** ^(The aConstraint[] array records WHERE clause constraints of the form:7824**7825** <blockquote>column OP expr</blockquote>7826**7827** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is7828** stored in aConstraint[].op using one of the7829** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^7830** ^(The index of the column is stored in7831** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the7832** expr on the right-hand side can be evaluated (and thus the constraint7833** is usable) and false if it cannot.)^7834**7835** ^The optimizer automatically inverts terms of the form "expr OP column"7836** and makes other simplifications to the WHERE clause in an attempt to7837** get as many WHERE clause terms into the form shown above as possible.7838** ^The aConstraint[] array only reports WHERE clause terms that are7839** relevant to the particular virtual table being queried.7840**7841** ^Information about the ORDER BY clause is stored in aOrderBy[].7842** ^Each term of aOrderBy records a column of the ORDER BY clause.7843**7844** The colUsed field indicates which columns of the virtual table may be7845** required by the current scan. Virtual table columns are numbered from7846** zero in the order in which they appear within the CREATE TABLE statement7847** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),7848** the corresponding bit is set within the colUsed mask if the column may be7849** required by SQLite. If the table has at least 64 columns and any column7850** to the right of the first 63 is required, then bit 63 of colUsed is also7851** set. In other words, column iCol may be required if the expression7852** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to7853** non-zero.7854**7855** The [xBestIndex] method must fill aConstraintUsage[] with information7856** about what parameters to pass to xFilter.  ^If argvIndex>0 then7857** the right-hand side of the corresponding aConstraint[] is evaluated7858** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit7859** is true, then the constraint is assumed to be fully handled by the7860** virtual table and might not be checked again by the byte code.)^ ^(The7861** aConstraintUsage[].omit flag is an optimization hint. When the omit flag7862** is left in its default setting of false, the constraint will always be7863** checked separately in byte code.  If the omit flag is change to true, then7864** the constraint may or may not be checked in byte code.  In other words,7865** when the omit flag is true there is no guarantee that the constraint will7866** not be checked again using byte code.)^7867**7868** ^The idxNum and idxStr values are recorded and passed into the7869** [xFilter] method.7870** ^[sqlite3_free()] is used to free idxStr if and only if7871** needToFreeIdxStr is true.7872**7873** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in7874** the correct order to satisfy the ORDER BY clause so that no separate7875** sorting step is required.7876**7877** ^The estimatedCost value is an estimate of the cost of a particular7878** strategy. A cost of N indicates that the cost of the strategy is similar7879** to a linear scan of an SQLite table with N rows. A cost of log(N)7880** indicates that the expense of the operation is similar to that of a7881** binary search on a unique indexed field of an SQLite table with N rows.7882**7883** ^The estimatedRows value is an estimate of the number of rows that7884** will be returned by the strategy.7885**7886** The xBestIndex method may optionally populate the idxFlags field with a7887** mask of SQLITE_INDEX_SCAN_* flags. One such flag is7888** [SQLITE_INDEX_SCAN_HEX], which if set causes the [EXPLAIN QUERY PLAN]7889** output to show the idxNum has hex instead of as decimal.  Another flag is7890** SQLITE_INDEX_SCAN_UNIQUE, which if set indicates that the query plan will7891** return at most one row.7892**7893** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then7894** SQLite also assumes that if a call to the xUpdate() method is made as7895** part of the same statement to delete or update a virtual table row and the7896** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback7897** any database changes. In other words, if the xUpdate() returns7898** SQLITE_CONSTRAINT, the database contents must be exactly as they were7899** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not7900** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by7901** the xUpdate method are automatically rolled back by SQLite.7902**7903** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info7904** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).7905** If a virtual table extension is7906** used with an SQLite version earlier than 3.8.2, the results of attempting7907** to read or write the estimatedRows field are undefined (but are likely7908** to include crashing the application). The estimatedRows field should7909** therefore only be used if [sqlite3_libversion_number()] returns a7910** value greater than or equal to 3008002. Similarly, the idxFlags field7911** was added for [version 3.9.0] ([dateof:3.9.0]).7912** It may therefore only be used if7913** sqlite3_libversion_number() returns a value greater than or equal to7914** 3009000.7915*/7916struct sqlite3_index_info {7917  /* Inputs */7918  int nConstraint;           /* Number of entries in aConstraint */7919  struct sqlite3_index_constraint {7920     int iColumn;              /* Column constrained.  -1 for ROWID */7921     unsigned char op;         /* Constraint operator */7922     unsigned char usable;     /* True if this constraint is usable */7923     int iTermOffset;          /* Used internally - xBestIndex should ignore */7924  } *aConstraint;            /* Table of WHERE clause constraints */7925  int nOrderBy;              /* Number of terms in the ORDER BY clause */7926  struct sqlite3_index_orderby {7927     int iColumn;              /* Column number */7928     unsigned char desc;       /* True for DESC.  False for ASC. */7929  } *aOrderBy;               /* The ORDER BY clause */7930  /* Outputs */7931  struct sqlite3_index_constraint_usage {7932    int argvIndex;           /* if >0, constraint is part of argv to xFilter */7933    unsigned char omit;      /* Do not code a test for this constraint */7934  } *aConstraintUsage;7935  int idxNum;                /* Number used to identify the index */7936  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */7937  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */7938  int orderByConsumed;       /* True if output is already ordered */7939  double estimatedCost;           /* Estimated cost of using this index */7940  /* Fields below are only available in SQLite 3.8.2 and later */7941  sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */7942  /* Fields below are only available in SQLite 3.9.0 and later */7943  int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */7944  /* Fields below are only available in SQLite 3.10.0 and later */7945  sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */7946};79477948/*7949** CAPI3REF: Virtual Table Scan Flags7950**7951** Virtual table implementations are allowed to set the7952** [sqlite3_index_info].idxFlags field to some combination of7953** these bits.7954*/7955#define SQLITE_INDEX_SCAN_UNIQUE 0x00000001 /* Scan visits at most 1 row */7956#define SQLITE_INDEX_SCAN_HEX    0x00000002 /* Display idxNum as hex */7957                                            /* in EXPLAIN QUERY PLAN */79587959/*7960** CAPI3REF: Virtual Table Constraint Operator Codes7961**7962** These macros define the allowed values for the7963** [sqlite3_index_info].aConstraint[].op field.  Each value represents7964** an operator that is part of a constraint term in the WHERE clause of7965** a query that uses a [virtual table].7966**7967** ^The left-hand operand of the operator is given by the corresponding7968** aConstraint[].iColumn field.  ^An iColumn of -1 indicates the left-hand7969** operand is the rowid.7970** The SQLITE_INDEX_CONSTRAINT_LIMIT and SQLITE_INDEX_CONSTRAINT_OFFSET7971** operators have no left-hand operand, and so for those operators the7972** corresponding aConstraint[].iColumn is meaningless and should not be7973** used.7974**7975** All operator values from SQLITE_INDEX_CONSTRAINT_FUNCTION through7976** value 255 are reserved to represent functions that are overloaded7977** by the [xFindFunction|xFindFunction method] of the virtual table7978** implementation.7979**7980** The right-hand operands for each constraint might be accessible using7981** the [sqlite3_vtab_rhs_value()] interface.  Usually the right-hand7982** operand is only available if it appears as a single constant literal7983** in the input SQL.  If the right-hand operand is another column or an7984** expression (even a constant expression) or a parameter, then the7985** sqlite3_vtab_rhs_value() probably will not be able to extract it.7986** ^The SQLITE_INDEX_CONSTRAINT_ISNULL and7987** SQLITE_INDEX_CONSTRAINT_ISNOTNULL operators have no right-hand operand7988** and hence calls to sqlite3_vtab_rhs_value() for those operators will7989** always return SQLITE_NOTFOUND.7990**7991** The collating sequence to be used for comparison can be found using7992** the [sqlite3_vtab_collation()] interface.  For most real-world virtual7993** tables, the collating sequence of constraints does not matter (for example7994** because the constraints are numeric) and so the sqlite3_vtab_collation()7995** interface is not commonly needed.7996*/7997#define SQLITE_INDEX_CONSTRAINT_EQ          27998#define SQLITE_INDEX_CONSTRAINT_GT          47999#define SQLITE_INDEX_CONSTRAINT_LE          88000#define SQLITE_INDEX_CONSTRAINT_LT         168001#define SQLITE_INDEX_CONSTRAINT_GE         328002#define SQLITE_INDEX_CONSTRAINT_MATCH      648003#define SQLITE_INDEX_CONSTRAINT_LIKE       658004#define SQLITE_INDEX_CONSTRAINT_GLOB       668005#define SQLITE_INDEX_CONSTRAINT_REGEXP     678006#define SQLITE_INDEX_CONSTRAINT_NE         688007#define SQLITE_INDEX_CONSTRAINT_ISNOT      698008#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL  708009#define SQLITE_INDEX_CONSTRAINT_ISNULL     718010#define SQLITE_INDEX_CONSTRAINT_IS         728011#define SQLITE_INDEX_CONSTRAINT_LIMIT      738012#define SQLITE_INDEX_CONSTRAINT_OFFSET     748013#define SQLITE_INDEX_CONSTRAINT_FUNCTION  15080148015/*8016** CAPI3REF: Register A Virtual Table Implementation8017** METHOD: sqlite38018**8019** ^These routines are used to register a new [virtual table module] name.8020** ^Module names must be registered before8021** creating a new [virtual table] using the module and before using a8022** preexisting [virtual table] for the module.8023**8024** ^The module name is registered on the [database connection] specified8025** by the first parameter.  ^The name of the module is given by the8026** second parameter.  ^The third parameter is a pointer to8027** the implementation of the [virtual table module].   ^The fourth8028** parameter is an arbitrary client data pointer that is passed through8029** into the [xCreate] and [xConnect] methods of the virtual table module8030** when a new virtual table is be being created or reinitialized.8031**8032** ^The sqlite3_create_module_v2() interface has a fifth parameter which8033** is a pointer to a destructor for the pClientData.  ^SQLite will8034** invoke the destructor function (if it is not NULL) when SQLite8035** no longer needs the pClientData pointer.  ^The destructor will also8036** be invoked if the call to sqlite3_create_module_v2() fails.8037** ^The sqlite3_create_module()8038** interface is equivalent to sqlite3_create_module_v2() with a NULL8039** destructor.8040**8041** ^If the third parameter (the pointer to the sqlite3_module object) is8042** NULL then no new module is created and any existing modules with the8043** same name are dropped.8044**8045** See also: [sqlite3_drop_modules()]8046*/8047SQLITE_API int sqlite3_create_module(8048  sqlite3 *db,               /* SQLite connection to register module with */8049  const char *zName,         /* Name of the module */8050  const sqlite3_module *p,   /* Methods for the module */8051  void *pClientData          /* Client data for xCreate/xConnect */8052);8053SQLITE_API int sqlite3_create_module_v2(8054  sqlite3 *db,               /* SQLite connection to register module with */8055  const char *zName,         /* Name of the module */8056  const sqlite3_module *p,   /* Methods for the module */8057  void *pClientData,         /* Client data for xCreate/xConnect */8058  void(*xDestroy)(void*)     /* Module destructor function */8059);80608061/*8062** CAPI3REF: Remove Unnecessary Virtual Table Implementations8063** METHOD: sqlite38064**8065** ^The sqlite3_drop_modules(D,L) interface removes all virtual8066** table modules from database connection D except those named on list L.8067** The L parameter must be either NULL or a pointer to an array of pointers8068** to strings where the array is terminated by a single NULL pointer.8069** ^If the L parameter is NULL, then all virtual table modules are removed.8070**8071** See also: [sqlite3_create_module()]8072*/8073SQLITE_API int sqlite3_drop_modules(8074  sqlite3 *db,                /* Remove modules from this connection */8075  const char **azKeep         /* Except, do not remove the ones named here */8076);80778078/*8079** CAPI3REF: Virtual Table Instance Object8080** KEYWORDS: sqlite3_vtab8081**8082** Every [virtual table module] implementation uses a subclass8083** of this object to describe a particular instance8084** of the [virtual table].  Each subclass will8085** be tailored to the specific needs of the module implementation.8086** The purpose of this superclass is to define certain fields that are8087** common to all module implementations.8088**8089** ^Virtual tables methods can set an error message by assigning a8090** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should8091** take care that any prior string is freed by a call to [sqlite3_free()]8092** prior to assigning a new string to zErrMsg.  ^After the error message8093** is delivered up to the client application, the string will be automatically8094** freed by sqlite3_free() and the zErrMsg field will be zeroed.8095*/8096struct sqlite3_vtab {8097  const sqlite3_module *pModule;  /* The module for this virtual table */8098  int nRef;                       /* Number of open cursors */8099  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */8100  /* Virtual table implementations will typically add additional fields */8101};81028103/*8104** CAPI3REF: Virtual Table Cursor Object8105** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}8106**8107** Every [virtual table module] implementation uses a subclass of the8108** following structure to describe cursors that point into the8109** [virtual table] and are used8110** to loop through the virtual table.  Cursors are created using the8111** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed8112** by the [sqlite3_module.xClose | xClose] method.  Cursors are used8113** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods8114** of the module.  Each module implementation will define8115** the content of a cursor structure to suit its own needs.8116**8117** This superclass exists in order to define fields of the cursor that8118** are common to all implementations.8119*/8120struct sqlite3_vtab_cursor {8121  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */8122  /* Virtual table implementations will typically add additional fields */8123};81248125/*8126** CAPI3REF: Declare The Schema Of A Virtual Table8127**8128** ^The [xCreate] and [xConnect] methods of a8129** [virtual table module] call this interface8130** to declare the format (the names and datatypes of the columns) of8131** the virtual tables they implement.8132*/8133SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);81348135/*8136** CAPI3REF: Overload A Function For A Virtual Table8137** METHOD: sqlite38138**8139** ^(Virtual tables can provide alternative implementations of functions8140** using the [xFindFunction] method of the [virtual table module].8141** But global versions of those functions8142** must exist in order to be overloaded.)^8143**8144** ^(This API makes sure a global version of a function with a particular8145** name and number of parameters exists.  If no such function exists8146** before this API is called, a new function is created.)^  ^The implementation8147** of the new function always causes an exception to be thrown.  So8148** the new function is not good for anything by itself.  Its only8149** purpose is to be a placeholder function that can be overloaded8150** by a [virtual table].8151*/8152SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);81538154/*8155** CAPI3REF: A Handle To An Open BLOB8156** KEYWORDS: {BLOB handle} {BLOB handles}8157**8158** An instance of this object represents an open BLOB on which8159** [sqlite3_blob_open | incremental BLOB I/O] can be performed.8160** ^Objects of this type are created by [sqlite3_blob_open()]8161** and destroyed by [sqlite3_blob_close()].8162** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces8163** can be used to read or write small subsections of the BLOB.8164** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.8165*/8166typedef struct sqlite3_blob sqlite3_blob;81678168/*8169** CAPI3REF: Open A BLOB For Incremental I/O8170** METHOD: sqlite38171** CONSTRUCTOR: sqlite3_blob8172**8173** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located8174** in row iRow, column zColumn, table zTable in database zDb;8175** in other words, the same BLOB that would be selected by:8176**8177** <pre>8178**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;8179** </pre>)^8180**8181** ^(Parameter zDb is not the filename that contains the database, but8182** rather the symbolic name of the database. For attached databases, this is8183** the name that appears after the AS keyword in the [ATTACH] statement.8184** For the main database file, the database name is "main". For TEMP8185** tables, the database name is "temp".)^8186**8187** ^If the flags parameter is non-zero, then the BLOB is opened for read8188** and write access. ^If the flags parameter is zero, the BLOB is opened for8189** read-only access.8190**8191** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored8192** in *ppBlob. Otherwise an [error code] is returned and, unless the error8193** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided8194** the API is not misused, it is always safe to call [sqlite3_blob_close()]8195** on *ppBlob after this function it returns.8196**8197** This function fails with SQLITE_ERROR if any of the following are true:8198** <ul>8199**   <li> ^(Database zDb does not exist)^,8200**   <li> ^(Table zTable does not exist within database zDb)^,8201**   <li> ^(Table zTable is a WITHOUT ROWID table)^,8202**   <li> ^(Column zColumn does not exist)^,8203**   <li> ^(Row iRow is not present in the table)^,8204**   <li> ^(The specified column of row iRow contains a value that is not8205**         a TEXT or BLOB value)^,8206**   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE8207**         constraint and the blob is being opened for read/write access)^,8208**   <li> ^([foreign key constraints | Foreign key constraints] are enabled,8209**         column zColumn is part of a [child key] definition and the blob is8210**         being opened for read/write access)^.8211** </ul>8212**8213** ^Unless it returns SQLITE_MISUSE, this function sets the8214** [database connection] error code and message accessible via8215** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.8216**8217** A BLOB referenced by sqlite3_blob_open() may be read using the8218** [sqlite3_blob_read()] interface and modified by using8219** [sqlite3_blob_write()].  The [BLOB handle] can be moved to a8220** different row of the same table using the [sqlite3_blob_reopen()]8221** interface.  However, the column, table, or database of a [BLOB handle]8222** cannot be changed after the [BLOB handle] is opened.8223**8224** ^(If the row that a BLOB handle points to is modified by an8225** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects8226** then the BLOB handle is marked as "expired".8227** This is true if any column of the row is changed, even a column8228** other than the one the BLOB handle is open on.)^8229** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for8230** an expired BLOB handle fail with a return code of [SQLITE_ABORT].8231** ^(Changes written into a BLOB prior to the BLOB expiring are not8232** rolled back by the expiration of the BLOB.  Such changes will eventually8233** commit if the transaction continues to completion.)^8234**8235** ^Use the [sqlite3_blob_bytes()] interface to determine the size of8236** the opened blob.  ^The size of a blob may not be changed by this8237** interface.  Use the [UPDATE] SQL command to change the size of a8238** blob.8239**8240** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces8241** and the built-in [zeroblob] SQL function may be used to create a8242** zero-filled blob to read or write using the incremental-blob interface.8243**8244** To avoid a resource leak, every open [BLOB handle] should eventually8245** be released by a call to [sqlite3_blob_close()].8246**8247** See also: [sqlite3_blob_close()],8248** [sqlite3_blob_reopen()], [sqlite3_blob_read()],8249** [sqlite3_blob_bytes()], [sqlite3_blob_write()].8250*/8251SQLITE_API int sqlite3_blob_open(8252  sqlite3*,8253  const char *zDb,8254  const char *zTable,8255  const char *zColumn,8256  sqlite3_int64 iRow,8257  int flags,8258  sqlite3_blob **ppBlob8259);82608261/*8262** CAPI3REF: Move a BLOB Handle to a New Row8263** METHOD: sqlite3_blob8264**8265** ^This function is used to move an existing [BLOB handle] so that it points8266** to a different row of the same database table. ^The new row is identified8267** by the rowid value passed as the second argument. Only the row can be8268** changed. ^The database, table and column on which the blob handle is open8269** remain the same. Moving an existing [BLOB handle] to a new row is8270** faster than closing the existing handle and opening a new one.8271**8272** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -8273** it must exist and there must be either a blob or text value stored in8274** the nominated column.)^ ^If the new row is not present in the table, or if8275** it does not contain a blob or text value, or if another error occurs, an8276** SQLite error code is returned and the blob handle is considered aborted.8277** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or8278** [sqlite3_blob_reopen()] on an aborted blob handle immediately return8279** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle8280** always returns zero.8281**8282** ^This function sets the database handle error code and message.8283*/8284SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);82858286/*8287** CAPI3REF: Close A BLOB Handle8288** DESTRUCTOR: sqlite3_blob8289**8290** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed8291** unconditionally.  Even if this routine returns an error code, the8292** handle is still closed.)^8293**8294** ^If the blob handle being closed was opened for read-write access, and if8295** the database is in auto-commit mode and there are no other open read-write8296** blob handles or active write statements, the current transaction is8297** committed. ^If an error occurs while committing the transaction, an error8298** code is returned and the transaction rolled back.8299**8300** Calling this function with an argument that is not a NULL pointer or an8301** open blob handle results in undefined behavior. ^Calling this routine8302** with a null pointer (such as would be returned by a failed call to8303** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function8304** is passed a valid open blob handle, the values returned by the8305** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.8306*/8307SQLITE_API int sqlite3_blob_close(sqlite3_blob *);83088309/*8310** CAPI3REF: Return The Size Of An Open BLOB8311** METHOD: sqlite3_blob8312**8313** ^Returns the size in bytes of the BLOB accessible via the8314** successfully opened [BLOB handle] in its only argument.  ^The8315** incremental blob I/O routines can only read or overwriting existing8316** blob content; they cannot change the size of a blob.8317**8318** This routine only works on a [BLOB handle] which has been created8319** by a prior successful call to [sqlite3_blob_open()] and which has not8320** been closed by [sqlite3_blob_close()].  Passing any other pointer in8321** to this routine results in undefined and probably undesirable behavior.8322*/8323SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);83248325/*8326** CAPI3REF: Read Data From A BLOB Incrementally8327** METHOD: sqlite3_blob8328**8329** ^(This function is used to read data from an open [BLOB handle] into a8330** caller-supplied buffer. N bytes of data are copied into buffer Z8331** from the open BLOB, starting at offset iOffset.)^8332**8333** ^If offset iOffset is less than N bytes from the end of the BLOB,8334** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is8335** less than zero, [SQLITE_ERROR] is returned and no data is read.8336** ^The size of the blob (and hence the maximum value of N+iOffset)8337** can be determined using the [sqlite3_blob_bytes()] interface.8338**8339** ^An attempt to read from an expired [BLOB handle] fails with an8340** error code of [SQLITE_ABORT].8341**8342** ^(On success, sqlite3_blob_read() returns SQLITE_OK.8343** Otherwise, an [error code] or an [extended error code] is returned.)^8344**8345** This routine only works on a [BLOB handle] which has been created8346** by a prior successful call to [sqlite3_blob_open()] and which has not8347** been closed by [sqlite3_blob_close()].  Passing any other pointer in8348** to this routine results in undefined and probably undesirable behavior.8349**8350** See also: [sqlite3_blob_write()].8351*/8352SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);83538354/*8355** CAPI3REF: Write Data Into A BLOB Incrementally8356** METHOD: sqlite3_blob8357**8358** ^(This function is used to write data into an open [BLOB handle] from a8359** caller-supplied buffer. N bytes of data are copied from the buffer Z8360** into the open BLOB, starting at offset iOffset.)^8361**8362** ^(On success, sqlite3_blob_write() returns SQLITE_OK.8363** Otherwise, an  [error code] or an [extended error code] is returned.)^8364** ^Unless SQLITE_MISUSE is returned, this function sets the8365** [database connection] error code and message accessible via8366** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.8367**8368** ^If the [BLOB handle] passed as the first argument was not opened for8369** writing (the flags parameter to [sqlite3_blob_open()] was zero),8370** this function returns [SQLITE_READONLY].8371**8372** This function may only modify the contents of the BLOB; it is8373** not possible to increase the size of a BLOB using this API.8374** ^If offset iOffset is less than N bytes from the end of the BLOB,8375** [SQLITE_ERROR] is returned and no data is written. The size of the8376** BLOB (and hence the maximum value of N+iOffset) can be determined8377** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less8378** than zero [SQLITE_ERROR] is returned and no data is written.8379**8380** ^An attempt to write to an expired [BLOB handle] fails with an8381** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred8382** before the [BLOB handle] expired are not rolled back by the8383** expiration of the handle, though of course those changes might8384** have been overwritten by the statement that expired the BLOB handle8385** or by other independent statements.8386**8387** This routine only works on a [BLOB handle] which has been created8388** by a prior successful call to [sqlite3_blob_open()] and which has not8389** been closed by [sqlite3_blob_close()].  Passing any other pointer in8390** to this routine results in undefined and probably undesirable behavior.8391**8392** See also: [sqlite3_blob_read()].8393*/8394SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);83958396/*8397** CAPI3REF: Virtual File System Objects8398**8399** A virtual filesystem (VFS) is an [sqlite3_vfs] object8400** that SQLite uses to interact8401** with the underlying operating system.  Most SQLite builds come with a8402** single default VFS that is appropriate for the host computer.8403** New VFSes can be registered and existing VFSes can be unregistered.8404** The following interfaces are provided.8405**8406** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.8407** ^Names are case sensitive.8408** ^Names are zero-terminated UTF-8 strings.8409** ^If there is no match, a NULL pointer is returned.8410** ^If zVfsName is NULL then the default VFS is returned.8411**8412** ^New VFSes are registered with sqlite3_vfs_register().8413** ^Each new VFS becomes the default VFS if the makeDflt flag is set.8414** ^The same VFS can be registered multiple times without injury.8415** ^To make an existing VFS into the default VFS, register it again8416** with the makeDflt flag set.  If two different VFSes with the8417** same name are registered, the behavior is undefined.  If a8418** VFS is registered with a name that is NULL or an empty string,8419** then the behavior is undefined.8420**8421** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.8422** ^(If the default VFS is unregistered, another VFS is chosen as8423** the default.  The choice for the new VFS is arbitrary.)^8424*/8425SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);8426SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);8427SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);84288429/*8430** CAPI3REF: Mutexes8431**8432** The SQLite core uses these routines for thread8433** synchronization. Though they are intended for internal8434** use by SQLite, code that links against SQLite is8435** permitted to use any of these routines.8436**8437** The SQLite source code contains multiple implementations8438** of these mutex routines.  An appropriate implementation8439** is selected automatically at compile-time.  The following8440** implementations are available in the SQLite core:8441**8442** <ul>8443** <li>   SQLITE_MUTEX_PTHREADS8444** <li>   SQLITE_MUTEX_W328445** <li>   SQLITE_MUTEX_NOOP8446** </ul>8447**8448** The SQLITE_MUTEX_NOOP implementation is a set of routines8449** that does no real locking and is appropriate for use in8450** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and8451** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix8452** and Windows.8453**8454** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor8455** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex8456** implementation is included with the library. In this case the8457** application must supply a custom mutex implementation using the8458** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function8459** before calling sqlite3_initialize() or any other public sqlite3_8460** function that calls sqlite3_initialize().8461**8462** ^The sqlite3_mutex_alloc() routine allocates a new8463** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()8464** routine returns NULL if it is unable to allocate the requested8465** mutex.  The argument to sqlite3_mutex_alloc() must one of these8466** integer constants:8467**8468** <ul>8469** <li>  SQLITE_MUTEX_FAST8470** <li>  SQLITE_MUTEX_RECURSIVE8471** <li>  SQLITE_MUTEX_STATIC_MAIN8472** <li>  SQLITE_MUTEX_STATIC_MEM8473** <li>  SQLITE_MUTEX_STATIC_OPEN8474** <li>  SQLITE_MUTEX_STATIC_PRNG8475** <li>  SQLITE_MUTEX_STATIC_LRU8476** <li>  SQLITE_MUTEX_STATIC_PMEM8477** <li>  SQLITE_MUTEX_STATIC_APP18478** <li>  SQLITE_MUTEX_STATIC_APP28479** <li>  SQLITE_MUTEX_STATIC_APP38480** <li>  SQLITE_MUTEX_STATIC_VFS18481** <li>  SQLITE_MUTEX_STATIC_VFS28482** <li>  SQLITE_MUTEX_STATIC_VFS38483** </ul>8484**8485** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)8486** cause sqlite3_mutex_alloc() to create8487** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE8488** is used but not necessarily so when SQLITE_MUTEX_FAST is used.8489** The mutex implementation does not need to make a distinction8490** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does8491** not want to.  SQLite will only request a recursive mutex in8492** cases where it really needs one.  If a faster non-recursive mutex8493** implementation is available on the host platform, the mutex subsystem8494** might return such a mutex in response to SQLITE_MUTEX_FAST.8495**8496** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other8497** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return8498** a pointer to a static preexisting mutex.  ^Nine static mutexes are8499** used by the current version of SQLite.  Future versions of SQLite8500** may add additional static mutexes.  Static mutexes are for internal8501** use by SQLite only.  Applications that use SQLite mutexes should8502** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or8503** SQLITE_MUTEX_RECURSIVE.8504**8505** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST8506** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()8507** returns a different mutex on every call.  ^For the static8508** mutex types, the same mutex is returned on every call that has8509** the same type number.8510**8511** ^The sqlite3_mutex_free() routine deallocates a previously8512** allocated dynamic mutex.  Attempting to deallocate a static8513** mutex results in undefined behavior.8514**8515** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt8516** to enter a mutex.  ^If another thread is already within the mutex,8517** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return8518** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]8519** upon successful entry.  ^(Mutexes created using8520** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.8521** In such cases, the8522** mutex must be exited an equal number of times before another thread8523** can enter.)^  If the same thread tries to enter any mutex other8524** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.8525**8526** ^(Some systems (for example, Windows 95) do not support the operation8527** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()8528** will always return SQLITE_BUSY. In most cases the SQLite core only uses8529** sqlite3_mutex_try() as an optimization, so this is acceptable8530** behavior. The exceptions are unix builds that set the8531** SQLITE_ENABLE_SETLK_TIMEOUT build option. In that case a working8532** sqlite3_mutex_try() is required.)^8533**8534** ^The sqlite3_mutex_leave() routine exits a mutex that was8535** previously entered by the same thread.   The behavior8536** is undefined if the mutex is not currently entered by the8537** calling thread or is not currently allocated.8538**8539** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(),8540** sqlite3_mutex_leave(), or sqlite3_mutex_free() is a NULL pointer,8541** then any of the four routines behaves as a no-op.8542**8543** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].8544*/8545SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);8546SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);8547SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);8548SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);8549SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);85508551/*8552** CAPI3REF: Mutex Methods Object8553**8554** An instance of this structure defines the low-level routines8555** used to allocate and use mutexes.8556**8557** Usually, the default mutex implementations provided by SQLite are8558** sufficient, however the application has the option of substituting a custom8559** implementation for specialized deployments or systems for which SQLite8560** does not provide a suitable implementation. In this case, the application8561** creates and populates an instance of this structure to pass8562** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.8563** Additionally, an instance of this structure can be used as an8564** output variable when querying the system for the current mutex8565** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.8566**8567** ^The xMutexInit method defined by this structure is invoked as8568** part of system initialization by the sqlite3_initialize() function.8569** ^The xMutexInit routine is called by SQLite exactly once for each8570** effective call to [sqlite3_initialize()].8571**8572** ^The xMutexEnd method defined by this structure is invoked as8573** part of system shutdown by the sqlite3_shutdown() function. The8574** implementation of this method is expected to release all outstanding8575** resources obtained by the mutex methods implementation, especially8576** those obtained by the xMutexInit method.  ^The xMutexEnd()8577** interface is invoked exactly once for each call to [sqlite3_shutdown()].8578**8579** ^(The remaining seven methods defined by this structure (xMutexAlloc,8580** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and8581** xMutexNotheld) implement the following interfaces (respectively):8582**8583** <ul>8584**   <li>  [sqlite3_mutex_alloc()] </li>8585**   <li>  [sqlite3_mutex_free()] </li>8586**   <li>  [sqlite3_mutex_enter()] </li>8587**   <li>  [sqlite3_mutex_try()] </li>8588**   <li>  [sqlite3_mutex_leave()] </li>8589**   <li>  [sqlite3_mutex_held()] </li>8590**   <li>  [sqlite3_mutex_notheld()] </li>8591** </ul>)^8592**8593** The only difference is that the public sqlite3_XXX functions enumerated8594** above silently ignore any invocations that pass a NULL pointer instead8595** of a valid mutex handle. The implementations of the methods defined8596** by this structure are not required to handle this case. The results8597** of passing a NULL pointer instead of a valid mutex handle are undefined8598** (i.e. it is acceptable to provide an implementation that segfaults if8599** it is passed a NULL pointer).8600**8601** The xMutexInit() method must be threadsafe.  It must be harmless to8602** invoke xMutexInit() multiple times within the same process and without8603** intervening calls to xMutexEnd().  Second and subsequent calls to8604** xMutexInit() must be no-ops.8605**8606** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]8607** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory8608** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite8609** memory allocation for a fast or recursive mutex.8610**8611** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is8612** called, but only if the prior call to xMutexInit returned SQLITE_OK.8613** If xMutexInit fails in any way, it is expected to clean up after itself8614** prior to returning.8615*/8616typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;8617struct sqlite3_mutex_methods {8618  int (*xMutexInit)(void);8619  int (*xMutexEnd)(void);8620  sqlite3_mutex *(*xMutexAlloc)(int);8621  void (*xMutexFree)(sqlite3_mutex *);8622  void (*xMutexEnter)(sqlite3_mutex *);8623  int (*xMutexTry)(sqlite3_mutex *);8624  void (*xMutexLeave)(sqlite3_mutex *);8625  int (*xMutexHeld)(sqlite3_mutex *);8626  int (*xMutexNotheld)(sqlite3_mutex *);8627};86288629/*8630** CAPI3REF: Mutex Verification Routines8631**8632** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines8633** are intended for use inside assert() statements.  The SQLite core8634** never uses these routines except inside an assert() and applications8635** are advised to follow the lead of the core.  The SQLite core only8636** provides implementations for these routines when it is compiled8637** with the SQLITE_DEBUG flag.  External mutex implementations8638** are only required to provide these routines if SQLITE_DEBUG is8639** defined and if NDEBUG is not defined.8640**8641** These routines should return true if the mutex in their argument8642** is held or not held, respectively, by the calling thread.8643**8644** The implementation is not required to provide versions of these8645** routines that actually work. If the implementation does not provide working8646** versions of these routines, it should at least provide stubs that always8647** return true so that one does not get spurious assertion failures.8648**8649** If the argument to sqlite3_mutex_held() is a NULL pointer then8650** the routine should return 1.   This seems counter-intuitive since8651** clearly the mutex cannot be held if it does not exist.  But8652** the reason the mutex does not exist is because the build is not8653** using mutexes.  And we do not want the assert() containing the8654** call to sqlite3_mutex_held() to fail, so a non-zero return is8655** the appropriate thing to do.  The sqlite3_mutex_notheld()8656** interface should also return 1 when given a NULL pointer.8657*/8658#ifndef NDEBUG8659SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);8660SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);8661#endif86628663/*8664** CAPI3REF: Mutex Types8665**8666** The [sqlite3_mutex_alloc()] interface takes a single argument8667** which is one of these integer constants.8668**8669** The set of static mutexes may change from one SQLite release to the8670** next.  Applications that override the built-in mutex logic must be8671** prepared to accommodate additional static mutexes.8672*/8673#define SQLITE_MUTEX_FAST             08674#define SQLITE_MUTEX_RECURSIVE        18675#define SQLITE_MUTEX_STATIC_MAIN      28676#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */8677#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */8678#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */8679#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_randomness() */8680#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */8681#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */8682#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */8683#define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */8684#define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */8685#define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */8686#define SQLITE_MUTEX_STATIC_VFS1     11  /* For use by built-in VFS */8687#define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */8688#define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */86898690/* Legacy compatibility: */8691#define SQLITE_MUTEX_STATIC_MASTER    2869286938694/*8695** CAPI3REF: Retrieve the mutex for a database connection8696** METHOD: sqlite38697**8698** ^This interface returns a pointer the [sqlite3_mutex] object that8699** serializes access to the [database connection] given in the argument8700** when the [threading mode] is Serialized.8701** ^If the [threading mode] is Single-thread or Multi-thread then this8702** routine returns a NULL pointer.8703*/8704SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);87058706/*8707** CAPI3REF: Low-Level Control Of Database Files8708** METHOD: sqlite38709** KEYWORDS: {file control}8710**8711** ^The [sqlite3_file_control()] interface makes a direct call to the8712** xFileControl method for the [sqlite3_io_methods] object associated8713** with a particular database identified by the second argument. ^The8714** name of the database is "main" for the main database or "temp" for the8715** TEMP database, or the name that appears after the AS keyword for8716** databases that are added using the [ATTACH] SQL command.8717** ^A NULL pointer can be used in place of "main" to refer to the8718** main database file.8719** ^The third and fourth parameters to this routine8720** are passed directly through to the second and third parameters of8721** the xFileControl method.  ^The return value of the xFileControl8722** method becomes the return value of this routine.8723**8724** A few opcodes for [sqlite3_file_control()] are handled directly8725** by the SQLite core and never invoke the8726** sqlite3_io_methods.xFileControl method.8727** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes8728** a pointer to the underlying [sqlite3_file] object to be written into8729** the space pointed to by the 4th parameter.  The8730** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns8731** the [sqlite3_file] object associated with the journal file instead of8732** the main database.  The [SQLITE_FCNTL_VFS_POINTER] opcode returns8733** a pointer to the underlying [sqlite3_vfs] object for the file.8734** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter8735** from the pager.8736**8737** ^If the second parameter (zDbName) does not match the name of any8738** open database file, then SQLITE_ERROR is returned.  ^This error8739** code is not remembered and will not be recalled by [sqlite3_errcode()]8740** or [sqlite3_errmsg()].  The underlying xFileControl method might8741** also return SQLITE_ERROR.  There is no way to distinguish between8742** an incorrect zDbName and an SQLITE_ERROR return from the underlying8743** xFileControl method.8744**8745** See also: [file control opcodes]8746*/8747SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);87488749/*8750** CAPI3REF: Testing Interface8751**8752** ^The sqlite3_test_control() interface is used to read out internal8753** state of SQLite and to inject faults into SQLite for testing8754** purposes.  ^The first parameter is an operation code that determines8755** the number, meaning, and operation of all subsequent parameters.8756**8757** This interface is not for use by applications.  It exists solely8758** for verifying the correct operation of the SQLite library.  Depending8759** on how the SQLite library is compiled, this interface might not exist.8760**8761** The details of the operation codes, their meanings, the parameters8762** they take, and what they do are all subject to change without notice.8763** Unlike most of the SQLite API, this function is not guaranteed to8764** operate consistently from one release to the next.8765*/8766SQLITE_API int sqlite3_test_control(int op, ...);87678768/*8769** CAPI3REF: Testing Interface Operation Codes8770**8771** These constants are the valid operation code parameters used8772** as the first argument to [sqlite3_test_control()].8773**8774** These parameters and their meanings are subject to change8775** without notice.  These values are for testing purposes only.8776** Applications should not use any of these parameters or the8777** [sqlite3_test_control()] interface.8778*/8779#define SQLITE_TESTCTRL_FIRST                    58780#define SQLITE_TESTCTRL_PRNG_SAVE                58781#define SQLITE_TESTCTRL_PRNG_RESTORE             68782#define SQLITE_TESTCTRL_PRNG_RESET               7  /* NOT USED */8783#define SQLITE_TESTCTRL_FK_NO_ACTION             78784#define SQLITE_TESTCTRL_BITVEC_TEST              88785#define SQLITE_TESTCTRL_FAULT_INSTALL            98786#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     108787#define SQLITE_TESTCTRL_PENDING_BYTE            118788#define SQLITE_TESTCTRL_ASSERT                  128789#define SQLITE_TESTCTRL_ALWAYS                  138790#define SQLITE_TESTCTRL_RESERVE                 14  /* NOT USED */8791#define SQLITE_TESTCTRL_JSON_SELFCHECK          148792#define SQLITE_TESTCTRL_OPTIMIZATIONS           158793#define SQLITE_TESTCTRL_ISKEYWORD               16  /* NOT USED */8794#define SQLITE_TESTCTRL_GETOPT                  168795#define SQLITE_TESTCTRL_SCRATCHMALLOC           17  /* NOT USED */8796#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS      178797#define SQLITE_TESTCTRL_LOCALTIME_FAULT         188798#define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */8799#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD    198800#define SQLITE_TESTCTRL_NEVER_CORRUPT           208801#define SQLITE_TESTCTRL_VDBE_COVERAGE           218802#define SQLITE_TESTCTRL_BYTEORDER               228803#define SQLITE_TESTCTRL_ISINIT                  238804#define SQLITE_TESTCTRL_SORTER_MMAP             248805#define SQLITE_TESTCTRL_IMPOSTER                258806#define SQLITE_TESTCTRL_PARSER_COVERAGE         268807#define SQLITE_TESTCTRL_RESULT_INTREAL          278808#define SQLITE_TESTCTRL_PRNG_SEED               288809#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     298810#define SQLITE_TESTCTRL_SEEK_COUNT              308811#define SQLITE_TESTCTRL_TRACEFLAGS              318812#define SQLITE_TESTCTRL_TUNE                    328813#define SQLITE_TESTCTRL_LOGEST                  338814#define SQLITE_TESTCTRL_USELONGDOUBLE           34  /* NOT USED */8815#define SQLITE_TESTCTRL_LAST                    34  /* Largest TESTCTRL */88168817/*8818** CAPI3REF: SQL Keyword Checking8819**8820** These routines provide access to the set of SQL language keywords8821** recognized by SQLite.  Applications can uses these routines to determine8822** whether or not a specific identifier needs to be escaped (for example,8823** by enclosing in double-quotes) so as not to confuse the parser.8824**8825** The sqlite3_keyword_count() interface returns the number of distinct8826** keywords understood by SQLite.8827**8828** The sqlite3_keyword_name(N,Z,L) interface finds the 0-based N-th keyword and8829** makes *Z point to that keyword expressed as UTF8 and writes the number8830** of bytes in the keyword into *L.  The string that *Z points to is not8831** zero-terminated.  The sqlite3_keyword_name(N,Z,L) routine returns8832** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z8833** or L are NULL or invalid pointers then calls to8834** sqlite3_keyword_name(N,Z,L) result in undefined behavior.8835**8836** The sqlite3_keyword_check(Z,L) interface checks to see whether or not8837** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero8838** if it is and zero if not.8839**8840** The parser used by SQLite is forgiving.  It is often possible to use8841** a keyword as an identifier as long as such use does not result in a8842** parsing ambiguity.  For example, the statement8843** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and8844** creates a new table named "BEGIN" with three columns named8845** "REPLACE", "PRAGMA", and "END".  Nevertheless, best practice is to avoid8846** using keywords as identifiers.  Common techniques used to avoid keyword8847** name collisions include:8848** <ul>8849** <li> Put all identifier names inside double-quotes.  This is the official8850**      SQL way to escape identifier names.8851** <li> Put identifier names inside &#91;...&#93;.  This is not standard SQL,8852**      but it is what SQL Server does and so lots of programmers use this8853**      technique.8854** <li> Begin every identifier with the letter "Z" as no SQL keywords start8855**      with "Z".8856** <li> Include a digit somewhere in every identifier name.8857** </ul>8858**8859** Note that the number of keywords understood by SQLite can depend on8860** compile-time options.  For example, "VACUUM" is not a keyword if8861** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option.  Also,8862** new keywords may be added to future releases of SQLite.8863*/8864SQLITE_API int sqlite3_keyword_count(void);8865SQLITE_API int sqlite3_keyword_name(int,const char**,int*);8866SQLITE_API int sqlite3_keyword_check(const char*,int);88678868/*8869** CAPI3REF: Dynamic String Object8870** KEYWORDS: {dynamic string}8871**8872** An instance of the sqlite3_str object contains a dynamically-sized8873** string under construction.8874**8875** The lifecycle of an sqlite3_str object is as follows:8876** <ol>8877** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].8878** <li> ^Text is appended to the sqlite3_str object using various8879** methods, such as [sqlite3_str_appendf()].8880** <li> ^The sqlite3_str object is destroyed and the string it created8881** is returned using the [sqlite3_str_finish()] interface.8882** </ol>8883*/8884typedef struct sqlite3_str sqlite3_str;88858886/*8887** CAPI3REF: Create A New Dynamic String Object8888** CONSTRUCTOR: sqlite3_str8889**8890** ^The [sqlite3_str_new(D)] interface allocates and initializes8891** a new [sqlite3_str] object.  To avoid memory leaks, the object returned by8892** [sqlite3_str_new()] must be freed by a subsequent call to8893** [sqlite3_str_finish(X)].8894**8895** ^The [sqlite3_str_new(D)] interface always returns a pointer to a8896** valid [sqlite3_str] object, though in the event of an out-of-memory8897** error the returned object might be a special singleton that will8898** silently reject new text, always return SQLITE_NOMEM from8899** [sqlite3_str_errcode()], always return 0 for8900** [sqlite3_str_length()], and always return NULL from8901** [sqlite3_str_finish(X)].  It is always safe to use the value8902** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter8903** to any of the other [sqlite3_str] methods.8904**8905** The D parameter to [sqlite3_str_new(D)] may be NULL.  If the8906** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum8907** length of the string contained in the [sqlite3_str] object will be8908** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead8909** of [SQLITE_MAX_LENGTH].8910*/8911SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);89128913/*8914** CAPI3REF: Finalize A Dynamic String8915** DESTRUCTOR: sqlite3_str8916**8917** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X8918** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]8919** that contains the constructed string.  The calling application should8920** pass the returned value to [sqlite3_free()] to avoid a memory leak.8921** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any8922** errors were encountered during construction of the string.  ^The8923** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the8924** string in [sqlite3_str] object X is zero bytes long.8925*/8926SQLITE_API char *sqlite3_str_finish(sqlite3_str*);89278928/*8929** CAPI3REF: Add Content To A Dynamic String8930** METHOD: sqlite3_str8931**8932** These interfaces add content to an sqlite3_str object previously obtained8933** from [sqlite3_str_new()].8934**8935** ^The [sqlite3_str_appendf(X,F,...)] and8936** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]8937** functionality of SQLite to append formatted text onto the end of8938** [sqlite3_str] object X.8939**8940** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S8941** onto the end of the [sqlite3_str] object X.  N must be non-negative.8942** S must contain at least N non-zero bytes of content.  To append a8943** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]8944** method instead.8945**8946** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of8947** zero-terminated string S onto the end of [sqlite3_str] object X.8948**8949** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the8950** single-byte character C onto the end of [sqlite3_str] object X.8951** ^This method can be used, for example, to add whitespace indentation.8952**8953** ^The [sqlite3_str_reset(X)] method resets the string under construction8954** inside [sqlite3_str] object X back to zero bytes in length.8955**8956** These methods do not return a result code.  ^If an error occurs, that fact8957** is recorded in the [sqlite3_str] object and can be recovered by a8958** subsequent call to [sqlite3_str_errcode(X)].8959*/8960SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);8961SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);8962SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);8963SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);8964SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);8965SQLITE_API void sqlite3_str_reset(sqlite3_str*);89668967/*8968** CAPI3REF: Status Of A Dynamic String8969** METHOD: sqlite3_str8970**8971** These interfaces return the current status of an [sqlite3_str] object.8972**8973** ^If any prior errors have occurred while constructing the dynamic string8974** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return8975** an appropriate error code.  ^The [sqlite3_str_errcode(X)] method returns8976** [SQLITE_NOMEM] following any out-of-memory error, or8977** [SQLITE_TOOBIG] if the size of the dynamic string exceeds8978** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.8979**8980** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,8981** of the dynamic string under construction in [sqlite3_str] object X.8982** ^The length returned by [sqlite3_str_length(X)] does not include the8983** zero-termination byte.8984**8985** ^The [sqlite3_str_value(X)] method returns a pointer to the current8986** content of the dynamic string under construction in X.  The value8987** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X8988** and might be freed or altered by any subsequent method on the same8989** [sqlite3_str] object.  Applications must not used the pointer returned8990** [sqlite3_str_value(X)] after any subsequent method call on the same8991** object.  ^Applications may change the content of the string returned8992** by [sqlite3_str_value(X)] as long as they do not write into any bytes8993** outside the range of 0 to [sqlite3_str_length(X)] and do not read or8994** write any byte after any subsequent sqlite3_str method call.8995*/8996SQLITE_API int sqlite3_str_errcode(sqlite3_str*);8997SQLITE_API int sqlite3_str_length(sqlite3_str*);8998SQLITE_API char *sqlite3_str_value(sqlite3_str*);89999000/*9001** CAPI3REF: SQLite Runtime Status9002**9003** ^These interfaces are used to retrieve runtime status information9004** about the performance of SQLite, and optionally to reset various9005** highwater marks.  ^The first argument is an integer code for9006** the specific parameter to measure.  ^(Recognized integer codes9007** are of the form [status parameters | SQLITE_STATUS_...].)^9008** ^The current value of the parameter is returned into *pCurrent.9009** ^The highest recorded value is returned in *pHighwater.  ^If the9010** resetFlag is true, then the highest record value is reset after9011** *pHighwater is written.  ^(Some parameters do not record the highest9012** value.  For those parameters9013** nothing is written into *pHighwater and the resetFlag is ignored.)^9014** ^(Other parameters record only the highwater mark and not the current9015** value.  For these latter parameters nothing is written into *pCurrent.)^9016**9017** ^The sqlite3_status() and sqlite3_status64() routines return9018** SQLITE_OK on success and a non-zero [error code] on failure.9019**9020** If either the current value or the highwater mark is too large to9021** be represented by a 32-bit integer, then the values returned by9022** sqlite3_status() are undefined.9023**9024** See also: [sqlite3_db_status()]9025*/9026SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);9027SQLITE_API int sqlite3_status64(9028  int op,9029  sqlite3_int64 *pCurrent,9030  sqlite3_int64 *pHighwater,9031  int resetFlag9032);903390349035/*9036** CAPI3REF: Status Parameters9037** KEYWORDS: {status parameters}9038**9039** These integer constants designate various run-time status parameters9040** that can be returned by [sqlite3_status()].9041**9042** <dl>9043** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>9044** <dd>This parameter is the current amount of memory checked out9045** using [sqlite3_malloc()], either directly or indirectly.  The9046** figure includes calls made to [sqlite3_malloc()] by the application9047** and internal memory usage by the SQLite library.  Auxiliary page-cache9048** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in9049** this parameter.  The amount returned is the sum of the allocation9050** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^9051**9052** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>9053** <dd>This parameter records the largest memory allocation request9054** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their9055** internal equivalents).  Only the value returned in the9056** *pHighwater parameter to [sqlite3_status()] is of interest.9057** The value written into the *pCurrent parameter is undefined.</dd>)^9058**9059** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>9060** <dd>This parameter records the number of separate memory allocations9061** currently checked out.</dd>)^9062**9063** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>9064** <dd>This parameter returns the number of pages used out of the9065** [pagecache memory allocator] that was configured using9066** [SQLITE_CONFIG_PAGECACHE].  The9067** value returned is in pages, not in bytes.</dd>)^9068**9069** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]9070** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>9071** <dd>This parameter returns the number of bytes of page cache9072** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]9073** buffer and where forced to overflow to [sqlite3_malloc()].  The9074** returned value includes allocations that overflowed because they9075** where too large (they were larger than the "sz" parameter to9076** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because9077** no space was left in the page cache.</dd>)^9078**9079** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>9080** <dd>This parameter records the largest memory allocation request9081** handed to the [pagecache memory allocator].  Only the value returned in the9082** *pHighwater parameter to [sqlite3_status()] is of interest.9083** The value written into the *pCurrent parameter is undefined.</dd>)^9084**9085** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>9086** <dd>No longer used.</dd>9087**9088** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>9089** <dd>No longer used.</dd>9090**9091** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>9092** <dd>No longer used.</dd>9093**9094** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>9095** <dd>The *pHighwater parameter records the deepest parser stack.9096** The *pCurrent value is undefined.  The *pHighwater value is only9097** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^9098** </dl>9099**9100** New status parameters may be added from time to time.9101*/9102#define SQLITE_STATUS_MEMORY_USED          09103#define SQLITE_STATUS_PAGECACHE_USED       19104#define SQLITE_STATUS_PAGECACHE_OVERFLOW   29105#define SQLITE_STATUS_SCRATCH_USED         3  /* NOT USED */9106#define SQLITE_STATUS_SCRATCH_OVERFLOW     4  /* NOT USED */9107#define SQLITE_STATUS_MALLOC_SIZE          59108#define SQLITE_STATUS_PARSER_STACK         69109#define SQLITE_STATUS_PAGECACHE_SIZE       79110#define SQLITE_STATUS_SCRATCH_SIZE         8  /* NOT USED */9111#define SQLITE_STATUS_MALLOC_COUNT         991129113/*9114** CAPI3REF: Database Connection Status9115** METHOD: sqlite39116**9117** ^This interface is used to retrieve runtime status information9118** about a single [database connection].  ^The first argument is the9119** database connection object to be interrogated.  ^The second argument9120** is an integer constant, taken from the set of9121** [SQLITE_DBSTATUS options], that9122** determines the parameter to interrogate.  The set of9123** [SQLITE_DBSTATUS options] is likely9124** to grow in future releases of SQLite.9125**9126** ^The current value of the requested parameter is written into *pCur9127** and the highest instantaneous value is written into *pHiwtr.  ^If9128** the resetFlg is true, then the highest instantaneous value is9129** reset back down to the current value.9130**9131** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a9132** non-zero [error code] on failure.9133**9134** See also: [sqlite3_status()] and [sqlite3_stmt_status()].9135*/9136SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);91379138/*9139** CAPI3REF: Status Parameters for database connections9140** KEYWORDS: {SQLITE_DBSTATUS options}9141**9142** These constants are the available integer "verbs" that can be passed as9143** the second argument to the [sqlite3_db_status()] interface.9144**9145** New verbs may be added in future releases of SQLite. Existing verbs9146** might be discontinued. Applications should check the return code from9147** [sqlite3_db_status()] to make sure that the call worked.9148** The [sqlite3_db_status()] interface will return a non-zero error code9149** if a discontinued or unsupported verb is invoked.9150**9151** <dl>9152** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>9153** <dd>This parameter returns the number of lookaside memory slots currently9154** checked out.</dd>)^9155**9156** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>9157** <dd>This parameter returns the number of malloc attempts that were9158** satisfied using lookaside memory. Only the high-water value is meaningful;9159** the current value is always zero.)^9160**9161** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]9162** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>9163** <dd>This parameter returns the number malloc attempts that might have9164** been satisfied using lookaside memory but failed due to the amount of9165** memory requested being larger than the lookaside slot size.9166** Only the high-water value is meaningful;9167** the current value is always zero.)^9168**9169** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]9170** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>9171** <dd>This parameter returns the number malloc attempts that might have9172** been satisfied using lookaside memory but failed due to all lookaside9173** memory already being in use.9174** Only the high-water value is meaningful;9175** the current value is always zero.)^9176**9177** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>9178** <dd>This parameter returns the approximate number of bytes of heap9179** memory used by all pager caches associated with the database connection.)^9180** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.9181**9182** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]9183** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>9184** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a9185** pager cache is shared between two or more connections the bytes of heap9186** memory used by that pager cache is divided evenly between the attached9187** connections.)^  In other words, if none of the pager caches associated9188** with the database connection are shared, this request returns the same9189** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are9190** shared, the value returned by this call will be smaller than that returned9191** by DBSTATUS_CACHE_USED. ^The highwater mark associated with9192** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.9193**9194** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>9195** <dd>This parameter returns the approximate number of bytes of heap9196** memory used to store the schema for all databases associated9197** with the connection - main, temp, and any [ATTACH]-ed databases.)^9198** ^The full amount of memory used by the schemas is reported, even if the9199** schema memory is shared with other database connections due to9200** [shared cache mode] being enabled.9201** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.9202**9203** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>9204** <dd>This parameter returns the approximate number of bytes of heap9205** and lookaside memory used by all prepared statements associated with9206** the database connection.)^9207** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.9208** </dd>9209**9210** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>9211** <dd>This parameter returns the number of pager cache hits that have9212** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT9213** is always 0.9214** </dd>9215**9216** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>9217** <dd>This parameter returns the number of pager cache misses that have9218** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS9219** is always 0.9220** </dd>9221**9222** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>9223** <dd>This parameter returns the number of dirty cache entries that have9224** been written to disk. Specifically, the number of pages written to the9225** wal file in wal mode databases, or the number of pages written to the9226** database file in rollback mode databases. Any pages written as part of9227** transaction rollback or database recovery operations are not included.9228** If an IO or other error occurs while writing a page to disk, the effect9229** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The9230** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.9231** </dd>9232**9233** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>9234** <dd>This parameter returns the number of dirty cache entries that have9235** been written to disk in the middle of a transaction due to the page9236** cache overflowing. Transactions are more efficient if they are written9237** to disk all at once. When pages spill mid-transaction, that introduces9238** additional overhead. This parameter can be used help identify9239** inefficiencies that can be resolved by increasing the cache size.9240** </dd>9241**9242** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>9243** <dd>This parameter returns zero for the current value if and only if9244** all foreign key constraints (deferred or immediate) have been9245** resolved.)^  ^The highwater mark is always 0.9246** </dd>9247** </dl>9248*/9249#define SQLITE_DBSTATUS_LOOKASIDE_USED       09250#define SQLITE_DBSTATUS_CACHE_USED           19251#define SQLITE_DBSTATUS_SCHEMA_USED          29252#define SQLITE_DBSTATUS_STMT_USED            39253#define SQLITE_DBSTATUS_LOOKASIDE_HIT        49254#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  59255#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  69256#define SQLITE_DBSTATUS_CACHE_HIT            79257#define SQLITE_DBSTATUS_CACHE_MISS           89258#define SQLITE_DBSTATUS_CACHE_WRITE          99259#define SQLITE_DBSTATUS_DEFERRED_FKS        109260#define SQLITE_DBSTATUS_CACHE_USED_SHARED   119261#define SQLITE_DBSTATUS_CACHE_SPILL         129262#define SQLITE_DBSTATUS_MAX                 12   /* Largest defined DBSTATUS */926392649265/*9266** CAPI3REF: Prepared Statement Status9267** METHOD: sqlite3_stmt9268**9269** ^(Each prepared statement maintains various9270** [SQLITE_STMTSTATUS counters] that measure the number9271** of times it has performed specific operations.)^  These counters can9272** be used to monitor the performance characteristics of the prepared9273** statements.  For example, if the number of table steps greatly exceeds9274** the number of table searches or result rows, that would tend to indicate9275** that the prepared statement is using a full table scan rather than9276** an index.9277**9278** ^(This interface is used to retrieve and reset counter values from9279** a [prepared statement].  The first argument is the prepared statement9280** object to be interrogated.  The second argument9281** is an integer code for a specific [SQLITE_STMTSTATUS counter]9282** to be interrogated.)^9283** ^The current value of the requested counter is returned.9284** ^If the resetFlg is true, then the counter is reset to zero after this9285** interface call returns.9286**9287** See also: [sqlite3_status()] and [sqlite3_db_status()].9288*/9289SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);92909291/*9292** CAPI3REF: Status Parameters for prepared statements9293** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}9294**9295** These preprocessor macros define integer codes that name counter9296** values associated with the [sqlite3_stmt_status()] interface.9297** The meanings of the various counters are as follows:9298**9299** <dl>9300** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>9301** <dd>^This is the number of times that SQLite has stepped forward in9302** a table as part of a full table scan.  Large numbers for this counter9303** may indicate opportunities for performance improvement through9304** careful use of indices.</dd>9305**9306** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>9307** <dd>^This is the number of sort operations that have occurred.9308** A non-zero value in this counter may indicate an opportunity to9309** improvement performance through careful use of indices.</dd>9310**9311** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>9312** <dd>^This is the number of rows inserted into transient indices that9313** were created automatically in order to help joins run faster.9314** A non-zero value in this counter may indicate an opportunity to9315** improvement performance by adding permanent indices that do not9316** need to be reinitialized each time the statement is run.</dd>9317**9318** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>9319** <dd>^This is the number of virtual machine operations executed9320** by the prepared statement if that number is less than or equal9321** to 2147483647.  The number of virtual machine operations can be9322** used as a proxy for the total work done by the prepared statement.9323** If the number of virtual machine operations exceeds 21474836479324** then the value returned by this statement status code is undefined.9325**9326** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>9327** <dd>^This is the number of times that the prepare statement has been9328** automatically regenerated due to schema changes or changes to9329** [bound parameters] that might affect the query plan.9330**9331** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>9332** <dd>^This is the number of times that the prepared statement has9333** been run.  A single "run" for the purposes of this counter is one9334** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].9335** The counter is incremented on the first [sqlite3_step()] call of each9336** cycle.9337**9338** [[SQLITE_STMTSTATUS_FILTER_MISS]]9339** [[SQLITE_STMTSTATUS_FILTER HIT]]9340** <dt>SQLITE_STMTSTATUS_FILTER_HIT<br>9341** SQLITE_STMTSTATUS_FILTER_MISS</dt>9342** <dd>^SQLITE_STMTSTATUS_FILTER_HIT is the number of times that a join9343** step was bypassed because a Bloom filter returned not-found.  The9344** corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of9345** times that the Bloom filter returned a find, and thus the join step9346** had to be processed as normal.9347**9348** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>9349** <dd>^This is the approximate number of bytes of heap memory9350** used to store the prepared statement.  ^This value is not actually9351** a counter, and so the resetFlg parameter to sqlite3_stmt_status()9352** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.9353** </dd>9354** </dl>9355*/9356#define SQLITE_STMTSTATUS_FULLSCAN_STEP     19357#define SQLITE_STMTSTATUS_SORT              29358#define SQLITE_STMTSTATUS_AUTOINDEX         39359#define SQLITE_STMTSTATUS_VM_STEP           49360#define SQLITE_STMTSTATUS_REPREPARE         59361#define SQLITE_STMTSTATUS_RUN               69362#define SQLITE_STMTSTATUS_FILTER_MISS       79363#define SQLITE_STMTSTATUS_FILTER_HIT        89364#define SQLITE_STMTSTATUS_MEMUSED           9993659366/*9367** CAPI3REF: Custom Page Cache Object9368**9369** The sqlite3_pcache type is opaque.  It is implemented by9370** the pluggable module.  The SQLite core has no knowledge of9371** its size or internal structure and never deals with the9372** sqlite3_pcache object except by holding and passing pointers9373** to the object.9374**9375** See [sqlite3_pcache_methods2] for additional information.9376*/9377typedef struct sqlite3_pcache sqlite3_pcache;93789379/*9380** CAPI3REF: Custom Page Cache Object9381**9382** The sqlite3_pcache_page object represents a single page in the9383** page cache.  The page cache will allocate instances of this9384** object.  Various methods of the page cache use pointers to instances9385** of this object as parameters or as their return value.9386**9387** See [sqlite3_pcache_methods2] for additional information.9388*/9389typedef struct sqlite3_pcache_page sqlite3_pcache_page;9390struct sqlite3_pcache_page {9391  void *pBuf;        /* The content of the page */9392  void *pExtra;      /* Extra information associated with the page */9393};93949395/*9396** CAPI3REF: Application Defined Page Cache.9397** KEYWORDS: {page cache}9398**9399** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can9400** register an alternative page cache implementation by passing in an9401** instance of the sqlite3_pcache_methods2 structure.)^9402** In many applications, most of the heap memory allocated by9403** SQLite is used for the page cache.9404** By implementing a9405** custom page cache using this API, an application can better control9406** the amount of memory consumed by SQLite, the way in which9407** that memory is allocated and released, and the policies used to9408** determine exactly which parts of a database file are cached and for9409** how long.9410**9411** The alternative page cache mechanism is an9412** extreme measure that is only needed by the most demanding applications.9413** The built-in page cache is recommended for most uses.9414**9415** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an9416** internal buffer by SQLite within the call to [sqlite3_config].  Hence9417** the application may discard the parameter after the call to9418** [sqlite3_config()] returns.)^9419**9420** [[the xInit() page cache method]]9421** ^(The xInit() method is called once for each effective9422** call to [sqlite3_initialize()])^9423** (usually only once during the lifetime of the process). ^(The xInit()9424** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^9425** The intent of the xInit() method is to set up global data structures9426** required by the custom page cache implementation.9427** ^(If the xInit() method is NULL, then the9428** built-in default page cache is used instead of the application defined9429** page cache.)^9430**9431** [[the xShutdown() page cache method]]9432** ^The xShutdown() method is called by [sqlite3_shutdown()].9433** It can be used to clean up9434** any outstanding resources before process shutdown, if required.9435** ^The xShutdown() method may be NULL.9436**9437** ^SQLite automatically serializes calls to the xInit method,9438** so the xInit method need not be threadsafe.  ^The9439** xShutdown method is only called from [sqlite3_shutdown()] so it does9440** not need to be threadsafe either.  All other methods must be threadsafe9441** in multithreaded applications.9442**9443** ^SQLite will never invoke xInit() more than once without an intervening9444** call to xShutdown().9445**9446** [[the xCreate() page cache methods]]9447** ^SQLite invokes the xCreate() method to construct a new cache instance.9448** SQLite will typically create one cache instance for each open database file,9449** though this is not guaranteed. ^The9450** first parameter, szPage, is the size in bytes of the pages that must9451** be allocated by the cache.  ^szPage will always a power of two.  ^The9452** second parameter szExtra is a number of bytes of extra storage9453** associated with each page cache entry.  ^The szExtra parameter will9454** a number less than 250.  SQLite will use the9455** extra szExtra bytes on each page to store metadata about the underlying9456** database page on disk.  The value passed into szExtra depends9457** on the SQLite version, the target platform, and how SQLite was compiled.9458** ^The third argument to xCreate(), bPurgeable, is true if the cache being9459** created will be used to cache database pages of a file stored on disk, or9460** false if it is used for an in-memory database. The cache implementation9461** does not have to do anything special based with the value of bPurgeable;9462** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will9463** never invoke xUnpin() except to deliberately delete a page.9464** ^In other words, calls to xUnpin() on a cache with bPurgeable set to9465** false will always have the "discard" flag set to true.9466** ^Hence, a cache created with bPurgeable false will9467** never contain any unpinned pages.9468**9469** [[the xCachesize() page cache method]]9470** ^(The xCachesize() method may be called at any time by SQLite to set the9471** suggested maximum cache-size (number of pages stored by) the cache9472** instance passed as the first argument. This is the value configured using9473** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable9474** parameter, the implementation is not required to do anything with this9475** value; it is advisory only.9476**9477** [[the xPagecount() page cache methods]]9478** The xPagecount() method must return the number of pages currently9479** stored in the cache, both pinned and unpinned.9480**9481** [[the xFetch() page cache methods]]9482** The xFetch() method locates a page in the cache and returns a pointer to9483** an sqlite3_pcache_page object associated with that page, or a NULL pointer.9484** The pBuf element of the returned sqlite3_pcache_page object will be a9485** pointer to a buffer of szPage bytes used to store the content of a9486** single database page.  The pExtra element of sqlite3_pcache_page will be9487** a pointer to the szExtra bytes of extra storage that SQLite has requested9488** for each entry in the page cache.9489**9490** The page to be fetched is determined by the key. ^The minimum key value9491** is 1.  After it has been retrieved using xFetch, the page is considered9492** to be "pinned".9493**9494** If the requested page is already in the page cache, then the page cache9495** implementation must return a pointer to the page buffer with its content9496** intact.  If the requested page is not already in the cache, then the9497** cache implementation should use the value of the createFlag9498** parameter to help it determined what action to take:9499**9500** <table border=1 width=85% align=center>9501** <tr><th> createFlag <th> Behavior when page is not already in cache9502** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.9503** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.9504**                 Otherwise return NULL.9505** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return9506**                 NULL if allocating a new page is effectively impossible.9507** </table>9508**9509** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite9510** will only use a createFlag of 2 after a prior call with a createFlag of 19511** failed.)^  In between the xFetch() calls, SQLite may9512** attempt to unpin one or more cache pages by spilling the content of9513** pinned pages to disk and synching the operating system disk cache.9514**9515** [[the xUnpin() page cache method]]9516** ^xUnpin() is called by SQLite with a pointer to a currently pinned page9517** as its second argument.  If the third parameter, discard, is non-zero,9518** then the page must be evicted from the cache.9519** ^If the discard parameter is9520** zero, then the page may be discarded or retained at the discretion of9521** page cache implementation. ^The page cache implementation9522** may choose to evict unpinned pages at any time.9523**9524** The cache must not perform any reference counting. A single9525** call to xUnpin() unpins the page regardless of the number of prior calls9526** to xFetch().9527**9528** [[the xRekey() page cache methods]]9529** The xRekey() method is used to change the key value associated with the9530** page passed as the second argument. If the cache9531** previously contains an entry associated with newKey, it must be9532** discarded. ^Any prior cache entry associated with newKey is guaranteed not9533** to be pinned.9534**9535** When SQLite calls the xTruncate() method, the cache must discard all9536** existing cache entries with page numbers (keys) greater than or equal9537** to the value of the iLimit parameter passed to xTruncate(). If any9538** of these pages are pinned, they are implicitly unpinned, meaning that9539** they can be safely discarded.9540**9541** [[the xDestroy() page cache method]]9542** ^The xDestroy() method is used to delete a cache allocated by xCreate().9543** All resources associated with the specified cache should be freed. ^After9544** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]9545** handle invalid, and will not use it with any other sqlite3_pcache_methods29546** functions.9547**9548** [[the xShrink() page cache method]]9549** ^SQLite invokes the xShrink() method when it wants the page cache to9550** free up as much of heap memory as possible.  The page cache implementation9551** is not obligated to free any memory, but well-behaved implementations should9552** do their best.9553*/9554typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;9555struct sqlite3_pcache_methods2 {9556  int iVersion;9557  void *pArg;9558  int (*xInit)(void*);9559  void (*xShutdown)(void*);9560  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);9561  void (*xCachesize)(sqlite3_pcache*, int nCachesize);9562  int (*xPagecount)(sqlite3_pcache*);9563  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);9564  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);9565  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,9566      unsigned oldKey, unsigned newKey);9567  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);9568  void (*xDestroy)(sqlite3_pcache*);9569  void (*xShrink)(sqlite3_pcache*);9570};95719572/*9573** This is the obsolete pcache_methods object that has now been replaced9574** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is9575** retained in the header file for backwards compatibility only.9576*/9577typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;9578struct sqlite3_pcache_methods {9579  void *pArg;9580  int (*xInit)(void*);9581  void (*xShutdown)(void*);9582  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);9583  void (*xCachesize)(sqlite3_pcache*, int nCachesize);9584  int (*xPagecount)(sqlite3_pcache*);9585  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);9586  void (*xUnpin)(sqlite3_pcache*, void*, int discard);9587  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);9588  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);9589  void (*xDestroy)(sqlite3_pcache*);9590};959195929593/*9594** CAPI3REF: Online Backup Object9595**9596** The sqlite3_backup object records state information about an ongoing9597** online backup operation.  ^The sqlite3_backup object is created by9598** a call to [sqlite3_backup_init()] and is destroyed by a call to9599** [sqlite3_backup_finish()].9600**9601** See Also: [Using the SQLite Online Backup API]9602*/9603typedef struct sqlite3_backup sqlite3_backup;96049605/*9606** CAPI3REF: Online Backup API.9607**9608** The backup API copies the content of one database into another.9609** It is useful either for creating backups of databases or9610** for copying in-memory databases to or from persistent files.9611**9612** See Also: [Using the SQLite Online Backup API]9613**9614** ^SQLite holds a write transaction open on the destination database file9615** for the duration of the backup operation.9616** ^The source database is read-locked only while it is being read;9617** it is not locked continuously for the entire backup operation.9618** ^Thus, the backup may be performed on a live source database without9619** preventing other database connections from9620** reading or writing to the source database while the backup is underway.9621**9622** ^(To perform a backup operation:9623**   <ol>9624**     <li><b>sqlite3_backup_init()</b> is called once to initialize the9625**         backup,9626**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer9627**         the data between the two databases, and finally9628**     <li><b>sqlite3_backup_finish()</b> is called to release all resources9629**         associated with the backup operation.9630**   </ol>)^9631** There should be exactly one call to sqlite3_backup_finish() for each9632** successful call to sqlite3_backup_init().9633**9634** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>9635**9636** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the9637** [database connection] associated with the destination database9638** and the database name, respectively.9639** ^The database name is "main" for the main database, "temp" for the9640** temporary database, or the name specified after the AS keyword in9641** an [ATTACH] statement for an attached database.9642** ^The S and M arguments passed to9643** sqlite3_backup_init(D,N,S,M) identify the [database connection]9644** and database name of the source database, respectively.9645** ^The source and destination [database connections] (parameters S and D)9646** must be different or else sqlite3_backup_init(D,N,S,M) will fail with9647** an error.9648**9649** ^A call to sqlite3_backup_init() will fail, returning NULL, if9650** there is already a read or read-write transaction open on the9651** destination database.9652**9653** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is9654** returned and an error code and error message are stored in the9655** destination [database connection] D.9656** ^The error code and message for the failed call to sqlite3_backup_init()9657** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or9658** [sqlite3_errmsg16()] functions.9659** ^A successful call to sqlite3_backup_init() returns a pointer to an9660** [sqlite3_backup] object.9661** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and9662** sqlite3_backup_finish() functions to perform the specified backup9663** operation.9664**9665** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>9666**9667** ^Function sqlite3_backup_step(B,N) will copy up to N pages between9668** the source and destination databases specified by [sqlite3_backup] object B.9669** ^If N is negative, all remaining source pages are copied.9670** ^If sqlite3_backup_step(B,N) successfully copies N pages and there9671** are still more pages to be copied, then the function returns [SQLITE_OK].9672** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages9673** from source to destination, then it returns [SQLITE_DONE].9674** ^If an error occurs while running sqlite3_backup_step(B,N),9675** then an [error code] is returned. ^As well as [SQLITE_OK] and9676** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],9677** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an9678** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.9679**9680** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if9681** <ol>9682** <li> the destination database was opened read-only, or9683** <li> the destination database is using write-ahead-log journaling9684** and the destination and source page sizes differ, or9685** <li> the destination database is an in-memory database and the9686** destination and source page sizes differ.9687** </ol>)^9688**9689** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then9690** the [sqlite3_busy_handler | busy-handler function]9691** is invoked (if one is specified). ^If the9692** busy-handler returns non-zero before the lock is available, then9693** [SQLITE_BUSY] is returned to the caller. ^In this case the call to9694** sqlite3_backup_step() can be retried later. ^If the source9695** [database connection]9696** is being used to write to the source database when sqlite3_backup_step()9697** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this9698** case the call to sqlite3_backup_step() can be retried later on. ^(If9699** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or9700** [SQLITE_READONLY] is returned, then9701** there is no point in retrying the call to sqlite3_backup_step(). These9702** errors are considered fatal.)^  The application must accept9703** that the backup operation has failed and pass the backup operation handle9704** to the sqlite3_backup_finish() to release associated resources.9705**9706** ^The first call to sqlite3_backup_step() obtains an exclusive lock9707** on the destination file. ^The exclusive lock is not released until either9708** sqlite3_backup_finish() is called or the backup operation is complete9709** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to9710** sqlite3_backup_step() obtains a [shared lock] on the source database that9711** lasts for the duration of the sqlite3_backup_step() call.9712** ^Because the source database is not locked between calls to9713** sqlite3_backup_step(), the source database may be modified mid-way9714** through the backup process.  ^If the source database is modified by an9715** external process or via a database connection other than the one being9716** used by the backup operation, then the backup will be automatically9717** restarted by the next call to sqlite3_backup_step(). ^If the source9718** database is modified by the using the same database connection as is used9719** by the backup operation, then the backup database is automatically9720** updated at the same time.9721**9722** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>9723**9724** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the9725** application wishes to abandon the backup operation, the application9726** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().9727** ^The sqlite3_backup_finish() interfaces releases all9728** resources associated with the [sqlite3_backup] object.9729** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any9730** active write-transaction on the destination database is rolled back.9731** The [sqlite3_backup] object is invalid9732** and may not be used following a call to sqlite3_backup_finish().9733**9734** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no9735** sqlite3_backup_step() errors occurred, regardless or whether or not9736** sqlite3_backup_step() completed.9737** ^If an out-of-memory condition or IO error occurred during any prior9738** sqlite3_backup_step() call on the same [sqlite3_backup] object, then9739** sqlite3_backup_finish() returns the corresponding [error code].9740**9741** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()9742** is not a permanent error and does not affect the return value of9743** sqlite3_backup_finish().9744**9745** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]9746** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>9747**9748** ^The sqlite3_backup_remaining() routine returns the number of pages still9749** to be backed up at the conclusion of the most recent sqlite3_backup_step().9750** ^The sqlite3_backup_pagecount() routine returns the total number of pages9751** in the source database at the conclusion of the most recent9752** sqlite3_backup_step().9753** ^(The values returned by these functions are only updated by9754** sqlite3_backup_step(). If the source database is modified in a way that9755** changes the size of the source database or the number of pages remaining,9756** those changes are not reflected in the output of sqlite3_backup_pagecount()9757** and sqlite3_backup_remaining() until after the next9758** sqlite3_backup_step().)^9759**9760** <b>Concurrent Usage of Database Handles</b>9761**9762** ^The source [database connection] may be used by the application for other9763** purposes while a backup operation is underway or being initialized.9764** ^If SQLite is compiled and configured to support threadsafe database9765** connections, then the source database connection may be used concurrently9766** from within other threads.9767**9768** However, the application must guarantee that the destination9769** [database connection] is not passed to any other API (by any thread) after9770** sqlite3_backup_init() is called and before the corresponding call to9771** sqlite3_backup_finish().  SQLite does not currently check to see9772** if the application incorrectly accesses the destination [database connection]9773** and so no error code is reported, but the operations may malfunction9774** nevertheless.  Use of the destination database connection while a9775** backup is in progress might also cause a mutex deadlock.9776**9777** If running in [shared cache mode], the application must9778** guarantee that the shared cache used by the destination database9779** is not accessed while the backup is running. In practice this means9780** that the application must guarantee that the disk file being9781** backed up to is not accessed by any connection within the process,9782** not just the specific connection that was passed to sqlite3_backup_init().9783**9784** The [sqlite3_backup] object itself is partially threadsafe. Multiple9785** threads may safely make multiple concurrent calls to sqlite3_backup_step().9786** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()9787** APIs are not strictly speaking threadsafe. If they are invoked at the9788** same time as another thread is invoking sqlite3_backup_step() it is9789** possible that they return invalid values.9790**9791** <b>Alternatives To Using The Backup API</b>9792**9793** Other techniques for safely creating a consistent backup of an SQLite9794** database include:9795**9796** <ul>9797** <li> The [VACUUM INTO] command.9798** <li> The [sqlite3_rsync] utility program.9799** </ul>9800*/9801SQLITE_API sqlite3_backup *sqlite3_backup_init(9802  sqlite3 *pDest,                        /* Destination database handle */9803  const char *zDestName,                 /* Destination database name */9804  sqlite3 *pSource,                      /* Source database handle */9805  const char *zSourceName                /* Source database name */9806);9807SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);9808SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);9809SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);9810SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);98119812/*9813** CAPI3REF: Unlock Notification9814** METHOD: sqlite39815**9816** ^When running in shared-cache mode, a database operation may fail with9817** an [SQLITE_LOCKED] error if the required locks on the shared-cache or9818** individual tables within the shared-cache cannot be obtained. See9819** [SQLite Shared-Cache Mode] for a description of shared-cache locking.9820** ^This API may be used to register a callback that SQLite will invoke9821** when the connection currently holding the required lock relinquishes it.9822** ^This API is only available if the library was compiled with the9823** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.9824**9825** See Also: [Using the SQLite Unlock Notification Feature].9826**9827** ^Shared-cache locks are released when a database connection concludes9828** its current transaction, either by committing it or rolling it back.9829**9830** ^When a connection (known as the blocked connection) fails to obtain a9831** shared-cache lock and SQLITE_LOCKED is returned to the caller, the9832** identity of the database connection (the blocking connection) that9833** has locked the required resource is stored internally. ^After an9834** application receives an SQLITE_LOCKED error, it may call the9835** sqlite3_unlock_notify() method with the blocked connection handle as9836** the first argument to register for a callback that will be invoked9837** when the blocking connections current transaction is concluded. ^The9838** callback is invoked from within the [sqlite3_step] or [sqlite3_close]9839** call that concludes the blocking connection's transaction.9840**9841** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,9842** there is a chance that the blocking connection will have already9843** concluded its transaction by the time sqlite3_unlock_notify() is invoked.9844** If this happens, then the specified callback is invoked immediately,9845** from within the call to sqlite3_unlock_notify().)^9846**9847** ^If the blocked connection is attempting to obtain a write-lock on a9848** shared-cache table, and more than one other connection currently holds9849** a read-lock on the same table, then SQLite arbitrarily selects one of9850** the other connections to use as the blocking connection.9851**9852** ^(There may be at most one unlock-notify callback registered by a9853** blocked connection. If sqlite3_unlock_notify() is called when the9854** blocked connection already has a registered unlock-notify callback,9855** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is9856** called with a NULL pointer as its second argument, then any existing9857** unlock-notify callback is canceled. ^The blocked connections9858** unlock-notify callback may also be canceled by closing the blocked9859** connection using [sqlite3_close()].9860**9861** The unlock-notify callback is not reentrant. If an application invokes9862** any sqlite3_xxx API functions from within an unlock-notify callback, a9863** crash or deadlock may be the result.9864**9865** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always9866** returns SQLITE_OK.9867**9868** <b>Callback Invocation Details</b>9869**9870** When an unlock-notify callback is registered, the application provides a9871** single void* pointer that is passed to the callback when it is invoked.9872** However, the signature of the callback function allows SQLite to pass9873** it an array of void* context pointers. The first argument passed to9874** an unlock-notify callback is a pointer to an array of void* pointers,9875** and the second is the number of entries in the array.9876**9877** When a blocking connection's transaction is concluded, there may be9878** more than one blocked connection that has registered for an unlock-notify9879** callback. ^If two or more such blocked connections have specified the9880** same callback function, then instead of invoking the callback function9881** multiple times, it is invoked once with the set of void* context pointers9882** specified by the blocked connections bundled together into an array.9883** This gives the application an opportunity to prioritize any actions9884** related to the set of unblocked database connections.9885**9886** <b>Deadlock Detection</b>9887**9888** Assuming that after registering for an unlock-notify callback a9889** database waits for the callback to be issued before taking any further9890** action (a reasonable assumption), then using this API may cause the9891** application to deadlock. For example, if connection X is waiting for9892** connection Y's transaction to be concluded, and similarly connection9893** Y is waiting on connection X's transaction, then neither connection9894** will proceed and the system may remain deadlocked indefinitely.9895**9896** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock9897** detection. ^If a given call to sqlite3_unlock_notify() would put the9898** system in a deadlocked state, then SQLITE_LOCKED is returned and no9899** unlock-notify callback is registered. The system is said to be in9900** a deadlocked state if connection A has registered for an unlock-notify9901** callback on the conclusion of connection B's transaction, and connection9902** B has itself registered for an unlock-notify callback when connection9903** A's transaction is concluded. ^Indirect deadlock is also detected, so9904** the system is also considered to be deadlocked if connection B has9905** registered for an unlock-notify callback on the conclusion of connection9906** C's transaction, where connection C is waiting on connection A. ^Any9907** number of levels of indirection are allowed.9908**9909** <b>The "DROP TABLE" Exception</b>9910**9911** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost9912** always appropriate to call sqlite3_unlock_notify(). There is however,9913** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,9914** SQLite checks if there are any currently executing SELECT statements9915** that belong to the same connection. If there are, SQLITE_LOCKED is9916** returned. In this case there is no "blocking connection", so invoking9917** sqlite3_unlock_notify() results in the unlock-notify callback being9918** invoked immediately. If the application then re-attempts the "DROP TABLE"9919** or "DROP INDEX" query, an infinite loop might be the result.9920**9921** One way around this problem is to check the extended error code returned9922** by an sqlite3_step() call. ^(If there is a blocking connection, then the9923** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in9924** the special "DROP TABLE/INDEX" case, the extended error code is just9925** SQLITE_LOCKED.)^9926*/9927SQLITE_API int sqlite3_unlock_notify(9928  sqlite3 *pBlocked,                          /* Waiting connection */9929  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */9930  void *pNotifyArg                            /* Argument to pass to xNotify */9931);993299339934/*9935** CAPI3REF: String Comparison9936**9937** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications9938** and extensions to compare the contents of two buffers containing UTF-89939** strings in a case-independent fashion, using the same definition of "case9940** independence" that SQLite uses internally when comparing identifiers.9941*/9942SQLITE_API int sqlite3_stricmp(const char *, const char *);9943SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);99449945/*9946** CAPI3REF: String Globbing9947*9948** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if9949** string X matches the [GLOB] pattern P.9950** ^The definition of [GLOB] pattern matching used in9951** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the9952** SQL dialect understood by SQLite.  ^The [sqlite3_strglob(P,X)] function9953** is case sensitive.9954**9955** Note that this routine returns zero on a match and non-zero if the strings9956** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].9957**9958** See also: [sqlite3_strlike()].9959*/9960SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);99619962/*9963** CAPI3REF: String LIKE Matching9964*9965** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if9966** string X matches the [LIKE] pattern P with escape character E.9967** ^The definition of [LIKE] pattern matching used in9968** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"9969** operator in the SQL dialect understood by SQLite.  ^For "X LIKE P" without9970** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.9971** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case9972** insensitive - equivalent upper and lower case ASCII characters match9973** one another.9974**9975** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though9976** only ASCII characters are case folded.9977**9978** Note that this routine returns zero on a match and non-zero if the strings9979** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].9980**9981** See also: [sqlite3_strglob()].9982*/9983SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);99849985/*9986** CAPI3REF: Error Logging Interface9987**9988** ^The [sqlite3_log()] interface writes a message into the [error log]9989** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].9990** ^If logging is enabled, the zFormat string and subsequent arguments are9991** used with [sqlite3_snprintf()] to generate the final output string.9992**9993** The sqlite3_log() interface is intended for use by extensions such as9994** virtual tables, collating functions, and SQL functions.  While there is9995** nothing to prevent an application from calling sqlite3_log(), doing so9996** is considered bad form.9997**9998** The zFormat string must not be NULL.9999**10000** To avoid deadlocks and other threading problems, the sqlite3_log() routine10001** will not use dynamically allocated memory.  The log message is stored in10002** a fixed-length buffer on the stack.  If the log message is longer than10003** a few hundred characters, it will be truncated to the length of the10004** buffer.10005*/10006SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);1000710008/*10009** CAPI3REF: Write-Ahead Log Commit Hook10010** METHOD: sqlite310011**10012** ^The [sqlite3_wal_hook()] function is used to register a callback that10013** is invoked each time data is committed to a database in wal mode.10014**10015** ^(The callback is invoked by SQLite after the commit has taken place and10016** the associated write-lock on the database released)^, so the implementation10017** may read, write or [checkpoint] the database as required.10018**10019** ^The first parameter passed to the callback function when it is invoked10020** is a copy of the third parameter passed to sqlite3_wal_hook() when10021** registering the callback. ^The second is a copy of the database handle.10022** ^The third parameter is the name of the database that was written to -10023** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter10024** is the number of pages currently in the write-ahead log file,10025** including those that were just committed.10026**10027** The callback function should normally return [SQLITE_OK].  ^If an error10028** code is returned, that error will propagate back up through the10029** SQLite code base to cause the statement that provoked the callback10030** to report an error, though the commit will have still occurred. If the10031** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value10032** that does not correspond to any valid SQLite error code, the results10033** are undefined.10034**10035** A single database handle may have at most a single write-ahead log callback10036** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any10037** previously registered write-ahead log callback. ^The return value is10038** a copy of the third parameter from the previous call, if any, or 0.10039** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the10040** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will10041** overwrite any prior [sqlite3_wal_hook()] settings.10042*/10043SQLITE_API void *sqlite3_wal_hook(10044  sqlite3*,10045  int(*)(void *,sqlite3*,const char*,int),10046  void*10047);1004810049/*10050** CAPI3REF: Configure an auto-checkpoint10051** METHOD: sqlite310052**10053** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around10054** [sqlite3_wal_hook()] that causes any database on [database connection] D10055** to automatically [checkpoint]10056** after committing a transaction if there are N or10057** more frames in the [write-ahead log] file.  ^Passing zero or10058** a negative value as the nFrame parameter disables automatic10059** checkpoints entirely.10060**10061** ^The callback registered by this function replaces any existing callback10062** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback10063** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism10064** configured by this function.10065**10066** ^The [wal_autocheckpoint pragma] can be used to invoke this interface10067** from SQL.10068**10069** ^Checkpoints initiated by this mechanism are10070** [sqlite3_wal_checkpoint_v2|PASSIVE].10071**10072** ^Every new [database connection] defaults to having the auto-checkpoint10073** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]10074** pages.  The use of this interface10075** is only necessary if the default setting is found to be suboptimal10076** for a particular application.10077*/10078SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);1007910080/*10081** CAPI3REF: Checkpoint a database10082** METHOD: sqlite310083**10084** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to10085** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^10086**10087** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the10088** [write-ahead log] for database X on [database connection] D to be10089** transferred into the database file and for the write-ahead log to10090** be reset.  See the [checkpointing] documentation for addition10091** information.10092**10093** This interface used to be the only way to cause a checkpoint to10094** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]10095** interface was added.  This interface is retained for backwards10096** compatibility and as a convenience for applications that need to manually10097** start a callback but which do not need the full power (and corresponding10098** complication) of [sqlite3_wal_checkpoint_v2()].10099*/10100SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);1010110102/*10103** CAPI3REF: Checkpoint a database10104** METHOD: sqlite310105**10106** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint10107** operation on database X of [database connection] D in mode M.  Status10108** information is written back into integers pointed to by L and C.)^10109** ^(The M parameter must be a valid [checkpoint mode]:)^10110**10111** <dl>10112** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>10113**   ^Checkpoint as many frames as possible without waiting for any database10114**   readers or writers to finish, then sync the database file if all frames10115**   in the log were checkpointed. ^The [busy-handler callback]10116**   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.10117**   ^On the other hand, passive mode might leave the checkpoint unfinished10118**   if there are concurrent readers or writers.10119**10120** <dt>SQLITE_CHECKPOINT_FULL<dd>10121**   ^This mode blocks (it invokes the10122**   [sqlite3_busy_handler|busy-handler callback]) until there is no10123**   database writer and all readers are reading from the most recent database10124**   snapshot. ^It then checkpoints all frames in the log file and syncs the10125**   database file. ^This mode blocks new database writers while it is pending,10126**   but new database readers are allowed to continue unimpeded.10127**10128** <dt>SQLITE_CHECKPOINT_RESTART<dd>10129**   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition10130**   that after checkpointing the log file it blocks (calls the10131**   [busy-handler callback])10132**   until all readers are reading from the database file only. ^This ensures10133**   that the next writer will restart the log file from the beginning.10134**   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new10135**   database writer attempts while it is pending, but does not impede readers.10136**10137** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>10138**   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the10139**   addition that it also truncates the log file to zero bytes just prior10140**   to a successful return.10141** </dl>10142**10143** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in10144** the log file or to -1 if the checkpoint could not run because10145** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not10146** NULL,then *pnCkpt is set to the total number of checkpointed frames in the10147** log file (including any that were already checkpointed before the function10148** was called) or to -1 if the checkpoint could not run due to an error or10149** because the database is not in WAL mode. ^Note that upon successful10150** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been10151** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.10152**10153** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If10154** any other process is running a checkpoint operation at the same time, the10155** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a10156** busy-handler configured, it will not be invoked in this case.10157**10158** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the10159** exclusive "writer" lock on the database file. ^If the writer lock cannot be10160** obtained immediately, and a busy-handler is configured, it is invoked and10161** the writer lock retried until either the busy-handler returns 0 or the lock10162** is successfully obtained. ^The busy-handler is also invoked while waiting for10163** database readers as described above. ^If the busy-handler returns 0 before10164** the writer lock is obtained or while waiting for database readers, the10165** checkpoint operation proceeds from that point in the same way as10166** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible10167** without blocking any further. ^SQLITE_BUSY is returned in this case.10168**10169** ^If parameter zDb is NULL or points to a zero length string, then the10170** specified operation is attempted on all WAL databases [attached] to10171** [database connection] db.  In this case the10172** values written to output parameters *pnLog and *pnCkpt are undefined. ^If10173** an SQLITE_BUSY error is encountered when processing one or more of the10174** attached WAL databases, the operation is still attempted on any remaining10175** attached databases and SQLITE_BUSY is returned at the end. ^If any other10176** error occurs while processing an attached database, processing is abandoned10177** and the error code is returned to the caller immediately. ^If no error10178** (SQLITE_BUSY or otherwise) is encountered while processing the attached10179** databases, SQLITE_OK is returned.10180**10181** ^If database zDb is the name of an attached database that is not in WAL10182** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If10183** zDb is not NULL (or a zero length string) and is not the name of any10184** attached database, SQLITE_ERROR is returned to the caller.10185**10186** ^Unless it returns SQLITE_MISUSE,10187** the sqlite3_wal_checkpoint_v2() interface10188** sets the error information that is queried by10189** [sqlite3_errcode()] and [sqlite3_errmsg()].10190**10191** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface10192** from SQL.10193*/10194SQLITE_API int sqlite3_wal_checkpoint_v2(10195  sqlite3 *db,                    /* Database handle */10196  const char *zDb,                /* Name of attached database (or NULL) */10197  int eMode,                      /* SQLITE_CHECKPOINT_* value */10198  int *pnLog,                     /* OUT: Size of WAL log in frames */10199  int *pnCkpt                     /* OUT: Total number of frames checkpointed */10200);1020110202/*10203** CAPI3REF: Checkpoint Mode Values10204** KEYWORDS: {checkpoint mode}10205**10206** These constants define all valid values for the "checkpoint mode" passed10207** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.10208** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the10209** meaning of each of these checkpoint modes.10210*/10211#define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */10212#define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */10213#define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for readers */10214#define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */1021510216/*10217** CAPI3REF: Virtual Table Interface Configuration10218**10219** This function may be called by either the [xConnect] or [xCreate] method10220** of a [virtual table] implementation to configure10221** various facets of the virtual table interface.10222**10223** If this interface is invoked outside the context of an xConnect or10224** xCreate virtual table method then the behavior is undefined.10225**10226** In the call sqlite3_vtab_config(D,C,...) the D parameter is the10227** [database connection] in which the virtual table is being created and10228** which is passed in as the first argument to the [xConnect] or [xCreate]10229** method that is invoking sqlite3_vtab_config().  The C parameter is one10230** of the [virtual table configuration options].  The presence and meaning10231** of parameters after C depend on which [virtual table configuration option]10232** is used.10233*/10234SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);1023510236/*10237** CAPI3REF: Virtual Table Configuration Options10238** KEYWORDS: {virtual table configuration options}10239** KEYWORDS: {virtual table configuration option}10240**10241** These macros define the various options to the10242** [sqlite3_vtab_config()] interface that [virtual table] implementations10243** can use to customize and optimize their behavior.10244**10245** <dl>10246** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]10247** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt>10248** <dd>Calls of the form10249** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,10250** where X is an integer.  If X is zero, then the [virtual table] whose10251** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not10252** support constraints.  In this configuration (which is the default) if10253** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire10254** statement is rolled back as if [ON CONFLICT | OR ABORT] had been10255** specified as part of the users SQL statement, regardless of the actual10256** ON CONFLICT mode specified.10257**10258** If X is non-zero, then the virtual table implementation guarantees10259** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before10260** any modifications to internal or persistent data structures have been made.10261** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite10262** is able to roll back a statement or database transaction, and abandon10263** or continue processing the current SQL statement as appropriate.10264** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns10265** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode10266** had been ABORT.10267**10268** Virtual table implementations that are required to handle OR REPLACE10269** must do so within the [xUpdate] method. If a call to the10270** [sqlite3_vtab_on_conflict()] function indicates that the current ON10271** CONFLICT policy is REPLACE, the virtual table implementation should10272** silently replace the appropriate rows within the xUpdate callback and10273** return SQLITE_OK. Or, if this is not possible, it may return10274** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT10275** constraint handling.10276** </dd>10277**10278** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt>10279** <dd>Calls of the form10280** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the10281** the [xConnect] or [xCreate] methods of a [virtual table] implementation10282** prohibits that virtual table from being used from within triggers and10283** views.10284** </dd>10285**10286** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>10287** <dd>Calls of the form10288** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the10289** the [xConnect] or [xCreate] methods of a [virtual table] implementation10290** identify that virtual table as being safe to use from within triggers10291** and views.  Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the10292** virtual table can do no serious harm even if it is controlled by a10293** malicious hacker.  Developers should avoid setting the SQLITE_VTAB_INNOCUOUS10294** flag unless absolutely necessary.10295** </dd>10296**10297** [[SQLITE_VTAB_USES_ALL_SCHEMAS]]<dt>SQLITE_VTAB_USES_ALL_SCHEMAS</dt>10298** <dd>Calls of the form10299** [sqlite3_vtab_config](db,SQLITE_VTAB_USES_ALL_SCHEMA) from within the10300** the [xConnect] or [xCreate] methods of a [virtual table] implementation10301** instruct the query planner to begin at least a read transaction on10302** all schemas ("main", "temp", and any ATTACH-ed databases) whenever the10303** virtual table is used.10304** </dd>10305** </dl>10306*/10307#define SQLITE_VTAB_CONSTRAINT_SUPPORT 110308#define SQLITE_VTAB_INNOCUOUS          210309#define SQLITE_VTAB_DIRECTONLY         310310#define SQLITE_VTAB_USES_ALL_SCHEMAS   41031110312/*10313** CAPI3REF: Determine The Virtual Table Conflict Policy10314**10315** This function may only be called from within a call to the [xUpdate] method10316** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The10317** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],10318** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode10319** of the SQL statement that triggered the call to the [xUpdate] method of the10320** [virtual table].10321*/10322SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);1032310324/*10325** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE10326**10327** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]10328** method of a [virtual table], then it might return true if the10329** column is being fetched as part of an UPDATE operation during which the10330** column value will not change.  The virtual table implementation can use10331** this hint as permission to substitute a return value that is less10332** expensive to compute and that the corresponding10333** [xUpdate] method understands as a "no-change" value.10334**10335** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that10336** the column is not changed by the UPDATE statement, then the xColumn10337** method can optionally return without setting a result, without calling10338** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].10339** In that case, [sqlite3_value_nochange(X)] will return true for the10340** same column in the [xUpdate] method.10341**10342** The sqlite3_vtab_nochange() routine is an optimization.  Virtual table10343** implementations should continue to give a correct answer even if the10344** sqlite3_vtab_nochange() interface were to always return false.  In the10345** current implementation, the sqlite3_vtab_nochange() interface does always10346** returns false for the enhanced [UPDATE FROM] statement.10347*/10348SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);1034910350/*10351** CAPI3REF: Determine The Collation For a Virtual Table Constraint10352** METHOD: sqlite3_index_info10353**10354** This function may only be called from within a call to the [xBestIndex]10355** method of a [virtual table].  This function returns a pointer to a string10356** that is the name of the appropriate collation sequence to use for text10357** comparisons on the constraint identified by its arguments.10358**10359** The first argument must be the pointer to the [sqlite3_index_info] object10360** that is the first parameter to the xBestIndex() method. The second argument10361** must be an index into the aConstraint[] array belonging to the10362** sqlite3_index_info structure passed to xBestIndex.10363**10364** Important:10365** The first parameter must be the same pointer that is passed into the10366** xBestMethod() method.  The first parameter may not be a pointer to a10367** different [sqlite3_index_info] object, even an exact copy.10368**10369** The return value is computed as follows:10370**10371** <ol>10372** <li><p> If the constraint comes from a WHERE clause expression that contains10373**         a [COLLATE operator], then the name of the collation specified by10374**         that COLLATE operator is returned.10375** <li><p> If there is no COLLATE operator, but the column that is the subject10376**         of the constraint specifies an alternative collating sequence via10377**         a [COLLATE clause] on the column definition within the CREATE TABLE10378**         statement that was passed into [sqlite3_declare_vtab()], then the10379**         name of that alternative collating sequence is returned.10380** <li><p> Otherwise, "BINARY" is returned.10381** </ol>10382*/10383SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int);1038410385/*10386** CAPI3REF: Determine if a virtual table query is DISTINCT10387** METHOD: sqlite3_index_info10388**10389** This API may only be used from within an [xBestIndex|xBestIndex method]10390** of a [virtual table] implementation. The result of calling this10391** interface from outside of xBestIndex() is undefined and probably harmful.10392**10393** ^The sqlite3_vtab_distinct() interface returns an integer between 0 and10394** 3.  The integer returned by sqlite3_vtab_distinct()10395** gives the virtual table additional information about how the query10396** planner wants the output to be ordered. As long as the virtual table10397** can meet the ordering requirements of the query planner, it may set10398** the "orderByConsumed" flag.10399**10400** <ol><li value="0"><p>10401** ^If the sqlite3_vtab_distinct() interface returns 0, that means10402** that the query planner needs the virtual table to return all rows in the10403** sort order defined by the "nOrderBy" and "aOrderBy" fields of the10404** [sqlite3_index_info] object.  This is the default expectation.  If the10405** virtual table outputs all rows in sorted order, then it is always safe for10406** the xBestIndex method to set the "orderByConsumed" flag, regardless of10407** the return value from sqlite3_vtab_distinct().10408** <li value="1"><p>10409** ^(If the sqlite3_vtab_distinct() interface returns 1, that means10410** that the query planner does not need the rows to be returned in sorted order10411** as long as all rows with the same values in all columns identified by the10412** "aOrderBy" field are adjacent.)^  This mode is used when the query planner10413** is doing a GROUP BY.10414** <li value="2"><p>10415** ^(If the sqlite3_vtab_distinct() interface returns 2, that means10416** that the query planner does not need the rows returned in any particular10417** order, as long as rows with the same values in all columns identified10418** by "aOrderBy" are adjacent.)^  ^(Furthermore, when two or more rows10419** contain the same values for all columns identified by "colUsed", all but10420** one such row may optionally be omitted from the result.)^10421** The virtual table is not required to omit rows that are duplicates10422** over the "colUsed" columns, but if the virtual table can do that without10423** too much extra effort, it could potentially help the query to run faster.10424** This mode is used for a DISTINCT query.10425** <li value="3"><p>10426** ^(If the sqlite3_vtab_distinct() interface returns 3, that means the10427** virtual table must return rows in the order defined by "aOrderBy" as10428** if the sqlite3_vtab_distinct() interface had returned 0.  However if10429** two or more rows in the result have the same values for all columns10430** identified by "colUsed", then all but one such row may optionally be10431** omitted.)^  Like when the return value is 2, the virtual table10432** is not required to omit rows that are duplicates over the "colUsed"10433** columns, but if the virtual table can do that without10434** too much extra effort, it could potentially help the query to run faster.10435** This mode is used for queries10436** that have both DISTINCT and ORDER BY clauses.10437** </ol>10438**10439** <p>The following table summarizes the conditions under which the10440** virtual table is allowed to set the "orderByConsumed" flag based on10441** the value returned by sqlite3_vtab_distinct().  This table is a10442** restatement of the previous four paragraphs:10443**10444** <table border=1 cellspacing=0 cellpadding=10 width="90%">10445** <tr>10446** <td valign="top">sqlite3_vtab_distinct() return value10447** <td valign="top">Rows are returned in aOrderBy order10448** <td valign="top">Rows with the same value in all aOrderBy columns are adjacent10449** <td valign="top">Duplicates over all colUsed columns may be omitted10450** <tr><td>0<td>yes<td>yes<td>no10451** <tr><td>1<td>no<td>yes<td>no10452** <tr><td>2<td>no<td>yes<td>yes10453** <tr><td>3<td>yes<td>yes<td>yes10454** </table>10455**10456** ^For the purposes of comparing virtual table output values to see if the10457** values are same value for sorting purposes, two NULL values are considered10458** to be the same.  In other words, the comparison operator is "IS"10459** (or "IS NOT DISTINCT FROM") and not "==".10460**10461** If a virtual table implementation is unable to meet the requirements10462** specified above, then it must not set the "orderByConsumed" flag in the10463** [sqlite3_index_info] object or an incorrect answer may result.10464**10465** ^A virtual table implementation is always free to return rows in any order10466** it wants, as long as the "orderByConsumed" flag is not set.  ^When the10467** the "orderByConsumed" flag is unset, the query planner will add extra10468** [bytecode] to ensure that the final results returned by the SQL query are10469** ordered correctly.  The use of the "orderByConsumed" flag and the10470** sqlite3_vtab_distinct() interface is merely an optimization.  ^Careful10471** use of the sqlite3_vtab_distinct() interface and the "orderByConsumed"10472** flag might help queries against a virtual table to run faster.  Being10473** overly aggressive and setting the "orderByConsumed" flag when it is not10474** valid to do so, on the other hand, might cause SQLite to return incorrect10475** results.10476*/10477SQLITE_API int sqlite3_vtab_distinct(sqlite3_index_info*);1047810479/*10480** CAPI3REF: Identify and handle IN constraints in xBestIndex10481**10482** This interface may only be used from within an10483** [xBestIndex|xBestIndex() method] of a [virtual table] implementation.10484** The result of invoking this interface from any other context is10485** undefined and probably harmful.10486**10487** ^(A constraint on a virtual table of the form10488** "[IN operator|column IN (...)]" is10489** communicated to the xBestIndex method as a10490** [SQLITE_INDEX_CONSTRAINT_EQ] constraint.)^  If xBestIndex wants to use10491** this constraint, it must set the corresponding10492** aConstraintUsage[].argvIndex to a positive integer.  ^(Then, under10493** the usual mode of handling IN operators, SQLite generates [bytecode]10494** that invokes the [xFilter|xFilter() method] once for each value10495** on the right-hand side of the IN operator.)^  Thus the virtual table10496** only sees a single value from the right-hand side of the IN operator10497** at a time.10498**10499** In some cases, however, it would be advantageous for the virtual10500** table to see all values on the right-hand of the IN operator all at10501** once.  The sqlite3_vtab_in() interfaces facilitates this in two ways:10502**10503** <ol>10504** <li><p>10505**   ^A call to sqlite3_vtab_in(P,N,-1) will return true (non-zero)10506**   if and only if the [sqlite3_index_info|P->aConstraint][N] constraint10507**   is an [IN operator] that can be processed all at once.  ^In other words,10508**   sqlite3_vtab_in() with -1 in the third argument is a mechanism10509**   by which the virtual table can ask SQLite if all-at-once processing10510**   of the IN operator is even possible.10511**10512** <li><p>10513**   ^A call to sqlite3_vtab_in(P,N,F) with F==1 or F==0 indicates10514**   to SQLite that the virtual table does or does not want to process10515**   the IN operator all-at-once, respectively.  ^Thus when the third10516**   parameter (F) is non-negative, this interface is the mechanism by10517**   which the virtual table tells SQLite how it wants to process the10518**   IN operator.10519** </ol>10520**10521** ^The sqlite3_vtab_in(P,N,F) interface can be invoked multiple times10522** within the same xBestIndex method call.  ^For any given P,N pair,10523** the return value from sqlite3_vtab_in(P,N,F) will always be the same10524** within the same xBestIndex call.  ^If the interface returns true10525** (non-zero), that means that the constraint is an IN operator10526** that can be processed all-at-once.  ^If the constraint is not an IN10527** operator or cannot be processed all-at-once, then the interface returns10528** false.10529**10530** ^(All-at-once processing of the IN operator is selected if both of the10531** following conditions are met:10532**10533** <ol>10534** <li><p> The P->aConstraintUsage[N].argvIndex value is set to a positive10535** integer.  This is how the virtual table tells SQLite that it wants to10536** use the N-th constraint.10537**10538** <li><p> The last call to sqlite3_vtab_in(P,N,F) for which F was10539** non-negative had F>=1.10540** </ol>)^10541**10542** ^If either or both of the conditions above are false, then SQLite uses10543** the traditional one-at-a-time processing strategy for the IN constraint.10544** ^If both conditions are true, then the argvIndex-th parameter to the10545** xFilter method will be an [sqlite3_value] that appears to be NULL,10546** but which can be passed to [sqlite3_vtab_in_first()] and10547** [sqlite3_vtab_in_next()] to find all values on the right-hand side10548** of the IN constraint.10549*/10550SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle);1055110552/*10553** CAPI3REF: Find all elements on the right-hand side of an IN constraint.10554**10555** These interfaces are only useful from within the10556** [xFilter|xFilter() method] of a [virtual table] implementation.10557** The result of invoking these interfaces from any other context10558** is undefined and probably harmful.10559**10560** The X parameter in a call to sqlite3_vtab_in_first(X,P) or10561** sqlite3_vtab_in_next(X,P) should be one of the parameters to the10562** xFilter method which invokes these routines, and specifically10563** a parameter that was previously selected for all-at-once IN constraint10564** processing use the [sqlite3_vtab_in()] interface in the10565** [xBestIndex|xBestIndex method].  ^(If the X parameter is not10566** an xFilter argument that was selected for all-at-once IN constraint10567** processing, then these routines return [SQLITE_ERROR].)^10568**10569** ^(Use these routines to access all values on the right-hand side10570** of the IN constraint using code like the following:10571**10572** <blockquote><pre>10573** &nbsp;  for(rc=sqlite3_vtab_in_first(pList, &pVal);10574** &nbsp;      rc==SQLITE_OK && pVal;10575** &nbsp;      rc=sqlite3_vtab_in_next(pList, &pVal)10576** &nbsp;  ){10577** &nbsp;    // do something with pVal10578** &nbsp;  }10579** &nbsp;  if( rc!=SQLITE_OK ){10580** &nbsp;    // an error has occurred10581** &nbsp;  }10582** </pre></blockquote>)^10583**10584** ^On success, the sqlite3_vtab_in_first(X,P) and sqlite3_vtab_in_next(X,P)10585** routines return SQLITE_OK and set *P to point to the first or next value10586** on the RHS of the IN constraint.  ^If there are no more values on the10587** right hand side of the IN constraint, then *P is set to NULL and these10588** routines return [SQLITE_DONE].  ^The return value might be10589** some other value, such as SQLITE_NOMEM, in the event of a malfunction.10590**10591** The *ppOut values returned by these routines are only valid until the10592** next call to either of these routines or until the end of the xFilter10593** method from which these routines were called.  If the virtual table10594** implementation needs to retain the *ppOut values for longer, it must make10595** copies.  The *ppOut values are [protected sqlite3_value|protected].10596*/10597SQLITE_API int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut);10598SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut);1059910600/*10601** CAPI3REF: Constraint values in xBestIndex()10602** METHOD: sqlite3_index_info10603**10604** This API may only be used from within the [xBestIndex|xBestIndex method]10605** of a [virtual table] implementation. The result of calling this interface10606** from outside of an xBestIndex method are undefined and probably harmful.10607**10608** ^When the sqlite3_vtab_rhs_value(P,J,V) interface is invoked from within10609** the [xBestIndex] method of a [virtual table] implementation, with P being10610** a copy of the [sqlite3_index_info] object pointer passed into xBestIndex and10611** J being a 0-based index into P->aConstraint[], then this routine10612** attempts to set *V to the value of the right-hand operand of10613** that constraint if the right-hand operand is known.  ^If the10614** right-hand operand is not known, then *V is set to a NULL pointer.10615** ^The sqlite3_vtab_rhs_value(P,J,V) interface returns SQLITE_OK if10616** and only if *V is set to a value.  ^The sqlite3_vtab_rhs_value(P,J,V)10617** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th10618** constraint is not available.  ^The sqlite3_vtab_rhs_value() interface10619** can return an result code other than SQLITE_OK or SQLITE_NOTFOUND if10620** something goes wrong.10621**10622** The sqlite3_vtab_rhs_value() interface is usually only successful if10623** the right-hand operand of a constraint is a literal value in the original10624** SQL statement.  If the right-hand operand is an expression or a reference10625** to some other column or a [host parameter], then sqlite3_vtab_rhs_value()10626** will probably return [SQLITE_NOTFOUND].10627**10628** ^(Some constraints, such as [SQLITE_INDEX_CONSTRAINT_ISNULL] and10629** [SQLITE_INDEX_CONSTRAINT_ISNOTNULL], have no right-hand operand.  For such10630** constraints, sqlite3_vtab_rhs_value() always returns SQLITE_NOTFOUND.)^10631**10632** ^The [sqlite3_value] object returned in *V is a protected sqlite3_value10633** and remains valid for the duration of the xBestIndex method call.10634** ^When xBestIndex returns, the sqlite3_value object returned by10635** sqlite3_vtab_rhs_value() is automatically deallocated.10636**10637** The "_rhs_" in the name of this routine is an abbreviation for10638** "Right-Hand Side".10639*/10640SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **ppVal);1064110642/*10643** CAPI3REF: Conflict resolution modes10644** KEYWORDS: {conflict resolution mode}10645**10646** These constants are returned by [sqlite3_vtab_on_conflict()] to10647** inform a [virtual table] implementation what the [ON CONFLICT] mode10648** is for the SQL statement being evaluated.10649**10650** Note that the [SQLITE_IGNORE] constant is also used as a potential10651** return value from the [sqlite3_set_authorizer()] callback and that10652** [SQLITE_ABORT] is also a [result code].10653*/10654#define SQLITE_ROLLBACK 110655/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */10656#define SQLITE_FAIL     310657/* #define SQLITE_ABORT 4  // Also an error code */10658#define SQLITE_REPLACE  51065910660/*10661** CAPI3REF: Prepared Statement Scan Status Opcodes10662** KEYWORDS: {scanstatus options}10663**10664** The following constants can be used for the T parameter to the10665** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a10666** different metric for sqlite3_stmt_scanstatus() to return.10667**10668** When the value returned to V is a string, space to hold that string is10669** managed by the prepared statement S and will be automatically freed when10670** S is finalized.10671**10672** Not all values are available for all query elements. When a value is10673** not available, the output variable is set to -1 if the value is numeric,10674** or to NULL if it is a string (SQLITE_SCANSTAT_NAME).10675**10676** <dl>10677** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>10678** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be10679** set to the total number of times that the X-th loop has run.</dd>10680**10681** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>10682** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be set10683** to the total number of rows examined by all iterations of the X-th loop.</dd>10684**10685** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>10686** <dd>^The "double" variable pointed to by the V parameter will be set to the10687** query planner's estimate for the average number of rows output from each10688** iteration of the X-th loop.  If the query planner's estimates was accurate,10689** then this value will approximate the quotient NVISIT/NLOOP and the10690** product of this value for all prior loops with the same SELECTID will10691** be the NLOOP value for the current loop.10692**10693** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>10694** <dd>^The "const char *" variable pointed to by the V parameter will be set10695** to a zero-terminated UTF-8 string containing the name of the index or table10696** used for the X-th loop.10697**10698** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>10699** <dd>^The "const char *" variable pointed to by the V parameter will be set10700** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]10701** description for the X-th loop.10702**10703** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECTID</dt>10704** <dd>^The "int" variable pointed to by the V parameter will be set to the10705** id for the X-th query plan element. The id value is unique within the10706** statement. The select-id is the same value as is output in the first10707** column of an [EXPLAIN QUERY PLAN] query.10708**10709** [[SQLITE_SCANSTAT_PARENTID]] <dt>SQLITE_SCANSTAT_PARENTID</dt>10710** <dd>The "int" variable pointed to by the V parameter will be set to the10711** the id of the parent of the current query element, if applicable, or10712** to zero if the query element has no parent. This is the same value as10713** returned in the second column of an [EXPLAIN QUERY PLAN] query.10714**10715** [[SQLITE_SCANSTAT_NCYCLE]] <dt>SQLITE_SCANSTAT_NCYCLE</dt>10716** <dd>The sqlite3_int64 output value is set to the number of cycles,10717** according to the processor time-stamp counter, that elapsed while the10718** query element was being processed. This value is not available for10719** all query elements - if it is unavailable the output variable is10720** set to -1.10721** </dl>10722*/10723#define SQLITE_SCANSTAT_NLOOP    010724#define SQLITE_SCANSTAT_NVISIT   110725#define SQLITE_SCANSTAT_EST      210726#define SQLITE_SCANSTAT_NAME     310727#define SQLITE_SCANSTAT_EXPLAIN  410728#define SQLITE_SCANSTAT_SELECTID 510729#define SQLITE_SCANSTAT_PARENTID 610730#define SQLITE_SCANSTAT_NCYCLE   71073110732/*10733** CAPI3REF: Prepared Statement Scan Status10734** METHOD: sqlite3_stmt10735**10736** These interfaces return information about the predicted and measured10737** performance for pStmt.  Advanced applications can use this10738** interface to compare the predicted and the measured performance and10739** issue warnings and/or rerun [ANALYZE] if discrepancies are found.10740**10741** Since this interface is expected to be rarely used, it is only10742** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]10743** compile-time option.10744**10745** The "iScanStatusOp" parameter determines which status information to return.10746** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior10747** of this interface is undefined. ^The requested measurement is written into10748** a variable pointed to by the "pOut" parameter.10749**10750** The "flags" parameter must be passed a mask of flags. At present only10751** one flag is defined - SQLITE_SCANSTAT_COMPLEX. If SQLITE_SCANSTAT_COMPLEX10752** is specified, then status information is available for all elements10753** of a query plan that are reported by "EXPLAIN QUERY PLAN" output. If10754** SQLITE_SCANSTAT_COMPLEX is not specified, then only query plan elements10755** that correspond to query loops (the "SCAN..." and "SEARCH..." elements of10756** the EXPLAIN QUERY PLAN output) are available. Invoking API10757** sqlite3_stmt_scanstatus() is equivalent to calling10758** sqlite3_stmt_scanstatus_v2() with a zeroed flags parameter.10759**10760** Parameter "idx" identifies the specific query element to retrieve statistics10761** for. Query elements are numbered starting from zero. A value of -1 may be10762** to query for statistics regarding the entire query. ^If idx is out of range10763** - less than -1 or greater than or equal to the total number of query10764** elements used to implement the statement - a non-zero value is returned and10765** the variable that pOut points to is unchanged.10766**10767** See also: [sqlite3_stmt_scanstatus_reset()]10768*/10769SQLITE_API int sqlite3_stmt_scanstatus(10770  sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */10771  int idx,                  /* Index of loop to report on */10772  int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */10773  void *pOut                /* Result written here */10774);10775SQLITE_API int sqlite3_stmt_scanstatus_v2(10776  sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */10777  int idx,                  /* Index of loop to report on */10778  int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */10779  int flags,                /* Mask of flags defined below */10780  void *pOut                /* Result written here */10781);1078210783/*10784** CAPI3REF: Prepared Statement Scan Status10785** KEYWORDS: {scan status flags}10786*/10787#define SQLITE_SCANSTAT_COMPLEX 0x00011078810789/*10790** CAPI3REF: Zero Scan-Status Counters10791** METHOD: sqlite3_stmt10792**10793** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.10794**10795** This API is only available if the library is built with pre-processor10796** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.10797*/10798SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);1079910800/*10801** CAPI3REF: Flush caches to disk mid-transaction10802** METHOD: sqlite310803**10804** ^If a write-transaction is open on [database connection] D when the10805** [sqlite3_db_cacheflush(D)] interface invoked, any dirty10806** pages in the pager-cache that are not currently in use are written out10807** to disk. A dirty page may be in use if a database cursor created by an10808** active SQL statement is reading from it, or if it is page 1 of a database10809** file (page 1 is always "in use").  ^The [sqlite3_db_cacheflush(D)]10810** interface flushes caches for all schemas - "main", "temp", and10811** any [attached] databases.10812**10813** ^If this function needs to obtain extra database locks before dirty pages10814** can be flushed to disk, it does so. ^If those locks cannot be obtained10815** immediately and there is a busy-handler callback configured, it is invoked10816** in the usual manner. ^If the required lock still cannot be obtained, then10817** the database is skipped and an attempt made to flush any dirty pages10818** belonging to the next (if any) database. ^If any databases are skipped10819** because locks cannot be obtained, but no other error occurs, this10820** function returns SQLITE_BUSY.10821**10822** ^If any other error occurs while flushing dirty pages to disk (for10823** example an IO error or out-of-memory condition), then processing is10824** abandoned and an SQLite [error code] is returned to the caller immediately.10825**10826** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.10827**10828** ^This function does not set the database handle error code or message10829** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.10830*/10831SQLITE_API int sqlite3_db_cacheflush(sqlite3*);1083210833/*10834** CAPI3REF: The pre-update hook.10835** METHOD: sqlite310836**10837** ^These interfaces are only available if SQLite is compiled using the10838** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.10839**10840** ^The [sqlite3_preupdate_hook()] interface registers a callback function10841** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation10842** on a database table.10843** ^At most one preupdate hook may be registered at a time on a single10844** [database connection]; each call to [sqlite3_preupdate_hook()] overrides10845** the previous setting.10846** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]10847** with a NULL pointer as the second parameter.10848** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as10849** the first parameter to callbacks.10850**10851** ^The preupdate hook only fires for changes to real database tables; the10852** preupdate hook is not invoked for changes to [virtual tables] or to10853** system tables like sqlite_sequence or sqlite_stat1.10854**10855** ^The second parameter to the preupdate callback is a pointer to10856** the [database connection] that registered the preupdate hook.10857** ^The third parameter to the preupdate callback is one of the constants10858** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the10859** kind of update operation that is about to occur.10860** ^(The fourth parameter to the preupdate callback is the name of the10861** database within the database connection that is being modified.  This10862** will be "main" for the main database or "temp" for TEMP tables or10863** the name given after the AS keyword in the [ATTACH] statement for attached10864** databases.)^10865** ^The fifth parameter to the preupdate callback is the name of the10866** table that is being modified.10867**10868** For an UPDATE or DELETE operation on a [rowid table], the sixth10869** parameter passed to the preupdate callback is the initial [rowid] of the10870** row being modified or deleted. For an INSERT operation on a rowid table,10871** or any operation on a WITHOUT ROWID table, the value of the sixth10872** parameter is undefined. For an INSERT or UPDATE on a rowid table the10873** seventh parameter is the final rowid value of the row being inserted10874** or updated. The value of the seventh parameter passed to the callback10875** function is not defined for operations on WITHOUT ROWID tables, or for10876** DELETE operations on rowid tables.10877**10878** ^The sqlite3_preupdate_hook(D,C,P) function returns the P argument from10879** the previous call on the same [database connection] D, or NULL for10880** the first call on D.10881**10882** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],10883** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces10884** provide additional information about a preupdate event. These routines10885** may only be called from within a preupdate callback.  Invoking any of10886** these routines from outside of a preupdate callback or with a10887** [database connection] pointer that is different from the one supplied10888** to the preupdate callback results in undefined and probably undesirable10889** behavior.10890**10891** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns10892** in the row that is being inserted, updated, or deleted.10893**10894** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to10895** a [protected sqlite3_value] that contains the value of the Nth column of10896** the table row before it is updated.  The N parameter must be between 010897** and one less than the number of columns or the behavior will be10898** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE10899** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the10900** behavior is undefined.  The [sqlite3_value] that P points to10901** will be destroyed when the preupdate callback returns.10902**10903** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to10904** a [protected sqlite3_value] that contains the value of the Nth column of10905** the table row after it is updated.  The N parameter must be between 010906** and one less than the number of columns or the behavior will be10907** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE10908** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the10909** behavior is undefined.  The [sqlite3_value] that P points to10910** will be destroyed when the preupdate callback returns.10911**10912** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate10913** callback was invoked as a result of a direct insert, update, or delete10914** operation; or 1 for inserts, updates, or deletes invoked by top-level10915** triggers; or 2 for changes resulting from triggers called by top-level10916** triggers; and so forth.10917**10918** When the [sqlite3_blob_write()] API is used to update a blob column,10919** the pre-update hook is invoked with SQLITE_DELETE. This is because the10920** in this case the new values are not available. In this case, when a10921** callback made with op==SQLITE_DELETE is actually a write using the10922** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns10923** the index of the column being written. In other cases, where the10924** pre-update hook is being invoked for some other reason, including a10925** regular DELETE, sqlite3_preupdate_blobwrite() returns -1.10926**10927** See also:  [sqlite3_update_hook()]10928*/10929#if defined(SQLITE_ENABLE_PREUPDATE_HOOK)10930SQLITE_API void *sqlite3_preupdate_hook(10931  sqlite3 *db,10932  void(*xPreUpdate)(10933    void *pCtx,                   /* Copy of third arg to preupdate_hook() */10934    sqlite3 *db,                  /* Database handle */10935    int op,                       /* SQLITE_UPDATE, DELETE or INSERT */10936    char const *zDb,              /* Database name */10937    char const *zName,            /* Table name */10938    sqlite3_int64 iKey1,          /* Rowid of row about to be deleted/updated */10939    sqlite3_int64 iKey2           /* New rowid value (for a rowid UPDATE) */10940  ),10941  void*10942);10943SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);10944SQLITE_API int sqlite3_preupdate_count(sqlite3 *);10945SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);10946SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);10947SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *);10948#endif1094910950/*10951** CAPI3REF: Low-level system error code10952** METHOD: sqlite310953**10954** ^Attempt to return the underlying operating system error code or error10955** number that caused the most recent I/O error or failure to open a file.10956** The return value is OS-dependent.  For example, on unix systems, after10957** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be10958** called to get back the underlying "errno" that caused the problem, such10959** as ENOSPC, EAUTH, EISDIR, and so forth.10960*/10961SQLITE_API int sqlite3_system_errno(sqlite3*);1096210963/*10964** CAPI3REF: Database Snapshot10965** KEYWORDS: {snapshot} {sqlite3_snapshot}10966**10967** An instance of the snapshot object records the state of a [WAL mode]10968** database for some specific point in history.10969**10970** In [WAL mode], multiple [database connections] that are open on the10971** same database file can each be reading a different historical version10972** of the database file.  When a [database connection] begins a read10973** transaction, that connection sees an unchanging copy of the database10974** as it existed for the point in time when the transaction first started.10975** Subsequent changes to the database from other connections are not seen10976** by the reader until a new read transaction is started.10977**10978** The sqlite3_snapshot object records state information about an historical10979** version of the database file so that it is possible to later open a new read10980** transaction that sees that historical version of the database rather than10981** the most recent version.10982*/10983typedef struct sqlite3_snapshot {10984  unsigned char hidden[48];10985} sqlite3_snapshot;1098610987/*10988** CAPI3REF: Record A Database Snapshot10989** CONSTRUCTOR: sqlite3_snapshot10990**10991** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a10992** new [sqlite3_snapshot] object that records the current state of10993** schema S in database connection D.  ^On success, the10994** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly10995** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.10996** If there is not already a read-transaction open on schema S when10997** this function is called, one is opened automatically.10998**10999** If a read-transaction is opened by this function, then it is guaranteed11000** that the returned snapshot object may not be invalidated by a database11001** writer or checkpointer until after the read-transaction is closed. This11002** is not guaranteed if a read-transaction is already open when this11003** function is called. In that case, any subsequent write or checkpoint11004** operation on the database may invalidate the returned snapshot handle,11005** even while the read-transaction remains open.11006**11007** The following must be true for this function to succeed. If any of11008** the following statements are false when sqlite3_snapshot_get() is11009** called, SQLITE_ERROR is returned. The final value of *P is undefined11010** in this case.11011**11012** <ul>11013**   <li> The database handle must not be in [autocommit mode].11014**11015**   <li> Schema S of [database connection] D must be a [WAL mode] database.11016**11017**   <li> There must not be a write transaction open on schema S of database11018**        connection D.11019**11020**   <li> One or more transactions must have been written to the current wal11021**        file since it was created on disk (by any connection). This means11022**        that a snapshot cannot be taken on a wal mode database with no wal11023**        file immediately after it is first opened. At least one transaction11024**        must be written to it first.11025** </ul>11026**11027** This function may also return SQLITE_NOMEM.  If it is called with the11028** database handle in autocommit mode but fails for some other reason,11029** whether or not a read transaction is opened on schema S is undefined.11030**11031** The [sqlite3_snapshot] object returned from a successful call to11032** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]11033** to avoid a memory leak.11034**11035** The [sqlite3_snapshot_get()] interface is only available when the11036** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.11037*/11038SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(11039  sqlite3 *db,11040  const char *zSchema,11041  sqlite3_snapshot **ppSnapshot11042);1104311044/*11045** CAPI3REF: Start a read transaction on an historical snapshot11046** METHOD: sqlite3_snapshot11047**11048** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read11049** transaction or upgrades an existing one for schema S of11050** [database connection] D such that the read transaction refers to11051** historical [snapshot] P, rather than the most recent change to the11052** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK11053** on success or an appropriate [error code] if it fails.11054**11055** ^In order to succeed, the database connection must not be in11056** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there11057** is already a read transaction open on schema S, then the database handle11058** must have no active statements (SELECT statements that have been passed11059** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).11060** SQLITE_ERROR is returned if either of these conditions is violated, or11061** if schema S does not exist, or if the snapshot object is invalid.11062**11063** ^A call to sqlite3_snapshot_open() will fail to open if the specified11064** snapshot has been overwritten by a [checkpoint]. In this case11065** SQLITE_ERROR_SNAPSHOT is returned.11066**11067** If there is already a read transaction open when this function is11068** invoked, then the same read transaction remains open (on the same11069** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT11070** is returned. If another error code - for example SQLITE_PROTOCOL or an11071** SQLITE_IOERR error code - is returned, then the final state of the11072** read transaction is undefined. If SQLITE_OK is returned, then the11073** read transaction is now open on database snapshot P.11074**11075** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the11076** database connection D does not know that the database file for11077** schema S is in [WAL mode].  A database connection might not know11078** that the database file is in [WAL mode] if there has been no prior11079** I/O on that database connection, or if the database entered [WAL mode]11080** after the most recent I/O on the database connection.)^11081** (Hint: Run "[PRAGMA application_id]" against a newly opened11082** database connection in order to make it ready to use snapshots.)11083**11084** The [sqlite3_snapshot_open()] interface is only available when the11085** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.11086*/11087SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(11088  sqlite3 *db,11089  const char *zSchema,11090  sqlite3_snapshot *pSnapshot11091);1109211093/*11094** CAPI3REF: Destroy a snapshot11095** DESTRUCTOR: sqlite3_snapshot11096**11097** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.11098** The application must eventually free every [sqlite3_snapshot] object11099** using this routine to avoid a memory leak.11100**11101** The [sqlite3_snapshot_free()] interface is only available when the11102** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.11103*/11104SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);1110511106/*11107** CAPI3REF: Compare the ages of two snapshot handles.11108** METHOD: sqlite3_snapshot11109**11110** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages11111** of two valid snapshot handles.11112**11113** If the two snapshot handles are not associated with the same database11114** file, the result of the comparison is undefined.11115**11116** Additionally, the result of the comparison is only valid if both of the11117** snapshot handles were obtained by calling sqlite3_snapshot_get() since the11118** last time the wal file was deleted. The wal file is deleted when the11119** database is changed back to rollback mode or when the number of database11120** clients drops to zero. If either snapshot handle was obtained before the11121** wal file was last deleted, the value returned by this function11122** is undefined.11123**11124** Otherwise, this API returns a negative value if P1 refers to an older11125** snapshot than P2, zero if the two handles refer to the same database11126** snapshot, and a positive value if P1 is a newer snapshot than P2.11127**11128** This interface is only available if SQLite is compiled with the11129** [SQLITE_ENABLE_SNAPSHOT] option.11130*/11131SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(11132  sqlite3_snapshot *p1,11133  sqlite3_snapshot *p211134);1113511136/*11137** CAPI3REF: Recover snapshots from a wal file11138** METHOD: sqlite3_snapshot11139**11140** If a [WAL file] remains on disk after all database connections close11141** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]11142** or because the last process to have the database opened exited without11143** calling [sqlite3_close()]) and a new connection is subsequently opened11144** on that database and [WAL file], the [sqlite3_snapshot_open()] interface11145** will only be able to open the last transaction added to the WAL file11146** even though the WAL file contains other valid transactions.11147**11148** This function attempts to scan the WAL file associated with database zDb11149** of database handle db and make all valid snapshots available to11150** sqlite3_snapshot_open(). It is an error if there is already a read11151** transaction open on the database, or if the database is not a WAL mode11152** database.11153**11154** SQLITE_OK is returned if successful, or an SQLite error code otherwise.11155**11156** This interface is only available if SQLite is compiled with the11157** [SQLITE_ENABLE_SNAPSHOT] option.11158*/11159SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);1116011161/*11162** CAPI3REF: Serialize a database11163**11164** The sqlite3_serialize(D,S,P,F) interface returns a pointer to11165** memory that is a serialization of the S database on11166** [database connection] D.  If S is a NULL pointer, the main database is used.11167** If P is not a NULL pointer, then the size of the database in bytes11168** is written into *P.11169**11170** For an ordinary on-disk database file, the serialization is just a11171** copy of the disk file.  For an in-memory database or a "TEMP" database,11172** the serialization is the same sequence of bytes which would be written11173** to disk if that database where backed up to disk.11174**11175** The usual case is that sqlite3_serialize() copies the serialization of11176** the database into memory obtained from [sqlite3_malloc64()] and returns11177** a pointer to that memory.  The caller is responsible for freeing the11178** returned value to avoid a memory leak.  However, if the F argument11179** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations11180** are made, and the sqlite3_serialize() function will return a pointer11181** to the contiguous memory representation of the database that SQLite11182** is currently using for that database, or NULL if the no such contiguous11183** memory representation of the database exists.  A contiguous memory11184** representation of the database will usually only exist if there has11185** been a prior call to [sqlite3_deserialize(D,S,...)] with the same11186** values of D and S.11187** The size of the database is written into *P even if the11188** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy11189** of the database exists.11190**11191** After the call, if the SQLITE_SERIALIZE_NOCOPY bit had been set,11192** the returned buffer content will remain accessible and unchanged11193** until either the next write operation on the connection or when11194** the connection is closed, and applications must not modify the11195** buffer. If the bit had been clear, the returned buffer will not11196** be accessed by SQLite after the call.11197**11198** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the11199** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory11200** allocation error occurs.11201**11202** This interface is omitted if SQLite is compiled with the11203** [SQLITE_OMIT_DESERIALIZE] option.11204*/11205SQLITE_API unsigned char *sqlite3_serialize(11206  sqlite3 *db,           /* The database connection */11207  const char *zSchema,   /* Which DB to serialize. ex: "main", "temp", ... */11208  sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */11209  unsigned int mFlags    /* Zero or more SQLITE_SERIALIZE_* flags */11210);1121111212/*11213** CAPI3REF: Flags for sqlite3_serialize11214**11215** Zero or more of the following constants can be OR-ed together for11216** the F argument to [sqlite3_serialize(D,S,P,F)].11217**11218** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return11219** a pointer to contiguous in-memory database that it is currently using,11220** without making a copy of the database.  If SQLite is not currently using11221** a contiguous in-memory database, then this option causes11222** [sqlite3_serialize()] to return a NULL pointer.  SQLite will only be11223** using a contiguous in-memory database if it has been initialized by a11224** prior call to [sqlite3_deserialize()].11225*/11226#define SQLITE_SERIALIZE_NOCOPY 0x001   /* Do no memory allocations */1122711228/*11229** CAPI3REF: Deserialize a database11230**11231** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the11232** [database connection] D to disconnect from database S and then11233** reopen S as an in-memory database based on the serialization contained11234** in P.  The serialized database P is N bytes in size.  M is the size of11235** the buffer P, which might be larger than N.  If M is larger than N, and11236** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is11237** permitted to add content to the in-memory database as long as the total11238** size does not exceed M bytes.11239**11240** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will11241** invoke sqlite3_free() on the serialization buffer when the database11242** connection closes.  If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then11243** SQLite will try to increase the buffer size using sqlite3_realloc64()11244** if writes on the database cause it to grow larger than M bytes.11245**11246** Applications must not modify the buffer P or invalidate it before11247** the database connection D is closed.11248**11249** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the11250** database is currently in a read transaction or is involved in a backup11251** operation.11252**11253** It is not possible to deserialized into the TEMP database.  If the11254** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the11255** function returns SQLITE_ERROR.11256**11257** The deserialized database should not be in [WAL mode].  If the database11258** is in WAL mode, then any attempt to use the database file will result11259** in an [SQLITE_CANTOPEN] error.  The application can set the11260** [file format version numbers] (bytes 18 and 19) of the input database P11261** to 0x01 prior to invoking sqlite3_deserialize(D,S,P,N,M,F) to force the11262** database file into rollback mode and work around this limitation.11263**11264** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the11265** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then11266** [sqlite3_free()] is invoked on argument P prior to returning.11267**11268** This interface is omitted if SQLite is compiled with the11269** [SQLITE_OMIT_DESERIALIZE] option.11270*/11271SQLITE_API int sqlite3_deserialize(11272  sqlite3 *db,            /* The database connection */11273  const char *zSchema,    /* Which DB to reopen with the deserialization */11274  unsigned char *pData,   /* The serialized database content */11275  sqlite3_int64 szDb,     /* Number bytes in the deserialization */11276  sqlite3_int64 szBuf,    /* Total size of buffer pData[] */11277  unsigned mFlags         /* Zero or more SQLITE_DESERIALIZE_* flags */11278);1127911280/*11281** CAPI3REF: Flags for sqlite3_deserialize()11282**11283** The following are allowed values for 6th argument (the F argument) to11284** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.11285**11286** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization11287** in the P argument is held in memory obtained from [sqlite3_malloc64()]11288** and that SQLite should take ownership of this memory and automatically11289** free it when it has finished using it.  Without this flag, the caller11290** is responsible for freeing any dynamically allocated memory.11291**11292** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to11293** grow the size of the database using calls to [sqlite3_realloc64()].  This11294** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.11295** Without this flag, the deserialized database cannot increase in size beyond11296** the number of bytes specified by the M parameter.11297**11298** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database11299** should be treated as read-only.11300*/11301#define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */11302#define SQLITE_DESERIALIZE_RESIZEABLE  2 /* Resize using sqlite3_realloc64() */11303#define SQLITE_DESERIALIZE_READONLY    4 /* Database is read-only */1130411305/*11306** Undo the hack that converts floating point types to integer for11307** builds on processors without floating point support.11308*/11309#ifdef SQLITE_OMIT_FLOATING_POINT11310# undef double11311#endif1131211313#if defined(__wasi__)11314# undef SQLITE_WASI11315# define SQLITE_WASI 111316# ifndef SQLITE_OMIT_LOAD_EXTENSION11317#  define SQLITE_OMIT_LOAD_EXTENSION11318# endif11319# ifndef SQLITE_THREADSAFE11320#  define SQLITE_THREADSAFE 011321# endif11322#endif1132311324#if 011325}  /* End of the 'extern "C"' block */11326#endif11327/* #endif for SQLITE3_H will be added by mksqlite3.tcl */1132811329/******** Begin file sqlite3rtree.h *********/11330/*11331** 2010 August 3011332**11333** The author disclaims copyright to this source code.  In place of11334** a legal notice, here is a blessing:11335**11336**    May you do good and not evil.11337**    May you find forgiveness for yourself and forgive others.11338**    May you share freely, never taking more than you give.11339**11340*************************************************************************11341*/1134211343#ifndef _SQLITE3RTREE_H_11344#define _SQLITE3RTREE_H_113451134611347#if 011348extern "C" {11349#endif1135011351typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;11352typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;1135311354/* The double-precision datatype used by RTree depends on the11355** SQLITE_RTREE_INT_ONLY compile-time option.11356*/11357#ifdef SQLITE_RTREE_INT_ONLY11358  typedef sqlite3_int64 sqlite3_rtree_dbl;11359#else11360  typedef double sqlite3_rtree_dbl;11361#endif1136211363/*11364** Register a geometry callback named zGeom that can be used as part of an11365** R-Tree geometry query as follows:11366**11367**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)11368*/11369SQLITE_API int sqlite3_rtree_geometry_callback(11370  sqlite3 *db,11371  const char *zGeom,11372  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),11373  void *pContext11374);113751137611377/*11378** A pointer to a structure of the following type is passed as the first11379** argument to callbacks registered using rtree_geometry_callback().11380*/11381struct sqlite3_rtree_geometry {11382  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */11383  int nParam;                     /* Size of array aParam[] */11384  sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */11385  void *pUser;                    /* Callback implementation user data */11386  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */11387};1138811389/*11390** Register a 2nd-generation geometry callback named zScore that can be11391** used as part of an R-Tree geometry query as follows:11392**11393**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)11394*/11395SQLITE_API int sqlite3_rtree_query_callback(11396  sqlite3 *db,11397  const char *zQueryFunc,11398  int (*xQueryFunc)(sqlite3_rtree_query_info*),11399  void *pContext,11400  void (*xDestructor)(void*)11401);114021140311404/*11405** A pointer to a structure of the following type is passed as the11406** argument to scored geometry callback registered using11407** sqlite3_rtree_query_callback().11408**11409** Note that the first 5 fields of this structure are identical to11410** sqlite3_rtree_geometry.  This structure is a subclass of11411** sqlite3_rtree_geometry.11412*/11413struct sqlite3_rtree_query_info {11414  void *pContext;                   /* pContext from when function registered */11415  int nParam;                       /* Number of function parameters */11416  sqlite3_rtree_dbl *aParam;        /* value of function parameters */11417  void *pUser;                      /* callback can use this, if desired */11418  void (*xDelUser)(void*);          /* function to free pUser */11419  sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */11420  unsigned int *anQueue;            /* Number of pending entries in the queue */11421  int nCoord;                       /* Number of coordinates */11422  int iLevel;                       /* Level of current node or entry */11423  int mxLevel;                      /* The largest iLevel value in the tree */11424  sqlite3_int64 iRowid;             /* Rowid for current entry */11425  sqlite3_rtree_dbl rParentScore;   /* Score of parent node */11426  int eParentWithin;                /* Visibility of parent node */11427  int eWithin;                      /* OUT: Visibility */11428  sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */11429  /* The following fields are only available in 3.8.11 and later */11430  sqlite3_value **apSqlParam;       /* Original SQL values of parameters */11431};1143211433/*11434** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.11435*/11436#define NOT_WITHIN       0   /* Object completely outside of query region */11437#define PARTLY_WITHIN    1   /* Object partially overlaps query region */11438#define FULLY_WITHIN     2   /* Object fully contained within query region */114391144011441#if 011442}  /* end of the 'extern "C"' block */11443#endif1144411445#endif  /* ifndef _SQLITE3RTREE_H_ */1144611447/******** End of sqlite3rtree.h *********/11448/******** Begin file sqlite3session.h *********/1144911450#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)11451#define __SQLITESESSION_H_ 11145211453/*11454** Make sure we can call this stuff from C++.11455*/11456#if 011457extern "C" {11458#endif114591146011461/*11462** CAPI3REF: Session Object Handle11463**11464** An instance of this object is a [session] that can be used to11465** record changes to a database.11466*/11467typedef struct sqlite3_session sqlite3_session;1146811469/*11470** CAPI3REF: Changeset Iterator Handle11471**11472** An instance of this object acts as a cursor for iterating11473** over the elements of a [changeset] or [patchset].11474*/11475typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;1147611477/*11478** CAPI3REF: Create A New Session Object11479** CONSTRUCTOR: sqlite3_session11480**11481** Create a new session object attached to database handle db. If successful,11482** a pointer to the new object is written to *ppSession and SQLITE_OK is11483** returned. If an error occurs, *ppSession is set to NULL and an SQLite11484** error code (e.g. SQLITE_NOMEM) is returned.11485**11486** It is possible to create multiple session objects attached to a single11487** database handle.11488**11489** Session objects created using this function should be deleted using the11490** [sqlite3session_delete()] function before the database handle that they11491** are attached to is itself closed. If the database handle is closed before11492** the session object is deleted, then the results of calling any session11493** module function, including [sqlite3session_delete()] on the session object11494** are undefined.11495**11496** Because the session module uses the [sqlite3_preupdate_hook()] API, it11497** is not possible for an application to register a pre-update hook on a11498** database handle that has one or more session objects attached. Nor is11499** it possible to create a session object attached to a database handle for11500** which a pre-update hook is already defined. The results of attempting11501** either of these things are undefined.11502**11503** The session object will be used to create changesets for tables in11504** database zDb, where zDb is either "main", or "temp", or the name of an11505** attached database. It is not an error if database zDb is not attached11506** to the database when the session object is created.11507*/11508SQLITE_API int sqlite3session_create(11509  sqlite3 *db,                    /* Database handle */11510  const char *zDb,                /* Name of db (e.g. "main") */11511  sqlite3_session **ppSession     /* OUT: New session object */11512);1151311514/*11515** CAPI3REF: Delete A Session Object11516** DESTRUCTOR: sqlite3_session11517**11518** Delete a session object previously allocated using11519** [sqlite3session_create()]. Once a session object has been deleted, the11520** results of attempting to use pSession with any other session module11521** function are undefined.11522**11523** Session objects must be deleted before the database handle to which they11524** are attached is closed. Refer to the documentation for11525** [sqlite3session_create()] for details.11526*/11527SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);1152811529/*11530** CAPI3REF: Configure a Session Object11531** METHOD: sqlite3_session11532**11533** This method is used to configure a session object after it has been11534** created. At present the only valid values for the second parameter are11535** [SQLITE_SESSION_OBJCONFIG_SIZE] and [SQLITE_SESSION_OBJCONFIG_ROWID].11536**11537*/11538SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg);1153911540/*11541** CAPI3REF: Options for sqlite3session_object_config11542**11543** The following values may passed as the the 2nd parameter to11544** sqlite3session_object_config().11545**11546** <dt>SQLITE_SESSION_OBJCONFIG_SIZE <dd>11547**   This option is used to set, clear or query the flag that enables11548**   the [sqlite3session_changeset_size()] API. Because it imposes some11549**   computational overhead, this API is disabled by default. Argument11550**   pArg must point to a value of type (int). If the value is initially11551**   0, then the sqlite3session_changeset_size() API is disabled. If it11552**   is greater than 0, then the same API is enabled. Or, if the initial11553**   value is less than zero, no change is made. In all cases the (int)11554**   variable is set to 1 if the sqlite3session_changeset_size() API is11555**   enabled following the current call, or 0 otherwise.11556**11557**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after11558**   the first table has been attached to the session object.11559**11560** <dt>SQLITE_SESSION_OBJCONFIG_ROWID <dd>11561**   This option is used to set, clear or query the flag that enables11562**   collection of data for tables with no explicit PRIMARY KEY.11563**11564**   Normally, tables with no explicit PRIMARY KEY are simply ignored11565**   by the sessions module. However, if this flag is set, it behaves11566**   as if such tables have a column "_rowid_ INTEGER PRIMARY KEY" inserted11567**   as their leftmost columns.11568**11569**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after11570**   the first table has been attached to the session object.11571*/11572#define SQLITE_SESSION_OBJCONFIG_SIZE  111573#define SQLITE_SESSION_OBJCONFIG_ROWID 21157411575/*11576** CAPI3REF: Enable Or Disable A Session Object11577** METHOD: sqlite3_session11578**11579** Enable or disable the recording of changes by a session object. When11580** enabled, a session object records changes made to the database. When11581** disabled - it does not. A newly created session object is enabled.11582** Refer to the documentation for [sqlite3session_changeset()] for further11583** details regarding how enabling and disabling a session object affects11584** the eventual changesets.11585**11586** Passing zero to this function disables the session. Passing a value11587** greater than zero enables it. Passing a value less than zero is a11588** no-op, and may be used to query the current state of the session.11589**11590** The return value indicates the final state of the session object: 0 if11591** the session is disabled, or 1 if it is enabled.11592*/11593SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);1159411595/*11596** CAPI3REF: Set Or Clear the Indirect Change Flag11597** METHOD: sqlite3_session11598**11599** Each change recorded by a session object is marked as either direct or11600** indirect. A change is marked as indirect if either:11601**11602** <ul>11603**   <li> The session object "indirect" flag is set when the change is11604**        made, or11605**   <li> The change is made by an SQL trigger or foreign key action11606**        instead of directly as a result of a users SQL statement.11607** </ul>11608**11609** If a single row is affected by more than one operation within a session,11610** then the change is considered indirect if all operations meet the criteria11611** for an indirect change above, or direct otherwise.11612**11613** This function is used to set, clear or query the session object indirect11614** flag.  If the second argument passed to this function is zero, then the11615** indirect flag is cleared. If it is greater than zero, the indirect flag11616** is set. Passing a value less than zero does not modify the current value11617** of the indirect flag, and may be used to query the current state of the11618** indirect flag for the specified session object.11619**11620** The return value indicates the final state of the indirect flag: 0 if11621** it is clear, or 1 if it is set.11622*/11623SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);1162411625/*11626** CAPI3REF: Attach A Table To A Session Object11627** METHOD: sqlite3_session11628**11629** If argument zTab is not NULL, then it is the name of a table to attach11630** to the session object passed as the first argument. All subsequent changes11631** made to the table while the session object is enabled will be recorded. See11632** documentation for [sqlite3session_changeset()] for further details.11633**11634** Or, if argument zTab is NULL, then changes are recorded for all tables11635** in the database. If additional tables are added to the database (by11636** executing "CREATE TABLE" statements) after this call is made, changes for11637** the new tables are also recorded.11638**11639** Changes can only be recorded for tables that have a PRIMARY KEY explicitly11640** defined as part of their CREATE TABLE statement. It does not matter if the11641** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY11642** KEY may consist of a single column, or may be a composite key.11643**11644** It is not an error if the named table does not exist in the database. Nor11645** is it an error if the named table does not have a PRIMARY KEY. However,11646** no changes will be recorded in either of these scenarios.11647**11648** Changes are not recorded for individual rows that have NULL values stored11649** in one or more of their PRIMARY KEY columns.11650**11651** SQLITE_OK is returned if the call completes without error. Or, if an error11652** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.11653**11654** <h3>Special sqlite_stat1 Handling</h3>11655**11656** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to11657** some of the rules above. In SQLite, the schema of sqlite_stat1 is:11658**  <pre>11659**  &nbsp;     CREATE TABLE sqlite_stat1(tbl,idx,stat)11660**  </pre>11661**11662** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are11663** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes11664** are recorded for rows for which (idx IS NULL) is true. However, for such11665** rows a zero-length blob (SQL value X'') is stored in the changeset or11666** patchset instead of a NULL value. This allows such changesets to be11667** manipulated by legacy implementations of sqlite3changeset_invert(),11668** concat() and similar.11669**11670** The sqlite3changeset_apply() function automatically converts the11671** zero-length blob back to a NULL value when updating the sqlite_stat111672** table. However, if the application calls sqlite3changeset_new(),11673** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset11674** iterator directly (including on a changeset iterator passed to a11675** conflict-handler callback) then the X'' value is returned. The application11676** must translate X'' to NULL itself if required.11677**11678** Legacy (older than 3.22.0) versions of the sessions module cannot capture11679** changes made to the sqlite_stat1 table. Legacy versions of the11680** sqlite3changeset_apply() function silently ignore any modifications to the11681** sqlite_stat1 table that are part of a changeset or patchset.11682*/11683SQLITE_API int sqlite3session_attach(11684  sqlite3_session *pSession,      /* Session object */11685  const char *zTab                /* Table name */11686);1168711688/*11689** CAPI3REF: Set a table filter on a Session Object.11690** METHOD: sqlite3_session11691**11692** The second argument (xFilter) is the "filter callback". For changes to rows11693** in tables that are not attached to the Session object, the filter is called11694** to determine whether changes to the table's rows should be tracked or not.11695** If xFilter returns 0, changes are not tracked. Note that once a table is11696** attached, xFilter will not be called again.11697*/11698SQLITE_API void sqlite3session_table_filter(11699  sqlite3_session *pSession,      /* Session object */11700  int(*xFilter)(11701    void *pCtx,                   /* Copy of third arg to _filter_table() */11702    const char *zTab              /* Table name */11703  ),11704  void *pCtx                      /* First argument passed to xFilter */11705);1170611707/*11708** CAPI3REF: Generate A Changeset From A Session Object11709** METHOD: sqlite3_session11710**11711** Obtain a changeset containing changes to the tables attached to the11712** session object passed as the first argument. If successful,11713** set *ppChangeset to point to a buffer containing the changeset11714** and *pnChangeset to the size of the changeset in bytes before returning11715** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to11716** zero and return an SQLite error code.11717**11718** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,11719** each representing a change to a single row of an attached table. An INSERT11720** change contains the values of each field of a new database row. A DELETE11721** contains the original values of each field of a deleted database row. An11722** UPDATE change contains the original values of each field of an updated11723** database row along with the updated values for each updated non-primary-key11724** column. It is not possible for an UPDATE change to represent a change that11725** modifies the values of primary key columns. If such a change is made, it11726** is represented in a changeset as a DELETE followed by an INSERT.11727**11728** Changes are not recorded for rows that have NULL values stored in one or11729** more of their PRIMARY KEY columns. If such a row is inserted or deleted,11730** no corresponding change is present in the changesets returned by this11731** function. If an existing row with one or more NULL values stored in11732** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,11733** only an INSERT is appears in the changeset. Similarly, if an existing row11734** with non-NULL PRIMARY KEY values is updated so that one or more of its11735** PRIMARY KEY columns are set to NULL, the resulting changeset contains a11736** DELETE change only.11737**11738** The contents of a changeset may be traversed using an iterator created11739** using the [sqlite3changeset_start()] API. A changeset may be applied to11740** a database with a compatible schema using the [sqlite3changeset_apply()]11741** API.11742**11743** Within a changeset generated by this function, all changes related to a11744** single table are grouped together. In other words, when iterating through11745** a changeset or when applying a changeset to a database, all changes related11746** to a single table are processed before moving on to the next table. Tables11747** are sorted in the same order in which they were attached (or auto-attached)11748** to the sqlite3_session object. The order in which the changes related to11749** a single table are stored is undefined.11750**11751** Following a successful call to this function, it is the responsibility of11752** the caller to eventually free the buffer that *ppChangeset points to using11753** [sqlite3_free()].11754**11755** <h3>Changeset Generation</h3>11756**11757** Once a table has been attached to a session object, the session object11758** records the primary key values of all new rows inserted into the table.11759** It also records the original primary key and other column values of any11760** deleted or updated rows. For each unique primary key value, data is only11761** recorded once - the first time a row with said primary key is inserted,11762** updated or deleted in the lifetime of the session.11763**11764** There is one exception to the previous paragraph: when a row is inserted,11765** updated or deleted, if one or more of its primary key columns contain a11766** NULL value, no record of the change is made.11767**11768** The session object therefore accumulates two types of records - those11769** that consist of primary key values only (created when the user inserts11770** a new record) and those that consist of the primary key values and the11771** original values of other table columns (created when the users deletes11772** or updates a record).11773**11774** When this function is called, the requested changeset is created using11775** both the accumulated records and the current contents of the database11776** file. Specifically:11777**11778** <ul>11779**   <li> For each record generated by an insert, the database is queried11780**        for a row with a matching primary key. If one is found, an INSERT11781**        change is added to the changeset. If no such row is found, no change11782**        is added to the changeset.11783**11784**   <li> For each record generated by an update or delete, the database is11785**        queried for a row with a matching primary key. If such a row is11786**        found and one or more of the non-primary key fields have been11787**        modified from their original values, an UPDATE change is added to11788**        the changeset. Or, if no such row is found in the table, a DELETE11789**        change is added to the changeset. If there is a row with a matching11790**        primary key in the database, but all fields contain their original11791**        values, no change is added to the changeset.11792** </ul>11793**11794** This means, amongst other things, that if a row is inserted and then later11795** deleted while a session object is active, neither the insert nor the delete11796** will be present in the changeset. Or if a row is deleted and then later a11797** row with the same primary key values inserted while a session object is11798** active, the resulting changeset will contain an UPDATE change instead of11799** a DELETE and an INSERT.11800**11801** When a session object is disabled (see the [sqlite3session_enable()] API),11802** it does not accumulate records when rows are inserted, updated or deleted.11803** This may appear to have some counter-intuitive effects if a single row11804** is written to more than once during a session. For example, if a row11805** is inserted while a session object is enabled, then later deleted while11806** the same session object is disabled, no INSERT record will appear in the11807** changeset, even though the delete took place while the session was disabled.11808** Or, if one field of a row is updated while a session is disabled, and11809** another field of the same row is updated while the session is enabled, the11810** resulting changeset will contain an UPDATE change that updates both fields.11811*/11812SQLITE_API int sqlite3session_changeset(11813  sqlite3_session *pSession,      /* Session object */11814  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */11815  void **ppChangeset              /* OUT: Buffer containing changeset */11816);1181711818/*11819** CAPI3REF: Return An Upper-limit For The Size Of The Changeset11820** METHOD: sqlite3_session11821**11822** By default, this function always returns 0. For it to return11823** a useful result, the sqlite3_session object must have been configured11824** to enable this API using sqlite3session_object_config() with the11825** SQLITE_SESSION_OBJCONFIG_SIZE verb.11826**11827** When enabled, this function returns an upper limit, in bytes, for the size11828** of the changeset that might be produced if sqlite3session_changeset() were11829** called. The final changeset size might be equal to or smaller than the11830** size in bytes returned by this function.11831*/11832SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession);1183311834/*11835** CAPI3REF: Load The Difference Between Tables Into A Session11836** METHOD: sqlite3_session11837**11838** If it is not already attached to the session object passed as the first11839** argument, this function attaches table zTbl in the same manner as the11840** [sqlite3session_attach()] function. If zTbl does not exist, or if it11841** does not have a primary key, this function is a no-op (but does not return11842** an error).11843**11844** Argument zFromDb must be the name of a database ("main", "temp" etc.)11845** attached to the same database handle as the session object that contains11846** a table compatible with the table attached to the session by this function.11847** A table is considered compatible if it:11848**11849** <ul>11850**   <li> Has the same name,11851**   <li> Has the same set of columns declared in the same order, and11852**   <li> Has the same PRIMARY KEY definition.11853** </ul>11854**11855** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables11856** are compatible but do not have any PRIMARY KEY columns, it is not an error11857** but no changes are added to the session object. As with other session11858** APIs, tables without PRIMARY KEYs are simply ignored.11859**11860** This function adds a set of changes to the session object that could be11861** used to update the table in database zFrom (call this the "from-table")11862** so that its content is the same as the table attached to the session11863** object (call this the "to-table"). Specifically:11864**11865** <ul>11866**   <li> For each row (primary key) that exists in the to-table but not in11867**     the from-table, an INSERT record is added to the session object.11868**11869**   <li> For each row (primary key) that exists in the to-table but not in11870**     the from-table, a DELETE record is added to the session object.11871**11872**   <li> For each row (primary key) that exists in both tables, but features11873**     different non-PK values in each, an UPDATE record is added to the11874**     session.11875** </ul>11876**11877** To clarify, if this function is called and then a changeset constructed11878** using [sqlite3session_changeset()], then after applying that changeset to11879** database zFrom the contents of the two compatible tables would be11880** identical.11881**11882** It an error if database zFrom does not exist or does not contain the11883** required compatible table.11884**11885** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite11886** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg11887** may be set to point to a buffer containing an English language error11888** message. It is the responsibility of the caller to free this buffer using11889** sqlite3_free().11890*/11891SQLITE_API int sqlite3session_diff(11892  sqlite3_session *pSession,11893  const char *zFromDb,11894  const char *zTbl,11895  char **pzErrMsg11896);118971189811899/*11900** CAPI3REF: Generate A Patchset From A Session Object11901** METHOD: sqlite3_session11902**11903** The differences between a patchset and a changeset are that:11904**11905** <ul>11906**   <li> DELETE records consist of the primary key fields only. The11907**        original values of other fields are omitted.11908**   <li> The original values of any modified fields are omitted from11909**        UPDATE records.11910** </ul>11911**11912** A patchset blob may be used with up to date versions of all11913** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),11914** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,11915** attempting to use a patchset blob with old versions of the11916** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.11917**11918** Because the non-primary key "old.*" fields are omitted, no11919** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset11920** is passed to the sqlite3changeset_apply() API. Other conflict types work11921** in the same way as for changesets.11922**11923** Changes within a patchset are ordered in the same way as for changesets11924** generated by the sqlite3session_changeset() function (i.e. all changes for11925** a single table are grouped together, tables appear in the order in which11926** they were attached to the session object).11927*/11928SQLITE_API int sqlite3session_patchset(11929  sqlite3_session *pSession,      /* Session object */11930  int *pnPatchset,                /* OUT: Size of buffer at *ppPatchset */11931  void **ppPatchset               /* OUT: Buffer containing patchset */11932);1193311934/*11935** CAPI3REF: Test if a changeset has recorded any changes.11936**11937** Return non-zero if no changes to attached tables have been recorded by11938** the session object passed as the first argument. Otherwise, if one or11939** more changes have been recorded, return zero.11940**11941** Even if this function returns zero, it is possible that calling11942** [sqlite3session_changeset()] on the session handle may still return a11943** changeset that contains no changes. This can happen when a row in11944** an attached table is modified and then later on the original values11945** are restored. However, if this function returns non-zero, then it is11946** guaranteed that a call to sqlite3session_changeset() will return a11947** changeset containing zero changes.11948*/11949SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);1195011951/*11952** CAPI3REF: Query for the amount of heap memory used by a session object.11953**11954** This API returns the total amount of heap memory in bytes currently11955** used by the session object passed as the only argument.11956*/11957SQLITE_API sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession);1195811959/*11960** CAPI3REF: Create An Iterator To Traverse A Changeset11961** CONSTRUCTOR: sqlite3_changeset_iter11962**11963** Create an iterator used to iterate through the contents of a changeset.11964** If successful, *pp is set to point to the iterator handle and SQLITE_OK11965** is returned. Otherwise, if an error occurs, *pp is set to zero and an11966** SQLite error code is returned.11967**11968** The following functions can be used to advance and query a changeset11969** iterator created by this function:11970**11971** <ul>11972**   <li> [sqlite3changeset_next()]11973**   <li> [sqlite3changeset_op()]11974**   <li> [sqlite3changeset_new()]11975**   <li> [sqlite3changeset_old()]11976** </ul>11977**11978** It is the responsibility of the caller to eventually destroy the iterator11979** by passing it to [sqlite3changeset_finalize()]. The buffer containing the11980** changeset (pChangeset) must remain valid until after the iterator is11981** destroyed.11982**11983** Assuming the changeset blob was created by one of the11984** [sqlite3session_changeset()], [sqlite3changeset_concat()] or11985** [sqlite3changeset_invert()] functions, all changes within the changeset11986** that apply to a single table are grouped together. This means that when11987** an application iterates through a changeset using an iterator created by11988** this function, all changes that relate to a single table are visited11989** consecutively. There is no chance that the iterator will visit a change11990** the applies to table X, then one for table Y, and then later on visit11991** another change for table X.11992**11993** The behavior of sqlite3changeset_start_v2() and its streaming equivalent11994** may be modified by passing a combination of11995** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.11996**11997** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>11998** and therefore subject to change.11999*/12000SQLITE_API int sqlite3changeset_start(12001  sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */12002  int nChangeset,                 /* Size of changeset blob in bytes */12003  void *pChangeset                /* Pointer to blob containing changeset */12004);12005SQLITE_API int sqlite3changeset_start_v2(12006  sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */12007  int nChangeset,                 /* Size of changeset blob in bytes */12008  void *pChangeset,               /* Pointer to blob containing changeset */12009  int flags                       /* SESSION_CHANGESETSTART_* flags */12010);1201112012/*12013** CAPI3REF: Flags for sqlite3changeset_start_v212014**12015** The following flags may passed via the 4th parameter to12016** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:12017**12018** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>12019**   Invert the changeset while iterating through it. This is equivalent to12020**   inverting a changeset using sqlite3changeset_invert() before applying it.12021**   It is an error to specify this flag with a patchset.12022*/12023#define SQLITE_CHANGESETSTART_INVERT        0x0002120241202512026/*12027** CAPI3REF: Advance A Changeset Iterator12028** METHOD: sqlite3_changeset_iter12029**12030** This function may only be used with iterators created by the function12031** [sqlite3changeset_start()]. If it is called on an iterator passed to12032** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE12033** is returned and the call has no effect.12034**12035** Immediately after an iterator is created by sqlite3changeset_start(), it12036** does not point to any change in the changeset. Assuming the changeset12037** is not empty, the first call to this function advances the iterator to12038** point to the first change in the changeset. Each subsequent call advances12039** the iterator to point to the next change in the changeset (if any). If12040** no error occurs and the iterator points to a valid change after a call12041** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.12042** Otherwise, if all changes in the changeset have already been visited,12043** SQLITE_DONE is returned.12044**12045** If an error occurs, an SQLite error code is returned. Possible error12046** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or12047** SQLITE_NOMEM.12048*/12049SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);1205012051/*12052** CAPI3REF: Obtain The Current Operation From A Changeset Iterator12053** METHOD: sqlite3_changeset_iter12054**12055** The pIter argument passed to this function may either be an iterator12056** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator12057** created by [sqlite3changeset_start()]. In the latter case, the most recent12058** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this12059** is not the case, this function returns [SQLITE_MISUSE].12060**12061** Arguments pOp, pnCol and pzTab may not be NULL. Upon return, three12062** outputs are set through these pointers:12063**12064** *pOp is set to one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],12065** depending on the type of change that the iterator currently points to;12066**12067** *pnCol is set to the number of columns in the table affected by the change; and12068**12069** *pzTab is set to point to a nul-terminated utf-8 encoded string containing12070** the name of the table affected by the current change. The buffer remains12071** valid until either sqlite3changeset_next() is called on the iterator12072** or until the conflict-handler function returns.12073**12074** If pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change12075** is an indirect change, or false (0) otherwise. See the documentation for12076** [sqlite3session_indirect()] for a description of direct and indirect12077** changes.12078**12079** If no error occurs, SQLITE_OK is returned. If an error does occur, an12080** SQLite error code is returned. The values of the output variables may not12081** be trusted in this case.12082*/12083SQLITE_API int sqlite3changeset_op(12084  sqlite3_changeset_iter *pIter,  /* Iterator object */12085  const char **pzTab,             /* OUT: Pointer to table name */12086  int *pnCol,                     /* OUT: Number of columns in table */12087  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */12088  int *pbIndirect                 /* OUT: True for an 'indirect' change */12089);1209012091/*12092** CAPI3REF: Obtain The Primary Key Definition Of A Table12093** METHOD: sqlite3_changeset_iter12094**12095** For each modified table, a changeset includes the following:12096**12097** <ul>12098**   <li> The number of columns in the table, and12099**   <li> Which of those columns make up the tables PRIMARY KEY.12100** </ul>12101**12102** This function is used to find which columns comprise the PRIMARY KEY of12103** the table modified by the change that iterator pIter currently points to.12104** If successful, *pabPK is set to point to an array of nCol entries, where12105** nCol is the number of columns in the table. Elements of *pabPK are set to12106** 0x01 if the corresponding column is part of the tables primary key, or12107** 0x00 if it is not.12108**12109** If argument pnCol is not NULL, then *pnCol is set to the number of columns12110** in the table.12111**12112** If this function is called when the iterator does not point to a valid12113** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,12114** SQLITE_OK is returned and the output variables populated as described12115** above.12116*/12117SQLITE_API int sqlite3changeset_pk(12118  sqlite3_changeset_iter *pIter,  /* Iterator object */12119  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */12120  int *pnCol                      /* OUT: Number of entries in output array */12121);1212212123/*12124** CAPI3REF: Obtain old.* Values From A Changeset Iterator12125** METHOD: sqlite3_changeset_iter12126**12127** The pIter argument passed to this function may either be an iterator12128** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator12129** created by [sqlite3changeset_start()]. In the latter case, the most recent12130** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.12131** Furthermore, it may only be called if the type of change that the iterator12132** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,12133** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.12134**12135** Argument iVal must be greater than or equal to 0, and less than the number12136** of columns in the table affected by the current change. Otherwise,12137** [SQLITE_RANGE] is returned and *ppValue is set to NULL.12138**12139** If successful, this function sets *ppValue to point to a protected12140** sqlite3_value object containing the iVal'th value from the vector of12141** original row values stored as part of the UPDATE or DELETE change and12142** returns SQLITE_OK. The name of the function comes from the fact that this12143** is similar to the "old.*" columns available to update or delete triggers.12144**12145** If some other error occurs (e.g. an OOM condition), an SQLite error code12146** is returned and *ppValue is set to NULL.12147*/12148SQLITE_API int sqlite3changeset_old(12149  sqlite3_changeset_iter *pIter,  /* Changeset iterator */12150  int iVal,                       /* Column number */12151  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */12152);1215312154/*12155** CAPI3REF: Obtain new.* Values From A Changeset Iterator12156** METHOD: sqlite3_changeset_iter12157**12158** The pIter argument passed to this function may either be an iterator12159** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator12160** created by [sqlite3changeset_start()]. In the latter case, the most recent12161** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.12162** Furthermore, it may only be called if the type of change that the iterator12163** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,12164** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.12165**12166** Argument iVal must be greater than or equal to 0, and less than the number12167** of columns in the table affected by the current change. Otherwise,12168** [SQLITE_RANGE] is returned and *ppValue is set to NULL.12169**12170** If successful, this function sets *ppValue to point to a protected12171** sqlite3_value object containing the iVal'th value from the vector of12172** new row values stored as part of the UPDATE or INSERT change and12173** returns SQLITE_OK. If the change is an UPDATE and does not include12174** a new value for the requested column, *ppValue is set to NULL and12175** SQLITE_OK returned. The name of the function comes from the fact that12176** this is similar to the "new.*" columns available to update or delete12177** triggers.12178**12179** If some other error occurs (e.g. an OOM condition), an SQLite error code12180** is returned and *ppValue is set to NULL.12181*/12182SQLITE_API int sqlite3changeset_new(12183  sqlite3_changeset_iter *pIter,  /* Changeset iterator */12184  int iVal,                       /* Column number */12185  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */12186);1218712188/*12189** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator12190** METHOD: sqlite3_changeset_iter12191**12192** This function should only be used with iterator objects passed to a12193** conflict-handler callback by [sqlite3changeset_apply()] with either12194** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function12195** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue12196** is set to NULL.12197**12198** Argument iVal must be greater than or equal to 0, and less than the number12199** of columns in the table affected by the current change. Otherwise,12200** [SQLITE_RANGE] is returned and *ppValue is set to NULL.12201**12202** If successful, this function sets *ppValue to point to a protected12203** sqlite3_value object containing the iVal'th value from the12204** "conflicting row" associated with the current conflict-handler callback12205** and returns SQLITE_OK.12206**12207** If some other error occurs (e.g. an OOM condition), an SQLite error code12208** is returned and *ppValue is set to NULL.12209*/12210SQLITE_API int sqlite3changeset_conflict(12211  sqlite3_changeset_iter *pIter,  /* Changeset iterator */12212  int iVal,                       /* Column number */12213  sqlite3_value **ppValue         /* OUT: Value from conflicting row */12214);1221512216/*12217** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations12218** METHOD: sqlite3_changeset_iter12219**12220** This function may only be called with an iterator passed to an12221** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case12222** it sets the output variable to the total number of known foreign key12223** violations in the destination database and returns SQLITE_OK.12224**12225** In all other cases this function returns SQLITE_MISUSE.12226*/12227SQLITE_API int sqlite3changeset_fk_conflicts(12228  sqlite3_changeset_iter *pIter,  /* Changeset iterator */12229  int *pnOut                      /* OUT: Number of FK violations */12230);122311223212233/*12234** CAPI3REF: Finalize A Changeset Iterator12235** METHOD: sqlite3_changeset_iter12236**12237** This function is used to finalize an iterator allocated with12238** [sqlite3changeset_start()].12239**12240** This function should only be called on iterators created using the12241** [sqlite3changeset_start()] function. If an application calls this12242** function with an iterator passed to a conflict-handler by12243** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the12244** call has no effect.12245**12246** If an error was encountered within a call to an sqlite3changeset_xxx()12247** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an12248** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding12249** to that error is returned by this function. Otherwise, SQLITE_OK is12250** returned. This is to allow the following pattern (pseudo-code):12251**12252** <pre>12253**   sqlite3changeset_start();12254**   while( SQLITE_ROW==sqlite3changeset_next() ){12255**     // Do something with change.12256**   }12257**   rc = sqlite3changeset_finalize();12258**   if( rc!=SQLITE_OK ){12259**     // An error has occurred12260**   }12261** </pre>12262*/12263SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);1226412265/*12266** CAPI3REF: Invert A Changeset12267**12268** This function is used to "invert" a changeset object. Applying an inverted12269** changeset to a database reverses the effects of applying the uninverted12270** changeset. Specifically:12271**12272** <ul>12273**   <li> Each DELETE change is changed to an INSERT, and12274**   <li> Each INSERT change is changed to a DELETE, and12275**   <li> For each UPDATE change, the old.* and new.* values are exchanged.12276** </ul>12277**12278** This function does not change the order in which changes appear within12279** the changeset. It merely reverses the sense of each individual change.12280**12281** If successful, a pointer to a buffer containing the inverted changeset12282** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and12283** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are12284** zeroed and an SQLite error code returned.12285**12286** It is the responsibility of the caller to eventually call sqlite3_free()12287** on the *ppOut pointer to free the buffer allocation following a successful12288** call to this function.12289**12290** WARNING/TODO: This function currently assumes that the input is a valid12291** changeset. If it is not, the results are undefined.12292*/12293SQLITE_API int sqlite3changeset_invert(12294  int nIn, const void *pIn,       /* Input changeset */12295  int *pnOut, void **ppOut        /* OUT: Inverse of input */12296);1229712298/*12299** CAPI3REF: Concatenate Two Changeset Objects12300**12301** This function is used to concatenate two changesets, A and B, into a12302** single changeset. The result is a changeset equivalent to applying12303** changeset A followed by changeset B.12304**12305** This function combines the two input changesets using an12306** sqlite3_changegroup object. Calling it produces similar results as the12307** following code fragment:12308**12309** <pre>12310**   sqlite3_changegroup *pGrp;12311**   rc = sqlite3_changegroup_new(&pGrp);12312**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);12313**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);12314**   if( rc==SQLITE_OK ){12315**     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);12316**   }else{12317**     *ppOut = 0;12318**     *pnOut = 0;12319**   }12320** </pre>12321**12322** Refer to the sqlite3_changegroup documentation below for details.12323*/12324SQLITE_API int sqlite3changeset_concat(12325  int nA,                         /* Number of bytes in buffer pA */12326  void *pA,                       /* Pointer to buffer containing changeset A */12327  int nB,                         /* Number of bytes in buffer pB */12328  void *pB,                       /* Pointer to buffer containing changeset B */12329  int *pnOut,                     /* OUT: Number of bytes in output changeset */12330  void **ppOut                    /* OUT: Buffer containing output changeset */12331);123321233312334/*12335** CAPI3REF: Upgrade the Schema of a Changeset/Patchset12336*/12337SQLITE_API int sqlite3changeset_upgrade(12338  sqlite3 *db,12339  const char *zDb,12340  int nIn, const void *pIn,       /* Input changeset */12341  int *pnOut, void **ppOut        /* OUT: Inverse of input */12342);12343123441234512346/*12347** CAPI3REF: Changegroup Handle12348**12349** A changegroup is an object used to combine two or more12350** [changesets] or [patchsets]12351*/12352typedef struct sqlite3_changegroup sqlite3_changegroup;1235312354/*12355** CAPI3REF: Create A New Changegroup Object12356** CONSTRUCTOR: sqlite3_changegroup12357**12358** An sqlite3_changegroup object is used to combine two or more changesets12359** (or patchsets) into a single changeset (or patchset). A single changegroup12360** object may combine changesets or patchsets, but not both. The output is12361** always in the same format as the input.12362**12363** If successful, this function returns SQLITE_OK and populates (*pp) with12364** a pointer to a new sqlite3_changegroup object before returning. The caller12365** should eventually free the returned object using a call to12366** sqlite3changegroup_delete(). If an error occurs, an SQLite error code12367** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.12368**12369** The usual usage pattern for an sqlite3_changegroup object is as follows:12370**12371** <ul>12372**   <li> It is created using a call to sqlite3changegroup_new().12373**12374**   <li> Zero or more changesets (or patchsets) are added to the object12375**        by calling sqlite3changegroup_add().12376**12377**   <li> The result of combining all input changesets together is obtained12378**        by the application via a call to sqlite3changegroup_output().12379**12380**   <li> The object is deleted using a call to sqlite3changegroup_delete().12381** </ul>12382**12383** Any number of calls to add() and output() may be made between the calls to12384** new() and delete(), and in any order.12385**12386** As well as the regular sqlite3changegroup_add() and12387** sqlite3changegroup_output() functions, also available are the streaming12388** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().12389*/12390SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);1239112392/*12393** CAPI3REF: Add a Schema to a Changegroup12394** METHOD: sqlite3_changegroup_schema12395**12396** This method may be used to optionally enforce the rule that the changesets12397** added to the changegroup handle must match the schema of database zDb12398** ("main", "temp", or the name of an attached database). If12399** sqlite3changegroup_add() is called to add a changeset that is not compatible12400** with the configured schema, SQLITE_SCHEMA is returned and the changegroup12401** object is left in an undefined state.12402**12403** A changeset schema is considered compatible with the database schema in12404** the same way as for sqlite3changeset_apply(). Specifically, for each12405** table in the changeset, there exists a database table with:12406**12407** <ul>12408**   <li> The name identified by the changeset, and12409**   <li> at least as many columns as recorded in the changeset, and12410**   <li> the primary key columns in the same position as recorded in12411**        the changeset.12412** </ul>12413**12414** The output of the changegroup object always has the same schema as the12415** database nominated using this function. In cases where changesets passed12416** to sqlite3changegroup_add() have fewer columns than the corresponding table12417** in the database schema, these are filled in using the default column12418** values from the database schema. This makes it possible to combined12419** changesets that have different numbers of columns for a single table12420** within a changegroup, provided that they are otherwise compatible.12421*/12422SQLITE_API int sqlite3changegroup_schema(sqlite3_changegroup*, sqlite3*, const char *zDb);1242312424/*12425** CAPI3REF: Add A Changeset To A Changegroup12426** METHOD: sqlite3_changegroup12427**12428** Add all changes within the changeset (or patchset) in buffer pData (size12429** nData bytes) to the changegroup.12430**12431** If the buffer contains a patchset, then all prior calls to this function12432** on the same changegroup object must also have specified patchsets. Or, if12433** the buffer contains a changeset, so must have the earlier calls to this12434** function. Otherwise, SQLITE_ERROR is returned and no changes are added12435** to the changegroup.12436**12437** Rows within the changeset and changegroup are identified by the values in12438** their PRIMARY KEY columns. A change in the changeset is considered to12439** apply to the same row as a change already present in the changegroup if12440** the two rows have the same primary key.12441**12442** Changes to rows that do not already appear in the changegroup are12443** simply copied into it. Or, if both the new changeset and the changegroup12444** contain changes that apply to a single row, the final contents of the12445** changegroup depends on the type of each change, as follows:12446**12447** <table border=1 style="margin-left:8ex;margin-right:8ex">12448**   <tr><th style="white-space:pre">Existing Change  </th>12449**       <th style="white-space:pre">New Change       </th>12450**       <th>Output Change12451**   <tr><td>INSERT <td>INSERT <td>12452**       The new change is ignored. This case does not occur if the new12453**       changeset was recorded immediately after the changesets already12454**       added to the changegroup.12455**   <tr><td>INSERT <td>UPDATE <td>12456**       The INSERT change remains in the changegroup. The values in the12457**       INSERT change are modified as if the row was inserted by the12458**       existing change and then updated according to the new change.12459**   <tr><td>INSERT <td>DELETE <td>12460**       The existing INSERT is removed from the changegroup. The DELETE is12461**       not added.12462**   <tr><td>UPDATE <td>INSERT <td>12463**       The new change is ignored. This case does not occur if the new12464**       changeset was recorded immediately after the changesets already12465**       added to the changegroup.12466**   <tr><td>UPDATE <td>UPDATE <td>12467**       The existing UPDATE remains within the changegroup. It is amended12468**       so that the accompanying values are as if the row was updated once12469**       by the existing change and then again by the new change.12470**   <tr><td>UPDATE <td>DELETE <td>12471**       The existing UPDATE is replaced by the new DELETE within the12472**       changegroup.12473**   <tr><td>DELETE <td>INSERT <td>12474**       If one or more of the column values in the row inserted by the12475**       new change differ from those in the row deleted by the existing12476**       change, the existing DELETE is replaced by an UPDATE within the12477**       changegroup. Otherwise, if the inserted row is exactly the same12478**       as the deleted row, the existing DELETE is simply discarded.12479**   <tr><td>DELETE <td>UPDATE <td>12480**       The new change is ignored. This case does not occur if the new12481**       changeset was recorded immediately after the changesets already12482**       added to the changegroup.12483**   <tr><td>DELETE <td>DELETE <td>12484**       The new change is ignored. This case does not occur if the new12485**       changeset was recorded immediately after the changesets already12486**       added to the changegroup.12487** </table>12488**12489** If the new changeset contains changes to a table that is already present12490** in the changegroup, then the number of columns and the position of the12491** primary key columns for the table must be consistent. If this is not the12492** case, this function fails with SQLITE_SCHEMA. Except, if the changegroup12493** object has been configured with a database schema using the12494** sqlite3changegroup_schema() API, then it is possible to combine changesets12495** with different numbers of columns for a single table, provided that12496** they are otherwise compatible.12497**12498** If the input changeset appears to be corrupt and the corruption is12499** detected, SQLITE_CORRUPT is returned. Or, if an out-of-memory condition12500** occurs during processing, this function returns SQLITE_NOMEM.12501**12502** In all cases, if an error occurs the state of the final contents of the12503** changegroup is undefined. If no error occurs, SQLITE_OK is returned.12504*/12505SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);1250612507/*12508** CAPI3REF: Add A Single Change To A Changegroup12509** METHOD: sqlite3_changegroup12510**12511** This function adds the single change currently indicated by the iterator12512** passed as the second argument to the changegroup object. The rules for12513** adding the change are just as described for [sqlite3changegroup_add()].12514**12515** If the change is successfully added to the changegroup, SQLITE_OK is12516** returned. Otherwise, an SQLite error code is returned.12517**12518** The iterator must point to a valid entry when this function is called.12519** If it does not, SQLITE_ERROR is returned and no change is added to the12520** changegroup. Additionally, the iterator must not have been opened with12521** the SQLITE_CHANGESETAPPLY_INVERT flag. In this case SQLITE_ERROR is also12522** returned.12523*/12524SQLITE_API int sqlite3changegroup_add_change(12525  sqlite3_changegroup*,12526  sqlite3_changeset_iter*12527);12528125291253012531/*12532** CAPI3REF: Obtain A Composite Changeset From A Changegroup12533** METHOD: sqlite3_changegroup12534**12535** Obtain a buffer containing a changeset (or patchset) representing the12536** current contents of the changegroup. If the inputs to the changegroup12537** were themselves changesets, the output is a changeset. Or, if the12538** inputs were patchsets, the output is also a patchset.12539**12540** As with the output of the sqlite3session_changeset() and12541** sqlite3session_patchset() functions, all changes related to a single12542** table are grouped together in the output of this function. Tables appear12543** in the same order as for the very first changeset added to the changegroup.12544** If the second or subsequent changesets added to the changegroup contain12545** changes for tables that do not appear in the first changeset, they are12546** appended onto the end of the output changeset, again in the order in12547** which they are first encountered.12548**12549** If an error occurs, an SQLite error code is returned and the output12550** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK12551** is returned and the output variables are set to the size of and a12552** pointer to the output buffer, respectively. In this case it is the12553** responsibility of the caller to eventually free the buffer using a12554** call to sqlite3_free().12555*/12556SQLITE_API int sqlite3changegroup_output(12557  sqlite3_changegroup*,12558  int *pnData,                    /* OUT: Size of output buffer in bytes */12559  void **ppData                   /* OUT: Pointer to output buffer */12560);1256112562/*12563** CAPI3REF: Delete A Changegroup Object12564** DESTRUCTOR: sqlite3_changegroup12565*/12566SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);1256712568/*12569** CAPI3REF: Apply A Changeset To A Database12570**12571** Apply a changeset or patchset to a database. These functions attempt to12572** update the "main" database attached to handle db with the changes found in12573** the changeset passed via the second and third arguments.12574**12575** The fourth argument (xFilter) passed to these functions is the "filter12576** callback". If it is not NULL, then for each table affected by at least one12577** change in the changeset, the filter callback is invoked with12578** the table name as the second argument, and a copy of the context pointer12579** passed as the sixth argument as the first. If the "filter callback"12580** returns zero, then no attempt is made to apply any changes to the table.12581** Otherwise, if the return value is non-zero or the xFilter argument to12582** is NULL, all changes related to the table are attempted.12583**12584** For each table that is not excluded by the filter callback, this function12585** tests that the target database contains a compatible table. A table is12586** considered compatible if all of the following are true:12587**12588** <ul>12589**   <li> The table has the same name as the name recorded in the12590**        changeset, and12591**   <li> The table has at least as many columns as recorded in the12592**        changeset, and12593**   <li> The table has primary key columns in the same position as12594**        recorded in the changeset.12595** </ul>12596**12597** If there is no compatible table, it is not an error, but none of the12598** changes associated with the table are applied. A warning message is issued12599** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most12600** one such warning is issued for each table in the changeset.12601**12602** For each change for which there is a compatible table, an attempt is made12603** to modify the table contents according to the UPDATE, INSERT or DELETE12604** change. If a change cannot be applied cleanly, the conflict handler12605** function passed as the fifth argument to sqlite3changeset_apply() may be12606** invoked. A description of exactly when the conflict handler is invoked for12607** each type of change is below.12608**12609** Unlike the xFilter argument, xConflict may not be passed NULL. The results12610** of passing anything other than a valid function pointer as the xConflict12611** argument are undefined.12612**12613** Each time the conflict handler function is invoked, it must return one12614** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or12615** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned12616** if the second argument passed to the conflict handler is either12617** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler12618** returns an illegal value, any changes already made are rolled back and12619** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different12620** actions are taken by sqlite3changeset_apply() depending on the value12621** returned by each invocation of the conflict-handler function. Refer to12622** the documentation for the three12623** [SQLITE_CHANGESET_OMIT|available return values] for details.12624**12625** <dl>12626** <dt>DELETE Changes<dd>12627**   For each DELETE change, the function checks if the target database12628**   contains a row with the same primary key value (or values) as the12629**   original row values stored in the changeset. If it does, and the values12630**   stored in all non-primary key columns also match the values stored in12631**   the changeset the row is deleted from the target database.12632**12633**   If a row with matching primary key values is found, but one or more of12634**   the non-primary key fields contains a value different from the original12635**   row value stored in the changeset, the conflict-handler function is12636**   invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the12637**   database table has more columns than are recorded in the changeset,12638**   only the values of those non-primary key fields are compared against12639**   the current database contents - any trailing database table columns12640**   are ignored.12641**12642**   If no row with matching primary key values is found in the database,12643**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]12644**   passed as the second argument.12645**12646**   If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT12647**   (which can only happen if a foreign key constraint is violated), the12648**   conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]12649**   passed as the second argument. This includes the case where the DELETE12650**   operation is attempted because an earlier call to the conflict handler12651**   function returned [SQLITE_CHANGESET_REPLACE].12652**12653** <dt>INSERT Changes<dd>12654**   For each INSERT change, an attempt is made to insert the new row into12655**   the database. If the changeset row contains fewer fields than the12656**   database table, the trailing fields are populated with their default12657**   values.12658**12659**   If the attempt to insert the row fails because the database already12660**   contains a row with the same primary key values, the conflict handler12661**   function is invoked with the second argument set to12662**   [SQLITE_CHANGESET_CONFLICT].12663**12664**   If the attempt to insert the row fails because of some other constraint12665**   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is12666**   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].12667**   This includes the case where the INSERT operation is re-attempted because12668**   an earlier call to the conflict handler function returned12669**   [SQLITE_CHANGESET_REPLACE].12670**12671** <dt>UPDATE Changes<dd>12672**   For each UPDATE change, the function checks if the target database12673**   contains a row with the same primary key value (or values) as the12674**   original row values stored in the changeset. If it does, and the values12675**   stored in all modified non-primary key columns also match the values12676**   stored in the changeset the row is updated within the target database.12677**12678**   If a row with matching primary key values is found, but one or more of12679**   the modified non-primary key fields contains a value different from an12680**   original row value stored in the changeset, the conflict-handler function12681**   is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since12682**   UPDATE changes only contain values for non-primary key fields that are12683**   to be modified, only those fields need to match the original values to12684**   avoid the SQLITE_CHANGESET_DATA conflict-handler callback.12685**12686**   If no row with matching primary key values is found in the database,12687**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]12688**   passed as the second argument.12689**12690**   If the UPDATE operation is attempted, but SQLite returns12691**   SQLITE_CONSTRAINT, the conflict-handler function is invoked with12692**   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.12693**   This includes the case where the UPDATE operation is attempted after12694**   an earlier call to the conflict handler function returned12695**   [SQLITE_CHANGESET_REPLACE].12696** </dl>12697**12698** It is safe to execute SQL statements, including those that write to the12699** table that the callback related to, from within the xConflict callback.12700** This can be used to further customize the application's conflict12701** resolution strategy.12702**12703** All changes made by these functions are enclosed in a savepoint transaction.12704** If any other error (aside from a constraint failure when attempting to12705** write to the target database) occurs, then the savepoint transaction is12706** rolled back, restoring the target database to its original state, and an12707** SQLite error code returned.12708**12709** If the output parameters (ppRebase) and (pnRebase) are non-NULL and12710** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()12711** may set (*ppRebase) to point to a "rebase" that may be used with the12712** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)12713** is set to the size of the buffer in bytes. It is the responsibility of the12714** caller to eventually free any such buffer using sqlite3_free(). The buffer12715** is only allocated and populated if one or more conflicts were encountered12716** while applying the patchset. See comments surrounding the sqlite3_rebaser12717** APIs for further details.12718**12719** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent12720** may be modified by passing a combination of12721** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.12722**12723** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>12724** and therefore subject to change.12725*/12726SQLITE_API int sqlite3changeset_apply(12727  sqlite3 *db,                    /* Apply change to "main" db of this handle */12728  int nChangeset,                 /* Size of changeset in bytes */12729  void *pChangeset,               /* Changeset blob */12730  int(*xFilter)(12731    void *pCtx,                   /* Copy of sixth arg to _apply() */12732    const char *zTab              /* Table name */12733  ),12734  int(*xConflict)(12735    void *pCtx,                   /* Copy of sixth arg to _apply() */12736    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */12737    sqlite3_changeset_iter *p     /* Handle describing change and conflict */12738  ),12739  void *pCtx                      /* First argument passed to xConflict */12740);12741SQLITE_API int sqlite3changeset_apply_v2(12742  sqlite3 *db,                    /* Apply change to "main" db of this handle */12743  int nChangeset,                 /* Size of changeset in bytes */12744  void *pChangeset,               /* Changeset blob */12745  int(*xFilter)(12746    void *pCtx,                   /* Copy of sixth arg to _apply() */12747    const char *zTab              /* Table name */12748  ),12749  int(*xConflict)(12750    void *pCtx,                   /* Copy of sixth arg to _apply() */12751    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */12752    sqlite3_changeset_iter *p     /* Handle describing change and conflict */12753  ),12754  void *pCtx,                     /* First argument passed to xConflict */12755  void **ppRebase, int *pnRebase, /* OUT: Rebase data */12756  int flags                       /* SESSION_CHANGESETAPPLY_* flags */12757);1275812759/*12760** CAPI3REF: Flags for sqlite3changeset_apply_v212761**12762** The following flags may passed via the 9th parameter to12763** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:12764**12765** <dl>12766** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>12767**   Usually, the sessions module encloses all operations performed by12768**   a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The12769**   SAVEPOINT is committed if the changeset or patchset is successfully12770**   applied, or rolled back if an error occurs. Specifying this flag12771**   causes the sessions module to omit this savepoint. In this case, if the12772**   caller has an open transaction or savepoint when apply_v2() is called,12773**   it may revert the partially applied changeset by rolling it back.12774**12775** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>12776**   Invert the changeset before applying it. This is equivalent to inverting12777**   a changeset using sqlite3changeset_invert() before applying it. It is12778**   an error to specify this flag with a patchset.12779**12780** <dt>SQLITE_CHANGESETAPPLY_IGNORENOOP <dd>12781**   Do not invoke the conflict handler callback for any changes that12782**   would not actually modify the database even if they were applied.12783**   Specifically, this means that the conflict handler is not invoked12784**   for:12785**    <ul>12786**    <li>a delete change if the row being deleted cannot be found,12787**    <li>an update change if the modified fields are already set to12788**        their new values in the conflicting row, or12789**    <li>an insert change if all fields of the conflicting row match12790**        the row being inserted.12791**    </ul>12792**12793** <dt>SQLITE_CHANGESETAPPLY_FKNOACTION <dd>12794**   If this flag it set, then all foreign key constraints in the target12795**   database behave as if they were declared with "ON UPDATE NO ACTION ON12796**   DELETE NO ACTION", even if they are actually CASCADE, RESTRICT, SET NULL12797**   or SET DEFAULT.12798*/12799#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x000112800#define SQLITE_CHANGESETAPPLY_INVERT        0x000212801#define SQLITE_CHANGESETAPPLY_IGNORENOOP    0x000412802#define SQLITE_CHANGESETAPPLY_FKNOACTION    0x00081280312804/*12805** CAPI3REF: Constants Passed To The Conflict Handler12806**12807** Values that may be passed as the second argument to a conflict-handler.12808**12809** <dl>12810** <dt>SQLITE_CHANGESET_DATA<dd>12811**   The conflict handler is invoked with CHANGESET_DATA as the second argument12812**   when processing a DELETE or UPDATE change if a row with the required12813**   PRIMARY KEY fields is present in the database, but one or more other12814**   (non primary-key) fields modified by the update do not contain the12815**   expected "before" values.12816**12817**   The conflicting row, in this case, is the database row with the matching12818**   primary key.12819**12820** <dt>SQLITE_CHANGESET_NOTFOUND<dd>12821**   The conflict handler is invoked with CHANGESET_NOTFOUND as the second12822**   argument when processing a DELETE or UPDATE change if a row with the12823**   required PRIMARY KEY fields is not present in the database.12824**12825**   There is no conflicting row in this case. The results of invoking the12826**   sqlite3changeset_conflict() API are undefined.12827**12828** <dt>SQLITE_CHANGESET_CONFLICT<dd>12829**   CHANGESET_CONFLICT is passed as the second argument to the conflict12830**   handler while processing an INSERT change if the operation would result12831**   in duplicate primary key values.12832**12833**   The conflicting row in this case is the database row with the matching12834**   primary key.12835**12836** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>12837**   If foreign key handling is enabled, and applying a changeset leaves the12838**   database in a state containing foreign key violations, the conflict12839**   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument12840**   exactly once before the changeset is committed. If the conflict handler12841**   returns CHANGESET_OMIT, the changes, including those that caused the12842**   foreign key constraint violation, are committed. Or, if it returns12843**   CHANGESET_ABORT, the changeset is rolled back.12844**12845**   No current or conflicting row information is provided. The only function12846**   it is possible to call on the supplied sqlite3_changeset_iter handle12847**   is sqlite3changeset_fk_conflicts().12848**12849** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>12850**   If any other constraint violation occurs while applying a change (i.e.12851**   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is12852**   invoked with CHANGESET_CONSTRAINT as the second argument.12853**12854**   There is no conflicting row in this case. The results of invoking the12855**   sqlite3changeset_conflict() API are undefined.12856**12857** </dl>12858*/12859#define SQLITE_CHANGESET_DATA        112860#define SQLITE_CHANGESET_NOTFOUND    212861#define SQLITE_CHANGESET_CONFLICT    312862#define SQLITE_CHANGESET_CONSTRAINT  412863#define SQLITE_CHANGESET_FOREIGN_KEY 51286412865/*12866** CAPI3REF: Constants Returned By The Conflict Handler12867**12868** A conflict handler callback must return one of the following three values.12869**12870** <dl>12871** <dt>SQLITE_CHANGESET_OMIT<dd>12872**   If a conflict handler returns this value no special action is taken. The12873**   change that caused the conflict is not applied. The session module12874**   continues to the next change in the changeset.12875**12876** <dt>SQLITE_CHANGESET_REPLACE<dd>12877**   This value may only be returned if the second argument to the conflict12878**   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this12879**   is not the case, any changes applied so far are rolled back and the12880**   call to sqlite3changeset_apply() returns SQLITE_MISUSE.12881**12882**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict12883**   handler, then the conflicting row is either updated or deleted, depending12884**   on the type of change.12885**12886**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict12887**   handler, then the conflicting row is removed from the database and a12888**   second attempt to apply the change is made. If this second attempt fails,12889**   the original row is restored to the database before continuing.12890**12891** <dt>SQLITE_CHANGESET_ABORT<dd>12892**   If this value is returned, any changes applied so far are rolled back12893**   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.12894** </dl>12895*/12896#define SQLITE_CHANGESET_OMIT       012897#define SQLITE_CHANGESET_REPLACE    112898#define SQLITE_CHANGESET_ABORT      21289912900/*12901** CAPI3REF: Rebasing changesets12902** EXPERIMENTAL12903**12904** Suppose there is a site hosting a database in state S0. And that12905** modifications are made that move that database to state S1 and a12906** changeset recorded (the "local" changeset). Then, a changeset based12907** on S0 is received from another site (the "remote" changeset) and12908** applied to the database. The database is then in state12909** (S1+"remote"), where the exact state depends on any conflict12910** resolution decisions (OMIT or REPLACE) made while applying "remote".12911** Rebasing a changeset is to update it to take those conflict12912** resolution decisions into account, so that the same conflicts12913** do not have to be resolved elsewhere in the network.12914**12915** For example, if both the local and remote changesets contain an12916** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":12917**12918**   local:  INSERT INTO t1 VALUES(1, 'v1');12919**   remote: INSERT INTO t1 VALUES(1, 'v2');12920**12921** and the conflict resolution is REPLACE, then the INSERT change is12922** removed from the local changeset (it was overridden). Or, if the12923** conflict resolution was "OMIT", then the local changeset is modified12924** to instead contain:12925**12926**           UPDATE t1 SET b = 'v2' WHERE a=1;12927**12928** Changes within the local changeset are rebased as follows:12929**12930** <dl>12931** <dt>Local INSERT<dd>12932**   This may only conflict with a remote INSERT. If the conflict12933**   resolution was OMIT, then add an UPDATE change to the rebased12934**   changeset. Or, if the conflict resolution was REPLACE, add12935**   nothing to the rebased changeset.12936**12937** <dt>Local DELETE<dd>12938**   This may conflict with a remote UPDATE or DELETE. In both cases the12939**   only possible resolution is OMIT. If the remote operation was a12940**   DELETE, then add no change to the rebased changeset. If the remote12941**   operation was an UPDATE, then the old.* fields of change are updated12942**   to reflect the new.* values in the UPDATE.12943**12944** <dt>Local UPDATE<dd>12945**   This may conflict with a remote UPDATE or DELETE. If it conflicts12946**   with a DELETE, and the conflict resolution was OMIT, then the update12947**   is changed into an INSERT. Any undefined values in the new.* record12948**   from the update change are filled in using the old.* values from12949**   the conflicting DELETE. Or, if the conflict resolution was REPLACE,12950**   the UPDATE change is simply omitted from the rebased changeset.12951**12952**   If conflict is with a remote UPDATE and the resolution is OMIT, then12953**   the old.* values are rebased using the new.* values in the remote12954**   change. Or, if the resolution is REPLACE, then the change is copied12955**   into the rebased changeset with updates to columns also updated by12956**   the conflicting remote UPDATE removed. If this means no columns would12957**   be updated, the change is omitted.12958** </dl>12959**12960** A local change may be rebased against multiple remote changes12961** simultaneously. If a single key is modified by multiple remote12962** changesets, they are combined as follows before the local changeset12963** is rebased:12964**12965** <ul>12966**    <li> If there has been one or more REPLACE resolutions on a12967**         key, it is rebased according to a REPLACE.12968**12969**    <li> If there have been no REPLACE resolutions on a key, then12970**         the local changeset is rebased according to the most recent12971**         of the OMIT resolutions.12972** </ul>12973**12974** Note that conflict resolutions from multiple remote changesets are12975** combined on a per-field basis, not per-row. This means that in the12976** case of multiple remote UPDATE operations, some fields of a single12977** local change may be rebased for REPLACE while others are rebased for12978** OMIT.12979**12980** In order to rebase a local changeset, the remote changeset must first12981** be applied to the local database using sqlite3changeset_apply_v2() and12982** the buffer of rebase information captured. Then:12983**12984** <ol>12985**   <li> An sqlite3_rebaser object is created by calling12986**        sqlite3rebaser_create().12987**   <li> The new object is configured with the rebase buffer obtained from12988**        sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().12989**        If the local changeset is to be rebased against multiple remote12990**        changesets, then sqlite3rebaser_configure() should be called12991**        multiple times, in the same order that the multiple12992**        sqlite3changeset_apply_v2() calls were made.12993**   <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().12994**   <li> The sqlite3_rebaser object is deleted by calling12995**        sqlite3rebaser_delete().12996** </ol>12997*/12998typedef struct sqlite3_rebaser sqlite3_rebaser;1299913000/*13001** CAPI3REF: Create a changeset rebaser object.13002** EXPERIMENTAL13003**13004** Allocate a new changeset rebaser object. If successful, set (*ppNew) to13005** point to the new object and return SQLITE_OK. Otherwise, if an error13006** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)13007** to NULL.13008*/13009SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);1301013011/*13012** CAPI3REF: Configure a changeset rebaser object.13013** EXPERIMENTAL13014**13015** Configure the changeset rebaser object to rebase changesets according13016** to the conflict resolutions described by buffer pRebase (size nRebase13017** bytes), which must have been obtained from a previous call to13018** sqlite3changeset_apply_v2().13019*/13020SQLITE_API int sqlite3rebaser_configure(13021  sqlite3_rebaser*,13022  int nRebase, const void *pRebase13023);1302413025/*13026** CAPI3REF: Rebase a changeset13027** EXPERIMENTAL13028**13029** Argument pIn must point to a buffer containing a changeset nIn bytes13030** in size. This function allocates and populates a buffer with a copy13031** of the changeset rebased according to the configuration of the13032** rebaser object passed as the first argument. If successful, (*ppOut)13033** is set to point to the new buffer containing the rebased changeset and13034** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the13035** responsibility of the caller to eventually free the new buffer using13036** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)13037** are set to zero and an SQLite error code returned.13038*/13039SQLITE_API int sqlite3rebaser_rebase(13040  sqlite3_rebaser*,13041  int nIn, const void *pIn,13042  int *pnOut, void **ppOut13043);1304413045/*13046** CAPI3REF: Delete a changeset rebaser object.13047** EXPERIMENTAL13048**13049** Delete the changeset rebaser object and all associated resources. There13050** should be one call to this function for each successful invocation13051** of sqlite3rebaser_create().13052*/13053SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);1305413055/*13056** CAPI3REF: Streaming Versions of API functions.13057**13058** The six streaming API xxx_strm() functions serve similar purposes to the13059** corresponding non-streaming API functions:13060**13061** <table border=1 style="margin-left:8ex;margin-right:8ex">13062**   <tr><th>Streaming function<th>Non-streaming equivalent</th>13063**   <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]13064**   <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]13065**   <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]13066**   <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]13067**   <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]13068**   <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]13069**   <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]13070** </table>13071**13072** Non-streaming functions that accept changesets (or patchsets) as input13073** require that the entire changeset be stored in a single buffer in memory.13074** Similarly, those that return a changeset or patchset do so by returning13075** a pointer to a single large buffer allocated using sqlite3_malloc().13076** Normally this is convenient. However, if an application running in a13077** low-memory environment is required to handle very large changesets, the13078** large contiguous memory allocations required can become onerous.13079**13080** In order to avoid this problem, instead of a single large buffer, input13081** is passed to a streaming API functions by way of a callback function that13082** the sessions module invokes to incrementally request input data as it is13083** required. In all cases, a pair of API function parameters such as13084**13085**  <pre>13086**  &nbsp;     int nChangeset,13087**  &nbsp;     void *pChangeset,13088**  </pre>13089**13090** Is replaced by:13091**13092**  <pre>13093**  &nbsp;     int (*xInput)(void *pIn, void *pData, int *pnData),13094**  &nbsp;     void *pIn,13095**  </pre>13096**13097** Each time the xInput callback is invoked by the sessions module, the first13098** argument passed is a copy of the supplied pIn context pointer. The second13099** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no13100** error occurs the xInput method should copy up to (*pnData) bytes of data13101** into the buffer and set (*pnData) to the actual number of bytes copied13102** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)13103** should be set to zero to indicate this. Or, if an error occurs, an SQLite13104** error code should be returned. In all cases, if an xInput callback returns13105** an error, all processing is abandoned and the streaming API function13106** returns a copy of the error code to the caller.13107**13108** In the case of sqlite3changeset_start_strm(), the xInput callback may be13109** invoked by the sessions module at any point during the lifetime of the13110** iterator. If such an xInput callback returns an error, the iterator enters13111** an error state, whereby all subsequent calls to iterator functions13112** immediately fail with the same error code as returned by xInput.13113**13114** Similarly, streaming API functions that return changesets (or patchsets)13115** return them in chunks by way of a callback function instead of via a13116** pointer to a single large buffer. In this case, a pair of parameters such13117** as:13118**13119**  <pre>13120**  &nbsp;     int *pnChangeset,13121**  &nbsp;     void **ppChangeset,13122**  </pre>13123**13124** Is replaced by:13125**13126**  <pre>13127**  &nbsp;     int (*xOutput)(void *pOut, const void *pData, int nData),13128**  &nbsp;     void *pOut13129**  </pre>13130**13131** The xOutput callback is invoked zero or more times to return data to13132** the application. The first parameter passed to each call is a copy of the13133** pOut pointer supplied by the application. The second parameter, pData,13134** points to a buffer nData bytes in size containing the chunk of output13135** data being returned. If the xOutput callback successfully processes the13136** supplied data, it should return SQLITE_OK to indicate success. Otherwise,13137** it should return some other SQLite error code. In this case processing13138** is immediately abandoned and the streaming API function returns a copy13139** of the xOutput error code to the application.13140**13141** The sessions module never invokes an xOutput callback with the third13142** parameter set to a value less than or equal to zero. Other than this,13143** no guarantees are made as to the size of the chunks of data returned.13144*/13145SQLITE_API int sqlite3changeset_apply_strm(13146  sqlite3 *db,                    /* Apply change to "main" db of this handle */13147  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */13148  void *pIn,                                          /* First arg for xInput */13149  int(*xFilter)(13150    void *pCtx,                   /* Copy of sixth arg to _apply() */13151    const char *zTab              /* Table name */13152  ),13153  int(*xConflict)(13154    void *pCtx,                   /* Copy of sixth arg to _apply() */13155    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */13156    sqlite3_changeset_iter *p     /* Handle describing change and conflict */13157  ),13158  void *pCtx                      /* First argument passed to xConflict */13159);13160SQLITE_API int sqlite3changeset_apply_v2_strm(13161  sqlite3 *db,                    /* Apply change to "main" db of this handle */13162  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */13163  void *pIn,                                          /* First arg for xInput */13164  int(*xFilter)(13165    void *pCtx,                   /* Copy of sixth arg to _apply() */13166    const char *zTab              /* Table name */13167  ),13168  int(*xConflict)(13169    void *pCtx,                   /* Copy of sixth arg to _apply() */13170    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */13171    sqlite3_changeset_iter *p     /* Handle describing change and conflict */13172  ),13173  void *pCtx,                     /* First argument passed to xConflict */13174  void **ppRebase, int *pnRebase,13175  int flags13176);13177SQLITE_API int sqlite3changeset_concat_strm(13178  int (*xInputA)(void *pIn, void *pData, int *pnData),13179  void *pInA,13180  int (*xInputB)(void *pIn, void *pData, int *pnData),13181  void *pInB,13182  int (*xOutput)(void *pOut, const void *pData, int nData),13183  void *pOut13184);13185SQLITE_API int sqlite3changeset_invert_strm(13186  int (*xInput)(void *pIn, void *pData, int *pnData),13187  void *pIn,13188  int (*xOutput)(void *pOut, const void *pData, int nData),13189  void *pOut13190);13191SQLITE_API int sqlite3changeset_start_strm(13192  sqlite3_changeset_iter **pp,13193  int (*xInput)(void *pIn, void *pData, int *pnData),13194  void *pIn13195);13196SQLITE_API int sqlite3changeset_start_v2_strm(13197  sqlite3_changeset_iter **pp,13198  int (*xInput)(void *pIn, void *pData, int *pnData),13199  void *pIn,13200  int flags13201);13202SQLITE_API int sqlite3session_changeset_strm(13203  sqlite3_session *pSession,13204  int (*xOutput)(void *pOut, const void *pData, int nData),13205  void *pOut13206);13207SQLITE_API int sqlite3session_patchset_strm(13208  sqlite3_session *pSession,13209  int (*xOutput)(void *pOut, const void *pData, int nData),13210  void *pOut13211);13212SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,13213    int (*xInput)(void *pIn, void *pData, int *pnData),13214    void *pIn13215);13216SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,13217    int (*xOutput)(void *pOut, const void *pData, int nData),13218    void *pOut13219);13220SQLITE_API int sqlite3rebaser_rebase_strm(13221  sqlite3_rebaser *pRebaser,13222  int (*xInput)(void *pIn, void *pData, int *pnData),13223  void *pIn,13224  int (*xOutput)(void *pOut, const void *pData, int nData),13225  void *pOut13226);1322713228/*13229** CAPI3REF: Configure global parameters13230**13231** The sqlite3session_config() interface is used to make global configuration13232** changes to the sessions module in order to tune it to the specific needs13233** of the application.13234**13235** The sqlite3session_config() interface is not threadsafe. If it is invoked13236** while any other thread is inside any other sessions method then the13237** results are undefined. Furthermore, if it is invoked after any sessions13238** related objects have been created, the results are also undefined.13239**13240** The first argument to the sqlite3session_config() function must be one13241** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The13242** interpretation of the (void*) value passed as the second parameter and13243** the effect of calling this function depends on the value of the first13244** parameter.13245**13246** <dl>13247** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>13248**    By default, the sessions module streaming interfaces attempt to input13249**    and output data in approximately 1 KiB chunks. This operand may be used13250**    to set and query the value of this configuration setting. The pointer13251**    passed as the second argument must point to a value of type (int).13252**    If this value is greater than 0, it is used as the new streaming data13253**    chunk size for both input and output. Before returning, the (int) value13254**    pointed to by pArg is set to the final value of the streaming interface13255**    chunk size.13256** </dl>13257**13258** This function returns SQLITE_OK if successful, or an SQLite error code13259** otherwise.13260*/13261SQLITE_API int sqlite3session_config(int op, void *pArg);1326213263/*13264** CAPI3REF: Values for sqlite3session_config().13265*/13266#define SQLITE_SESSION_CONFIG_STRMSIZE 11326713268/*13269** Make sure we can call this stuff from C++.13270*/13271#if 013272}13273#endif1327413275#endif  /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */1327613277/******** End of sqlite3session.h *********/13278/******** Begin file fts5.h *********/13279/*13280** 2014 May 3113281**13282** The author disclaims copyright to this source code.  In place of13283** a legal notice, here is a blessing:13284**13285**    May you do good and not evil.13286**    May you find forgiveness for yourself and forgive others.13287**    May you share freely, never taking more than you give.13288**13289******************************************************************************13290**13291** Interfaces to extend FTS5. Using the interfaces defined in this file,13292** FTS5 may be extended with:13293**13294**     * custom tokenizers, and13295**     * custom auxiliary functions.13296*/132971329813299#ifndef _FTS5_H13300#define _FTS5_H133011330213303#if 013304extern "C" {13305#endif1330613307/*************************************************************************13308** CUSTOM AUXILIARY FUNCTIONS13309**13310** Virtual table implementations may overload SQL functions by implementing13311** the sqlite3_module.xFindFunction() method.13312*/1331313314typedef struct Fts5ExtensionApi Fts5ExtensionApi;13315typedef struct Fts5Context Fts5Context;13316typedef struct Fts5PhraseIter Fts5PhraseIter;1331713318typedef void (*fts5_extension_function)(13319  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */13320  Fts5Context *pFts,              /* First arg to pass to pApi functions */13321  sqlite3_context *pCtx,          /* Context for returning result/error */13322  int nVal,                       /* Number of values in apVal[] array */13323  sqlite3_value **apVal           /* Array of trailing arguments */13324);1332513326struct Fts5PhraseIter {13327  const unsigned char *a;13328  const unsigned char *b;13329};1333013331/*13332** EXTENSION API FUNCTIONS13333**13334** xUserData(pFts):13335**   Return a copy of the pUserData pointer passed to the xCreateFunction()13336**   API when the extension function was registered.13337**13338** xColumnTotalSize(pFts, iCol, pnToken):13339**   If parameter iCol is less than zero, set output variable *pnToken13340**   to the total number of tokens in the FTS5 table. Or, if iCol is13341**   non-negative but less than the number of columns in the table, return13342**   the total number of tokens in column iCol, considering all rows in13343**   the FTS5 table.13344**13345**   If parameter iCol is greater than or equal to the number of columns13346**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.13347**   an OOM condition or IO error), an appropriate SQLite error code is13348**   returned.13349**13350** xColumnCount(pFts):13351**   Return the number of columns in the table.13352**13353** xColumnSize(pFts, iCol, pnToken):13354**   If parameter iCol is less than zero, set output variable *pnToken13355**   to the total number of tokens in the current row. Or, if iCol is13356**   non-negative but less than the number of columns in the table, set13357**   *pnToken to the number of tokens in column iCol of the current row.13358**13359**   If parameter iCol is greater than or equal to the number of columns13360**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.13361**   an OOM condition or IO error), an appropriate SQLite error code is13362**   returned.13363**13364**   This function may be quite inefficient if used with an FTS5 table13365**   created with the "columnsize=0" option.13366**13367** xColumnText:13368**   If parameter iCol is less than zero, or greater than or equal to the13369**   number of columns in the table, SQLITE_RANGE is returned.13370**13371**   Otherwise, this function attempts to retrieve the text of column iCol of13372**   the current document. If successful, (*pz) is set to point to a buffer13373**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes13374**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,13375**   if an error occurs, an SQLite error code is returned and the final values13376**   of (*pz) and (*pn) are undefined.13377**13378** xPhraseCount:13379**   Returns the number of phrases in the current query expression.13380**13381** xPhraseSize:13382**   If parameter iCol is less than zero, or greater than or equal to the13383**   number of phrases in the current query, as returned by xPhraseCount,13384**   0 is returned. Otherwise, this function returns the number of tokens in13385**   phrase iPhrase of the query. Phrases are numbered starting from zero.13386**13387** xInstCount:13388**   Set *pnInst to the total number of occurrences of all phrases within13389**   the query within the current row. Return SQLITE_OK if successful, or13390**   an error code (i.e. SQLITE_NOMEM) if an error occurs.13391**13392**   This API can be quite slow if used with an FTS5 table created with the13393**   "detail=none" or "detail=column" option. If the FTS5 table is created13394**   with either "detail=none" or "detail=column" and "content=" option13395**   (i.e. if it is a contentless table), then this API always returns 0.13396**13397** xInst:13398**   Query for the details of phrase match iIdx within the current row.13399**   Phrase matches are numbered starting from zero, so the iIdx argument13400**   should be greater than or equal to zero and smaller than the value13401**   output by xInstCount(). If iIdx is less than zero or greater than13402**   or equal to the value returned by xInstCount(), SQLITE_RANGE is returned.13403**13404**   Otherwise, output parameter *piPhrase is set to the phrase number, *piCol13405**   to the column in which it occurs and *piOff the token offset of the13406**   first token of the phrase. SQLITE_OK is returned if successful, or an13407**   error code (i.e. SQLITE_NOMEM) if an error occurs.13408**13409**   This API can be quite slow if used with an FTS5 table created with the13410**   "detail=none" or "detail=column" option.13411**13412** xRowid:13413**   Returns the rowid of the current row.13414**13415** xTokenize:13416**   Tokenize text using the tokenizer belonging to the FTS5 table.13417**13418** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):13419**   This API function is used to query the FTS table for phrase iPhrase13420**   of the current query. Specifically, a query equivalent to:13421**13422**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid13423**13424**   with $p set to a phrase equivalent to the phrase iPhrase of the13425**   current query is executed. Any column filter that applies to13426**   phrase iPhrase of the current query is included in $p. For each13427**   row visited, the callback function passed as the fourth argument13428**   is invoked. The context and API objects passed to the callback13429**   function may be used to access the properties of each matched row.13430**   Invoking Api.xUserData() returns a copy of the pointer passed as13431**   the third argument to pUserData.13432**13433**   If parameter iPhrase is less than zero, or greater than or equal to13434**   the number of phrases in the query, as returned by xPhraseCount(),13435**   this function returns SQLITE_RANGE.13436**13437**   If the callback function returns any value other than SQLITE_OK, the13438**   query is abandoned and the xQueryPhrase function returns immediately.13439**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.13440**   Otherwise, the error code is propagated upwards.13441**13442**   If the query runs to completion without incident, SQLITE_OK is returned.13443**   Or, if some error occurs before the query completes or is aborted by13444**   the callback, an SQLite error code is returned.13445**13446**13447** xSetAuxdata(pFts5, pAux, xDelete)13448**13449**   Save the pointer passed as the second argument as the extension function's13450**   "auxiliary data". The pointer may then be retrieved by the current or any13451**   future invocation of the same fts5 extension function made as part of13452**   the same MATCH query using the xGetAuxdata() API.13453**13454**   Each extension function is allocated a single auxiliary data slot for13455**   each FTS query (MATCH expression). If the extension function is invoked13456**   more than once for a single FTS query, then all invocations share a13457**   single auxiliary data context.13458**13459**   If there is already an auxiliary data pointer when this function is13460**   invoked, then it is replaced by the new pointer. If an xDelete callback13461**   was specified along with the original pointer, it is invoked at this13462**   point.13463**13464**   The xDelete callback, if one is specified, is also invoked on the13465**   auxiliary data pointer after the FTS5 query has finished.13466**13467**   If an error (e.g. an OOM condition) occurs within this function,13468**   the auxiliary data is set to NULL and an error code returned. If the13469**   xDelete parameter was not NULL, it is invoked on the auxiliary data13470**   pointer before returning.13471**13472**13473** xGetAuxdata(pFts5, bClear)13474**13475**   Returns the current auxiliary data pointer for the fts5 extension13476**   function. See the xSetAuxdata() method for details.13477**13478**   If the bClear argument is non-zero, then the auxiliary data is cleared13479**   (set to NULL) before this function returns. In this case the xDelete,13480**   if any, is not invoked.13481**13482**13483** xRowCount(pFts5, pnRow)13484**13485**   This function is used to retrieve the total number of rows in the table.13486**   In other words, the same value that would be returned by:13487**13488**        SELECT count(*) FROM ftstable;13489**13490** xPhraseFirst()13491**   This function is used, along with type Fts5PhraseIter and the xPhraseNext13492**   method, to iterate through all instances of a single query phrase within13493**   the current row. This is the same information as is accessible via the13494**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient13495**   to use, this API may be faster under some circumstances. To iterate13496**   through instances of phrase iPhrase, use the following code:13497**13498**       Fts5PhraseIter iter;13499**       int iCol, iOff;13500**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);13501**           iCol>=0;13502**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)13503**       ){13504**         // An instance of phrase iPhrase at offset iOff of column iCol13505**       }13506**13507**   The Fts5PhraseIter structure is defined above. Applications should not13508**   modify this structure directly - it should only be used as shown above13509**   with the xPhraseFirst() and xPhraseNext() API methods (and by13510**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).13511**13512**   This API can be quite slow if used with an FTS5 table created with the13513**   "detail=none" or "detail=column" option. If the FTS5 table is created13514**   with either "detail=none" or "detail=column" and "content=" option13515**   (i.e. if it is a contentless table), then this API always iterates13516**   through an empty set (all calls to xPhraseFirst() set iCol to -1).13517**13518**   In all cases, matches are visited in (column ASC, offset ASC) order.13519**   i.e. all those in column 0, sorted by offset, followed by those in13520**   column 1, etc.13521**13522** xPhraseNext()13523**   See xPhraseFirst above.13524**13525** xPhraseFirstColumn()13526**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()13527**   and xPhraseNext() APIs described above. The difference is that instead13528**   of iterating through all instances of a phrase in the current row, these13529**   APIs are used to iterate through the set of columns in the current row13530**   that contain one or more instances of a specified phrase. For example:13531**13532**       Fts5PhraseIter iter;13533**       int iCol;13534**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);13535**           iCol>=0;13536**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)13537**       ){13538**         // Column iCol contains at least one instance of phrase iPhrase13539**       }13540**13541**   This API can be quite slow if used with an FTS5 table created with the13542**   "detail=none" option. If the FTS5 table is created with either13543**   "detail=none" "content=" option (i.e. if it is a contentless table),13544**   then this API always iterates through an empty set (all calls to13545**   xPhraseFirstColumn() set iCol to -1).13546**13547**   The information accessed using this API and its companion13548**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext13549**   (or xInst/xInstCount). The chief advantage of this API is that it is13550**   significantly more efficient than those alternatives when used with13551**   "detail=column" tables.13552**13553** xPhraseNextColumn()13554**   See xPhraseFirstColumn above.13555**13556** xQueryToken(pFts5, iPhrase, iToken, ppToken, pnToken)13557**   This is used to access token iToken of phrase iPhrase of the current13558**   query. Before returning, output parameter *ppToken is set to point13559**   to a buffer containing the requested token, and *pnToken to the13560**   size of this buffer in bytes.13561**13562**   If iPhrase or iToken are less than zero, or if iPhrase is greater than13563**   or equal to the number of phrases in the query as reported by13564**   xPhraseCount(), or if iToken is equal to or greater than the number of13565**   tokens in the phrase, SQLITE_RANGE is returned and *ppToken and *pnToken13566     are both zeroed.13567**13568**   The output text is not a copy of the query text that specified the13569**   token. It is the output of the tokenizer module. For tokendata=113570**   tables, this includes any embedded 0x00 and trailing data.13571**13572** xInstToken(pFts5, iIdx, iToken, ppToken, pnToken)13573**   This is used to access token iToken of phrase hit iIdx within the13574**   current row. If iIdx is less than zero or greater than or equal to the13575**   value returned by xInstCount(), SQLITE_RANGE is returned.  Otherwise,13576**   output variable (*ppToken) is set to point to a buffer containing the13577**   matching document token, and (*pnToken) to the size of that buffer in13578**   bytes.13579**13580**   The output text is not a copy of the document text that was tokenized.13581**   It is the output of the tokenizer module. For tokendata=1 tables, this13582**   includes any embedded 0x00 and trailing data.13583**13584**   This API may be slow in some cases if the token identified by parameters13585**   iIdx and iToken matched a prefix token in the query. In most cases, the13586**   first call to this API for each prefix token in the query is forced13587**   to scan the portion of the full-text index that matches the prefix13588**   token to collect the extra data required by this API. If the prefix13589**   token matches a large number of token instances in the document set,13590**   this may be a performance problem.13591**13592**   If the user knows in advance that a query may use this API for a13593**   prefix token, FTS5 may be configured to collect all required data as part13594**   of the initial querying of the full-text index, avoiding the second scan13595**   entirely. This also causes prefix queries that do not use this API to13596**   run more slowly and use more memory. FTS5 may be configured in this way13597**   either on a per-table basis using the [FTS5 insttoken | 'insttoken']13598**   option, or on a per-query basis using the13599**   [fts5_insttoken | fts5_insttoken()] user function.13600**13601**   This API can be quite slow if used with an FTS5 table created with the13602**   "detail=none" or "detail=column" option.13603**13604** xColumnLocale(pFts5, iIdx, pzLocale, pnLocale)13605**   If parameter iCol is less than zero, or greater than or equal to the13606**   number of columns in the table, SQLITE_RANGE is returned.13607**13608**   Otherwise, this function attempts to retrieve the locale associated13609**   with column iCol of the current row. Usually, there is no associated13610**   locale, and output parameters (*pzLocale) and (*pnLocale) are set13611**   to NULL and 0, respectively. However, if the fts5_locale() function13612**   was used to associate a locale with the value when it was inserted13613**   into the fts5 table, then (*pzLocale) is set to point to a nul-terminated13614**   buffer containing the name of the locale in utf-8 encoding. (*pnLocale)13615**   is set to the size in bytes of the buffer, not including the13616**   nul-terminator.13617**13618**   If successful, SQLITE_OK is returned. Or, if an error occurs, an13619**   SQLite error code is returned. The final value of the output parameters13620**   is undefined in this case.13621**13622** xTokenize_v2:13623**   Tokenize text using the tokenizer belonging to the FTS5 table. This13624**   API is the same as the xTokenize() API, except that it allows a tokenizer13625**   locale to be specified.13626*/13627struct Fts5ExtensionApi {13628  int iVersion;                   /* Currently always set to 4 */1362913630  void *(*xUserData)(Fts5Context*);1363113632  int (*xColumnCount)(Fts5Context*);13633  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);13634  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);1363513636  int (*xTokenize)(Fts5Context*,13637    const char *pText, int nText, /* Text to tokenize */13638    void *pCtx,                   /* Context passed to xToken() */13639    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */13640  );1364113642  int (*xPhraseCount)(Fts5Context*);13643  int (*xPhraseSize)(Fts5Context*, int iPhrase);1364413645  int (*xInstCount)(Fts5Context*, int *pnInst);13646  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);1364713648  sqlite3_int64 (*xRowid)(Fts5Context*);13649  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);13650  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);1365113652  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,13653    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)13654  );13655  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));13656  void *(*xGetAuxdata)(Fts5Context*, int bClear);1365713658  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);13659  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);1366013661  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);13662  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);1366313664  /* Below this point are iVersion>=3 only */13665  int (*xQueryToken)(Fts5Context*,13666      int iPhrase, int iToken,13667      const char **ppToken, int *pnToken13668  );13669  int (*xInstToken)(Fts5Context*, int iIdx, int iToken, const char**, int*);1367013671  /* Below this point are iVersion>=4 only */13672  int (*xColumnLocale)(Fts5Context*, int iCol, const char **pz, int *pn);13673  int (*xTokenize_v2)(Fts5Context*,13674    const char *pText, int nText,      /* Text to tokenize */13675    const char *pLocale, int nLocale,  /* Locale to pass to tokenizer */13676    void *pCtx,                        /* Context passed to xToken() */13677    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */13678  );13679};1368013681/*13682** CUSTOM AUXILIARY FUNCTIONS13683*************************************************************************/1368413685/*************************************************************************13686** CUSTOM TOKENIZERS13687**13688** Applications may also register custom tokenizer types. A tokenizer13689** is registered by providing fts5 with a populated instance of the13690** following structure. All structure methods must be defined, setting13691** any member of the fts5_tokenizer struct to NULL leads to undefined13692** behaviour. The structure methods are expected to function as follows:13693**13694** xCreate:13695**   This function is used to allocate and initialize a tokenizer instance.13696**   A tokenizer instance is required to actually tokenize text.13697**13698**   The first argument passed to this function is a copy of the (void*)13699**   pointer provided by the application when the fts5_tokenizer_v2 object13700**   was registered with FTS5 (the third argument to xCreateTokenizer()).13701**   The second and third arguments are an array of nul-terminated strings13702**   containing the tokenizer arguments, if any, specified following the13703**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used13704**   to create the FTS5 table.13705**13706**   The final argument is an output variable. If successful, (*ppOut)13707**   should be set to point to the new tokenizer handle and SQLITE_OK13708**   returned. If an error occurs, some value other than SQLITE_OK should13709**   be returned. In this case, fts5 assumes that the final value of *ppOut13710**   is undefined.13711**13712** xDelete:13713**   This function is invoked to delete a tokenizer handle previously13714**   allocated using xCreate(). Fts5 guarantees that this function will13715**   be invoked exactly once for each successful call to xCreate().13716**13717** xTokenize:13718**   This function is expected to tokenize the nText byte string indicated13719**   by argument pText. pText may or may not be nul-terminated. The first13720**   argument passed to this function is a pointer to an Fts5Tokenizer object13721**   returned by an earlier call to xCreate().13722**13723**   The third argument indicates the reason that FTS5 is requesting13724**   tokenization of the supplied text. This is always one of the following13725**   four values:13726**13727**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into13728**            or removed from the FTS table. The tokenizer is being invoked to13729**            determine the set of tokens to add to (or delete from) the13730**            FTS index.13731**13732**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed13733**            against the FTS index. The tokenizer is being called to tokenize13734**            a bareword or quoted string specified as part of the query.13735**13736**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as13737**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is13738**            followed by a "*" character, indicating that the last token13739**            returned by the tokenizer will be treated as a token prefix.13740**13741**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to13742**            satisfy an fts5_api.xTokenize() request made by an auxiliary13743**            function. Or an fts5_api.xColumnSize() request made by the same13744**            on a columnsize=0 database.13745**   </ul>13746**13747**   The sixth and seventh arguments passed to xTokenize() - pLocale and13748**   nLocale - are a pointer to a buffer containing the locale to use for13749**   tokenization (e.g. "en_US") and its size in bytes, respectively. The13750**   pLocale buffer is not nul-terminated. pLocale may be passed NULL (in13751**   which case nLocale is always 0) to indicate that the tokenizer should13752**   use its default locale.13753**13754**   For each token in the input string, the supplied callback xToken() must13755**   be invoked. The first argument to it should be a copy of the pointer13756**   passed as the second argument to xTokenize(). The third and fourth13757**   arguments are a pointer to a buffer containing the token text, and the13758**   size of the token in bytes. The 4th and 5th arguments are the byte offsets13759**   of the first byte of and first byte immediately following the text from13760**   which the token is derived within the input.13761**13762**   The second argument passed to the xToken() callback ("tflags") should13763**   normally be set to 0. The exception is if the tokenizer supports13764**   synonyms. In this case see the discussion below for details.13765**13766**   FTS5 assumes the xToken() callback is invoked for each token in the13767**   order that they occur within the input text.13768**13769**   If an xToken() callback returns any value other than SQLITE_OK, then13770**   the tokenization should be abandoned and the xTokenize() method should13771**   immediately return a copy of the xToken() return value. Or, if the13772**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,13773**   if an error occurs with the xTokenize() implementation itself, it13774**   may abandon the tokenization and return any error code other than13775**   SQLITE_OK or SQLITE_DONE.13776**13777**   If the tokenizer is registered using an fts5_tokenizer_v2 object,13778**   then the xTokenize() method has two additional arguments - pLocale13779**   and nLocale. These specify the locale that the tokenizer should use13780**   for the current request. If pLocale and nLocale are both 0, then the13781**   tokenizer should use its default locale. Otherwise, pLocale points to13782**   an nLocale byte buffer containing the name of the locale to use as utf-813783**   text. pLocale is not nul-terminated.13784**13785** FTS5_TOKENIZER13786**13787** There is also an fts5_tokenizer object. This is an older, deprecated,13788** version of fts5_tokenizer_v2. It is similar except that:13789**13790**  <ul>13791**    <li> There is no "iVersion" field, and13792**    <li> The xTokenize() method does not take a locale argument.13793**  </ul>13794**13795** Legacy fts5_tokenizer tokenizers must be registered using the13796** legacy xCreateTokenizer() function, instead of xCreateTokenizer_v2().13797**13798** Tokenizer implementations registered using either API may be retrieved13799** using both xFindTokenizer() and xFindTokenizer_v2().13800**13801** SYNONYM SUPPORT13802**13803**   Custom tokenizers may also support synonyms. Consider a case in which a13804**   user wishes to query for a phrase such as "first place". Using the13805**   built-in tokenizers, the FTS5 query 'first + place' will match instances13806**   of "first place" within the document set, but not alternative forms13807**   such as "1st place". In some applications, it would be better to match13808**   all instances of "first place" or "1st place" regardless of which form13809**   the user specified in the MATCH query text.13810**13811**   There are several ways to approach this in FTS5:13812**13813**   <ol><li> By mapping all synonyms to a single token. In this case, using13814**            the above example, this means that the tokenizer returns the13815**            same token for inputs "first" and "1st". Say that token is in13816**            fact "first", so that when the user inserts the document "I won13817**            1st place" entries are added to the index for tokens "i", "won",13818**            "first" and "place". If the user then queries for '1st + place',13819**            the tokenizer substitutes "first" for "1st" and the query works13820**            as expected.13821**13822**       <li> By querying the index for all synonyms of each query term13823**            separately. In this case, when tokenizing query text, the13824**            tokenizer may provide multiple synonyms for a single term13825**            within the document. FTS5 then queries the index for each13826**            synonym individually. For example, faced with the query:13827**13828**   <codeblock>13829**     ... MATCH 'first place'</codeblock>13830**13831**            the tokenizer offers both "1st" and "first" as synonyms for the13832**            first token in the MATCH query and FTS5 effectively runs a query13833**            similar to:13834**13835**   <codeblock>13836**     ... MATCH '(first OR 1st) place'</codeblock>13837**13838**            except that, for the purposes of auxiliary functions, the query13839**            still appears to contain just two phrases - "(first OR 1st)"13840**            being treated as a single phrase.13841**13842**       <li> By adding multiple synonyms for a single term to the FTS index.13843**            Using this method, when tokenizing document text, the tokenizer13844**            provides multiple synonyms for each token. So that when a13845**            document such as "I won first place" is tokenized, entries are13846**            added to the FTS index for "i", "won", "first", "1st" and13847**            "place".13848**13849**            This way, even if the tokenizer does not provide synonyms13850**            when tokenizing query text (it should not - to do so would be13851**            inefficient), it doesn't matter if the user queries for13852**            'first + place' or '1st + place', as there are entries in the13853**            FTS index corresponding to both forms of the first token.13854**   </ol>13855**13856**   Whether it is parsing document or query text, any call to xToken that13857**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit13858**   is considered to supply a synonym for the previous token. For example,13859**   when parsing the document "I won first place", a tokenizer that supports13860**   synonyms would call xToken() 5 times, as follows:13861**13862**   <codeblock>13863**       xToken(pCtx, 0, "i",                      1,  0,  1);13864**       xToken(pCtx, 0, "won",                    3,  2,  5);13865**       xToken(pCtx, 0, "first",                  5,  6, 11);13866**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);13867**       xToken(pCtx, 0, "place",                  5, 12, 17);13868**</codeblock>13869**13870**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time13871**   xToken() is called. Multiple synonyms may be specified for a single token13872**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.13873**   There is no limit to the number of synonyms that may be provided for a13874**   single token.13875**13876**   In many cases, method (1) above is the best approach. It does not add13877**   extra data to the FTS index or require FTS5 to query for multiple terms,13878**   so it is efficient in terms of disk space and query speed. However, it13879**   does not support prefix queries very well. If, as suggested above, the13880**   token "first" is substituted for "1st" by the tokenizer, then the query:13881**13882**   <codeblock>13883**     ... MATCH '1s*'</codeblock>13884**13885**   will not match documents that contain the token "1st" (as the tokenizer13886**   will probably not map "1s" to any prefix of "first").13887**13888**   For full prefix support, method (3) may be preferred. In this case,13889**   because the index contains entries for both "first" and "1st", prefix13890**   queries such as 'fi*' or '1s*' will match correctly. However, because13891**   extra entries are added to the FTS index, this method uses more space13892**   within the database.13893**13894**   Method (2) offers a midpoint between (1) and (3). Using this method,13895**   a query such as '1s*' will match documents that contain the literal13896**   token "1st", but not "first" (assuming the tokenizer is not able to13897**   provide synonyms for prefixes). However, a non-prefix query like '1st'13898**   will match against "1st" and "first". This method does not require13899**   extra disk space, as no extra entries are added to the FTS index.13900**   On the other hand, it may require more CPU cycles to run MATCH queries,13901**   as separate queries of the FTS index are required for each synonym.13902**13903**   When using methods (2) or (3), it is important that the tokenizer only13904**   provide synonyms when tokenizing document text (method (3)) or query13905**   text (method (2)), not both. Doing so will not cause any errors, but is13906**   inefficient.13907*/13908typedef struct Fts5Tokenizer Fts5Tokenizer;13909typedef struct fts5_tokenizer_v2 fts5_tokenizer_v2;13910struct fts5_tokenizer_v2 {13911  int iVersion;             /* Currently always 2 */1391213913  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);13914  void (*xDelete)(Fts5Tokenizer*);13915  int (*xTokenize)(Fts5Tokenizer*,13916      void *pCtx,13917      int flags,            /* Mask of FTS5_TOKENIZE_* flags */13918      const char *pText, int nText,13919      const char *pLocale, int nLocale,13920      int (*xToken)(13921        void *pCtx,         /* Copy of 2nd argument to xTokenize() */13922        int tflags,         /* Mask of FTS5_TOKEN_* flags */13923        const char *pToken, /* Pointer to buffer containing token */13924        int nToken,         /* Size of token in bytes */13925        int iStart,         /* Byte offset of token within input text */13926        int iEnd            /* Byte offset of end of token within input text */13927      )13928  );13929};1393013931/*13932** New code should use the fts5_tokenizer_v2 type to define tokenizer13933** implementations. The following type is included for legacy applications13934** that still use it.13935*/13936typedef struct fts5_tokenizer fts5_tokenizer;13937struct fts5_tokenizer {13938  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);13939  void (*xDelete)(Fts5Tokenizer*);13940  int (*xTokenize)(Fts5Tokenizer*,13941      void *pCtx,13942      int flags,            /* Mask of FTS5_TOKENIZE_* flags */13943      const char *pText, int nText,13944      int (*xToken)(13945        void *pCtx,         /* Copy of 2nd argument to xTokenize() */13946        int tflags,         /* Mask of FTS5_TOKEN_* flags */13947        const char *pToken, /* Pointer to buffer containing token */13948        int nToken,         /* Size of token in bytes */13949        int iStart,         /* Byte offset of token within input text */13950        int iEnd            /* Byte offset of end of token within input text */13951      )13952  );13953};139541395513956/* Flags that may be passed as the third argument to xTokenize() */13957#define FTS5_TOKENIZE_QUERY     0x000113958#define FTS5_TOKENIZE_PREFIX    0x000213959#define FTS5_TOKENIZE_DOCUMENT  0x000413960#define FTS5_TOKENIZE_AUX       0x00081396113962/* Flags that may be passed by the tokenizer implementation back to FTS513963** as the third argument to the supplied xToken callback. */13964#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */1396513966/*13967** END OF CUSTOM TOKENIZERS13968*************************************************************************/1396913970/*************************************************************************13971** FTS5 EXTENSION REGISTRATION API13972*/13973typedef struct fts5_api fts5_api;13974struct fts5_api {13975  int iVersion;                   /* Currently always set to 3 */1397613977  /* Create a new tokenizer */13978  int (*xCreateTokenizer)(13979    fts5_api *pApi,13980    const char *zName,13981    void *pUserData,13982    fts5_tokenizer *pTokenizer,13983    void (*xDestroy)(void*)13984  );1398513986  /* Find an existing tokenizer */13987  int (*xFindTokenizer)(13988    fts5_api *pApi,13989    const char *zName,13990    void **ppUserData,13991    fts5_tokenizer *pTokenizer13992  );1399313994  /* Create a new auxiliary function */13995  int (*xCreateFunction)(13996    fts5_api *pApi,13997    const char *zName,13998    void *pUserData,13999    fts5_extension_function xFunction,14000    void (*xDestroy)(void*)14001  );1400214003  /* APIs below this point are only available if iVersion>=3 */1400414005  /* Create a new tokenizer */14006  int (*xCreateTokenizer_v2)(14007    fts5_api *pApi,14008    const char *zName,14009    void *pUserData,14010    fts5_tokenizer_v2 *pTokenizer,14011    void (*xDestroy)(void*)14012  );1401314014  /* Find an existing tokenizer */14015  int (*xFindTokenizer_v2)(14016    fts5_api *pApi,14017    const char *zName,14018    void **ppUserData,14019    fts5_tokenizer_v2 **ppTokenizer14020  );14021};1402214023/*14024** END OF REGISTRATION API14025*************************************************************************/1402614027#if 014028}  /* end of the 'extern "C"' block */14029#endif1403014031#endif /* _FTS5_H */1403214033/******** End of fts5.h *********/14034#endif /* SQLITE3_H */1403514036/************** End of sqlite3.h *********************************************/14037/************** Continuing where we left off in sqliteInt.h ******************/1403814039/*14040** Reuse the STATIC_LRU for mutex access to sqlite3_temp_directory.14041*/14042#define SQLITE_MUTEX_STATIC_TEMPDIR SQLITE_MUTEX_STATIC_VFS11404314044/*14045** Include the configuration header output by 'configure' if we're using the14046** autoconf-based build14047*/14048#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)14049#include "sqlite_cfg.h"14050#define SQLITECONFIG_H 114051#endif1405214053/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/14054/************** Begin file sqliteLimit.h *************************************/14055/*14056** 2007 May 714057**14058** The author disclaims copyright to this source code.  In place of14059** a legal notice, here is a blessing:14060**14061**    May you do good and not evil.14062**    May you find forgiveness for yourself and forgive others.14063**    May you share freely, never taking more than you give.14064**14065*************************************************************************14066**14067** This file defines various limits of what SQLite can process.14068*/1406914070/*14071** The maximum length of a TEXT or BLOB in bytes.   This also14072** limits the size of a row in a table or index.14073**14074** The hard limit is the ability of a 32-bit signed integer14075** to count the size: 2^31-1 or 2147483647.14076*/14077#ifndef SQLITE_MAX_LENGTH14078# define SQLITE_MAX_LENGTH 100000000014079#endif14080#define SQLITE_MIN_LENGTH 30   /* Minimum value for the length limit */1408114082/*14083** This is the maximum number of14084**14085**    * Columns in a table14086**    * Columns in an index14087**    * Columns in a view14088**    * Terms in the SET clause of an UPDATE statement14089**    * Terms in the result set of a SELECT statement14090**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.14091**    * Terms in the VALUES clause of an INSERT statement14092**14093** The hard upper limit here is 32676.  Most database people will14094** tell you that in a well-normalized database, you usually should14095** not have more than a dozen or so columns in any table.  And if14096** that is the case, there is no point in having more than a few14097** dozen values in any of the other situations described above.14098*/14099#ifndef SQLITE_MAX_COLUMN14100# define SQLITE_MAX_COLUMN 200014101#endif1410214103/*14104** The maximum length of a single SQL statement in bytes.14105**14106** It used to be the case that setting this value to zero would14107** turn the limit off.  That is no longer true.  It is not possible14108** to turn this limit off.14109*/14110#ifndef SQLITE_MAX_SQL_LENGTH14111# define SQLITE_MAX_SQL_LENGTH 100000000014112#endif1411314114/*14115** The maximum depth of an expression tree. This is limited to14116** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might14117** want to place more severe limits on the complexity of an14118** expression. A value of 0 means that there is no limit.14119*/14120#ifndef SQLITE_MAX_EXPR_DEPTH14121# define SQLITE_MAX_EXPR_DEPTH 100014122#endif1412314124/*14125** The maximum number of terms in a compound SELECT statement.14126** The code generator for compound SELECT statements does one14127** level of recursion for each term.  A stack overflow can result14128** if the number of terms is too large.  In practice, most SQL14129** never has more than 3 or 4 terms.  Use a value of 0 to disable14130** any limit on the number of terms in a compound SELECT.14131*/14132#ifndef SQLITE_MAX_COMPOUND_SELECT14133# define SQLITE_MAX_COMPOUND_SELECT 50014134#endif1413514136/*14137** The maximum number of opcodes in a VDBE program.14138** Not currently enforced.14139*/14140#ifndef SQLITE_MAX_VDBE_OP14141# define SQLITE_MAX_VDBE_OP 25000000014142#endif1414314144/*14145** The maximum number of arguments to an SQL function.14146**14147** This value has a hard upper limit of 32767 due to storage14148** constraints (it needs to fit inside a i16).  We keep it14149** lower than that to prevent abuse.14150*/14151#ifndef SQLITE_MAX_FUNCTION_ARG14152# define SQLITE_MAX_FUNCTION_ARG 100014153#endif1415414155/*14156** The suggested maximum number of in-memory pages to use for14157** the main database table and for temporary tables.14158**14159** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,14160** which means the cache size is limited to 2048000 bytes of memory.14161** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be14162** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.14163*/14164#ifndef SQLITE_DEFAULT_CACHE_SIZE14165# define SQLITE_DEFAULT_CACHE_SIZE  -200014166#endif1416714168/*14169** The default number of frames to accumulate in the log file before14170** checkpointing the database in WAL mode.14171*/14172#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT14173# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  100014174#endif1417514176/*14177** The maximum number of attached databases.  This must be between 014178** and 125.  The upper bound of 125 is because the attached databases are14179** counted using a signed 8-bit integer which has a maximum value of 12714180** and we have to allow 2 extra counts for the "main" and "temp" databases.14181*/14182#ifndef SQLITE_MAX_ATTACHED14183# define SQLITE_MAX_ATTACHED 1014184#endif141851418614187/*14188** The maximum value of a ?nnn wildcard that the parser will accept.14189** If the value exceeds 32767 then extra space is required for the Expr14190** structure.  But otherwise, we believe that the number can be as large14191** as a signed 32-bit integer can hold.14192*/14193#ifndef SQLITE_MAX_VARIABLE_NUMBER14194# define SQLITE_MAX_VARIABLE_NUMBER 3276614195#endif1419614197/* Maximum page size.  The upper bound on this value is 65536.  This a limit14198** imposed by the use of 16-bit offsets within each page.14199**14200** Earlier versions of SQLite allowed the user to change this value at14201** compile time. This is no longer permitted, on the grounds that it creates14202** a library that is technically incompatible with an SQLite library14203** compiled with a different limit. If a process operating on a database14204** with a page-size of 65536 bytes crashes, then an instance of SQLite14205** compiled with the default page-size limit will not be able to rollback14206** the aborted transaction. This could lead to database corruption.14207*/14208#ifdef SQLITE_MAX_PAGE_SIZE14209# undef SQLITE_MAX_PAGE_SIZE14210#endif14211#define SQLITE_MAX_PAGE_SIZE 65536142121421314214/*14215** The default size of a database page.14216*/14217#ifndef SQLITE_DEFAULT_PAGE_SIZE14218# define SQLITE_DEFAULT_PAGE_SIZE 409614219#endif14220#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE14221# undef SQLITE_DEFAULT_PAGE_SIZE14222# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE14223#endif1422414225/*14226** Ordinarily, if no value is explicitly provided, SQLite creates databases14227** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain14228** device characteristics (sector-size and atomic write() support),14229** SQLite may choose a larger value. This constant is the maximum value14230** SQLite will choose on its own.14231*/14232#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE14233# define SQLITE_MAX_DEFAULT_PAGE_SIZE 819214234#endif14235#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE14236# undef SQLITE_MAX_DEFAULT_PAGE_SIZE14237# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE14238#endif142391424014241/*14242** Maximum number of pages in one database file.14243**14244** This is really just the default value for the max_page_count pragma.14245** This value can be lowered (or raised) at run-time using that the14246** max_page_count macro.14247*/14248#ifndef SQLITE_MAX_PAGE_COUNT14249# define SQLITE_MAX_PAGE_COUNT 0xfffffffe /* 4294967294 */14250#endif1425114252/*14253** Maximum length (in bytes) of the pattern in a LIKE or GLOB14254** operator.14255*/14256#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH14257# define SQLITE_MAX_LIKE_PATTERN_LENGTH 5000014258#endif1425914260/*14261** Maximum depth of recursion for triggers.14262**14263** A value of 1 means that a trigger program will not be able to itself14264** fire any triggers. A value of 0 means that no trigger programs at all14265** may be executed.14266*/14267#ifndef SQLITE_MAX_TRIGGER_DEPTH14268# define SQLITE_MAX_TRIGGER_DEPTH 100014269#endif1427014271/************** End of sqliteLimit.h *****************************************/14272/************** Continuing where we left off in sqliteInt.h ******************/1427314274/* Disable nuisance warnings on Borland compilers */14275#if defined(__BORLANDC__)14276#pragma warn -rch /* unreachable code */14277#pragma warn -ccc /* Condition is always true or false */14278#pragma warn -aus /* Assigned value is never used */14279#pragma warn -csu /* Comparing signed and unsigned */14280#pragma warn -spa /* Suspicious pointer arithmetic */14281#endif1428214283/*14284** A few places in the code require atomic load/store of aligned14285** integer values.14286*/14287#ifndef __has_extension14288# define __has_extension(x) 0     /* compatibility with non-clang compilers */14289#endif14290#if GCC_VERSION>=4007000 || __has_extension(c_atomic)14291# define SQLITE_ATOMIC_INTRINSICS 114292# define AtomicLoad(PTR)       __atomic_load_n((PTR),__ATOMIC_RELAXED)14293# define AtomicStore(PTR,VAL)  __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)14294#else14295# define SQLITE_ATOMIC_INTRINSICS 014296# define AtomicLoad(PTR)       (*(PTR))14297# define AtomicStore(PTR,VAL)  (*(PTR) = (VAL))14298#endif1429914300/*14301** Include standard header files as necessary14302*/14303#ifdef HAVE_STDINT_H14304#include <stdint.h>14305#endif14306#ifdef HAVE_INTTYPES_H14307#include <inttypes.h>14308#endif1430914310/*14311** The following macros are used to cast pointers to integers and14312** integers to pointers.  The way you do this varies from one compiler14313** to the next, so we have developed the following set of #if statements14314** to generate appropriate macros for a wide range of compilers.14315**14316** The correct "ANSI" way to do this is to use the intptr_t type.14317** Unfortunately, that typedef is not available on all compilers, or14318** if it is available, it requires an #include of specific headers14319** that vary from one machine to the next.14320**14321** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on14322** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).14323** So we have to define the macros in different ways depending on the14324** compiler.14325*/14326#if defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */14327# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))14328# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))14329#elif defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */14330# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))14331# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))14332#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */14333# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])14334# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))14335#else                          /* Generates a warning - but it always works */14336# define SQLITE_INT_TO_PTR(X)  ((void*)(X))14337# define SQLITE_PTR_TO_INT(X)  ((int)(X))14338#endif1433914340/*14341** Macros to hint to the compiler that a function should or should not be14342** inlined.14343*/14344#if defined(__GNUC__)14345#  define SQLITE_NOINLINE  __attribute__((noinline))14346#  define SQLITE_INLINE    __attribute__((always_inline)) inline14347#elif defined(_MSC_VER) && _MSC_VER>=131014348#  define SQLITE_NOINLINE  __declspec(noinline)14349#  define SQLITE_INLINE    __forceinline14350#else14351#  define SQLITE_NOINLINE14352#  define SQLITE_INLINE14353#endif14354#if defined(SQLITE_COVERAGE_TEST) || defined(__STRICT_ANSI__)14355# undef SQLITE_INLINE14356# define SQLITE_INLINE14357#endif1435814359/*14360** Make sure that the compiler intrinsics we desire are enabled when14361** compiling with an appropriate version of MSVC unless prevented by14362** the SQLITE_DISABLE_INTRINSIC define.14363*/14364#if !defined(SQLITE_DISABLE_INTRINSIC)14365#  if defined(_MSC_VER) && _MSC_VER>=140014366#    if !defined(_WIN32_WCE)14367#      include <intrin.h>14368#      pragma intrinsic(_byteswap_ushort)14369#      pragma intrinsic(_byteswap_ulong)14370#      pragma intrinsic(_byteswap_uint64)14371#      pragma intrinsic(_ReadWriteBarrier)14372#    else14373#      include <cmnintrin.h>14374#    endif14375#  endif14376#endif1437714378/*14379** Enable SQLITE_USE_SEH by default on MSVC builds.  Only omit14380** SEH support if the -DSQLITE_OMIT_SEH option is given.14381*/14382#if defined(_MSC_VER) && !defined(SQLITE_OMIT_SEH)14383# define SQLITE_USE_SEH 114384#else14385# undef SQLITE_USE_SEH14386#endif1438714388/*14389** Enable SQLITE_DIRECT_OVERFLOW_READ, unless the build explicitly14390** disables it using -DSQLITE_DIRECT_OVERFLOW_READ=014391*/14392#if defined(SQLITE_DIRECT_OVERFLOW_READ) && SQLITE_DIRECT_OVERFLOW_READ+1==114393  /* Disable if -DSQLITE_DIRECT_OVERFLOW_READ=0 */14394# undef SQLITE_DIRECT_OVERFLOW_READ14395#else14396  /* In all other cases, enable */14397# define SQLITE_DIRECT_OVERFLOW_READ 114398#endif143991440014401/*14402** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.14403** 0 means mutexes are permanently disable and the library is never14404** threadsafe.  1 means the library is serialized which is the highest14405** level of threadsafety.  2 means the library is multithreaded - multiple14406** threads can use SQLite as long as no two threads try to use the same14407** database connection at the same time.14408**14409** Older versions of SQLite used an optional THREADSAFE macro.14410** We support that for legacy.14411**14412** To ensure that the correct value of "THREADSAFE" is reported when querying14413** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this14414** logic is partially replicated in ctime.c. If it is updated here, it should14415** also be updated there.14416*/14417#if !defined(SQLITE_THREADSAFE)14418# if defined(THREADSAFE)14419#   define SQLITE_THREADSAFE THREADSAFE14420# else14421#   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */14422# endif14423#endif1442414425/*14426** Powersafe overwrite is on by default.  But can be turned off using14427** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.14428*/14429#ifndef SQLITE_POWERSAFE_OVERWRITE14430# define SQLITE_POWERSAFE_OVERWRITE 114431#endif1443214433/*14434** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by14435** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in14436** which case memory allocation statistics are disabled by default.14437*/14438#if !defined(SQLITE_DEFAULT_MEMSTATUS)14439# define SQLITE_DEFAULT_MEMSTATUS 114440#endif1444114442/*14443** Exactly one of the following macros must be defined in order to14444** specify which memory allocation subsystem to use.14445**14446**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()14447**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API14448**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails14449**     SQLITE_MEMDEBUG               // Debugging version of system malloc()14450**14451** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the14452** assert() macro is enabled, each call into the Win32 native heap subsystem14453** will cause HeapValidate to be called.  If heap validation should fail, an14454** assertion will be triggered.14455**14456** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as14457** the default.14458*/14459#if defined(SQLITE_SYSTEM_MALLOC) \14460  + defined(SQLITE_WIN32_MALLOC) \14461  + defined(SQLITE_ZERO_MALLOC) \14462  + defined(SQLITE_MEMDEBUG)>114463# error "Two or more of the following compile-time configuration options\14464 are defined but at most one is allowed:\14465 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\14466 SQLITE_ZERO_MALLOC"14467#endif14468#if defined(SQLITE_SYSTEM_MALLOC) \14469  + defined(SQLITE_WIN32_MALLOC) \14470  + defined(SQLITE_ZERO_MALLOC) \14471  + defined(SQLITE_MEMDEBUG)==014472# define SQLITE_SYSTEM_MALLOC 114473#endif1447414475/*14476** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the14477** sizes of memory allocations below this value where possible.14478*/14479#if !defined(SQLITE_MALLOC_SOFT_LIMIT)14480# define SQLITE_MALLOC_SOFT_LIMIT 102414481#endif1448214483/*14484** We need to define _XOPEN_SOURCE as follows in order to enable14485** recursive mutexes on most Unix systems and fchmod() on OpenBSD.14486** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit14487** it.14488*/14489#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)14490#  define _XOPEN_SOURCE 60014491#endif1449214493/*14494** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that14495** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,14496** make it true by defining or undefining NDEBUG.14497**14498** Setting NDEBUG makes the code smaller and faster by disabling the14499** assert() statements in the code.  So we want the default action14500** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG14501** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out14502** feature.14503*/14504#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)14505# define NDEBUG 114506#endif14507#if defined(NDEBUG) && defined(SQLITE_DEBUG)14508# undef NDEBUG14509#endif1451014511/*14512** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.14513*/14514#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)14515# define SQLITE_ENABLE_EXPLAIN_COMMENTS 114516#endif1451714518/*14519** The testcase() macro is used to aid in coverage testing.  When14520** doing coverage testing, the condition inside the argument to14521** testcase() must be evaluated both true and false in order to14522** get full branch coverage.  The testcase() macro is inserted14523** to help ensure adequate test coverage in places where simple14524** condition/decision coverage is inadequate.  For example, testcase()14525** can be used to make sure boundary values are tested.  For14526** bitmask tests, testcase() can be used to make sure each bit14527** is significant and used at least once.  On switch statements14528** where multiple cases go to the same block of code, testcase()14529** can insure that all cases are evaluated.14530*/14531#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)14532# ifndef SQLITE_AMALGAMATION14533    extern unsigned int sqlite3CoverageCounter;14534# endif14535# define testcase(X)  if( X ){ sqlite3CoverageCounter += (unsigned)__LINE__; }14536#else14537# define testcase(X)14538#endif1453914540/*14541** The TESTONLY macro is used to enclose variable declarations or14542** other bits of code that are needed to support the arguments14543** within testcase() and assert() macros.14544*/14545#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)14546# define TESTONLY(X)  X14547#else14548# define TESTONLY(X)14549#endif1455014551/*14552** Sometimes we need a small amount of code such as a variable initialization14553** to setup for a later assert() statement.  We do not want this code to14554** appear when assert() is disabled.  The following macro is therefore14555** used to contain that setup code.  The "VVA" acronym stands for14556** "Verification, Validation, and Accreditation".  In other words, the14557** code within VVA_ONLY() will only run during verification processes.14558*/14559#ifndef NDEBUG14560# define VVA_ONLY(X)  X14561#else14562# define VVA_ONLY(X)14563#endif1456414565/*14566** Disable ALWAYS() and NEVER() (make them pass-throughs) for coverage14567** and mutation testing14568*/14569#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)14570# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS  114571#endif1457214573/*14574** The ALWAYS and NEVER macros surround boolean expressions which14575** are intended to always be true or false, respectively.  Such14576** expressions could be omitted from the code completely.  But they14577** are included in a few cases in order to enhance the resilience14578** of SQLite to unexpected behavior - to make the code "self-healing"14579** or "ductile" rather than being "brittle" and crashing at the first14580** hint of unplanned behavior.14581**14582** In other words, ALWAYS and NEVER are added for defensive code.14583**14584** When doing coverage testing ALWAYS and NEVER are hard-coded to14585** be true and false so that the unreachable code they specify will14586** not be counted as untested code.14587*/14588#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)14589# define ALWAYS(X)      (1)14590# define NEVER(X)       (0)14591#elif !defined(NDEBUG)14592# define ALWAYS(X)      ((X)?1:(assert(0),0))14593# define NEVER(X)       ((X)?(assert(0),1):0)14594#else14595# define ALWAYS(X)      (X)14596# define NEVER(X)       (X)14597#endif1459814599/*14600** Some conditionals are optimizations only.  In other words, if the14601** conditionals are replaced with a constant 1 (true) or 0 (false) then14602** the correct answer is still obtained, though perhaps not as quickly.14603**14604** The following macros mark these optimizations conditionals.14605*/14606#if defined(SQLITE_MUTATION_TEST)14607# define OK_IF_ALWAYS_TRUE(X)  (1)14608# define OK_IF_ALWAYS_FALSE(X) (0)14609#else14610# define OK_IF_ALWAYS_TRUE(X)  (X)14611# define OK_IF_ALWAYS_FALSE(X) (X)14612#endif1461314614/*14615** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is14616** defined.  We need to defend against those failures when testing with14617** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches14618** during a normal build.  The following macro can be used to disable tests14619** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.14620*/14621#if defined(SQLITE_TEST_REALLOC_STRESS)14622# define ONLY_IF_REALLOC_STRESS(X)  (X)14623#elif !defined(NDEBUG)14624# define ONLY_IF_REALLOC_STRESS(X)  ((X)?(assert(0),1):0)14625#else14626# define ONLY_IF_REALLOC_STRESS(X)  (0)14627#endif1462814629/*14630** Declarations used for tracing the operating system interfaces.14631*/14632#if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \14633    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)14634  extern int sqlite3OSTrace;14635# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X14636# define SQLITE_HAVE_OS_TRACE14637#else14638# define OSTRACE(X)14639# undef  SQLITE_HAVE_OS_TRACE14640#endif1464114642/*14643** Is the sqlite3ErrName() function needed in the build?  Currently,14644** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when14645** OSTRACE is enabled), and by several "test*.c" files (which are14646** compiled using SQLITE_TEST).14647*/14648#if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \14649    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)14650# define SQLITE_NEED_ERR_NAME14651#else14652# undef  SQLITE_NEED_ERR_NAME14653#endif1465414655/*14656** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN14657*/14658#ifdef SQLITE_OMIT_EXPLAIN14659# undef SQLITE_ENABLE_EXPLAIN_COMMENTS14660#endif1466114662/*14663** SQLITE_OMIT_VIRTUALTABLE implies SQLITE_OMIT_ALTERTABLE14664*/14665#if defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_ALTERTABLE)14666# define SQLITE_OMIT_ALTERTABLE14667#endif1466814669#define SQLITE_DIGIT_SEPARATOR '_'1467014671/*14672** Return true (non-zero) if the input is an integer that is too large14673** to fit in 32-bits.  This macro is used inside of various testcase()14674** macros to verify that we have tested SQLite for large-file support.14675*/14676#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)1467714678/*14679** The macro unlikely() is a hint that surrounds a boolean14680** expression that is usually false.  Macro likely() surrounds14681** a boolean expression that is usually true.  These hints could,14682** in theory, be used by the compiler to generate better code, but14683** currently they are just comments for human readers.14684*/14685#define likely(X)    (X)14686#define unlikely(X)  (X)1468714688/************** Include hash.h in the middle of sqliteInt.h ******************/14689/************** Begin file hash.h ********************************************/14690/*14691** 2001 September 2214692**14693** The author disclaims copyright to this source code.  In place of14694** a legal notice, here is a blessing:14695**14696**    May you do good and not evil.14697**    May you find forgiveness for yourself and forgive others.14698**    May you share freely, never taking more than you give.14699**14700*************************************************************************14701** This is the header file for the generic hash-table implementation14702** used in SQLite.14703*/14704#ifndef SQLITE_HASH_H14705#define SQLITE_HASH_H1470614707/* Forward declarations of structures. */14708typedef struct Hash Hash;14709typedef struct HashElem HashElem;1471014711/* A complete hash table is an instance of the following structure.14712** The internals of this structure are intended to be opaque -- client14713** code should not attempt to access or modify the fields of this structure14714** directly.  Change this structure only by using the routines below.14715** However, some of the "procedures" and "functions" for modifying and14716** accessing this structure are really macros, so we can't really make14717** this structure opaque.14718**14719** All elements of the hash table are on a single doubly-linked list.14720** Hash.first points to the head of this list.14721**14722** There are Hash.htsize buckets.  Each bucket points to a spot in14723** the global doubly-linked list.  The contents of the bucket are the14724** element pointed to plus the next _ht.count-1 elements in the list.14725**14726** Hash.htsize and Hash.ht may be zero.  In that case lookup is done14727** by a linear search of the global list.  For small tables, the14728** Hash.ht table is never allocated because if there are few elements14729** in the table, it is faster to do a linear search than to manage14730** the hash table.14731*/14732struct Hash {14733  unsigned int htsize;      /* Number of buckets in the hash table */14734  unsigned int count;       /* Number of entries in this table */14735  HashElem *first;          /* The first element of the array */14736  struct _ht {              /* the hash table */14737    unsigned int count;        /* Number of entries with this hash */14738    HashElem *chain;           /* Pointer to first entry with this hash */14739  } *ht;14740};1474114742/* Each element in the hash table is an instance of the following14743** structure.  All elements are stored on a single doubly-linked list.14744**14745** Again, this structure is intended to be opaque, but it can't really14746** be opaque because it is used by macros.14747*/14748struct HashElem {14749  HashElem *next, *prev;       /* Next and previous elements in the table */14750  void *data;                  /* Data associated with this element */14751  const char *pKey;            /* Key associated with this element */14752};1475314754/*14755** Access routines.  To delete, insert a NULL pointer.14756*/14757SQLITE_PRIVATE void sqlite3HashInit(Hash*);14758SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);14759SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);14760SQLITE_PRIVATE void sqlite3HashClear(Hash*);1476114762/*14763** Macros for looping over all elements of a hash table.  The idiom is14764** like this:14765**14766**   Hash h;14767**   HashElem *p;14768**   ...14769**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){14770**     SomeStructure *pData = sqliteHashData(p);14771**     // do something with pData14772**   }14773*/14774#define sqliteHashFirst(H)  ((H)->first)14775#define sqliteHashNext(E)   ((E)->next)14776#define sqliteHashData(E)   ((E)->data)14777/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */14778/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */1477914780/*14781** Number of entries in a hash table14782*/14783#define sqliteHashCount(H)  ((H)->count)1478414785#endif /* SQLITE_HASH_H */1478614787/************** End of hash.h ************************************************/14788/************** Continuing where we left off in sqliteInt.h ******************/14789/************** Include parse.h in the middle of sqliteInt.h *****************/14790/************** Begin file parse.h *******************************************/14791#define TK_SEMI                             114792#define TK_EXPLAIN                          214793#define TK_QUERY                            314794#define TK_PLAN                             414795#define TK_BEGIN                            514796#define TK_TRANSACTION                      614797#define TK_DEFERRED                         714798#define TK_IMMEDIATE                        814799#define TK_EXCLUSIVE                        914800#define TK_COMMIT                          1014801#define TK_END                             1114802#define TK_ROLLBACK                        1214803#define TK_SAVEPOINT                       1314804#define TK_RELEASE                         1414805#define TK_TO                              1514806#define TK_TABLE                           1614807#define TK_CREATE                          1714808#define TK_IF                              1814809#define TK_NOT                             1914810#define TK_EXISTS                          2014811#define TK_TEMP                            2114812#define TK_LP                              2214813#define TK_RP                              2314814#define TK_AS                              2414815#define TK_COMMA                           2514816#define TK_WITHOUT                         2614817#define TK_ABORT                           2714818#define TK_ACTION                          2814819#define TK_AFTER                           2914820#define TK_ANALYZE                         3014821#define TK_ASC                             3114822#define TK_ATTACH                          3214823#define TK_BEFORE                          3314824#define TK_BY                              3414825#define TK_CASCADE                         3514826#define TK_CAST                            3614827#define TK_CONFLICT                        3714828#define TK_DATABASE                        3814829#define TK_DESC                            3914830#define TK_DETACH                          4014831#define TK_EACH                            4114832#define TK_FAIL                            4214833#define TK_OR                              4314834#define TK_AND                             4414835#define TK_IS                              4514836#define TK_ISNOT                           4614837#define TK_MATCH                           4714838#define TK_LIKE_KW                         4814839#define TK_BETWEEN                         4914840#define TK_IN                              5014841#define TK_ISNULL                          5114842#define TK_NOTNULL                         5214843#define TK_NE                              5314844#define TK_EQ                              5414845#define TK_GT                              5514846#define TK_LE                              5614847#define TK_LT                              5714848#define TK_GE                              5814849#define TK_ESCAPE                          5914850#define TK_ID                              6014851#define TK_COLUMNKW                        6114852#define TK_DO                              6214853#define TK_FOR                             6314854#define TK_IGNORE                          6414855#define TK_INITIALLY                       6514856#define TK_INSTEAD                         6614857#define TK_NO                              6714858#define TK_KEY                             6814859#define TK_OF                              6914860#define TK_OFFSET                          7014861#define TK_PRAGMA                          7114862#define TK_RAISE                           7214863#define TK_RECURSIVE                       7314864#define TK_REPLACE                         7414865#define TK_RESTRICT                        7514866#define TK_ROW                             7614867#define TK_ROWS                            7714868#define TK_TRIGGER                         7814869#define TK_VACUUM                          7914870#define TK_VIEW                            8014871#define TK_VIRTUAL                         8114872#define TK_WITH                            8214873#define TK_NULLS                           8314874#define TK_FIRST                           8414875#define TK_LAST                            8514876#define TK_CURRENT                         8614877#define TK_FOLLOWING                       8714878#define TK_PARTITION                       8814879#define TK_PRECEDING                       8914880#define TK_RANGE                           9014881#define TK_UNBOUNDED                       9114882#define TK_EXCLUDE                         9214883#define TK_GROUPS                          9314884#define TK_OTHERS                          9414885#define TK_TIES                            9514886#define TK_GENERATED                       9614887#define TK_ALWAYS                          9714888#define TK_MATERIALIZED                    9814889#define TK_REINDEX                         9914890#define TK_RENAME                         10014891#define TK_CTIME_KW                       10114892#define TK_ANY                            10214893#define TK_BITAND                         10314894#define TK_BITOR                          10414895#define TK_LSHIFT                         10514896#define TK_RSHIFT                         10614897#define TK_PLUS                           10714898#define TK_MINUS                          10814899#define TK_STAR                           10914900#define TK_SLASH                          11014901#define TK_REM                            11114902#define TK_CONCAT                         11214903#define TK_PTR                            11314904#define TK_COLLATE                        11414905#define TK_BITNOT                         11514906#define TK_ON                             11614907#define TK_INDEXED                        11714908#define TK_STRING                         11814909#define TK_JOIN_KW                        11914910#define TK_CONSTRAINT                     12014911#define TK_DEFAULT                        12114912#define TK_NULL                           12214913#define TK_PRIMARY                        12314914#define TK_UNIQUE                         12414915#define TK_CHECK                          12514916#define TK_REFERENCES                     12614917#define TK_AUTOINCR                       12714918#define TK_INSERT                         12814919#define TK_DELETE                         12914920#define TK_UPDATE                         13014921#define TK_SET                            13114922#define TK_DEFERRABLE                     13214923#define TK_FOREIGN                        13314924#define TK_DROP                           13414925#define TK_UNION                          13514926#define TK_ALL                            13614927#define TK_EXCEPT                         13714928#define TK_INTERSECT                      13814929#define TK_SELECT                         13914930#define TK_VALUES                         14014931#define TK_DISTINCT                       14114932#define TK_DOT                            14214933#define TK_FROM                           14314934#define TK_JOIN                           14414935#define TK_USING                          14514936#define TK_ORDER                          14614937#define TK_GROUP                          14714938#define TK_HAVING                         14814939#define TK_LIMIT                          14914940#define TK_WHERE                          15014941#define TK_RETURNING                      15114942#define TK_INTO                           15214943#define TK_NOTHING                        15314944#define TK_FLOAT                          15414945#define TK_BLOB                           15514946#define TK_INTEGER                        15614947#define TK_VARIABLE                       15714948#define TK_CASE                           15814949#define TK_WHEN                           15914950#define TK_THEN                           16014951#define TK_ELSE                           16114952#define TK_INDEX                          16214953#define TK_ALTER                          16314954#define TK_ADD                            16414955#define TK_WINDOW                         16514956#define TK_OVER                           16614957#define TK_FILTER                         16714958#define TK_COLUMN                         16814959#define TK_AGG_FUNCTION                   16914960#define TK_AGG_COLUMN                     17014961#define TK_TRUEFALSE                      17114962#define TK_FUNCTION                       17214963#define TK_UPLUS                          17314964#define TK_UMINUS                         17414965#define TK_TRUTH                          17514966#define TK_REGISTER                       17614967#define TK_VECTOR                         17714968#define TK_SELECT_COLUMN                  17814969#define TK_IF_NULL_ROW                    17914970#define TK_ASTERISK                       18014971#define TK_SPAN                           18114972#define TK_ERROR                          18214973#define TK_QNUMBER                        18314974#define TK_SPACE                          18414975#define TK_COMMENT                        18514976#define TK_ILLEGAL                        1861497714978/************** End of parse.h ***********************************************/14979/************** Continuing where we left off in sqliteInt.h ******************/14980#include <stdio.h>14981#include <stdlib.h>14982#include <string.h>14983#include <assert.h>14984#include <stddef.h>14985#include <ctype.h>1498614987/*14988** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.14989** This allows better measurements of where memcpy() is used when running14990** cachegrind.  But this macro version of memcpy() is very slow so it14991** should not be used in production.  This is a performance measurement14992** hack only.14993*/14994#ifdef SQLITE_INLINE_MEMCPY14995# define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\14996                        int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}14997#endif1499814999/*15000** If compiling for a processor that lacks floating point support,15001** substitute integer for floating-point15002*/15003#ifdef SQLITE_OMIT_FLOATING_POINT15004# define double sqlite_int6415005# define float sqlite_int6415006# define fabs(X) ((X)<0?-(X):(X))15007# define sqlite3IsOverflow(X) 015008# ifndef SQLITE_BIG_DBL15009#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)15010# endif15011# define SQLITE_OMIT_DATETIME_FUNCS 115012# define SQLITE_OMIT_TRACE 115013# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT15014# undef SQLITE_HAVE_ISNAN15015#endif15016#ifndef SQLITE_BIG_DBL15017# define SQLITE_BIG_DBL (1e99)15018#endif1501915020/*15021** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 015022** afterward. Having this macro allows us to cause the C compiler15023** to omit code used by TEMP tables without messy #ifndef statements.15024*/15025#ifdef SQLITE_OMIT_TEMPDB15026#define OMIT_TEMPDB 115027#else15028#define OMIT_TEMPDB 015029#endif1503015031/*15032** The "file format" number is an integer that is incremented whenever15033** the VDBE-level file format changes.  The following macros define the15034** the default file format for new databases and the maximum file format15035** that the library can read.15036*/15037#define SQLITE_MAX_FILE_FORMAT 415038#ifndef SQLITE_DEFAULT_FILE_FORMAT15039# define SQLITE_DEFAULT_FILE_FORMAT 415040#endif1504115042/*15043** Determine whether triggers are recursive by default.  This can be15044** changed at run-time using a pragma.15045*/15046#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS15047# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 015048#endif1504915050/*15051** Provide a default value for SQLITE_TEMP_STORE in case it is not specified15052** on the command-line15053*/15054#ifndef SQLITE_TEMP_STORE15055# define SQLITE_TEMP_STORE 115056#endif1505715058/*15059** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if15060** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it15061** to zero.15062*/15063#if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==015064# undef SQLITE_MAX_WORKER_THREADS15065# define SQLITE_MAX_WORKER_THREADS 015066#endif15067#ifndef SQLITE_MAX_WORKER_THREADS15068# define SQLITE_MAX_WORKER_THREADS 815069#endif15070#ifndef SQLITE_DEFAULT_WORKER_THREADS15071# define SQLITE_DEFAULT_WORKER_THREADS 015072#endif15073#if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS15074# undef SQLITE_MAX_WORKER_THREADS15075# define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS15076#endif1507715078/*15079** The default initial allocation for the pagecache when using separate15080** pagecaches for each database connection.  A positive number is the15081** number of pages.  A negative number N translations means that a buffer15082** of -1024*N bytes is allocated and used for as many pages as it will hold.15083**15084** The default value of "20" was chosen to minimize the run-time of the15085** speedtest1 test program with options: --shrink-memory --reprepare15086*/15087#ifndef SQLITE_DEFAULT_PCACHE_INITSZ15088# define SQLITE_DEFAULT_PCACHE_INITSZ 2015089#endif1509015091/*15092** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.15093*/15094#ifndef SQLITE_DEFAULT_SORTERREF_SIZE15095# define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff15096#endif1509715098/*15099** The compile-time options SQLITE_MMAP_READWRITE and15100** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.15101** You must choose one or the other (or neither) but not both.15102*/15103#if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)15104#error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE15105#endif1510615107/*15108** GCC does not define the offsetof() macro so we'll have to do it15109** ourselves.15110*/15111#ifndef offsetof15112#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))15113#endif1511415115/*15116** Macros to compute minimum and maximum of two numbers.15117*/15118#ifndef MIN15119# define MIN(A,B) ((A)<(B)?(A):(B))15120#endif15121#ifndef MAX15122# define MAX(A,B) ((A)>(B)?(A):(B))15123#endif1512415125/*15126** Swap two objects of type TYPE.15127*/15128#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}1512915130/*15131** Check to see if this machine uses EBCDIC.  (Yes, believe it or15132** not, there are still machines out there that use EBCDIC.)15133*/15134#if 'A' == '\301'15135# define SQLITE_EBCDIC 115136#else15137# define SQLITE_ASCII 115138#endif1513915140/*15141** Integers of known sizes.  These typedefs might change for architectures15142** where the sizes very.  Preprocessor macros are available so that the15143** types can be conveniently redefined at compile-type.  Like this:15144**15145**         cc '-DUINTPTR_TYPE=long long int' ...15146*/15147#ifndef UINT32_TYPE15148# ifdef HAVE_UINT32_T15149#  define UINT32_TYPE uint32_t15150# else15151#  define UINT32_TYPE unsigned int15152# endif15153#endif15154#ifndef UINT16_TYPE15155# ifdef HAVE_UINT16_T15156#  define UINT16_TYPE uint16_t15157# else15158#  define UINT16_TYPE unsigned short int15159# endif15160#endif15161#ifndef INT16_TYPE15162# ifdef HAVE_INT16_T15163#  define INT16_TYPE int16_t15164# else15165#  define INT16_TYPE short int15166# endif15167#endif15168#ifndef UINT8_TYPE15169# ifdef HAVE_UINT8_T15170#  define UINT8_TYPE uint8_t15171# else15172#  define UINT8_TYPE unsigned char15173# endif15174#endif15175#ifndef INT8_TYPE15176# ifdef HAVE_INT8_T15177#  define INT8_TYPE int8_t15178# else15179#  define INT8_TYPE signed char15180# endif15181#endif15182typedef sqlite_int64 i64;          /* 8-byte signed integer */15183typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */15184typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */15185typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */15186typedef INT16_TYPE i16;            /* 2-byte signed integer */15187typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */15188typedef INT8_TYPE i8;              /* 1-byte signed integer */1518915190/*15191** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value15192** that can be stored in a u32 without loss of data.  The value15193** is 0x00000000ffffffff.  But because of quirks of some compilers, we15194** have to specify the value in the less intuitive manner shown:15195*/15196#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)1519715198/*15199** The datatype used to store estimates of the number of rows in a15200** table or index.15201*/15202typedef u64 tRowcnt;1520315204/*15205** Estimated quantities used for query planning are stored as 16-bit15206** logarithms.  For quantity X, the value stored is 10*log2(X).  This15207** gives a possible range of values of approximately 1.0e986 to 1e-986.15208** But the allowed values are "grainy".  Not every value is representable.15209** For example, quantities 16 and 17 are both represented by a LogEst15210** of 40.  However, since LogEst quantities are suppose to be estimates,15211** not exact values, this imprecision is not a problem.15212**15213** "LogEst" is short for "Logarithmic Estimate".15214**15215** Examples:15216**      1 -> 0              20 -> 43          10000 -> 13215217**      2 -> 10             25 -> 46          25000 -> 14615218**      3 -> 16            100 -> 66        1000000 -> 19915219**      4 -> 20           1000 -> 99        1048576 -> 20015220**     10 -> 33           1024 -> 100    4294967296 -> 32015221**15222** The LogEst can be negative to indicate fractional values.15223** Examples:15224**15225**    0.5 -> -10           0.1 -> -33        0.0625 -> -4015226*/15227typedef INT16_TYPE LogEst;15228#define LOGEST_MIN (-32768)15229#define LOGEST_MAX (32767)1523015231/*15232** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer15233*/15234#ifndef SQLITE_PTRSIZE15235# if defined(__SIZEOF_POINTER__)15236#   define SQLITE_PTRSIZE __SIZEOF_POINTER__15237# elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \15238       defined(_M_ARM)   || defined(__arm__)    || defined(__x86)   ||    \15239      (defined(__APPLE__) && defined(__ppc__)) ||                         \15240      (defined(__TOS_AIX__) && !defined(__64BIT__))15241#   define SQLITE_PTRSIZE 415242# else15243#   define SQLITE_PTRSIZE 815244# endif15245#endif1524615247/* The uptr type is an unsigned integer large enough to hold a pointer15248*/15249#if defined(HAVE_STDINT_H)15250  typedef uintptr_t uptr;15251#elif SQLITE_PTRSIZE==415252  typedef u32 uptr;15253#else15254  typedef u64 uptr;15255#endif1525615257/*15258** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to15259** something between S (inclusive) and E (exclusive).15260**15261** In other words, S is a buffer and E is a pointer to the first byte after15262** the end of buffer S.  This macro returns true if P points to something15263** contained within the buffer S.15264*/15265#define SQLITE_WITHIN(P,S,E)   (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))1526615267/*15268** P is one byte past the end of a large buffer. Return true if a span of bytes15269** between S..E crosses the end of that buffer.  In other words, return true15270** if the sub-buffer S..E-1 overflows the buffer whose last byte is P-1.15271**15272** S is the start of the span.  E is one byte past the end of end of span.15273**15274**                        P15275**     |-----------------|                FALSE15276**               |-------|15277**               S        E15278**15279**                        P15280**     |-----------------|15281**                    |-------|           TRUE15282**                    S        E15283**15284**                        P15285**     |-----------------|15286**                        |-------|       FALSE15287**                        S        E15288*/15289#define SQLITE_OVERFLOW(P,S,E) (((uptr)(S)<(uptr)(P))&&((uptr)(E)>(uptr)(P)))1529015291/*15292** Macros to determine whether the machine is big or little endian,15293** and whether or not that determination is run-time or compile-time.15294**15295** For best performance, an attempt is made to guess at the byte-order15296** using C-preprocessor macros.  If that is unsuccessful, or if15297** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined15298** at run-time.15299**15300** If you are building SQLite on some obscure platform for which the15301** following ifdef magic does not work, you can always include either:15302**15303**    -DSQLITE_BYTEORDER=123415304**15305** or15306**15307**    -DSQLITE_BYTEORDER=432115308**15309** to cause the build to work for little-endian or big-endian processors,15310** respectively.15311*/15312#ifndef SQLITE_BYTEORDER  /* Replicate changes at tag-20230904a */15313# if defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_BIG_ENDIAN__15314#   define SQLITE_BYTEORDER 432115315# elif defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__15316#   define SQLITE_BYTEORDER 123415317# elif defined(__BIG_ENDIAN__) && __BIG_ENDIAN__==115318#   define SQLITE_BYTEORDER 432115319# elif defined(i386)    || defined(__i386__)      || defined(_M_IX86) ||    \15320     defined(__x86_64)  || defined(__x86_64__)    || defined(_M_X64)  ||    \15321     defined(_M_AMD64)  || defined(_M_ARM)        || defined(__x86)   ||    \15322     defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)15323#   define SQLITE_BYTEORDER 123415324# elif defined(sparc)   || defined(__ARMEB__)     || defined(__AARCH64EB__)15325#   define SQLITE_BYTEORDER 432115326# else15327#   define SQLITE_BYTEORDER 015328# endif15329#endif15330#if SQLITE_BYTEORDER==432115331# define SQLITE_BIGENDIAN    115332# define SQLITE_LITTLEENDIAN 015333# define SQLITE_UTF16NATIVE  SQLITE_UTF16BE15334#elif SQLITE_BYTEORDER==123415335# define SQLITE_BIGENDIAN    015336# define SQLITE_LITTLEENDIAN 115337# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE15338#else15339# ifdef SQLITE_AMALGAMATION15340  const int sqlite3one = 1;15341# else15342  extern const int sqlite3one;15343# endif15344# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)15345# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)15346# define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)15347#endif1534815349/*15350** Constants for the largest and smallest possible 64-bit signed integers.15351** These macros are designed to work correctly on both 32-bit and 64-bit15352** compilers.15353*/15354#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))15355#define LARGEST_UINT64 (0xffffffff|(((u64)0xffffffff)<<32))15356#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)1535715358/*15359** Round up a number to the next larger multiple of 8.  This is used15360** to force 8-byte alignment on 64-bit architectures.15361**15362** ROUND8() always does the rounding, for any argument.15363**15364** ROUND8P() assumes that the argument is already an integer number of15365** pointers in size, and so it is a no-op on systems where the pointer15366** size is 8.15367*/15368#define ROUND8(x)     (((x)+7)&~7)15369#if SQLITE_PTRSIZE==815370# define ROUND8P(x)   (x)15371#else15372# define ROUND8P(x)   (((x)+7)&~7)15373#endif1537415375/*15376** Round down to the nearest multiple of 815377*/15378#define ROUNDDOWN8(x) ((x)&~7)1537915380/*15381** Assert that the pointer X is aligned to an 8-byte boundary.  This15382** macro is used only within assert() to verify that the code gets15383** all alignment restrictions correct.15384**15385** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the15386** underlying malloc() implementation might return us 4-byte aligned15387** pointers.  In that case, only verify 4-byte alignment.15388*/15389#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC15390# define EIGHT_BYTE_ALIGNMENT(X)   ((((uptr)(X) - (uptr)0)&3)==0)15391#else15392# define EIGHT_BYTE_ALIGNMENT(X)   ((((uptr)(X) - (uptr)0)&7)==0)15393#endif1539415395/*15396** Disable MMAP on platforms where it is known to not work15397*/15398#if defined(__OpenBSD__) || defined(__QNXNTO__)15399# undef SQLITE_MAX_MMAP_SIZE15400# define SQLITE_MAX_MMAP_SIZE 015401#endif1540215403/*15404** Default maximum size of memory used by memory-mapped I/O in the VFS15405*/15406#ifdef __APPLE__15407# include <TargetConditionals.h>15408#endif15409#ifndef SQLITE_MAX_MMAP_SIZE15410# if defined(__linux__) \15411  || defined(_WIN32) \15412  || (defined(__APPLE__) && defined(__MACH__)) \15413  || defined(__sun) \15414  || defined(__FreeBSD__) \15415  || defined(__DragonFly__)15416#   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */15417# else15418#   define SQLITE_MAX_MMAP_SIZE 015419# endif15420#endif1542115422/*15423** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger15424** default MMAP_SIZE is specified at compile-time, make sure that it does15425** not exceed the maximum mmap size.15426*/15427#ifndef SQLITE_DEFAULT_MMAP_SIZE15428# define SQLITE_DEFAULT_MMAP_SIZE 015429#endif15430#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE15431# undef SQLITE_DEFAULT_MMAP_SIZE15432# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE15433#endif1543415435/*15436** TREETRACE_ENABLED will be either 1 or 0 depending on whether or not15437** the Abstract Syntax Tree tracing logic is turned on.15438*/15439#if !defined(SQLITE_AMALGAMATION)15440SQLITE_PRIVATE u32 sqlite3TreeTrace;15441#endif15442#if defined(SQLITE_DEBUG) \15443    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_SELECTTRACE) \15444                             || defined(SQLITE_ENABLE_TREETRACE))15445# define TREETRACE_ENABLED 115446# define TREETRACE(K,P,S,X)  \15447  if(sqlite3TreeTrace&(K))   \15448    sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\15449    sqlite3DebugPrintf X15450#else15451# define TREETRACE(K,P,S,X)15452# define TREETRACE_ENABLED 015453#endif1545415455/* TREETRACE flag meanings:15456**15457**   0x00000001     Beginning and end of SELECT processing15458**   0x00000002     WHERE clause processing15459**   0x00000004     Query flattener15460**   0x00000008     Result-set wildcard expansion15461**   0x00000010     Query name resolution15462**   0x00000020     Aggregate analysis15463**   0x00000040     Window functions15464**   0x00000080     Generated column names15465**   0x00000100     Move HAVING terms into WHERE15466**   0x00000200     Count-of-view optimization15467**   0x00000400     Compound SELECT processing15468**   0x00000800     Drop superfluous ORDER BY15469**   0x00001000     LEFT JOIN simplifies to JOIN15470**   0x00002000     Constant propagation15471**   0x00004000     Push-down optimization15472**   0x00008000     After all FROM-clause analysis15473**   0x00010000     Beginning of DELETE/INSERT/UPDATE processing15474**   0x00020000     Transform DISTINCT into GROUP BY15475**   0x00040000     SELECT tree dump after all code has been generated15476**   0x00080000     NOT NULL strength reduction15477*/1547815479/*15480** Macros for "wheretrace"15481*/15482SQLITE_PRIVATE u32 sqlite3WhereTrace;15483#if defined(SQLITE_DEBUG) \15484    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))15485# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X15486# define WHERETRACE_ENABLED 115487#else15488# define WHERETRACE(K,X)15489#endif1549015491/*15492** Bits for the sqlite3WhereTrace mask:15493**15494** (---any--)   Top-level block structure15495** 0x-------F   High-level debug messages15496** 0x----FFF-   More detail15497** 0xFFFF----   Low-level debug messages15498**15499** 0x00000001   Code generation15500** 0x00000002   Solver (Use 0x40000 for less detail)15501** 0x00000004   Solver costs15502** 0x00000008   WhereLoop inserts15503**15504** 0x00000010   Display sqlite3_index_info xBestIndex calls15505** 0x00000020   Range an equality scan metrics15506** 0x00000040   IN operator decisions15507** 0x00000080   WhereLoop cost adjustments15508** 0x0000010015509** 0x00000200   Covering index decisions15510** 0x00000400   OR optimization15511** 0x00000800   Index scanner15512** 0x00001000   More details associated with code generation15513** 0x0000200015514** 0x00004000   Show all WHERE terms at key points15515** 0x00008000   Show the full SELECT statement at key places15516**15517** 0x00010000   Show more detail when printing WHERE terms15518** 0x00020000   Show WHERE terms returned from whereScanNext()15519** 0x00040000   Solver overview messages15520** 0x00080000   Star-query heuristic15521*/155221552315524/*15525** An instance of the following structure is used to store the busy-handler15526** callback for a given sqlite handle.15527**15528** The sqlite.busyHandler member of the sqlite struct contains the busy15529** callback for the database handle. Each pager opened via the sqlite15530** handle is passed a pointer to sqlite.busyHandler. The busy-handler15531** callback is currently invoked only from within pager.c.15532*/15533typedef struct BusyHandler BusyHandler;15534struct BusyHandler {15535  int (*xBusyHandler)(void *,int);  /* The busy callback */15536  void *pBusyArg;                   /* First arg to busy callback */15537  int nBusy;                        /* Incremented with each busy call */15538};1553915540/*15541** Name of table that holds the database schema.15542**15543** The PREFERRED names are used wherever possible.  But LEGACY is also15544** used for backwards compatibility.15545**15546**  1.  Queries can use either the PREFERRED or the LEGACY names15547**  2.  The sqlite3_set_authorizer() callback uses the LEGACY name15548**  3.  The PRAGMA table_list statement uses the PREFERRED name15549**15550** The LEGACY names are stored in the internal symbol hash table15551** in support of (2).  Names are translated using sqlite3PreferredTableName()15552** for (3).  The sqlite3FindTable() function takes care of translating15553** names for (1).15554**15555** Note that "sqlite_temp_schema" can also be called "temp.sqlite_schema".15556*/15557#define LEGACY_SCHEMA_TABLE          "sqlite_master"15558#define LEGACY_TEMP_SCHEMA_TABLE     "sqlite_temp_master"15559#define PREFERRED_SCHEMA_TABLE       "sqlite_schema"15560#define PREFERRED_TEMP_SCHEMA_TABLE  "sqlite_temp_schema"155611556215563/*15564** The root-page of the schema table.15565*/15566#define SCHEMA_ROOT    11556715568/*15569** The name of the schema table.  The name is different for TEMP.15570*/15571#define SCHEMA_TABLE(x) \15572    ((!OMIT_TEMPDB)&&(x==1)?LEGACY_TEMP_SCHEMA_TABLE:LEGACY_SCHEMA_TABLE)1557315574/*15575** A convenience macro that returns the number of elements in15576** an array.15577*/15578#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))1557915580/*15581** Determine if the argument is a power of two15582*/15583#define IsPowerOfTwo(X) (((X)&((X)-1))==0)1558415585/*15586** The following value as a destructor means to use sqlite3DbFree().15587** The sqlite3DbFree() routine requires two parameters instead of the15588** one parameter that destructors normally want.  So we have to introduce15589** this magic value that the code knows to handle differently.  Any15590** pointer will work here as long as it is distinct from SQLITE_STATIC15591** and SQLITE_TRANSIENT.15592*/15593#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3OomClear)1559415595/*15596** When SQLITE_OMIT_WSD is defined, it means that the target platform does15597** not support Writable Static Data (WSD) such as global and static variables.15598** All variables must either be on the stack or dynamically allocated from15599** the heap.  When WSD is unsupported, the variable declarations scattered15600** throughout the SQLite code must become constants instead.  The SQLITE_WSD15601** macro is used for this purpose.  And instead of referencing the variable15602** directly, we use its constant as a key to lookup the run-time allocated15603** buffer that holds real variable.  The constant is also the initializer15604** for the run-time allocated buffer.15605**15606** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL15607** macros become no-ops and have zero performance impact.15608*/15609#ifdef SQLITE_OMIT_WSD15610  #define SQLITE_WSD const15611  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))15612  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)15613SQLITE_API int sqlite3_wsd_init(int N, int J);15614SQLITE_API void *sqlite3_wsd_find(void *K, int L);15615#else15616  #define SQLITE_WSD15617  #define GLOBAL(t,v) v15618  #define sqlite3GlobalConfig sqlite3Config15619#endif1562015621/*15622** The following macros are used to suppress compiler warnings and to15623** make it clear to human readers when a function parameter is deliberately15624** left unused within the body of a function. This usually happens when15625** a function is called via a function pointer. For example the15626** implementation of an SQL aggregate step callback may not use the15627** parameter indicating the number of arguments passed to the aggregate,15628** if it knows that this is enforced elsewhere.15629**15630** When a function parameter is not used at all within the body of a function,15631** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.15632** However, these macros may also be used to suppress warnings related to15633** parameters that may or may not be used depending on compilation options.15634** For example those parameters only used in assert() statements. In these15635** cases the parameters are named as per the usual conventions.15636*/15637#define UNUSED_PARAMETER(x) (void)(x)15638#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)1563915640/*15641** Forward references to structures15642*/15643typedef struct AggInfo AggInfo;15644typedef struct AuthContext AuthContext;15645typedef struct AutoincInfo AutoincInfo;15646typedef struct Bitvec Bitvec;15647typedef struct CollSeq CollSeq;15648typedef struct Column Column;15649typedef struct Cte Cte;15650typedef struct CteUse CteUse;15651typedef struct Db Db;15652typedef struct DbClientData DbClientData;15653typedef struct DbFixer DbFixer;15654typedef struct Schema Schema;15655typedef struct Expr Expr;15656typedef struct ExprList ExprList;15657typedef struct FKey FKey;15658typedef struct FpDecode FpDecode;15659typedef struct FuncDestructor FuncDestructor;15660typedef struct FuncDef FuncDef;15661typedef struct FuncDefHash FuncDefHash;15662typedef struct IdList IdList;15663typedef struct Index Index;15664typedef struct IndexedExpr IndexedExpr;15665typedef struct IndexSample IndexSample;15666typedef struct KeyClass KeyClass;15667typedef struct KeyInfo KeyInfo;15668typedef struct Lookaside Lookaside;15669typedef struct LookasideSlot LookasideSlot;15670typedef struct Module Module;15671typedef struct NameContext NameContext;15672typedef struct OnOrUsing OnOrUsing;15673typedef struct Parse Parse;15674typedef struct ParseCleanup ParseCleanup;15675typedef struct PreUpdate PreUpdate;15676typedef struct PrintfArguments PrintfArguments;15677typedef struct RCStr RCStr;15678typedef struct RenameToken RenameToken;15679typedef struct Returning Returning;15680typedef struct RowSet RowSet;15681typedef struct Savepoint Savepoint;15682typedef struct Select Select;15683typedef struct SQLiteThread SQLiteThread;15684typedef struct SelectDest SelectDest;15685typedef struct Subquery Subquery;15686typedef struct SrcItem SrcItem;15687typedef struct SrcList SrcList;15688typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */15689typedef struct Table Table;15690typedef struct TableLock TableLock;15691typedef struct Token Token;15692typedef struct TreeView TreeView;15693typedef struct Trigger Trigger;15694typedef struct TriggerPrg TriggerPrg;15695typedef struct TriggerStep TriggerStep;15696typedef struct UnpackedRecord UnpackedRecord;15697typedef struct Upsert Upsert;15698typedef struct VTable VTable;15699typedef struct VtabCtx VtabCtx;15700typedef struct Walker Walker;15701typedef struct WhereInfo WhereInfo;15702typedef struct Window Window;15703typedef struct With With;157041570515706/*15707** The bitmask datatype defined below is used for various optimizations.15708**15709** Changing this from a 64-bit to a 32-bit type limits the number of15710** tables in a join to 32 instead of 64.  But it also reduces the size15711** of the library by 738 bytes on ix86.15712*/15713#ifdef SQLITE_BITMASK_TYPE15714  typedef SQLITE_BITMASK_TYPE Bitmask;15715#else15716  typedef u64 Bitmask;15717#endif1571815719/*15720** The number of bits in a Bitmask.  "BMS" means "BitMask Size".15721*/15722#define BMS  ((int)(sizeof(Bitmask)*8))1572315724/*15725** A bit in a Bitmask15726*/15727#define MASKBIT(n)    (((Bitmask)1)<<(n))15728#define MASKBIT64(n)  (((u64)1)<<(n))15729#define MASKBIT32(n)  (((unsigned int)1)<<(n))15730#define SMASKBIT32(n) ((n)<=31?((unsigned int)1)<<(n):0)15731#define ALLBITS       ((Bitmask)-1)15732#define TOPBIT        (((Bitmask)1)<<(BMS-1))1573315734/* A VList object records a mapping between parameters/variables/wildcards15735** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer15736** variable number associated with that parameter.  See the format description15737** on the sqlite3VListAdd() routine for more information.  A VList is really15738** just an array of integers.15739*/15740typedef int VList;1574115742/*15743** Defer sourcing vdbe.h and btree.h until after the "u8" and15744** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque15745** pointer types (i.e. FuncDef) defined above.15746*/15747/************** Include os.h in the middle of sqliteInt.h ********************/15748/************** Begin file os.h **********************************************/15749/*15750** 2001 September 1615751**15752** The author disclaims copyright to this source code.  In place of15753** a legal notice, here is a blessing:15754**15755**    May you do good and not evil.15756**    May you find forgiveness for yourself and forgive others.15757**    May you share freely, never taking more than you give.15758**15759******************************************************************************15760**15761** This header file (together with is companion C source-code file15762** "os.c") attempt to abstract the underlying operating system so that15763** the SQLite library will work on both POSIX and windows systems.15764**15765** This header file is #include-ed by sqliteInt.h and thus ends up15766** being included by every source file.15767*/15768#ifndef _SQLITE_OS_H_15769#define _SQLITE_OS_H_1577015771/*15772** Attempt to automatically detect the operating system and setup the15773** necessary pre-processor macros for it.15774*/15775/************** Include os_setup.h in the middle of os.h *********************/15776/************** Begin file os_setup.h ****************************************/15777/*15778** 2013 November 2515779**15780** The author disclaims copyright to this source code.  In place of15781** a legal notice, here is a blessing:15782**15783**    May you do good and not evil.15784**    May you find forgiveness for yourself and forgive others.15785**    May you share freely, never taking more than you give.15786**15787******************************************************************************15788**15789** This file contains pre-processor directives related to operating system15790** detection and/or setup.15791*/15792#ifndef SQLITE_OS_SETUP_H15793#define SQLITE_OS_SETUP_H1579415795/*15796** Figure out if we are dealing with Unix, Windows, or some other operating15797** system.15798**15799** After the following block of preprocess macros, all of15800**15801**    SQLITE_OS_KV15802**    SQLITE_OS_OTHER15803**    SQLITE_OS_UNIX15804**    SQLITE_OS_WIN15805**15806** will defined to either 1 or 0. One of them will be 1. The others will be 0.15807** If none of the macros are initially defined, then select either15808** SQLITE_OS_UNIX or SQLITE_OS_WIN depending on the target platform.15809**15810** If SQLITE_OS_OTHER=1 is specified at compile-time, then the application15811** must provide its own VFS implementation together with sqlite3_os_init()15812** and sqlite3_os_end() routines.15813*/15814#if !defined(SQLITE_OS_KV) && !defined(SQLITE_OS_OTHER) && \15815       !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_WIN)15816#  if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \15817          defined(__MINGW32__) || defined(__BORLANDC__)15818#    define SQLITE_OS_WIN 115819#    define SQLITE_OS_UNIX 015820#  else15821#    define SQLITE_OS_WIN 015822#    define SQLITE_OS_UNIX 115823#  endif15824#endif15825#if SQLITE_OS_OTHER+1>115826#  undef SQLITE_OS_KV15827#  define SQLITE_OS_KV 015828#  undef SQLITE_OS_UNIX15829#  define SQLITE_OS_UNIX 015830#  undef SQLITE_OS_WIN15831#  define SQLITE_OS_WIN 015832#endif15833#if SQLITE_OS_KV+1>115834#  undef SQLITE_OS_OTHER15835#  define SQLITE_OS_OTHER 015836#  undef SQLITE_OS_UNIX15837#  define SQLITE_OS_UNIX 015838#  undef SQLITE_OS_WIN15839#  define SQLITE_OS_WIN 015840#  define SQLITE_OMIT_LOAD_EXTENSION 115841#  define SQLITE_OMIT_WAL 115842#  define SQLITE_OMIT_DEPRECATED 115843#  undef SQLITE_TEMP_STORE15844#  define SQLITE_TEMP_STORE 3  /* Always use memory for temporary storage */15845#  define SQLITE_DQS 015846#  define SQLITE_OMIT_SHARED_CACHE 115847#  define SQLITE_OMIT_AUTOINIT 115848#endif15849#if SQLITE_OS_UNIX+1>115850#  undef SQLITE_OS_KV15851#  define SQLITE_OS_KV 015852#  undef SQLITE_OS_OTHER15853#  define SQLITE_OS_OTHER 015854#  undef SQLITE_OS_WIN15855#  define SQLITE_OS_WIN 015856#endif15857#if SQLITE_OS_WIN+1>115858#  undef SQLITE_OS_KV15859#  define SQLITE_OS_KV 015860#  undef SQLITE_OS_OTHER15861#  define SQLITE_OS_OTHER 015862#  undef SQLITE_OS_UNIX15863#  define SQLITE_OS_UNIX 015864#endif158651586615867#endif /* SQLITE_OS_SETUP_H */1586815869/************** End of os_setup.h ********************************************/15870/************** Continuing where we left off in os.h *************************/1587115872/* If the SET_FULLSYNC macro is not defined above, then make it15873** a no-op15874*/15875#ifndef SET_FULLSYNC15876# define SET_FULLSYNC(x,y)15877#endif1587815879/* Maximum pathname length.  Note: FILENAME_MAX defined by stdio.h15880*/15881#ifndef SQLITE_MAX_PATHLEN15882# define SQLITE_MAX_PATHLEN FILENAME_MAX15883#endif1588415885/* Maximum number of symlinks that will be resolved while trying to15886** expand a filename in xFullPathname() in the VFS.15887*/15888#ifndef SQLITE_MAX_SYMLINK15889# define SQLITE_MAX_SYMLINK 20015890#endif1589115892/*15893** The default size of a disk sector15894*/15895#ifndef SQLITE_DEFAULT_SECTOR_SIZE15896# define SQLITE_DEFAULT_SECTOR_SIZE 409615897#endif1589815899/*15900** Temporary files are named starting with this prefix followed by 16 random15901** alphanumeric characters, and no file extension. They are stored in the15902** OS's standard temporary file directory, and are deleted prior to exit.15903** If sqlite is being embedded in another program, you may wish to change the15904** prefix to reflect your program's name, so that if your program exits15905** prematurely, old temporary files can be easily identified. This can be done15906** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.15907**15908** 2006-10-31:  The default prefix used to be "sqlite_".  But then15909** Mcafee started using SQLite in their anti-virus product and it15910** started putting files with the "sqlite" name in the c:/temp folder.15911** This annoyed many windows users.  Those users would then do a15912** Google search for "sqlite", find the telephone numbers of the15913** developers and call to wake them up at night and complain.15914** For this reason, the default name prefix is changed to be "sqlite"15915** spelled backwards.  So the temp files are still identified, but15916** anybody smart enough to figure out the code is also likely smart15917** enough to know that calling the developer will not help get rid15918** of the file.15919*/15920#ifndef SQLITE_TEMP_FILE_PREFIX15921# define SQLITE_TEMP_FILE_PREFIX "etilqs_"15922#endif1592315924/*15925** The following values may be passed as the second argument to15926** sqlite3OsLock(). The various locks exhibit the following semantics:15927**15928** SHARED:    Any number of processes may hold a SHARED lock simultaneously.15929** RESERVED:  A single process may hold a RESERVED lock on a file at15930**            any time. Other processes may hold and obtain new SHARED locks.15931** PENDING:   A single process may hold a PENDING lock on a file at15932**            any one time. Existing SHARED locks may persist, but no new15933**            SHARED locks may be obtained by other processes.15934** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.15935**15936** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a15937** process that requests an EXCLUSIVE lock may actually obtain a PENDING15938** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to15939** sqlite3OsLock().15940*/15941#define NO_LOCK         015942#define SHARED_LOCK     115943#define RESERVED_LOCK   215944#define PENDING_LOCK    315945#define EXCLUSIVE_LOCK  41594615947/*15948** File Locking Notes:  (Mostly about windows but also some info for Unix)15949**15950** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because15951** those functions are not available.  So we use only LockFile() and15952** UnlockFile().15953**15954** LockFile() prevents not just writing but also reading by other processes.15955** A SHARED_LOCK is obtained by locking a single randomly-chosen15956** byte out of a specific range of bytes. The lock byte is obtained at15957** random so two separate readers can probably access the file at the15958** same time, unless they are unlucky and choose the same lock byte.15959** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.15960** There can only be one writer.  A RESERVED_LOCK is obtained by locking15961** a single byte of the file that is designated as the reserved lock byte.15962** A PENDING_LOCK is obtained by locking a designated byte different from15963** the RESERVED_LOCK byte.15964**15965** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,15966** which means we can use reader/writer locks.  When reader/writer locks15967** are used, the lock is placed on the same range of bytes that is used15968** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme15969** will support two or more Win95 readers or two or more WinNT readers.15970** But a single Win95 reader will lock out all WinNT readers and a single15971** WinNT reader will lock out all other Win95 readers.15972**15973** The following #defines specify the range of bytes used for locking.15974** SHARED_SIZE is the number of bytes available in the pool from which15975** a random byte is selected for a shared lock.  The pool of bytes for15976** shared locks begins at SHARED_FIRST.15977**15978** The same locking strategy and15979** byte ranges are used for Unix.  This leaves open the possibility of having15980** clients on win95, winNT, and unix all talking to the same shared file15981** and all locking correctly.  To do so would require that samba (or whatever15982** tool is being used for file sharing) implements locks correctly between15983** windows and unix.  I'm guessing that isn't likely to happen, but by15984** using the same locking range we are at least open to the possibility.15985**15986** Locking in windows is manditory.  For this reason, we cannot store15987** actual data in the bytes used for locking.  The pager never allocates15988** the pages involved in locking therefore.  SHARED_SIZE is selected so15989** that all locks will fit on a single page even at the minimum page size.15990** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE15991** is set high so that we don't have to allocate an unused page except15992** for very large databases.  But one should test the page skipping logic15993** by setting PENDING_BYTE low and running the entire regression suite.15994**15995** Changing the value of PENDING_BYTE results in a subtly incompatible15996** file format.  Depending on how it is changed, you might not notice15997** the incompatibility right away, even running a full regression test.15998** The default location of PENDING_BYTE is the first byte past the15999** 1GB boundary.16000**16001*/16002#ifdef SQLITE_OMIT_WSD16003# define PENDING_BYTE     (0x40000000)16004#else16005# define PENDING_BYTE      sqlite3PendingByte16006#endif16007#define RESERVED_BYTE     (PENDING_BYTE+1)16008#define SHARED_FIRST      (PENDING_BYTE+2)16009#define SHARED_SIZE       5101601016011/*16012** Wrapper around OS specific sqlite3_os_init() function.16013*/16014SQLITE_PRIVATE int sqlite3OsInit(void);1601516016/*16017** Functions for accessing sqlite3_file methods16018*/16019SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);16020SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);16021SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);16022SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);16023SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);16024SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);16025SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);16026SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);16027SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);16028SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);16029SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);16030#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa016031SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);16032SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);16033#ifndef SQLITE_OMIT_WAL16034SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);16035SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);16036SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);16037SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);16038#endif /* SQLITE_OMIT_WAL */16039SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);16040SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);160411604216043/*16044** Functions for accessing sqlite3_vfs methods16045*/16046SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);16047SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);16048SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);16049SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);16050#ifndef SQLITE_OMIT_LOAD_EXTENSION16051SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);16052SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);16053SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);16054SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);16055#endif /* SQLITE_OMIT_LOAD_EXTENSION */16056SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);16057SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);16058SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);16059SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);1606016061/*16062** Convenience functions for opening and closing files using16063** sqlite3_malloc() to obtain space for the file-handle structure.16064*/16065SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);16066SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);1606716068#endif /* _SQLITE_OS_H_ */1606916070/************** End of os.h **************************************************/16071/************** Continuing where we left off in sqliteInt.h ******************/16072/************** Include pager.h in the middle of sqliteInt.h *****************/16073/************** Begin file pager.h *******************************************/16074/*16075** 2001 September 1516076**16077** The author disclaims copyright to this source code.  In place of16078** a legal notice, here is a blessing:16079**16080**    May you do good and not evil.16081**    May you find forgiveness for yourself and forgive others.16082**    May you share freely, never taking more than you give.16083**16084*************************************************************************16085** This header file defines the interface that the sqlite page cache16086** subsystem.  The page cache subsystem reads and writes a file a page16087** at a time and provides a journal for rollback.16088*/1608916090#ifndef SQLITE_PAGER_H16091#define SQLITE_PAGER_H1609216093/*16094** Default maximum size for persistent journal files. A negative16095** value means no limit. This value may be overridden using the16096** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".16097*/16098#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT16099  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -116100#endif1610116102/*16103** The type used to represent a page number.  The first page in a file16104** is called page 1.  0 is used to represent "not a page".16105*/16106typedef u32 Pgno;1610716108/*16109** Each open file is managed by a separate instance of the "Pager" structure.16110*/16111typedef struct Pager Pager;1611216113/*16114** Handle type for pages.16115*/16116typedef struct PgHdr DbPage;1611716118/*16119** Page number PAGER_SJ_PGNO is never used in an SQLite database (it is16120** reserved for working around a windows/posix incompatibility). It is16121** used in the journal to signify that the remainder of the journal file16122** is devoted to storing a super-journal name - there are no more pages to16123** roll back. See comments for function writeSuperJournal() in pager.c16124** for details.16125*/16126#define PAGER_SJ_PGNO_COMPUTED(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))16127#define PAGER_SJ_PGNO(x)          ((x)->lckPgno)1612816129/*16130** Allowed values for the flags parameter to sqlite3PagerOpen().16131**16132** NOTE: These values must match the corresponding BTREE_ values in btree.h.16133*/16134#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */16135#define PAGER_MEMORY        0x0002    /* In-memory database */1613616137/*16138** Valid values for the second argument to sqlite3PagerLockingMode().16139*/16140#define PAGER_LOCKINGMODE_QUERY      -116141#define PAGER_LOCKINGMODE_NORMAL      016142#define PAGER_LOCKINGMODE_EXCLUSIVE   11614316144/*16145** Numeric constants that encode the journalmode.16146**16147** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)16148** are exposed in the API via the "PRAGMA journal_mode" command and16149** therefore cannot be changed without a compatibility break.16150*/16151#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */16152#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */16153#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */16154#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */16155#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */16156#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */16157#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */1615816159#define isWalMode(x) ((x)==PAGER_JOURNALMODE_WAL)1616016161/*16162** The argument to this macro is a file descriptor (type sqlite3_file*).16163** Return 0 if it is not open, or non-zero (but not 1) if it is.16164**16165** This is so that expressions can be written as:16166**16167**   if( isOpen(pPager->jfd) ){ ...16168**16169** instead of16170**16171**   if( pPager->jfd->pMethods ){ ...16172*/16173#define isOpen(pFd) ((pFd)->pMethods!=0)1617416175/*16176** Flags that make up the mask passed to sqlite3PagerGet().16177*/16178#define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */16179#define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */1618016181/*16182** Flags for sqlite3PagerSetFlags()16183**16184** Value constraints (enforced via assert()):16185**    PAGER_FULLFSYNC      == SQLITE_FullFSync16186**    PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync16187**    PAGER_CACHE_SPILL    == SQLITE_CacheSpill16188*/16189#define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */16190#define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */16191#define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */16192#define PAGER_SYNCHRONOUS_EXTRA     0x04  /* PRAGMA synchronous=EXTRA */16193#define PAGER_SYNCHRONOUS_MASK      0x07  /* Mask for four values above */16194#define PAGER_FULLFSYNC             0x08  /* PRAGMA fullfsync=ON */16195#define PAGER_CKPT_FULLFSYNC        0x10  /* PRAGMA checkpoint_fullfsync=ON */16196#define PAGER_CACHESPILL            0x20  /* PRAGMA cache_spill=ON */16197#define PAGER_FLAGS_MASK            0x38  /* All above except SYNCHRONOUS */1619816199/*16200** The remainder of this file contains the declarations of the functions16201** that make up the Pager sub-system API. See source code comments for16202** a detailed description of each routine.16203*/1620416205/* Open and close a Pager connection. */16206SQLITE_PRIVATE int sqlite3PagerOpen(16207  sqlite3_vfs*,16208  Pager **ppPager,16209  const char*,16210  int,16211  int,16212  int,16213  void(*)(DbPage*)16214);16215SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);16216SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);1621716218/* Functions used to configure a Pager object. */16219SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);16220SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);16221SQLITE_PRIVATE Pgno sqlite3PagerMaxPageCount(Pager*, Pgno);16222SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);16223SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);16224SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);16225SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);16226SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);16227SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);16228SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);16229SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);16230SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);16231SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);16232SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);16233SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);1623416235/* Functions used to obtain and release page references. */16236SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);16237SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);16238SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);16239SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);16240SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);16241SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);1624216243/* Operations on page references. */16244SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);16245SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);16246SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);16247SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);16248SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);16249SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);1625016251/* Functions used to manage pager transactions and savepoints. */16252SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);16253SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);16254SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zSuper, int);16255SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);16256SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zSuper);16257SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);16258SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);16259SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);16260SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);16261SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);1626216263#ifndef SQLITE_OMIT_WAL16264SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);16265SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);16266SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);16267SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);16268SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);16269# ifdef SQLITE_ENABLE_SNAPSHOT16270SQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager*, sqlite3_snapshot **ppSnapshot);16271SQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager*, sqlite3_snapshot *pSnapshot);16272SQLITE_PRIVATE   int sqlite3PagerSnapshotRecover(Pager *pPager);16273SQLITE_PRIVATE   int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);16274SQLITE_PRIVATE   void sqlite3PagerSnapshotUnlock(Pager *pPager);16275# endif16276#endif1627716278#if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_ENABLE_SETLK_TIMEOUT)16279SQLITE_PRIVATE   int sqlite3PagerWalWriteLock(Pager*, int);16280SQLITE_PRIVATE   void sqlite3PagerWalDb(Pager*, sqlite3*);16281#else16282# define sqlite3PagerWalWriteLock(y,z) SQLITE_OK16283# define sqlite3PagerWalDb(x,y)16284#endif1628516286#ifdef SQLITE_DIRECT_OVERFLOW_READ16287SQLITE_PRIVATE   int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);16288#endif1628916290#ifdef SQLITE_ENABLE_ZIPVFS16291SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);16292#endif1629316294/* Functions used to query pager state and configuration. */16295SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);16296SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);16297#ifdef SQLITE_DEBUG16298SQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);16299#endif16300SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);16301SQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager*, int);16302SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);16303SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);16304SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);16305SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);16306SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);16307SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);16308SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, u64*);16309SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);16310SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);1631116312/* Functions used to truncate the database file. */16313SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);1631416315SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);1631616317/* Functions to support testing and debugging. */16318#if !defined(NDEBUG) || defined(SQLITE_TEST)16319SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);16320SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);16321#endif16322#ifdef SQLITE_TEST16323SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);16324SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);16325  void disable_simulated_io_errors(void);16326  void enable_simulated_io_errors(void);16327#else16328# define disable_simulated_io_errors()16329# define enable_simulated_io_errors()16330#endif1633116332#if defined(SQLITE_USE_SEH) && !defined(SQLITE_OMIT_WAL)16333SQLITE_PRIVATE int sqlite3PagerWalSystemErrno(Pager*);16334#endif1633516336#endif /* SQLITE_PAGER_H */1633716338/************** End of pager.h ***********************************************/16339/************** Continuing where we left off in sqliteInt.h ******************/16340/************** Include btree.h in the middle of sqliteInt.h *****************/16341/************** Begin file btree.h *******************************************/16342/*16343** 2001 September 1516344**16345** The author disclaims copyright to this source code.  In place of16346** a legal notice, here is a blessing:16347**16348**    May you do good and not evil.16349**    May you find forgiveness for yourself and forgive others.16350**    May you share freely, never taking more than you give.16351**16352*************************************************************************16353** This header file defines the interface that the sqlite B-Tree file16354** subsystem.  See comments in the source code for a detailed description16355** of what each interface routine does.16356*/16357#ifndef SQLITE_BTREE_H16358#define SQLITE_BTREE_H1635916360/* TODO: This definition is just included so other modules compile. It16361** needs to be revisited.16362*/16363#define SQLITE_N_BTREE_META 161636416365/*16366** If defined as non-zero, auto-vacuum is enabled by default. Otherwise16367** it must be turned on for each database using "PRAGMA auto_vacuum = 1".16368*/16369#ifndef SQLITE_DEFAULT_AUTOVACUUM16370  #define SQLITE_DEFAULT_AUTOVACUUM 016371#endif1637216373#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */16374#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */16375#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */1637616377/*16378** Forward declarations of structure16379*/16380typedef struct Btree Btree;16381typedef struct BtCursor BtCursor;16382typedef struct BtShared BtShared;16383typedef struct BtreePayload BtreePayload;163841638516386SQLITE_PRIVATE int sqlite3BtreeOpen(16387  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */16388  const char *zFilename,   /* Name of database file to open */16389  sqlite3 *db,             /* Associated database connection */16390  Btree **ppBtree,         /* Return open Btree* here */16391  int flags,               /* Flags */16392  int vfsFlags             /* Flags passed through to VFS open */16393);1639416395/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the16396** following values.16397**16398** NOTE:  These values must match the corresponding PAGER_ values in16399** pager.h.16400*/16401#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */16402#define BTREE_MEMORY        2  /* This is an in-memory DB */16403#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */16404#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */1640516406SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);16407SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);16408SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);16409#if SQLITE_MAX_MMAP_SIZE>016410SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);16411#endif16412SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);16413SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);16414SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);16415SQLITE_PRIVATE Pgno sqlite3BtreeMaxPageCount(Btree*,Pgno);16416SQLITE_PRIVATE Pgno sqlite3BtreeLastPage(Btree*);16417SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);16418SQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree*);16419SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);16420SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);16421SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);16422SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int,int*);16423SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char*);16424SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);16425SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);16426SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);16427SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);16428SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, Pgno*, int flags);16429SQLITE_PRIVATE int sqlite3BtreeTxnState(Btree*);16430SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);1643116432SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));16433SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);16434#ifndef SQLITE_OMIT_SHARED_CACHE16435SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);16436#endif1643716438/* Savepoints are named, nestable SQL transactions mostly implemented */16439/* in vdbe.c and pager.c See https://sqlite.org/lang_savepoint.html */16440SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);1644116442/* "Checkpoint" only refers to WAL. See https://sqlite.org/wal.html#ckpt */16443#ifndef SQLITE_OMIT_WAL16444SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);16445#endif1644616447SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);16448SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);16449SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);1645016451SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);1645216453/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR16454** of the flags shown below.16455**16456** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.16457** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data16458** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With16459** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored16460** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL16461** indices.)16462*/16463#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */16464#define BTREE_BLOBKEY    2    /* Table has keys only - no data */1646516466SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);16467SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, i64*);16468SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);16469SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);1647016471SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);16472SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);1647316474SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);1647516476/*16477** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta16478** should be one of the following values. The integer values are assigned16479** to constants so that the offset of the corresponding field in an16480** SQLite database header may be found using the following formula:16481**16482**   offset = 36 + (idx * 4)16483**16484** For example, the free-page-count field is located at byte offset 36 of16485** the database file header. The incr-vacuum-flag field is located at16486** byte offset 64 (== 36+4*7).16487**16488** The BTREE_DATA_VERSION value is not really a value stored in the header.16489** It is a read-only number computed by the pager.  But we merge it with16490** the header value access routines since its access pattern is the same.16491** Call it a "virtual meta value".16492*/16493#define BTREE_FREE_PAGE_COUNT     016494#define BTREE_SCHEMA_VERSION      116495#define BTREE_FILE_FORMAT         216496#define BTREE_DEFAULT_CACHE_SIZE  316497#define BTREE_LARGEST_ROOT_PAGE   416498#define BTREE_TEXT_ENCODING       516499#define BTREE_USER_VERSION        616500#define BTREE_INCR_VACUUM         716501#define BTREE_APPLICATION_ID      816502#define BTREE_DATA_VERSION        15  /* A virtual meta-value */1650316504/*16505** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()16506** interface.16507**16508** BTREE_HINT_RANGE  (arguments: Expr*, Mem*)16509**16510**     The first argument is an Expr* (which is guaranteed to be constant for16511**     the lifetime of the cursor) that defines constraints on which rows16512**     might be fetched with this cursor.  The Expr* tree may contain16513**     TK_REGISTER nodes that refer to values stored in the array of registers16514**     passed as the second parameter.  In other words, if Expr.op==TK_REGISTER16515**     then the value of the node is the value in Mem[pExpr.iTable].  Any16516**     TK_COLUMN node in the expression tree refers to the Expr.iColumn-th16517**     column of the b-tree of the cursor.  The Expr tree will not contain16518**     any function calls nor subqueries nor references to b-trees other than16519**     the cursor being hinted.16520**16521**     The design of the _RANGE hint is aid b-tree implementations that try16522**     to prefetch content from remote machines - to provide those16523**     implementations with limits on what needs to be prefetched and thereby16524**     reduce network bandwidth.16525**16526** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by16527** standard SQLite.  The other hints are provided for extensions that use16528** the SQLite parser and code generator but substitute their own storage16529** engine.16530*/16531#define BTREE_HINT_RANGE 0       /* Range constraints on queries */1653216533/*16534** Values that may be OR'd together to form the argument to the16535** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():16536**16537** The BTREE_BULKLOAD flag is set on index cursors when the index is going16538** to be filled with content that is already in sorted order.16539**16540** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or16541** OP_SeekLE opcodes for a range search, but where the range of entries16542** selected will all have the same key.  In other words, the cursor will16543** be used only for equality key searches.16544**16545*/16546#define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */16547#define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */1654816549/*16550** Flags passed as the third argument to sqlite3BtreeCursor().16551**16552** For read-only cursors the wrFlag argument is always zero. For read-write16553** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just16554** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will16555** only be used by SQLite for the following:16556**16557**   * to seek to and then delete specific entries, and/or16558**16559**   * to read values that will be used to create keys that other16560**     BTREE_FORDELETE cursors will seek to and delete.16561**16562** The BTREE_FORDELETE flag is an optimization hint.  It is not used by16563** by this, the native b-tree engine of SQLite, but it is available to16564** alternative storage engines that might be substituted in place of this16565** b-tree system.  For alternative storage engines in which a delete of16566** the main table row automatically deletes corresponding index rows,16567** the FORDELETE flag hint allows those alternative storage engines to16568** skip a lot of work.  Namely:  FORDELETE cursors may treat all SEEK16569** and DELETE operations as no-ops, and any READ operation against a16570** FORDELETE cursor may return a null row: 0x01 0x00.16571*/16572#define BTREE_WRCSR     0x00000004     /* read-write cursor */16573#define BTREE_FORDELETE 0x00000008     /* Cursor is for seek/delete only */1657416575SQLITE_PRIVATE int sqlite3BtreeCursor(16576  Btree*,                              /* BTree containing table to open */16577  Pgno iTable,                         /* Index of root page */16578  int wrFlag,                          /* 1 for writing.  0 for read-only */16579  struct KeyInfo*,                     /* First argument to compare function */16580  BtCursor *pCursor                    /* Space to write cursor structure */16581);16582SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);16583SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);16584#ifdef SQLITE_DEBUG16585SQLITE_PRIVATE int sqlite3BtreeClosesWithCursor(Btree*,BtCursor*);16586#endif16587SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);16588SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);16589#ifdef SQLITE_ENABLE_CURSOR_HINTS16590SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);16591#endif1659216593SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);16594SQLITE_PRIVATE int sqlite3BtreeTableMoveto(16595  BtCursor*,16596  i64 intKey,16597  int bias,16598  int *pRes16599);16600SQLITE_PRIVATE int sqlite3BtreeIndexMoveto(16601  BtCursor*,16602  UnpackedRecord *pUnKey,16603  int *pRes16604);16605SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);16606SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);16607SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);1660816609/* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */16610#define BTREE_SAVEPOSITION 0x02  /* Leave cursor pointing at NEXT or PREV */16611#define BTREE_AUXDELETE    0x04  /* not the primary delete operation */16612#define BTREE_APPEND       0x08  /* Insert is likely an append */16613#define BTREE_PREFORMAT    0x80  /* Inserted data is a preformated cell */1661416615/* An instance of the BtreePayload object describes the content of a single16616** entry in either an index or table btree.16617**16618** Index btrees (used for indexes and also WITHOUT ROWID tables) contain16619** an arbitrary key and no data.  These btrees have pKey,nKey set to the16620** key and the pData,nData,nZero fields are uninitialized.  The aMem,nMem16621** fields give an array of Mem objects that are a decomposition of the key.16622** The nMem field might be zero, indicating that no decomposition is available.16623**16624** Table btrees (used for rowid tables) contain an integer rowid used as16625** the key and passed in the nKey field.  The pKey field is zero.16626** pData,nData hold the content of the new entry.  nZero extra zero bytes16627** are appended to the end of the content when constructing the entry.16628** The aMem,nMem fields are uninitialized for table btrees.16629**16630** Field usage summary:16631**16632**               Table BTrees                   Index Btrees16633**16634**   pKey        always NULL                    encoded key16635**   nKey        the ROWID                      length of pKey16636**   pData       data                           not used16637**   aMem        not used                       decomposed key value16638**   nMem        not used                       entries in aMem16639**   nData       length of pData                not used16640**   nZero       extra zeros after pData        not used16641**16642** This object is used to pass information into sqlite3BtreeInsert().  The16643** same information used to be passed as five separate parameters.  But placing16644** the information into this object helps to keep the interface more16645** organized and understandable, and it also helps the resulting code to16646** run a little faster by using fewer registers for parameter passing.16647*/16648struct BtreePayload {16649  const void *pKey;       /* Key content for indexes.  NULL for tables */16650  sqlite3_int64 nKey;     /* Size of pKey for indexes.  PRIMARY KEY for tabs */16651  const void *pData;      /* Data for tables. */16652  sqlite3_value *aMem;    /* First of nMem value in the unpacked pKey */16653  u16 nMem;               /* Number of aMem[] value.  Might be zero */16654  int nData;              /* Size of pData.  0 if none. */16655  int nZero;              /* Extra zero data appended after pData,nData */16656};1665716658SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,16659                       int flags, int seekResult);16660SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);16661SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);16662SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);16663SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);16664SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);16665SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);16666SQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor*);16667SQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor*);16668SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);16669SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);16670SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);16671SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);16672SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*);1667316674SQLITE_PRIVATE int sqlite3BtreeIntegrityCheck(16675  sqlite3 *db,  /* Database connection that is running the check */16676  Btree *p,     /* The btree to be checked */16677  Pgno *aRoot,  /* An array of root pages numbers for individual trees */16678  sqlite3_value *aCnt,  /* OUT: entry counts for each btree in aRoot[] */16679  int nRoot,    /* Number of entries in aRoot[] */16680  int mxErr,    /* Stop reporting errors after this many */16681  int *pnErr,   /* OUT: Write number of errors seen to this variable */16682  char **pzOut  /* OUT: Write the error message string here */16683);16684SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);16685SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);1668616687#ifndef SQLITE_OMIT_INCRBLOB16688SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);16689SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);16690SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);16691#endif16692SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);16693SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);16694SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);16695SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);16696SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);1669716698#ifdef SQLITE_DEBUG16699SQLITE_PRIVATE sqlite3_uint64 sqlite3BtreeSeekCount(Btree*);16700#else16701# define sqlite3BtreeSeekCount(X) 016702#endif1670316704#ifndef NDEBUG16705SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);16706#endif16707SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);1670816709SQLITE_PRIVATE int sqlite3BtreeCount(sqlite3*, BtCursor*, i64*);1671016711#ifdef SQLITE_TEST16712SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);16713SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);16714#endif1671516716#ifndef SQLITE_OMIT_WAL16717SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);16718#endif1671916720SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor*, BtCursor*, i64);1672116722SQLITE_PRIVATE void sqlite3BtreeClearCache(Btree*);1672316724/*16725** If we are not using shared cache, then there is no need to16726** use mutexes to access the BtShared structures.  So make the16727** Enter and Leave procedures no-ops.16728*/16729#ifndef SQLITE_OMIT_SHARED_CACHE16730SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);16731SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);16732SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);16733SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);16734SQLITE_PRIVATE   int sqlite3BtreeConnectionCount(Btree*);16735#else16736# define sqlite3BtreeEnter(X)16737# define sqlite3BtreeEnterAll(X)16738# define sqlite3BtreeSharable(X) 016739# define sqlite3BtreeEnterCursor(X)16740# define sqlite3BtreeConnectionCount(X) 116741#endif1674216743#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE16744SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);16745SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);16746SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);16747#ifndef NDEBUG16748  /* These routines are used inside assert() statements only. */16749SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);16750SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);16751SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);16752#endif16753#else1675416755# define sqlite3BtreeLeave(X)16756# define sqlite3BtreeLeaveCursor(X)16757# define sqlite3BtreeLeaveAll(X)1675816759# define sqlite3BtreeHoldsMutex(X) 116760# define sqlite3BtreeHoldsAllMutexes(X) 116761# define sqlite3SchemaMutexHeld(X,Y,Z) 116762#endif167631676416765#endif /* SQLITE_BTREE_H */1676616767/************** End of btree.h ***********************************************/16768/************** Continuing where we left off in sqliteInt.h ******************/16769/************** Include vdbe.h in the middle of sqliteInt.h ******************/16770/************** Begin file vdbe.h ********************************************/16771/*16772** 2001 September 1516773**16774** The author disclaims copyright to this source code.  In place of16775** a legal notice, here is a blessing:16776**16777**    May you do good and not evil.16778**    May you find forgiveness for yourself and forgive others.16779**    May you share freely, never taking more than you give.16780**16781*************************************************************************16782** Header file for the Virtual DataBase Engine (VDBE)16783**16784** This header defines the interface to the virtual database engine16785** or VDBE.  The VDBE implements an abstract machine that runs a16786** simple program to access and modify the underlying database.16787*/16788#ifndef SQLITE_VDBE_H16789#define SQLITE_VDBE_H16790/* #include <stdio.h> */1679116792/*16793** A single VDBE is an opaque structure named "Vdbe".  Only routines16794** in the source file sqliteVdbe.c are allowed to see the insides16795** of this structure.16796*/16797typedef struct Vdbe Vdbe;1679816799/*16800** The names of the following types declared in vdbeInt.h are required16801** for the VdbeOp definition.16802*/16803typedef struct sqlite3_value Mem;16804typedef struct SubProgram SubProgram;16805typedef struct SubrtnSig SubrtnSig;1680616807/*16808** A signature for a reusable subroutine that materializes the RHS of16809** an IN operator.16810*/16811struct SubrtnSig {16812  int selId;          /* SELECT-id for the SELECT statement on the RHS */16813  u8 bComplete;       /* True if fully coded and available for reusable */16814  char *zAff;         /* Affinity of the overall IN expression */16815  int iTable;         /* Ephemeral table generated by the subroutine */16816  int iAddr;          /* Subroutine entry address */16817  int regReturn;      /* Register used to hold return address */16818};1681916820/*16821** A single instruction of the virtual machine has an opcode16822** and as many as three operands.  The instruction is recorded16823** as an instance of the following structure:16824*/16825struct VdbeOp {16826  u8 opcode;          /* What operation to perform */16827  signed char p4type; /* One of the P4_xxx constants for p4 */16828  u16 p5;             /* Fifth parameter is an unsigned 16-bit integer */16829  int p1;             /* First operand */16830  int p2;             /* Second parameter (often the jump destination) */16831  int p3;             /* The third parameter */16832  union p4union {     /* fourth parameter */16833    int i;                 /* Integer value if p4type==P4_INT32 */16834    void *p;               /* Generic pointer */16835    char *z;               /* Pointer to data for string (char array) types */16836    i64 *pI64;             /* Used when p4type is P4_INT64 */16837    double *pReal;         /* Used when p4type is P4_REAL */16838    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */16839    sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */16840    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */16841    Mem *pMem;             /* Used when p4type is P4_MEM */16842    VTable *pVtab;         /* Used when p4type is P4_VTAB */16843    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */16844    u32 *ai;               /* Used when p4type is P4_INTARRAY */16845    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */16846    Table *pTab;           /* Used when p4type is P4_TABLE */16847    SubrtnSig *pSubrtnSig; /* Used when p4type is P4_SUBRTNSIG */16848#ifdef SQLITE_ENABLE_CURSOR_HINTS16849    Expr *pExpr;           /* Used when p4type is P4_EXPR */16850#endif16851  } p4;16852#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS16853  char *zComment;          /* Comment to improve readability */16854#endif16855#ifdef SQLITE_VDBE_COVERAGE16856  u32 iSrcLine;            /* Source-code line that generated this opcode16857                           ** with flags in the upper 8 bits */16858#endif16859#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)16860  u64 nExec;16861  u64 nCycle;16862#endif16863};16864typedef struct VdbeOp VdbeOp;168651686616867/*16868** A sub-routine used to implement a trigger program.16869*/16870struct SubProgram {16871  VdbeOp *aOp;                  /* Array of opcodes for sub-program */16872  int nOp;                      /* Elements in aOp[] */16873  int nMem;                     /* Number of memory cells required */16874  int nCsr;                     /* Number of cursors required */16875  u8 *aOnce;                    /* Array of OP_Once flags */16876  void *token;                  /* id that may be used to recursive triggers */16877  SubProgram *pNext;            /* Next sub-program already visited */16878};1687916880/*16881** A smaller version of VdbeOp used for the VdbeAddOpList() function because16882** it takes up less space.16883*/16884struct VdbeOpList {16885  u8 opcode;          /* What operation to perform */16886  signed char p1;     /* First operand */16887  signed char p2;     /* Second parameter (often the jump destination) */16888  signed char p3;     /* Third parameter */16889};16890typedef struct VdbeOpList VdbeOpList;1689116892/*16893** Allowed values of VdbeOp.p4type16894*/16895#define P4_NOTUSED      0   /* The P4 parameter is not used */16896#define P4_TRANSIENT    0   /* P4 is a pointer to a transient string */16897#define P4_STATIC     (-1)  /* Pointer to a static string */16898#define P4_COLLSEQ    (-2)  /* P4 is a pointer to a CollSeq structure */16899#define P4_INT32      (-3)  /* P4 is a 32-bit signed integer */16900#define P4_SUBPROGRAM (-4)  /* P4 is a pointer to a SubProgram structure */16901#define P4_TABLE      (-5)  /* P4 is a pointer to a Table structure */16902/* Above do not own any resources.  Must free those below */16903#define P4_FREE_IF_LE (-6)16904#define P4_DYNAMIC    (-6)  /* Pointer to memory from sqliteMalloc() */16905#define P4_FUNCDEF    (-7)  /* P4 is a pointer to a FuncDef structure */16906#define P4_KEYINFO    (-8)  /* P4 is a pointer to a KeyInfo structure */16907#define P4_EXPR       (-9) /* P4 is a pointer to an Expr tree */16908#define P4_MEM        (-10) /* P4 is a pointer to a Mem*    structure */16909#define P4_VTAB       (-11) /* P4 is a pointer to an sqlite3_vtab structure */16910#define P4_REAL       (-12) /* P4 is a 64-bit floating point value */16911#define P4_INT64      (-13) /* P4 is a 64-bit signed integer */16912#define P4_INTARRAY   (-14) /* P4 is a vector of 32-bit integers */16913#define P4_FUNCCTX    (-15) /* P4 is a pointer to an sqlite3_context object */16914#define P4_TABLEREF   (-16) /* Like P4_TABLE, but reference counted */16915#define P4_SUBRTNSIG  (-17) /* P4 is a SubrtnSig pointer */1691616917/* Error message codes for OP_Halt */16918#define P5_ConstraintNotNull 116919#define P5_ConstraintUnique  216920#define P5_ConstraintCheck   316921#define P5_ConstraintFK      41692216923/*16924** The Vdbe.aColName array contains 5n Mem structures, where n is the16925** number of columns of data returned by the statement.16926*/16927#define COLNAME_NAME     016928#define COLNAME_DECLTYPE 116929#define COLNAME_DATABASE 216930#define COLNAME_TABLE    316931#define COLNAME_COLUMN   416932#ifdef SQLITE_ENABLE_COLUMN_METADATA16933# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */16934#else16935# ifdef SQLITE_OMIT_DECLTYPE16936#   define COLNAME_N      1      /* Store only the name */16937# else16938#   define COLNAME_N      2      /* Store the name and decltype */16939# endif16940#endif1694116942/*16943** The following macro converts a label returned by sqlite3VdbeMakeLabel()16944** into an index into the Parse.aLabel[] array that contains the resolved16945** address of that label.16946*/16947#define ADDR(X)  (~(X))1694816949/*16950** The makefile scans the vdbe.c source file and creates the "opcodes.h"16951** header file that defines a number for each opcode used by the VDBE.16952*/16953/************** Include opcodes.h in the middle of vdbe.h ********************/16954/************** Begin file opcodes.h *****************************************/16955/* Automatically generated.  Do not edit */16956/* See the tool/mkopcodeh.tcl script for details */16957#define OP_Savepoint       016958#define OP_AutoCommit      116959#define OP_Transaction     216960#define OP_Checkpoint      316961#define OP_JournalMode     416962#define OP_Vacuum          516963#define OP_VFilter         6 /* jump, synopsis: iplan=r[P3] zplan='P4'     */16964#define OP_VUpdate         7 /* synopsis: data=r[P3@P2]                    */16965#define OP_Init            8 /* jump0, synopsis: Start at P2               */16966#define OP_Goto            9 /* jump                                       */16967#define OP_Gosub          10 /* jump                                       */16968#define OP_InitCoroutine  11 /* jump0                                      */16969#define OP_Yield          12 /* jump0                                      */16970#define OP_MustBeInt      13 /* jump0                                      */16971#define OP_Jump           14 /* jump                                       */16972#define OP_Once           15 /* jump                                       */16973#define OP_If             16 /* jump                                       */16974#define OP_IfNot          17 /* jump                                       */16975#define OP_IsType         18 /* jump, synopsis: if typeof(P1.P3) in P5 goto P2 */16976#define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */16977#define OP_IfNullRow      20 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */16978#define OP_SeekLT         21 /* jump0, synopsis: key=r[P3@P4]              */16979#define OP_SeekLE         22 /* jump0, synopsis: key=r[P3@P4]              */16980#define OP_SeekGE         23 /* jump0, synopsis: key=r[P3@P4]              */16981#define OP_SeekGT         24 /* jump0, synopsis: key=r[P3@P4]              */16982#define OP_IfNotOpen      25 /* jump, synopsis: if( !csr[P1] ) goto P2     */16983#define OP_IfNoHope       26 /* jump, synopsis: key=r[P3@P4]               */16984#define OP_NoConflict     27 /* jump, synopsis: key=r[P3@P4]               */16985#define OP_NotFound       28 /* jump, synopsis: key=r[P3@P4]               */16986#define OP_Found          29 /* jump, synopsis: key=r[P3@P4]               */16987#define OP_SeekRowid      30 /* jump0, synopsis: intkey=r[P3]              */16988#define OP_NotExists      31 /* jump, synopsis: intkey=r[P3]               */16989#define OP_Last           32 /* jump0                                      */16990#define OP_IfSizeBetween  33 /* jump                                       */16991#define OP_SorterSort     34 /* jump                                       */16992#define OP_Sort           35 /* jump                                       */16993#define OP_Rewind         36 /* jump0                                      */16994#define OP_SorterNext     37 /* jump                                       */16995#define OP_Prev           38 /* jump                                       */16996#define OP_Next           39 /* jump                                       */16997#define OP_IdxLE          40 /* jump, synopsis: key=r[P3@P4]               */16998#define OP_IdxGT          41 /* jump, synopsis: key=r[P3@P4]               */16999#define OP_IdxLT          42 /* jump, synopsis: key=r[P3@P4]               */17000#define OP_Or             43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */17001#define OP_And            44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */17002#define OP_IdxGE          45 /* jump, synopsis: key=r[P3@P4]               */17003#define OP_RowSetRead     46 /* jump, synopsis: r[P3]=rowset(P1)           */17004#define OP_RowSetTest     47 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */17005#define OP_Program        48 /* jump0                                      */17006#define OP_FkIfZero       49 /* jump, synopsis: if fkctr[P1]==0 goto P2    */17007#define OP_IfPos          50 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */17008#define OP_IsNull         51 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */17009#define OP_NotNull        52 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */17010#define OP_Ne             53 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */17011#define OP_Eq             54 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */17012#define OP_Gt             55 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */17013#define OP_Le             56 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */17014#define OP_Lt             57 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */17015#define OP_Ge             58 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */17016#define OP_ElseEq         59 /* jump, same as TK_ESCAPE                    */17017#define OP_IfNotZero      60 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */17018#define OP_DecrJumpZero   61 /* jump, synopsis: if (--r[P1])==0 goto P2    */17019#define OP_IncrVacuum     62 /* jump                                       */17020#define OP_VNext          63 /* jump                                       */17021#define OP_Filter         64 /* jump, synopsis: if key(P3@P4) not in filter(P1) goto P2 */17022#define OP_PureFunc       65 /* synopsis: r[P3]=func(r[P2@NP])             */17023#define OP_Function       66 /* synopsis: r[P3]=func(r[P2@NP])             */17024#define OP_Return         6717025#define OP_EndCoroutine   6817026#define OP_HaltIfNull     69 /* synopsis: if r[P3]=null halt               */17027#define OP_Halt           7017028#define OP_Integer        71 /* synopsis: r[P2]=P1                         */17029#define OP_Int64          72 /* synopsis: r[P2]=P4                         */17030#define OP_String         73 /* synopsis: r[P2]='P4' (len=P1)              */17031#define OP_BeginSubrtn    74 /* synopsis: r[P2]=NULL                       */17032#define OP_Null           75 /* synopsis: r[P2..P3]=NULL                   */17033#define OP_SoftNull       76 /* synopsis: r[P1]=NULL                       */17034#define OP_Blob           77 /* synopsis: r[P2]=P4 (len=P1)                */17035#define OP_Variable       78 /* synopsis: r[P2]=parameter(P1)              */17036#define OP_Move           79 /* synopsis: r[P2@P3]=r[P1@P3]                */17037#define OP_Copy           80 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */17038#define OP_SCopy          81 /* synopsis: r[P2]=r[P1]                      */17039#define OP_IntCopy        82 /* synopsis: r[P2]=r[P1]                      */17040#define OP_FkCheck        8317041#define OP_ResultRow      84 /* synopsis: output=r[P1@P2]                  */17042#define OP_CollSeq        8517043#define OP_AddImm         86 /* synopsis: r[P1]=r[P1]+P2                   */17044#define OP_RealAffinity   8717045#define OP_Cast           88 /* synopsis: affinity(r[P1])                  */17046#define OP_Permutation    8917047#define OP_Compare        90 /* synopsis: r[P1@P3] <-> r[P2@P3]            */17048#define OP_IsTrue         91 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */17049#define OP_ZeroOrNull     92 /* synopsis: r[P2] = 0 OR NULL                */17050#define OP_Offset         93 /* synopsis: r[P3] = sqlite_offset(P1)        */17051#define OP_Column         94 /* synopsis: r[P3]=PX cursor P1 column P2     */17052#define OP_TypeCheck      95 /* synopsis: typecheck(r[P1@P2])              */17053#define OP_Affinity       96 /* synopsis: affinity(r[P1@P2])               */17054#define OP_MakeRecord     97 /* synopsis: r[P3]=mkrec(r[P1@P2])            */17055#define OP_Count          98 /* synopsis: r[P2]=count()                    */17056#define OP_ReadCookie     9917057#define OP_SetCookie     10017058#define OP_ReopenIdx     101 /* synopsis: root=P2 iDb=P3                   */17059#define OP_OpenRead      102 /* synopsis: root=P2 iDb=P3                   */17060#define OP_BitAnd        103 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */17061#define OP_BitOr         104 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */17062#define OP_ShiftLeft     105 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */17063#define OP_ShiftRight    106 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */17064#define OP_Add           107 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */17065#define OP_Subtract      108 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */17066#define OP_Multiply      109 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */17067#define OP_Divide        110 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */17068#define OP_Remainder     111 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */17069#define OP_Concat        112 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */17070#define OP_OpenWrite     113 /* synopsis: root=P2 iDb=P3                   */17071#define OP_OpenDup       11417072#define OP_BitNot        115 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */17073#define OP_OpenAutoindex 116 /* synopsis: nColumn=P2                       */17074#define OP_OpenEphemeral 117 /* synopsis: nColumn=P2                       */17075#define OP_String8       118 /* same as TK_STRING, synopsis: r[P2]='P4'    */17076#define OP_SorterOpen    11917077#define OP_SequenceTest  120 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */17078#define OP_OpenPseudo    121 /* synopsis: P3 columns in r[P2]              */17079#define OP_Close         12217080#define OP_ColumnsUsed   12317081#define OP_SeekScan      124 /* synopsis: Scan-ahead up to P1 rows         */17082#define OP_SeekHit       125 /* synopsis: set P2<=seekHit<=P3              */17083#define OP_Sequence      126 /* synopsis: r[P2]=cursor[P1].ctr++           */17084#define OP_NewRowid      127 /* synopsis: r[P2]=rowid                      */17085#define OP_Insert        128 /* synopsis: intkey=r[P3] data=r[P2]          */17086#define OP_RowCell       12917087#define OP_Delete        13017088#define OP_ResetCount    13117089#define OP_SorterCompare 132 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */17090#define OP_SorterData    133 /* synopsis: r[P2]=data                       */17091#define OP_RowData       134 /* synopsis: r[P2]=data                       */17092#define OP_Rowid         135 /* synopsis: r[P2]=PX rowid of P1             */17093#define OP_NullRow       13617094#define OP_SeekEnd       13717095#define OP_IdxInsert     138 /* synopsis: key=r[P2]                        */17096#define OP_SorterInsert  139 /* synopsis: key=r[P2]                        */17097#define OP_IdxDelete     140 /* synopsis: key=r[P2@P3]                     */17098#define OP_DeferredSeek  141 /* synopsis: Move P3 to P1.rowid if needed    */17099#define OP_IdxRowid      142 /* synopsis: r[P2]=rowid                      */17100#define OP_FinishSeek    14317101#define OP_Destroy       14417102#define OP_Clear         14517103#define OP_ResetSorter   14617104#define OP_CreateBtree   147 /* synopsis: r[P2]=root iDb=P1 flags=P3       */17105#define OP_SqlExec       14817106#define OP_ParseSchema   14917107#define OP_LoadAnalysis  15017108#define OP_DropTable     15117109#define OP_DropIndex     15217110#define OP_DropTrigger   15317111#define OP_Real          154 /* same as TK_FLOAT, synopsis: r[P2]=P4       */17112#define OP_IntegrityCk   15517113#define OP_RowSetAdd     156 /* synopsis: rowset(P1)=r[P2]                 */17114#define OP_Param         15717115#define OP_FkCounter     158 /* synopsis: fkctr[P1]+=P2                    */17116#define OP_MemMax        159 /* synopsis: r[P1]=max(r[P1],r[P2])           */17117#define OP_OffsetLimit   160 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */17118#define OP_AggInverse    161 /* synopsis: accum=r[P3] inverse(r[P2@P5])    */17119#define OP_AggStep       162 /* synopsis: accum=r[P3] step(r[P2@P5])       */17120#define OP_AggStep1      163 /* synopsis: accum=r[P3] step(r[P2@P5])       */17121#define OP_AggValue      164 /* synopsis: r[P3]=value N=P2                 */17122#define OP_AggFinal      165 /* synopsis: accum=r[P1] N=P2                 */17123#define OP_Expire        16617124#define OP_CursorLock    16717125#define OP_CursorUnlock  16817126#define OP_TableLock     169 /* synopsis: iDb=P1 root=P2 write=P3          */17127#define OP_VBegin        17017128#define OP_VCreate       17117129#define OP_VDestroy      17217130#define OP_VOpen         17317131#define OP_VCheck        17417132#define OP_VInitIn       175 /* synopsis: r[P2]=ValueList(P1,P3)           */17133#define OP_VColumn       176 /* synopsis: r[P3]=vcolumn(P2)                */17134#define OP_VRename       17717135#define OP_Pagecount     17817136#define OP_MaxPgcnt      17917137#define OP_ClrSubtype    180 /* synopsis: r[P1].subtype = 0                */17138#define OP_GetSubtype    181 /* synopsis: r[P2] = r[P1].subtype            */17139#define OP_SetSubtype    182 /* synopsis: r[P2].subtype = r[P1]            */17140#define OP_FilterAdd     183 /* synopsis: filter(P1) += key(P3@P4)         */17141#define OP_Trace         18417142#define OP_CursorHint    18517143#define OP_ReleaseReg    186 /* synopsis: release r[P1@P2] mask P3         */17144#define OP_Noop          18717145#define OP_Explain       18817146#define OP_Abortable     1891714717148/* Properties such as "out2" or "jump" that are specified in17149** comments following the "case" for each opcode in the vdbe.c17150** are encoded into bitvectors as follows:17151*/17152#define OPFLG_JUMP        0x01  /* jump:  P2 holds jmp target */17153#define OPFLG_IN1         0x02  /* in1:   P1 is an input */17154#define OPFLG_IN2         0x04  /* in2:   P2 is an input */17155#define OPFLG_IN3         0x08  /* in3:   P3 is an input */17156#define OPFLG_OUT2        0x10  /* out2:  P2 is an output */17157#define OPFLG_OUT3        0x20  /* out3:  P3 is an output */17158#define OPFLG_NCYCLE      0x40  /* ncycle:Cycles count against P1 */17159#define OPFLG_JUMP0       0x80  /* jump0:  P2 might be zero */17160#define OPFLG_INITIALIZER {\17161/*   0 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x41, 0x00,\17162/*   8 */ 0x81, 0x01, 0x01, 0x81, 0x83, 0x83, 0x01, 0x01,\17163/*  16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0xc9, 0xc9, 0xc9,\17164/*  24 */ 0xc9, 0x01, 0x49, 0x49, 0x49, 0x49, 0xc9, 0x49,\17165/*  32 */ 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x41, 0x41,\17166/*  40 */ 0x41, 0x41, 0x41, 0x26, 0x26, 0x41, 0x23, 0x0b,\17167/*  48 */ 0x81, 0x01, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b,\17168/*  56 */ 0x0b, 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x01, 0x41,\17169/*  64 */ 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10,\17170/*  72 */ 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10, 0x00,\17171/*  80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x02, 0x02,\17172/*  88 */ 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20, 0x40, 0x00,\17173/*  96 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x40, 0x26,\17174/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\17175/* 112 */ 0x26, 0x00, 0x40, 0x12, 0x40, 0x40, 0x10, 0x00,\17176/* 120 */ 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10, 0x10,\17177/* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x50,\17178/* 136 */ 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40,\17179/* 144 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\17180/* 152 */ 0x00, 0x00, 0x10, 0x00, 0x06, 0x10, 0x00, 0x04,\17181/* 160 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\17182/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50,\17183/* 176 */ 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12, 0x00,\17184/* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}1718517186/* The resolve3P2Values() routine is able to run faster if it knows17187** the value of the largest JUMP opcode.  The smaller the maximum17188** JUMP opcode the better, so the mkopcodeh.tcl script that17189** generated this include file strives to group all JUMP opcodes17190** together near the beginning of the list.17191*/17192#define SQLITE_MX_JUMP_OPCODE  64  /* Maximum JUMP opcode */1719317194/************** End of opcodes.h *********************************************/17195/************** Continuing where we left off in vdbe.h ***********************/1719617197/*17198** Additional non-public SQLITE_PREPARE_* flags17199*/17200#define SQLITE_PREPARE_SAVESQL  0x80  /* Preserve SQL text */17201#define SQLITE_PREPARE_MASK     0x1f  /* Mask of public flags */1720217203/*17204** Prototypes for the VDBE interface.  See comments on the implementation17205** for a description of what each of these routines does.17206*/17207SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);17208SQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe*);17209SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);17210SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);17211SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);17212SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);17213SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);17214SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);17215SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);17216SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);17217SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);17218SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);17219SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(Parse*,int,int,int,int,const FuncDef*,int);17220SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);17221#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)17222SQLITE_PRIVATE   void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);17223SQLITE_PRIVATE   void sqlite3VdbeVerifyNoResultRow(Vdbe *p);17224#else17225# define sqlite3VdbeVerifyNoMallocRequired(A,B)17226# define sqlite3VdbeVerifyNoResultRow(A)17227#endif17228#if defined(SQLITE_DEBUG)17229SQLITE_PRIVATE   void sqlite3VdbeVerifyAbortable(Vdbe *p, int);17230SQLITE_PRIVATE   void sqlite3VdbeNoJumpsOutsideSubrtn(Vdbe*,int,int,int);17231#else17232# define sqlite3VdbeVerifyAbortable(A,B)17233# define sqlite3VdbeNoJumpsOutsideSubrtn(A,B,C,D)17234#endif17235SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);17236#ifndef SQLITE_OMIT_EXPLAIN17237SQLITE_PRIVATE   int sqlite3VdbeExplain(Parse*,u8,const char*,...);17238SQLITE_PRIVATE   void sqlite3VdbeExplainPop(Parse*);17239SQLITE_PRIVATE   int sqlite3VdbeExplainParent(Parse*);17240# define ExplainQueryPlan(P)        sqlite3VdbeExplain P17241# ifdef SQLITE_ENABLE_STMT_SCANSTATUS17242#  define ExplainQueryPlan2(V,P)     (V = sqlite3VdbeExplain P)17243# else17244#  define ExplainQueryPlan2(V,P)     ExplainQueryPlan(P)17245# endif17246# define ExplainQueryPlanPop(P)     sqlite3VdbeExplainPop(P)17247# define ExplainQueryPlanParent(P)  sqlite3VdbeExplainParent(P)17248#else17249# define ExplainQueryPlan(P)17250# define ExplainQueryPlan2(V,P)17251# define ExplainQueryPlanPop(P)17252# define ExplainQueryPlanParent(P) 017253# define sqlite3ExplainBreakpoint(A,B) /*no-op*/17254#endif17255#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)17256SQLITE_PRIVATE   void sqlite3ExplainBreakpoint(const char*,const char*);17257#else17258# define sqlite3ExplainBreakpoint(A,B) /*no-op*/17259#endif17260SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*, int, char*, u16);17261SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, int addr, u8);17262SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);17263SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);17264SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);17265SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);17266SQLITE_PRIVATE void sqlite3VdbeTypeofColumn(Vdbe*, int);17267SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);17268SQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe*, int addr);17269SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);17270SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);17271#ifdef SQLITE_DEBUG17272SQLITE_PRIVATE   void sqlite3VdbeReleaseRegisters(Parse*,int addr, int n, u32 mask, int);17273#else17274# define sqlite3VdbeReleaseRegisters(P,A,N,M,F)17275#endif17276SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);17277SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);17278SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);17279SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);17280SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);17281SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetLastOp(Vdbe*);17282SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse*);17283SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);17284SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);17285SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);17286SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);17287SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);17288SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);17289SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);17290#ifdef SQLITE_DEBUG17291SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);17292#endif17293SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);17294SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);17295SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);17296SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);17297SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));17298SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);17299SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);17300SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);17301SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);17302#ifdef SQLITE_ENABLE_NORMALIZE17303SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3*,Vdbe*,const char*);17304SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*);17305#endif17306SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);17307SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);17308SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);17309SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);17310#ifndef SQLITE_OMIT_TRACE17311SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);17312#endif17313SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);17314SQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*);1731517316SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);17317SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);17318SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);17319SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);1732017321typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);17322SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);1732317324SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);17325SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe*);1732617327SQLITE_PRIVATE void sqlite3MemSetArrayInt64(sqlite3_value *aMem, int iIdx, i64 val);1732817329SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);17330#ifdef SQLITE_ENABLE_BYTECODE_VTAB17331SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3*);17332#endif1733317334/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on17335** each VDBE opcode.17336**17337** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op17338** comments in VDBE programs that show key decision points in the code17339** generator.17340*/17341#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS17342SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);17343# define VdbeComment(X)  sqlite3VdbeComment X17344SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);17345# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X17346# ifdef SQLITE_ENABLE_MODULE_COMMENTS17347#   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X17348# else17349#   define VdbeModuleComment(X)17350# endif17351#else17352# define VdbeComment(X)17353# define VdbeNoopComment(X)17354# define VdbeModuleComment(X)17355#endif1735617357/*17358** The VdbeCoverage macros are used to set a coverage testing point17359** for VDBE branch instructions.  The coverage testing points are line17360** numbers in the sqlite3.c source file.  VDBE branch coverage testing17361** only works with an amalgamation build.  That's ok since a VDBE branch17362** coverage build designed for testing the test suite only.  No application17363** should ever ship with VDBE branch coverage measuring turned on.17364**17365**    VdbeCoverage(v)                  // Mark the previously coded instruction17366**                                     // as a branch17367**17368**    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true17369**17370**    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken17371**17372**    VdbeCoverageNeverTaken(v)        // Previous branch is never taken17373**17374**    VdbeCoverageNeverNull(v)         // Previous three-way branch is only17375**                                     // taken on the first two ways.  The17376**                                     // NULL option is not possible17377**17378**    VdbeCoverageEqNe(v)              // Previous OP_Jump is only interested17379**                                     // in distinguishing equal and not-equal.17380**17381** Every VDBE branch operation must be tagged with one of the macros above.17382** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and17383** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()17384** routine in vdbe.c, alerting the developer to the missed tag.17385**17386** During testing, the test application will invoke17387** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback17388** routine that is invoked as each bytecode branch is taken.  The callback17389** contains the sqlite3.c source line number of the VdbeCoverage macro and17390** flags to indicate whether or not the branch was taken.  The test application17391** is responsible for keeping track of this and reporting byte-code branches17392** that are never taken.17393**17394** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the17395** vdbe.c source file for additional information.17396*/17397#ifdef SQLITE_VDBE_COVERAGE17398SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);17399# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)17400# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)17401# define VdbeCoverageAlwaysTaken(v) \17402         sqlite3VdbeSetLineNumber(v,__LINE__|0x5000000);17403# define VdbeCoverageNeverTaken(v) \17404         sqlite3VdbeSetLineNumber(v,__LINE__|0x6000000);17405# define VdbeCoverageNeverNull(v) \17406         sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);17407# define VdbeCoverageNeverNullIf(v,x) \17408         if(x)sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);17409# define VdbeCoverageEqNe(v) \17410         sqlite3VdbeSetLineNumber(v,__LINE__|0x8000000);17411# define VDBE_OFFSET_LINENO(x) (__LINE__+x)17412#else17413# define VdbeCoverage(v)17414# define VdbeCoverageIf(v,x)17415# define VdbeCoverageAlwaysTaken(v)17416# define VdbeCoverageNeverTaken(v)17417# define VdbeCoverageNeverNull(v)17418# define VdbeCoverageNeverNullIf(v,x)17419# define VdbeCoverageEqNe(v)17420# define VDBE_OFFSET_LINENO(x) 017421#endif1742217423#ifdef SQLITE_ENABLE_STMT_SCANSTATUS17424SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);17425SQLITE_PRIVATE void sqlite3VdbeScanStatusRange(Vdbe*, int, int, int);17426SQLITE_PRIVATE void sqlite3VdbeScanStatusCounters(Vdbe*, int, int, int);17427#else17428# define sqlite3VdbeScanStatus(a,b,c,d,e,f)17429# define sqlite3VdbeScanStatusRange(a,b,c,d)17430# define sqlite3VdbeScanStatusCounters(a,b,c,d)17431#endif1743217433#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)17434SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);17435#endif1743617437#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)17438SQLITE_PRIVATE int sqlite3CursorRangeHintExprCheck(Walker *pWalker, Expr *pExpr);17439#endif1744017441#endif /* SQLITE_VDBE_H */1744217443/************** End of vdbe.h ************************************************/17444/************** Continuing where we left off in sqliteInt.h ******************/17445/************** Include pcache.h in the middle of sqliteInt.h ****************/17446/************** Begin file pcache.h ******************************************/17447/*17448** 2008 August 0517449**17450** The author disclaims copyright to this source code.  In place of17451** a legal notice, here is a blessing:17452**17453**    May you do good and not evil.17454**    May you find forgiveness for yourself and forgive others.17455**    May you share freely, never taking more than you give.17456**17457*************************************************************************17458** This header file defines the interface that the sqlite page cache17459** subsystem.17460*/1746117462#ifndef _PCACHE_H_1746317464typedef struct PgHdr PgHdr;17465typedef struct PCache PCache;1746617467/*17468** Every page in the cache is controlled by an instance of the following17469** structure.17470*/17471struct PgHdr {17472  sqlite3_pcache_page *pPage;    /* Pcache object page handle */17473  void *pData;                   /* Page data */17474  void *pExtra;                  /* Extra content */17475  PCache *pCache;                /* PRIVATE: Cache that owns this page */17476  PgHdr *pDirty;                 /* Transient list of dirty sorted by pgno */17477  Pager *pPager;                 /* The pager this page is part of */17478  Pgno pgno;                     /* Page number for this page */17479#ifdef SQLITE_CHECK_PAGES17480  u32 pageHash;                  /* Hash of page content */17481#endif17482  u16 flags;                     /* PGHDR flags defined below */1748317484  /**********************************************************************17485  ** Elements above, except pCache, are public.  All that follow are17486  ** private to pcache.c and should not be accessed by other modules.17487  ** pCache is grouped with the public elements for efficiency.17488  */17489  i64 nRef;                      /* Number of users of this page */17490  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */17491  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */17492                          /* NB: pDirtyNext and pDirtyPrev are undefined if the17493                          ** PgHdr object is not dirty */17494};1749517496/* Bit values for PgHdr.flags */17497#define PGHDR_CLEAN           0x001  /* Page not on the PCache.pDirty list */17498#define PGHDR_DIRTY           0x002  /* Page is on the PCache.pDirty list */17499#define PGHDR_WRITEABLE       0x004  /* Journaled and ready to modify */17500#define PGHDR_NEED_SYNC       0x008  /* Fsync the rollback journal before17501                                     ** writing this page to the database */17502#define PGHDR_DONT_WRITE      0x010  /* Do not write content to disk */17503#define PGHDR_MMAP            0x020  /* This is an mmap page object */1750417505#define PGHDR_WAL_APPEND      0x040  /* Appended to wal file */1750617507/* Initialize and shutdown the page cache subsystem */17508SQLITE_PRIVATE int sqlite3PcacheInitialize(void);17509SQLITE_PRIVATE void sqlite3PcacheShutdown(void);1751017511/* Page cache buffer management:17512** These routines implement SQLITE_CONFIG_PAGECACHE.17513*/17514SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);1751517516/* Create a new pager cache.17517** Under memory stress, invoke xStress to try to make pages clean.17518** Only clean and unpinned pages can be reclaimed.17519*/17520SQLITE_PRIVATE int sqlite3PcacheOpen(17521  int szPage,                    /* Size of every page */17522  int szExtra,                   /* Extra space associated with each page */17523  int bPurgeable,                /* True if pages are on backing store */17524  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */17525  void *pStress,                 /* Argument to xStress */17526  PCache *pToInit                /* Preallocated space for the PCache */17527);1752817529/* Modify the page-size after the cache has been created. */17530SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);1753117532/* Return the size in bytes of a PCache object.  Used to preallocate17533** storage space.17534*/17535SQLITE_PRIVATE int sqlite3PcacheSize(void);1753617537/* One release per successful fetch.  Page is pinned until released.17538** Reference counted.17539*/17540SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);17541SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);17542SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);17543SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);1754417545SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */17546SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */17547SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */17548SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */17549SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);1755017551/* Change a page number.  Used by incr-vacuum. */17552SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);1755317554/* Remove all pages with pgno>x.  Reset the cache if x==0 */17555SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);1755617557/* Get a list of all dirty pages in the cache, sorted by page number */17558SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);1755917560/* Reset and close the cache object */17561SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);1756217563/* Clear flags from pages of the page cache */17564SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);1756517566/* Discard the contents of the cache */17567SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);1756817569/* Return the total number of outstanding page references */17570SQLITE_PRIVATE i64 sqlite3PcacheRefCount(PCache*);1757117572/* Increment the reference count of an existing page */17573SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);1757417575SQLITE_PRIVATE i64 sqlite3PcachePageRefcount(PgHdr*);1757617577/* Return the total number of pages stored in the cache */17578SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);1757917580#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)17581/* Iterate through all dirty pages currently stored in the cache. This17582** interface is only available if SQLITE_CHECK_PAGES is defined when the17583** library is built.17584*/17585SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));17586#endif1758717588#if defined(SQLITE_DEBUG)17589/* Check invariants on a PgHdr object */17590SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);17591#endif1759217593/* Set and get the suggested cache-size for the specified pager-cache.17594**17595** If no global maximum is configured, then the system attempts to limit17596** the total number of pages cached by purgeable pager-caches to the sum17597** of the suggested cache-sizes.17598*/17599SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);17600#ifdef SQLITE_TEST17601SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);17602#endif1760317604/* Set or get the suggested spill-size for the specified pager-cache.17605**17606** The spill-size is the minimum number of pages in cache before the cache17607** will attempt to spill dirty pages by calling xStress.17608*/17609SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);1761017611/* Free up as much memory as possible from the page cache */17612SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);1761317614#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT17615/* Try to return memory used by the pcache module to the main memory heap */17616SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);17617#endif1761817619#ifdef SQLITE_TEST17620SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);17621#endif1762217623SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);1762417625/* Return the header size */17626SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);17627SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);1762817629/* Number of dirty pages as a percentage of the configured cache size */17630SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);1763117632#ifdef SQLITE_DIRECT_OVERFLOW_READ17633SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);17634#endif1763517636#endif /* _PCACHE_H_ */1763717638/************** End of pcache.h **********************************************/17639/************** Continuing where we left off in sqliteInt.h ******************/17640/************** Include mutex.h in the middle of sqliteInt.h *****************/17641/************** Begin file mutex.h *******************************************/17642/*17643** 2007 August 2817644**17645** The author disclaims copyright to this source code.  In place of17646** a legal notice, here is a blessing:17647**17648**    May you do good and not evil.17649**    May you find forgiveness for yourself and forgive others.17650**    May you share freely, never taking more than you give.17651**17652*************************************************************************17653**17654** This file contains the common header for all mutex implementations.17655** The sqliteInt.h header #includes this file so that it is available17656** to all source files.  We break it out in an effort to keep the code17657** better organized.17658**17659** NOTE:  source files should *not* #include this header file directly.17660** Source files should #include the sqliteInt.h file and let that file17661** include this one indirectly.17662*/176631766417665/*17666** Figure out what version of the code to use.  The choices are17667**17668**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The17669**                             mutexes implementation cannot be overridden17670**                             at start-time.17671**17672**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No17673**                             mutual exclusion is provided.  But this17674**                             implementation can be overridden at17675**                             start-time.17676**17677**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.17678**17679**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.17680*/17681#if !SQLITE_THREADSAFE17682# define SQLITE_MUTEX_OMIT17683#endif17684#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)17685#  if SQLITE_OS_UNIX17686#    define SQLITE_MUTEX_PTHREADS17687#  elif SQLITE_OS_WIN17688#    define SQLITE_MUTEX_W3217689#  else17690#    define SQLITE_MUTEX_NOOP17691#  endif17692#endif1769317694#ifdef SQLITE_MUTEX_OMIT17695/*17696** If this is a no-op implementation, implement everything as macros.17697*/17698#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)17699#define sqlite3_mutex_free(X)17700#define sqlite3_mutex_enter(X)17701#define sqlite3_mutex_try(X)      SQLITE_OK17702#define sqlite3_mutex_leave(X)17703#define sqlite3_mutex_held(X)     ((void)(X),1)17704#define sqlite3_mutex_notheld(X)  ((void)(X),1)17705#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)17706#define sqlite3MutexInit()        SQLITE_OK17707#define sqlite3MutexEnd()17708#define MUTEX_LOGIC(X)17709#else17710#define MUTEX_LOGIC(X)            X17711SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);17712#endif /* defined(SQLITE_MUTEX_OMIT) */1771317714/************** End of mutex.h ***********************************************/17715/************** Continuing where we left off in sqliteInt.h ******************/1771617717/* The SQLITE_EXTRA_DURABLE compile-time option used to set the default17718** synchronous setting to EXTRA.  It is no longer supported.17719*/17720#ifdef SQLITE_EXTRA_DURABLE17721# warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE17722# define SQLITE_DEFAULT_SYNCHRONOUS 317723#endif1772417725/*17726** Default synchronous levels.17727**17728** Note that (for historical reasons) the PAGER_SYNCHRONOUS_* macros differ17729** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.17730**17731**           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS17732**   OFF           1                         017733**   NORMAL        2                         117734**   FULL          3                         217735**   EXTRA         4                         317736**17737** The "PRAGMA synchronous" statement also uses the zero-based numbers.17738** In other words, the zero-based numbers are used for all external interfaces17739** and the one-based values are used internally.17740*/17741#ifndef SQLITE_DEFAULT_SYNCHRONOUS17742# define SQLITE_DEFAULT_SYNCHRONOUS 217743#endif17744#ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS17745# define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS17746#endif1774717748/*17749** Each database file to be accessed by the system is an instance17750** of the following structure.  There are normally two of these structures17751** in the sqlite.aDb[] array.  aDb[0] is the main database file and17752** aDb[1] is the database file used to hold temporary tables.  Additional17753** databases may be attached.17754*/17755struct Db {17756  char *zDbSName;      /* Name of this database. (schema name, not filename) */17757  Btree *pBt;          /* The B*Tree structure for this database file */17758  u8 safety_level;     /* How aggressive at syncing data to disk */17759  u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */17760  Schema *pSchema;     /* Pointer to database schema (possibly shared) */17761};1776217763/*17764** An instance of the following structure stores a database schema.17765**17766** Most Schema objects are associated with a Btree.  The exception is17767** the Schema for the TEMP database (sqlite3.aDb[1]) which is free-standing.17768** In shared cache mode, a single Schema object can be shared by multiple17769** Btrees that refer to the same underlying BtShared object.17770**17771** Schema objects are automatically deallocated when the last Btree that17772** references them is destroyed.   The TEMP Schema is manually freed by17773** sqlite3_close().17774*17775** A thread must be holding a mutex on the corresponding Btree in order17776** to access Schema content.  This implies that the thread must also be17777** holding a mutex on the sqlite3 connection pointer that owns the Btree.17778** For a TEMP Schema, only the connection mutex is required.17779*/17780struct Schema {17781  int schema_cookie;   /* Database schema version number for this file */17782  int iGeneration;     /* Generation counter.  Incremented with each change */17783  Hash tblHash;        /* All tables indexed by name */17784  Hash idxHash;        /* All (named) indices indexed by name */17785  Hash trigHash;       /* All triggers indexed by name */17786  Hash fkeyHash;       /* All foreign keys by referenced table name */17787  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */17788  u8 file_format;      /* Schema format version for this file */17789  u8 enc;              /* Text encoding used by this database */17790  u16 schemaFlags;     /* Flags associated with this schema */17791  int cache_size;      /* Number of pages to use in the cache */17792};1779317794/*17795** These macros can be used to test, set, or clear bits in the17796** Db.pSchema->flags field.17797*/17798#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))17799#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)17800#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)17801#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)1780217803/*17804** Allowed values for the DB.pSchema->flags field.17805**17806** The DB_SchemaLoaded flag is set after the database schema has been17807** read into internal hash tables.17808**17809** DB_UnresetViews means that one or more views have column names that17810** have been filled out.  If the schema changes, these column names might17811** changes and so the view will need to be reset.17812*/17813#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */17814#define DB_UnresetViews    0x0002  /* Some views have defined column names */17815#define DB_ResetWanted     0x0008  /* Reset the schema when nSchemaLock==0 */1781617817/*17818** The number of different kinds of things that can be limited17819** using the sqlite3_limit() interface.17820*/17821#define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)1782217823/*17824** Lookaside malloc is a set of fixed-size buffers that can be used17825** to satisfy small transient memory allocation requests for objects17826** associated with a particular database connection.  The use of17827** lookaside malloc provides a significant performance enhancement17828** (approx 10%) by avoiding numerous malloc/free requests while parsing17829** SQL statements.17830**17831** The Lookaside structure holds configuration information about the17832** lookaside malloc subsystem.  Each available memory allocation in17833** the lookaside subsystem is stored on a linked list of LookasideSlot17834** objects.17835**17836** Lookaside allocations are only allowed for objects that are associated17837** with a particular database connection.  Hence, schema information cannot17838** be stored in lookaside because in shared cache mode the schema information17839** is shared by multiple database connections.  Therefore, while parsing17840** schema information, the Lookaside.bEnabled flag is cleared so that17841** lookaside allocations are not used to construct the schema objects.17842**17843** New lookaside allocations are only allowed if bDisable==0.  When17844** bDisable is greater than zero, sz is set to zero which effectively17845** disables lookaside without adding a new test for the bDisable flag17846** in a performance-critical path.  sz should be set by to szTrue whenever17847** bDisable changes back to zero.17848**17849** Lookaside buffers are initially held on the pInit list.  As they are17850** used and freed, they are added back to the pFree list.  New allocations17851** come off of pFree first, then pInit as a fallback.  This dual-list17852** allows use to compute a high-water mark - the maximum number of allocations17853** outstanding at any point in the past - by subtracting the number of17854** allocations on the pInit list from the total number of allocations.17855**17856** Enhancement on 2019-12-12:  Two-size-lookaside17857** The default lookaside configuration is 100 slots of 1200 bytes each.17858** The larger slot sizes are important for performance, but they waste17859** a lot of space, as most lookaside allocations are less than 128 bytes.17860** The two-size-lookaside enhancement breaks up the lookaside allocation17861** into two pools:  One of 128-byte slots and the other of the default size17862** (1200-byte) slots.   Allocations are filled from the small-pool first,17863** failing over to the full-size pool if that does not work.  Thus more17864** lookaside slots are available while also using less memory.17865** This enhancement can be omitted by compiling with17866** SQLITE_OMIT_TWOSIZE_LOOKASIDE.17867*/17868struct Lookaside {17869  u32 bDisable;           /* Only operate the lookaside when zero */17870  u16 sz;                 /* Size of each buffer in bytes */17871  u16 szTrue;             /* True value of sz, even if disabled */17872  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */17873  u32 nSlot;              /* Number of lookaside slots allocated */17874  u32 anStat[3];          /* 0: hits.  1: size misses.  2: full misses */17875  LookasideSlot *pInit;   /* List of buffers not previously used */17876  LookasideSlot *pFree;   /* List of available buffers */17877#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE17878  LookasideSlot *pSmallInit; /* List of small buffers not previously used */17879  LookasideSlot *pSmallFree; /* List of available small buffers */17880  void *pMiddle;          /* First byte past end of full-size buffers and17881                          ** the first byte of LOOKASIDE_SMALL buffers */17882#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */17883  void *pStart;           /* First byte of available memory space */17884  void *pEnd;             /* First byte past end of available space */17885  void *pTrueEnd;         /* True value of pEnd, when db->pnBytesFreed!=0 */17886};17887struct LookasideSlot {17888  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */17889};1789017891#define DisableLookaside  db->lookaside.bDisable++;db->lookaside.sz=017892#define EnableLookaside   db->lookaside.bDisable--;\17893   db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue1789417895/* Size of the smaller allocations in two-size lookaside */17896#ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE17897#  define LOOKASIDE_SMALL           017898#else17899#  define LOOKASIDE_SMALL         12817900#endif1790117902/*17903** A hash table for built-in function definitions.  (Application-defined17904** functions use a regular table table from hash.h.)17905**17906** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.17907** Collisions are on the FuncDef.u.pHash chain.  Use the SQLITE_FUNC_HASH()17908** macro to compute a hash on the function name.17909*/17910#define SQLITE_FUNC_HASH_SZ 2317911struct FuncDefHash {17912  FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */17913};17914#define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)1791517916/*17917** typedef for the authorization callback function.17918*/17919typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,17920                             const char*);1792117922#ifndef SQLITE_OMIT_DEPRECATED17923/* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing17924** in the style of sqlite3_trace()17925*/17926#define SQLITE_TRACE_LEGACY          0x40     /* Use the legacy xTrace */17927#define SQLITE_TRACE_XPROFILE        0x80     /* Use the legacy xProfile */17928#else17929#define SQLITE_TRACE_LEGACY          017930#define SQLITE_TRACE_XPROFILE        017931#endif /* SQLITE_OMIT_DEPRECATED */17932#define SQLITE_TRACE_NONLEGACY_MASK  0x0f     /* Normal flags */1793317934/*17935** Maximum number of sqlite3.aDb[] entries.  This is the number of attached17936** databases plus 2 for "main" and "temp".17937*/17938#define SQLITE_MAX_DB (SQLITE_MAX_ATTACHED+2)1793917940/*17941** Each database connection is an instance of the following structure.17942*/17943struct sqlite3 {17944  sqlite3_vfs *pVfs;            /* OS Interface */17945  struct Vdbe *pVdbe;           /* List of active virtual machines */17946  CollSeq *pDfltColl;           /* BINARY collseq for the database encoding */17947  sqlite3_mutex *mutex;         /* Connection mutex */17948  Db *aDb;                      /* All backends */17949  int nDb;                      /* Number of backends currently in use */17950  u32 mDbFlags;                 /* flags recording internal state */17951  u64 flags;                    /* flags settable by pragmas. See below */17952  i64 lastRowid;                /* ROWID of most recent insert (see above) */17953  i64 szMmap;                   /* Default mmap_size setting */17954  u32 nSchemaLock;              /* Do not reset the schema when non-zero */17955  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */17956  int errCode;                  /* Most recent error code (SQLITE_*) */17957  int errByteOffset;            /* Byte offset of error in SQL statement */17958  int errMask;                  /* & result codes with this before returning */17959  int iSysErrno;                /* Errno value from last system error */17960  u32 dbOptFlags;               /* Flags to enable/disable optimizations */17961  u8 enc;                       /* Text encoding */17962  u8 autoCommit;                /* The auto-commit flag. */17963  u8 temp_store;                /* 1: file 2: memory 0: default */17964  u8 mallocFailed;              /* True if we have seen a malloc failure */17965  u8 bBenignMalloc;             /* Do not require OOMs if true */17966  u8 dfltLockMode;              /* Default locking-mode for attached dbs */17967  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */17968  u8 suppressErr;               /* Do not issue error messages if true */17969  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */17970  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */17971  u8 mTrace;                    /* zero or more SQLITE_TRACE flags */17972  u8 noSharedCache;             /* True if no shared-cache backends */17973  u8 nSqlExec;                  /* Number of pending OP_SqlExec opcodes */17974  u8 eOpenState;                /* Current condition of the connection */17975  int nextPagesize;             /* Pagesize after VACUUM if >0 */17976  i64 nChange;                  /* Value returned by sqlite3_changes() */17977  i64 nTotalChange;             /* Value returned by sqlite3_total_changes() */17978  int aLimit[SQLITE_N_LIMIT];   /* Limits */17979  int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */17980  struct sqlite3InitInfo {      /* Information used during initialization */17981    Pgno newTnum;               /* Rootpage of table being initialized */17982    u8 iDb;                     /* Which db file is being initialized */17983    u8 busy;                    /* TRUE if currently initializing */17984    unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */17985    unsigned imposterTable : 1; /* Building an imposter table */17986    unsigned reopenMemdb : 1;   /* ATTACH is really a reopen using MemDB */17987    const char **azInit;        /* "type", "name", and "tbl_name" columns */17988  } init;17989  int nVdbeActive;              /* Number of VDBEs currently running */17990  int nVdbeRead;                /* Number of active VDBEs that read or write */17991  int nVdbeWrite;               /* Number of active VDBEs that read and write */17992  int nVdbeExec;                /* Number of nested calls to VdbeExec() */17993  int nVDestroy;                /* Number of active OP_VDestroy operations */17994  int nExtension;               /* Number of loaded extensions */17995  void **aExtension;            /* Array of shared library handles */17996  union {17997    void (*xLegacy)(void*,const char*);   /* mTrace==SQLITE_TRACE_LEGACY */17998    int (*xV2)(u32,void*,void*,void*);    /* All other mTrace values */17999  } trace;18000  void *pTraceArg;                        /* Argument to the trace function */18001#ifndef SQLITE_OMIT_DEPRECATED18002  void (*xProfile)(void*,const char*,u64);  /* Profiling function */18003  void *pProfileArg;                        /* Argument to profile function */18004#endif18005  void *pCommitArg;                 /* Argument to xCommitCallback() */18006  int (*xCommitCallback)(void*);    /* Invoked at every commit. */18007  void *pRollbackArg;               /* Argument to xRollbackCallback() */18008  void (*xRollbackCallback)(void*); /* Invoked at every commit. */18009  void *pUpdateArg;18010  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);18011  void *pAutovacPagesArg;           /* Client argument to autovac_pages */18012  void (*xAutovacDestr)(void*);     /* Destructor for pAutovacPAgesArg */18013  unsigned int (*xAutovacPages)(void*,const char*,u32,u32,u32);18014  Parse *pParse;                /* Current parse */18015#ifdef SQLITE_ENABLE_PREUPDATE_HOOK18016  void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */18017  void (*xPreUpdateCallback)(   /* Registered using sqlite3_preupdate_hook() */18018    void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int6418019  );18020  PreUpdate *pPreUpdate;        /* Context for active pre-update callback */18021#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */18022#ifndef SQLITE_OMIT_WAL18023  int (*xWalCallback)(void *, sqlite3 *, const char *, int);18024  void *pWalArg;18025#endif18026  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);18027  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);18028  void *pCollNeededArg;18029  sqlite3_value *pErr;          /* Most recent error message */18030  union {18031    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */18032    double notUsed1;            /* Spacer */18033  } u1;18034  Lookaside lookaside;          /* Lookaside malloc configuration */18035#ifndef SQLITE_OMIT_AUTHORIZATION18036  sqlite3_xauth xAuth;          /* Access authorization function */18037  void *pAuthArg;               /* 1st argument to the access auth function */18038#endif18039#ifndef SQLITE_OMIT_PROGRESS_CALLBACK18040  int (*xProgress)(void *);     /* The progress callback */18041  void *pProgressArg;           /* Argument to the progress callback */18042  unsigned nProgressOps;        /* Number of opcodes for progress callback */18043#endif18044#ifndef SQLITE_OMIT_VIRTUALTABLE18045  int nVTrans;                  /* Allocated size of aVTrans */18046  Hash aModule;                 /* populated by sqlite3_create_module() */18047  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */18048  VTable **aVTrans;             /* Virtual tables with open transactions */18049  VTable *pDisconnect;          /* Disconnect these in next sqlite3_prepare() */18050#endif18051  Hash aFunc;                   /* Hash table of connection functions */18052  Hash aCollSeq;                /* All collating sequences */18053  BusyHandler busyHandler;      /* Busy callback */18054  Db aDbStatic[2];              /* Static space for the 2 default backends */18055  Savepoint *pSavepoint;        /* List of active savepoints */18056  int nAnalysisLimit;           /* Number of index rows to ANALYZE */18057  int busyTimeout;              /* Busy handler timeout, in msec */18058  int nSavepoint;               /* Number of non-transaction savepoints */18059  int nStatement;               /* Number of nested statement-transactions  */18060  i64 nDeferredCons;            /* Net deferred constraints this transaction. */18061  i64 nDeferredImmCons;         /* Net deferred immediate constraints */18062  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */18063  DbClientData *pDbData;        /* sqlite3_set_clientdata() content */18064#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY18065  /* The following variables are all protected by the STATIC_MAIN18066  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.18067  **18068  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to18069  ** unlock so that it can proceed.18070  **18071  ** When X.pBlockingConnection==Y, that means that something that X tried18072  ** tried to do recently failed with an SQLITE_LOCKED error due to locks18073  ** held by Y.18074  */18075  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */18076  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */18077  void *pUnlockArg;                     /* Argument to xUnlockNotify */18078  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */18079  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */18080#endif18081};1808218083/*18084** A macro to discover the encoding of a database.18085*/18086#define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)18087#define ENC(db)        ((db)->enc)1808818089/*18090** A u64 constant where the lower 32 bits are all zeros.  Only the18091** upper 32 bits are included in the argument.  Necessary because some18092** C-compilers still do not accept LL integer literals.18093*/18094#define HI(X)  ((u64)(X)<<32)1809518096/*18097** Possible values for the sqlite3.flags.18098**18099** Value constraints (enforced via assert()):18100**      SQLITE_FullFSync     == PAGER_FULLFSYNC18101**      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC18102**      SQLITE_CacheSpill    == PAGER_CACHE_SPILL18103*/18104#define SQLITE_WriteSchema    0x00000001  /* OK to update SQLITE_SCHEMA */18105#define SQLITE_LegacyFileFmt  0x00000002  /* Create new databases in format 1 */18106#define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */18107#define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */18108#define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */18109#define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */18110#define SQLITE_ShortColNames  0x00000040  /* Show short columns names */18111#define SQLITE_TrustedSchema  0x00000080  /* Allow unsafe functions and18112                                          ** vtabs in the schema definition */18113#define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */18114                                          /*   result set is empty */18115#define SQLITE_IgnoreChecks   0x00000200  /* Do not enforce check constraints */18116#define SQLITE_StmtScanStatus 0x00000400  /* Enable stmt_scanstats() counters */18117#define SQLITE_NoCkptOnClose  0x00000800  /* No checkpoint on close()/DETACH */18118#define SQLITE_ReverseOrder   0x00001000  /* Reverse unordered SELECTs */18119#define SQLITE_RecTriggers    0x00002000  /* Enable recursive triggers */18120#define SQLITE_ForeignKeys    0x00004000  /* Enforce foreign key constraints  */18121#define SQLITE_AutoIndex      0x00008000  /* Enable automatic indexes */18122#define SQLITE_LoadExtension  0x00010000  /* Enable load_extension */18123#define SQLITE_LoadExtFunc    0x00020000  /* Enable load_extension() SQL func */18124#define SQLITE_EnableTrigger  0x00040000  /* True to enable triggers */18125#define SQLITE_DeferFKs       0x00080000  /* Defer all FK constraints */18126#define SQLITE_QueryOnly      0x00100000  /* Disable database changes */18127#define SQLITE_CellSizeCk     0x00200000  /* Check btree cell sizes on load */18128#define SQLITE_Fts3Tokenizer  0x00400000  /* Enable fts3_tokenizer(2) */18129#define SQLITE_EnableQPSG     0x00800000  /* Query Planner Stability Guarantee*/18130#define SQLITE_TriggerEQP     0x01000000  /* Show trigger EXPLAIN QUERY PLAN */18131#define SQLITE_ResetDatabase  0x02000000  /* Reset the database */18132#define SQLITE_LegacyAlter    0x04000000  /* Legacy ALTER TABLE behaviour */18133#define SQLITE_NoSchemaError  0x08000000  /* Do not report schema parse errors*/18134#define SQLITE_Defensive      0x10000000  /* Input SQL is likely hostile */18135#define SQLITE_DqsDDL         0x20000000  /* dbl-quoted strings allowed in DDL*/18136#define SQLITE_DqsDML         0x40000000  /* dbl-quoted strings allowed in DML*/18137#define SQLITE_EnableView     0x80000000  /* Enable the use of views */18138#define SQLITE_CountRows      HI(0x00001) /* Count rows changed by INSERT, */18139                                          /*   DELETE, or UPDATE and return */18140                                          /*   the count using a callback. */18141#define SQLITE_CorruptRdOnly  HI(0x00002) /* Prohibit writes due to error */18142#define SQLITE_ReadUncommit   HI(0x00004) /* READ UNCOMMITTED in shared-cache */18143#define SQLITE_FkNoAction     HI(0x00008) /* Treat all FK as NO ACTION */18144#define SQLITE_AttachCreate   HI(0x00010) /* ATTACH allowed to create new dbs */18145#define SQLITE_AttachWrite    HI(0x00020) /* ATTACH allowed to open for write */18146#define SQLITE_Comments       HI(0x00040) /* Enable SQL comments */1814718148/* Flags used only if debugging */18149#ifdef SQLITE_DEBUG18150#define SQLITE_SqlTrace       HI(0x0100000) /* Debug print SQL as it executes */18151#define SQLITE_VdbeListing    HI(0x0200000) /* Debug listings of VDBE progs */18152#define SQLITE_VdbeTrace      HI(0x0400000) /* True to trace VDBE execution */18153#define SQLITE_VdbeAddopTrace HI(0x0800000) /* Trace sqlite3VdbeAddOp() calls */18154#define SQLITE_VdbeEQP        HI(0x1000000) /* Debug EXPLAIN QUERY PLAN */18155#define SQLITE_ParserTrace    HI(0x2000000) /* PRAGMA parser_trace=ON */18156#endif1815718158/*18159** Allowed values for sqlite3.mDbFlags18160*/18161#define DBFLAG_SchemaChange   0x0001  /* Uncommitted Hash table changes */18162#define DBFLAG_PreferBuiltin  0x0002  /* Preference to built-in funcs */18163#define DBFLAG_Vacuum         0x0004  /* Currently in a VACUUM */18164#define DBFLAG_VacuumInto     0x0008  /* Currently running VACUUM INTO */18165#define DBFLAG_SchemaKnownOk  0x0010  /* Schema is known to be valid */18166#define DBFLAG_InternalFunc   0x0020  /* Allow use of internal functions */18167#define DBFLAG_EncodingFixed  0x0040  /* No longer possible to change enc. */1816818169/*18170** Bits of the sqlite3.dbOptFlags field that are used by the18171** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to18172** selectively disable various optimizations.18173*/18174#define SQLITE_QueryFlattener 0x00000001 /* Query flattening */18175#define SQLITE_WindowFunc     0x00000002 /* Use xInverse for window functions */18176#define SQLITE_GroupByOrder   0x00000004 /* GROUPBY cover of ORDERBY */18177#define SQLITE_FactorOutConst 0x00000008 /* Constant factoring */18178#define SQLITE_DistinctOpt    0x00000010 /* DISTINCT using indexes */18179#define SQLITE_CoverIdxScan   0x00000020 /* Covering index scans */18180#define SQLITE_OrderByIdxJoin 0x00000040 /* ORDER BY of joins via index */18181#define SQLITE_Transitive     0x00000080 /* Transitive constraints */18182#define SQLITE_OmitNoopJoin   0x00000100 /* Omit unused tables in joins */18183#define SQLITE_CountOfView    0x00000200 /* The count-of-view optimization */18184#define SQLITE_CursorHints    0x00000400 /* Add OP_CursorHint opcodes */18185#define SQLITE_Stat4          0x00000800 /* Use STAT4 data */18186   /* TH3 expects this value  ^^^^^^^^^^ to be 0x0000800. Don't change it */18187#define SQLITE_PushDown       0x00001000 /* WHERE-clause push-down opt */18188#define SQLITE_SimplifyJoin   0x00002000 /* Convert LEFT JOIN to JOIN */18189#define SQLITE_SkipScan       0x00004000 /* Skip-scans */18190#define SQLITE_PropagateConst 0x00008000 /* The constant propagation opt */18191#define SQLITE_MinMaxOpt      0x00010000 /* The min/max optimization */18192#define SQLITE_SeekScan       0x00020000 /* The OP_SeekScan optimization */18193#define SQLITE_OmitOrderBy    0x00040000 /* Omit pointless ORDER BY */18194   /* TH3 expects this value  ^^^^^^^^^^ to be 0x40000. Coordinate any change */18195#define SQLITE_BloomFilter    0x00080000 /* Use a Bloom filter on searches */18196#define SQLITE_BloomPulldown  0x00100000 /* Run Bloom filters early */18197#define SQLITE_BalancedMerge  0x00200000 /* Balance multi-way merges */18198#define SQLITE_ReleaseReg     0x00400000 /* Use OP_ReleaseReg for testing */18199#define SQLITE_FlttnUnionAll  0x00800000 /* Disable the UNION ALL flattener */18200   /* TH3 expects this value  ^^^^^^^^^^ See flatten04.test */18201#define SQLITE_IndexedExpr    0x01000000 /* Pull exprs from index when able */18202#define SQLITE_Coroutines     0x02000000 /* Co-routines for subqueries */18203#define SQLITE_NullUnusedCols 0x04000000 /* NULL unused columns in subqueries */18204#define SQLITE_OnePass        0x08000000 /* Single-pass DELETE and UPDATE */18205#define SQLITE_OrderBySubq    0x10000000 /* ORDER BY in subquery helps outer */18206#define SQLITE_StarQuery      0x20000000 /* Heurists for star queries */18207#define SQLITE_AllOpts        0xffffffff /* All optimizations */1820818209/*18210** Macros for testing whether or not optimizations are enabled or disabled.18211*/18212#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)18213#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)1821418215/*18216** Return true if it OK to factor constant expressions into the initialization18217** code. The argument is a Parse object for the code generator.18218*/18219#define ConstFactorOk(P) ((P)->okConstFactor)1822018221/* Possible values for the sqlite3.eOpenState field.18222** The numbers are randomly selected such that a minimum of three bits must18223** change to convert any number to another or to zero18224*/18225#define SQLITE_STATE_OPEN     0x76  /* Database is open */18226#define SQLITE_STATE_CLOSED   0xce  /* Database is closed */18227#define SQLITE_STATE_SICK     0xba  /* Error and awaiting close */18228#define SQLITE_STATE_BUSY     0x6d  /* Database currently in use */18229#define SQLITE_STATE_ERROR    0xd5  /* An SQLITE_MISUSE error occurred */18230#define SQLITE_STATE_ZOMBIE   0xa7  /* Close with last statement close */1823118232/*18233** Each SQL function is defined by an instance of the following18234** structure.  For global built-in functions (ex: substr(), max(), count())18235** a pointer to this structure is held in the sqlite3BuiltinFunctions object.18236** For per-connection application-defined functions, a pointer to this18237** structure is held in the db->aHash hash table.18238**18239** The u.pHash field is used by the global built-ins.  The u.pDestructor18240** field is used by per-connection app-def functions.18241*/18242struct FuncDef {18243  i16 nArg;            /* Number of arguments.  -1 means unlimited */18244  u32 funcFlags;       /* Some combination of SQLITE_FUNC_* */18245  void *pUserData;     /* User data parameter */18246  FuncDef *pNext;      /* Next function with same name */18247  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */18248  void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */18249  void (*xValue)(sqlite3_context*);                     /* Current agg value */18250  void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */18251  const char *zName;   /* SQL name of the function. */18252  union {18253    FuncDef *pHash;      /* Next with a different name but the same hash */18254    FuncDestructor *pDestructor;   /* Reference counted destructor function */18255  } u; /* pHash if SQLITE_FUNC_BUILTIN, pDestructor otherwise */18256};1825718258/*18259** This structure encapsulates a user-function destructor callback (as18260** configured using create_function_v2()) and a reference counter. When18261** create_function_v2() is called to create a function with a destructor,18262** a single object of this type is allocated. FuncDestructor.nRef is set to18263** the number of FuncDef objects created (either 1 or 3, depending on whether18264** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor18265** member of each of the new FuncDef objects is set to point to the allocated18266** FuncDestructor.18267**18268** Thereafter, when one of the FuncDef objects is deleted, the reference18269** count on this object is decremented. When it reaches 0, the destructor18270** is invoked and the FuncDestructor structure freed.18271*/18272struct FuncDestructor {18273  int nRef;18274  void (*xDestroy)(void *);18275  void *pUserData;18276};1827718278/*18279** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF18280** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  And18281** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC.  There18282** are assert() statements in the code to verify this.18283**18284** Value constraints (enforced via assert()):18285**     SQLITE_FUNC_MINMAX      ==  NC_MinMaxAgg      == SF_MinMaxAgg18286**     SQLITE_FUNC_ANYORDER    ==  NC_OrderAgg       == SF_OrderByReqd18287**     SQLITE_FUNC_LENGTH      ==  OPFLAG_LENGTHARG18288**     SQLITE_FUNC_TYPEOF      ==  OPFLAG_TYPEOFARG18289**     SQLITE_FUNC_BYTELEN     ==  OPFLAG_BYTELENARG18290**     SQLITE_FUNC_CONSTANT    ==  SQLITE_DETERMINISTIC from the API18291**     SQLITE_FUNC_DIRECT      ==  SQLITE_DIRECTONLY from the API18292**     SQLITE_FUNC_UNSAFE      ==  SQLITE_INNOCUOUS  -- opposite meanings!!!18293**     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API18294**18295** Note that even though SQLITE_FUNC_UNSAFE and SQLITE_INNOCUOUS have the18296** same bit value, their meanings are inverted.  SQLITE_FUNC_UNSAFE is18297** used internally and if set means that the function has side effects.18298** SQLITE_INNOCUOUS is used by application code and means "not unsafe".18299** See multiple instances of tag-20230109-1.18300*/18301#define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */18302#define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */18303#define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */18304#define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */18305#define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/18306#define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */18307#define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */18308#define SQLITE_FUNC_BYTELEN  0x00c0 /* Built-in octet_length() function */18309#define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */18310/*                           0x0200 -- available for reuse */18311#define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */18312#define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */18313#define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */18314#define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a18315                                    ** single query - might change over time */18316#define SQLITE_FUNC_TEST     0x4000 /* Built-in testing functions */18317#define SQLITE_FUNC_RUNONLY  0x8000 /* Cannot be used by valueFromFunction */18318#define SQLITE_FUNC_WINDOW   0x00010000 /* Built-in window-only function */18319#define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */18320#define SQLITE_FUNC_DIRECT   0x00080000 /* Not for use in TRIGGERs or VIEWs */18321/* SQLITE_SUBTYPE            0x00100000 // Consumer of subtypes */18322#define SQLITE_FUNC_UNSAFE   0x00200000 /* Function has side effects */18323#define SQLITE_FUNC_INLINE   0x00400000 /* Functions implemented in-line */18324#define SQLITE_FUNC_BUILTIN  0x00800000 /* This is a built-in function */18325/*  SQLITE_RESULT_SUBTYPE    0x01000000 // Generator of subtypes */18326#define SQLITE_FUNC_ANYORDER 0x08000000 /* count/min/max aggregate */1832718328/* Identifier numbers for each in-line function */18329#define INLINEFUNC_coalesce             018330#define INLINEFUNC_implies_nonnull_row  118331#define INLINEFUNC_expr_implies_expr    218332#define INLINEFUNC_expr_compare         318333#define INLINEFUNC_affinity             418334#define INLINEFUNC_iif                  518335#define INLINEFUNC_sqlite_offset        618336#define INLINEFUNC_unlikely            99  /* Default case */1833718338/*18339** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are18340** used to create the initializers for the FuncDef structures.18341**18342**   FUNCTION(zName, nArg, iArg, bNC, xFunc)18343**     Used to create a scalar function definition of a function zName18344**     implemented by C function xFunc that accepts nArg arguments. The18345**     value passed as iArg is cast to a (void*) and made available18346**     as the user-data (sqlite3_user_data()) for the function. If18347**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.18348**18349**   VFUNCTION(zName, nArg, iArg, bNC, xFunc)18350**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.18351**18352**   SFUNCTION(zName, nArg, iArg, bNC, xFunc)18353**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and18354**     adds the SQLITE_DIRECTONLY flag.18355**18356**   INLINE_FUNC(zName, nArg, iFuncId, mFlags)18357**     zName is the name of a function that is implemented by in-line18358**     byte code rather than by the usual callbacks. The iFuncId18359**     parameter determines the function id.  The mFlags parameter is18360**     optional SQLITE_FUNC_ flags for this function.18361**18362**   TEST_FUNC(zName, nArg, iFuncId, mFlags)18363**     zName is the name of a test-only function implemented by in-line18364**     byte code rather than by the usual callbacks. The iFuncId18365**     parameter determines the function id.  The mFlags parameter is18366**     optional SQLITE_FUNC_ flags for this function.18367**18368**   DFUNCTION(zName, nArg, iArg, bNC, xFunc)18369**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and18370**     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions18371**     and functions like sqlite_version() that can change, but not during18372**     a single query.  The iArg is ignored.  The user-data is always set18373**     to a NULL pointer.  The bNC parameter is not used.18374**18375**   MFUNCTION(zName, nArg, xPtr, xFunc)18376**     For math-library functions.  xPtr is an arbitrary pointer.18377**18378**   PURE_DATE(zName, nArg, iArg, bNC, xFunc)18379**     Used for "pure" date/time functions, this macro is like DFUNCTION18380**     except that it does set the SQLITE_FUNC_CONSTANT flags.  iArg is18381**     ignored and the user-data for these functions is set to an18382**     arbitrary non-NULL pointer.  The bNC parameter is not used.18383**18384**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)18385**     Used to create an aggregate function definition implemented by18386**     the C functions xStep and xFinal. The first four parameters18387**     are interpreted in the same way as the first 4 parameters to18388**     FUNCTION().18389**18390**   WAGGREGATE(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)18391**     Used to create an aggregate function definition implemented by18392**     the C functions xStep and xFinal. The first four parameters18393**     are interpreted in the same way as the first 4 parameters to18394**     FUNCTION().18395**18396**   LIKEFUNC(zName, nArg, pArg, flags)18397**     Used to create a scalar function definition of a function zName18398**     that accepts nArg arguments and is implemented by a call to C18399**     function likeFunc. Argument pArg is cast to a (void *) and made18400**     available as the function user-data (sqlite3_user_data()). The18401**     FuncDef.flags variable is set to the value passed as the flags18402**     parameter.18403*/18404#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \18405  {nArg, SQLITE_FUNC_BUILTIN|\18406   SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \18407   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }18408#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \18409  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \18410   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }18411#define SFUNCTION(zName, nArg, iArg, bNC, xFunc) \18412  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \18413   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }18414#define MFUNCTION(zName, nArg, xPtr, xFunc) \18415  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8, \18416   xPtr, 0, xFunc, 0, 0, 0, #zName, {0} }18417#define JFUNCTION(zName, nArg, bUseCache, bWS, bRS, bJsonB, iArg, xFunc) \18418  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_DETERMINISTIC|SQLITE_FUNC_CONSTANT|\18419   SQLITE_UTF8|((bUseCache)*SQLITE_FUNC_RUNONLY)|\18420   ((bRS)*SQLITE_SUBTYPE)|((bWS)*SQLITE_RESULT_SUBTYPE), \18421   SQLITE_INT_TO_PTR(iArg|((bJsonB)*JSON_BLOB)),0,xFunc,0, 0, 0, #zName, {0} }18422#define INLINE_FUNC(zName, nArg, iArg, mFlags) \18423  {nArg, SQLITE_FUNC_BUILTIN|\18424   SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \18425   SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }18426#define TEST_FUNC(zName, nArg, iArg, mFlags) \18427  {nArg, SQLITE_FUNC_BUILTIN|\18428         SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \18429         SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \18430   SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }18431#define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \18432  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \18433   0, 0, xFunc, 0, 0, 0, #zName, {0} }18434#define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \18435  {nArg, SQLITE_FUNC_BUILTIN|\18436         SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \18437   (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }18438#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \18439  {nArg, SQLITE_FUNC_BUILTIN|\18440   SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\18441   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }18442#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \18443  {nArg, SQLITE_FUNC_BUILTIN|\18444   SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \18445   pArg, 0, xFunc, 0, 0, 0, #zName, }18446#define LIKEFUNC(zName, nArg, arg, flags) \18447  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \18448   (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }18449#define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \18450  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \18451   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}18452#define INTERNAL_FUNCTION(zName, nArg, xFunc) \18453  {nArg, SQLITE_FUNC_BUILTIN|\18454   SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \18455   0, 0, xFunc, 0, 0, 0, #zName, {0} }184561845718458/*18459** All current savepoints are stored in a linked list starting at18460** sqlite3.pSavepoint. The first element in the list is the most recently18461** opened savepoint. Savepoints are added to the list by the vdbe18462** OP_Savepoint instruction.18463*/18464struct Savepoint {18465  char *zName;                        /* Savepoint name (nul-terminated) */18466  i64 nDeferredCons;                  /* Number of deferred fk violations */18467  i64 nDeferredImmCons;               /* Number of deferred imm fk. */18468  Savepoint *pNext;                   /* Parent savepoint (if any) */18469};1847018471/*18472** The following are used as the second parameter to sqlite3Savepoint(),18473** and as the P1 argument to the OP_Savepoint instruction.18474*/18475#define SAVEPOINT_BEGIN      018476#define SAVEPOINT_RELEASE    118477#define SAVEPOINT_ROLLBACK   2184781847918480/*18481** Each SQLite module (virtual table definition) is defined by an18482** instance of the following structure, stored in the sqlite3.aModule18483** hash table.18484*/18485struct Module {18486  const sqlite3_module *pModule;       /* Callback pointers */18487  const char *zName;                   /* Name passed to create_module() */18488  int nRefModule;                      /* Number of pointers to this object */18489  void *pAux;                          /* pAux passed to create_module() */18490  void (*xDestroy)(void *);            /* Module destructor function */18491  Table *pEpoTab;                      /* Eponymous table for this module */18492};1849318494/*18495** Information about each column of an SQL table is held in an instance18496** of the Column structure, in the Table.aCol[] array.18497**18498** Definitions:18499**18500**   "table column index"     This is the index of the column in the18501**                            Table.aCol[] array, and also the index of18502**                            the column in the original CREATE TABLE stmt.18503**18504**   "storage column index"   This is the index of the column in the18505**                            record BLOB generated by the OP_MakeRecord18506**                            opcode.  The storage column index is less than18507**                            or equal to the table column index.  It is18508**                            equal if and only if there are no VIRTUAL18509**                            columns to the left.18510**18511** Notes on zCnName:18512** The zCnName field stores the name of the column, the datatype of the18513** column, and the collating sequence for the column, in that order, all in18514** a single allocation.  Each string is 0x00 terminated.  The datatype18515** is only included if the COLFLAG_HASTYPE bit of colFlags is set and the18516** collating sequence name is only included if the COLFLAG_HASCOLL bit is18517** set.18518*/18519struct Column {18520  char *zCnName;        /* Name of this column */18521  unsigned notNull :4;  /* An OE_ code for handling a NOT NULL constraint */18522  unsigned eCType :4;   /* One of the standard types */18523  char affinity;        /* One of the SQLITE_AFF_... values */18524  u8 szEst;             /* Est size of value in this column. sizeof(INT)==1 */18525  u8 hName;             /* Column name hash for faster lookup */18526  u16 iDflt;            /* 1-based index of DEFAULT.  0 means "none" */18527  u16 colFlags;         /* Boolean properties.  See COLFLAG_ defines below */18528};1852918530/* Allowed values for Column.eCType.18531**18532** Values must match entries in the global constant arrays18533** sqlite3StdTypeLen[] and sqlite3StdType[].  Each value is one more18534** than the offset into these arrays for the corresponding name.18535** Adjust the SQLITE_N_STDTYPE value if adding or removing entries.18536*/18537#define COLTYPE_CUSTOM      0   /* Type appended to zName */18538#define COLTYPE_ANY         118539#define COLTYPE_BLOB        218540#define COLTYPE_INT         318541#define COLTYPE_INTEGER     418542#define COLTYPE_REAL        518543#define COLTYPE_TEXT        618544#define SQLITE_N_STDTYPE    6  /* Number of standard types */1854518546/* Allowed values for Column.colFlags.18547**18548** Constraints:18549**         TF_HasVirtual == COLFLAG_VIRTUAL18550**         TF_HasStored  == COLFLAG_STORED18551**         TF_HasHidden  == COLFLAG_HIDDEN18552*/18553#define COLFLAG_PRIMKEY   0x0001   /* Column is part of the primary key */18554#define COLFLAG_HIDDEN    0x0002   /* A hidden column in a virtual table */18555#define COLFLAG_HASTYPE   0x0004   /* Type name follows column name */18556#define COLFLAG_UNIQUE    0x0008   /* Column def contains "UNIQUE" or "PK" */18557#define COLFLAG_SORTERREF 0x0010   /* Use sorter-refs with this column */18558#define COLFLAG_VIRTUAL   0x0020   /* GENERATED ALWAYS AS ... VIRTUAL */18559#define COLFLAG_STORED    0x0040   /* GENERATED ALWAYS AS ... STORED */18560#define COLFLAG_NOTAVAIL  0x0080   /* STORED column not yet calculated */18561#define COLFLAG_BUSY      0x0100   /* Blocks recursion on GENERATED columns */18562#define COLFLAG_HASCOLL   0x0200   /* Has collating sequence name in zCnName */18563#define COLFLAG_NOEXPAND  0x0400   /* Omit this column when expanding "*" */18564#define COLFLAG_GENERATED 0x0060   /* Combo: _STORED, _VIRTUAL */18565#define COLFLAG_NOINSERT  0x0062   /* Combo: _HIDDEN, _STORED, _VIRTUAL */1856618567/*18568** A "Collating Sequence" is defined by an instance of the following18569** structure. Conceptually, a collating sequence consists of a name and18570** a comparison routine that defines the order of that sequence.18571**18572** If CollSeq.xCmp is NULL, it means that the18573** collating sequence is undefined.  Indices built on an undefined18574** collating sequence may not be read or written.18575*/18576struct CollSeq {18577  char *zName;          /* Name of the collating sequence, UTF-8 encoded */18578  u8 enc;               /* Text encoding handled by xCmp() */18579  void *pUser;          /* First argument to xCmp() */18580  int (*xCmp)(void*,int, const void*, int, const void*);18581  void (*xDel)(void*);  /* Destructor for pUser */18582};1858318584/*18585** A sort order can be either ASC or DESC.18586*/18587#define SQLITE_SO_ASC       0  /* Sort in ascending order */18588#define SQLITE_SO_DESC      1  /* Sort in ascending order */18589#define SQLITE_SO_UNDEFINED -1 /* No sort order specified */1859018591/*18592** Column affinity types.18593**18594** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and18595** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve18596** the speed a little by numbering the values consecutively.18597**18598** But rather than start with 0 or 1, we begin with 'A'.  That way,18599** when multiple affinity types are concatenated into a string and18600** used as the P4 operand, they will be more readable.18601**18602** Note also that the numeric types are grouped together so that testing18603** for a numeric type is a single comparison.  And the BLOB type is first.18604*/18605#define SQLITE_AFF_NONE     0x40  /* '@' */18606#define SQLITE_AFF_BLOB     0x41  /* 'A' */18607#define SQLITE_AFF_TEXT     0x42  /* 'B' */18608#define SQLITE_AFF_NUMERIC  0x43  /* 'C' */18609#define SQLITE_AFF_INTEGER  0x44  /* 'D' */18610#define SQLITE_AFF_REAL     0x45  /* 'E' */18611#define SQLITE_AFF_FLEXNUM  0x46  /* 'F' */1861218613#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)1861418615/*18616** The SQLITE_AFF_MASK values masks off the significant bits of an18617** affinity value.18618*/18619#define SQLITE_AFF_MASK     0x471862018621/*18622** Additional bit values that can be ORed with an affinity without18623** changing the affinity.18624**18625** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.18626** It causes an assert() to fire if either operand to a comparison18627** operator is NULL.  It is added to certain comparison operators to18628** prove that the operands are always NOT NULL.18629*/18630#define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */18631#define SQLITE_NULLEQ       0x80  /* NULL=NULL */18632#define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */1863318634/*18635** An object of this type is created for each virtual table present in18636** the database schema.18637**18638** If the database schema is shared, then there is one instance of this18639** structure for each database connection (sqlite3*) that uses the shared18640** schema. This is because each database connection requires its own unique18641** instance of the sqlite3_vtab* handle used to access the virtual table18642** implementation. sqlite3_vtab* handles can not be shared between18643** database connections, even when the rest of the in-memory database18644** schema is shared, as the implementation often stores the database18645** connection handle passed to it via the xConnect() or xCreate() method18646** during initialization internally. This database connection handle may18647** then be used by the virtual table implementation to access real tables18648** within the database. So that they appear as part of the callers18649** transaction, these accesses need to be made via the same database18650** connection as that used to execute SQL operations on the virtual table.18651**18652** All VTable objects that correspond to a single table in a shared18653** database schema are initially stored in a linked-list pointed to by18654** the Table.pVTable member variable of the corresponding Table object.18655** When an sqlite3_prepare() operation is required to access the virtual18656** table, it searches the list for the VTable that corresponds to the18657** database connection doing the preparing so as to use the correct18658** sqlite3_vtab* handle in the compiled query.18659**18660** When an in-memory Table object is deleted (for example when the18661** schema is being reloaded for some reason), the VTable objects are not18662** deleted and the sqlite3_vtab* handles are not xDisconnect()ed18663** immediately. Instead, they are moved from the Table.pVTable list to18664** another linked list headed by the sqlite3.pDisconnect member of the18665** corresponding sqlite3 structure. They are then deleted/xDisconnected18666** next time a statement is prepared using said sqlite3*. This is done18667** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.18668** Refer to comments above function sqlite3VtabUnlockList() for an18669** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect18670** list without holding the corresponding sqlite3.mutex mutex.18671**18672** The memory for objects of this type is always allocated by18673** sqlite3DbMalloc(), using the connection handle stored in VTable.db as18674** the first argument.18675*/18676struct VTable {18677  sqlite3 *db;              /* Database connection associated with this table */18678  Module *pMod;             /* Pointer to module implementation */18679  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */18680  int nRef;                 /* Number of pointers to this structure */18681  u8 bConstraint;           /* True if constraints are supported */18682  u8 bAllSchemas;           /* True if might use any attached schema */18683  u8 eVtabRisk;             /* Riskiness of allowing hacker access */18684  int iSavepoint;           /* Depth of the SAVEPOINT stack */18685  VTable *pNext;            /* Next in linked list (see above) */18686};1868718688/* Allowed values for VTable.eVtabRisk18689*/18690#define SQLITE_VTABRISK_Low          018691#define SQLITE_VTABRISK_Normal       118692#define SQLITE_VTABRISK_High         21869318694/*18695** The schema for each SQL table, virtual table, and view is represented18696** in memory by an instance of the following structure.18697*/18698struct Table {18699  char *zName;         /* Name of the table or view */18700  Column *aCol;        /* Information about each column */18701  Index *pIndex;       /* List of SQL indexes on this table. */18702  char *zColAff;       /* String defining the affinity of each column */18703  ExprList *pCheck;    /* All CHECK constraints */18704                       /*   ... also used as column name list in a VIEW */18705  Pgno tnum;           /* Root BTree page for this table */18706  u32 nTabRef;         /* Number of pointers to this Table */18707  u32 tabFlags;        /* Mask of TF_* values */18708  i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */18709  i16 nCol;            /* Number of columns in this table */18710  i16 nNVCol;          /* Number of columns that are not VIRTUAL */18711  LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */18712  LogEst szTabRow;     /* Estimated size of each table row in bytes */18713#ifdef SQLITE_ENABLE_COSTMULT18714  LogEst costMult;     /* Cost multiplier for using this table */18715#endif18716  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */18717  u8 eTabType;         /* 0: normal, 1: virtual, 2: view */18718  union {18719    struct {             /* Used by ordinary tables: */18720      int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */18721      FKey *pFKey;         /* Linked list of all foreign keys in this table */18722      ExprList *pDfltList; /* DEFAULT clauses on various columns.18723                           ** Or the AS clause for generated columns. */18724    } tab;18725    struct {             /* Used by views: */18726      Select *pSelect;     /* View definition */18727    } view;18728    struct {             /* Used by virtual tables only: */18729      int nArg;            /* Number of arguments to the module */18730      char **azArg;        /* 0: module 1: schema 2: vtab name 3...: args */18731      VTable *p;           /* List of VTable objects. */18732    } vtab;18733  } u;18734  Trigger *pTrigger;   /* List of triggers on this object */18735  Schema *pSchema;     /* Schema that contains this table */18736};1873718738/*18739** Allowed values for Table.tabFlags.18740**18741** TF_OOOHidden applies to tables or view that have hidden columns that are18742** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING18743** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,18744** the TF_OOOHidden attribute would apply in this case.  Such tables require18745** special handling during INSERT processing. The "OOO" means "Out Of Order".18746**18747** Constraints:18748**18749**         TF_HasVirtual == COLFLAG_VIRTUAL18750**         TF_HasStored  == COLFLAG_STORED18751**         TF_HasHidden  == COLFLAG_HIDDEN18752*/18753#define TF_Readonly       0x00000001 /* Read-only system table */18754#define TF_HasHidden      0x00000002 /* Has one or more hidden columns */18755#define TF_HasPrimaryKey  0x00000004 /* Table has a primary key */18756#define TF_Autoincrement  0x00000008 /* Integer primary key is autoincrement */18757#define TF_HasStat1       0x00000010 /* nRowLogEst set from sqlite_stat1 */18758#define TF_HasVirtual     0x00000020 /* Has one or more VIRTUAL columns */18759#define TF_HasStored      0x00000040 /* Has one or more STORED columns */18760#define TF_HasGenerated   0x00000060 /* Combo: HasVirtual + HasStored */18761#define TF_WithoutRowid   0x00000080 /* No rowid.  PRIMARY KEY is the key */18762#define TF_MaybeReanalyze 0x00000100 /* Maybe run ANALYZE on this table */18763#define TF_NoVisibleRowid 0x00000200 /* No user-visible "rowid" column */18764#define TF_OOOHidden      0x00000400 /* Out-of-Order hidden columns */18765#define TF_HasNotNull     0x00000800 /* Contains NOT NULL constraints */18766#define TF_Shadow         0x00001000 /* True for a shadow table */18767#define TF_HasStat4       0x00002000 /* STAT4 info available for this table */18768#define TF_Ephemeral      0x00004000 /* An ephemeral table */18769#define TF_Eponymous      0x00008000 /* An eponymous virtual table */18770#define TF_Strict         0x00010000 /* STRICT mode */1877118772/*18773** Allowed values for Table.eTabType18774*/18775#define TABTYP_NORM      0     /* Ordinary table */18776#define TABTYP_VTAB      1     /* Virtual table */18777#define TABTYP_VIEW      2     /* A view */1877818779#define IsView(X)           ((X)->eTabType==TABTYP_VIEW)18780#define IsOrdinaryTable(X)  ((X)->eTabType==TABTYP_NORM)1878118782/*18783** Test to see whether or not a table is a virtual table.  This is18784** done as a macro so that it will be optimized out when virtual18785** table support is omitted from the build.18786*/18787#ifndef SQLITE_OMIT_VIRTUALTABLE18788#  define IsVirtual(X)      ((X)->eTabType==TABTYP_VTAB)18789#  define ExprIsVtab(X)  \18790   ((X)->op==TK_COLUMN && (X)->y.pTab->eTabType==TABTYP_VTAB)18791#else18792#  define IsVirtual(X)      018793#  define ExprIsVtab(X)     018794#endif1879518796/*18797** Macros to determine if a column is hidden.  IsOrdinaryHiddenColumn()18798** only works for non-virtual tables (ordinary tables and views) and is18799** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined.  The18800** IsHiddenColumn() macro is general purpose.18801*/18802#if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)18803#  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)18804#  define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)18805#elif !defined(SQLITE_OMIT_VIRTUALTABLE)18806#  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)18807#  define IsOrdinaryHiddenColumn(X) 018808#else18809#  define IsHiddenColumn(X)         018810#  define IsOrdinaryHiddenColumn(X) 018811#endif188121881318814/* Does the table have a rowid */18815#define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)18816#define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)1881718818/* Macro is true if the SQLITE_ALLOW_ROWID_IN_VIEW (mis-)feature is18819** available.  By default, this macro is false18820*/18821#ifndef SQLITE_ALLOW_ROWID_IN_VIEW18822# define ViewCanHaveRowid     018823#else18824# define ViewCanHaveRowid     (sqlite3Config.mNoVisibleRowid==0)18825#endif1882618827/*18828** Each foreign key constraint is an instance of the following structure.18829**18830** A foreign key is associated with two tables.  The "from" table is18831** the table that contains the REFERENCES clause that creates the foreign18832** key.  The "to" table is the table that is named in the REFERENCES clause.18833** Consider this example:18834**18835**     CREATE TABLE ex1(18836**       a INTEGER PRIMARY KEY,18837**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)18838**     );18839**18840** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".18841** Equivalent names:18842**18843**     from-table == child-table18844**       to-table == parent-table18845**18846** Each REFERENCES clause generates an instance of the following structure18847** which is attached to the from-table.  The to-table need not exist when18848** the from-table is created.  The existence of the to-table is not checked.18849**18850** The list of all parents for child Table X is held at X.pFKey.18851**18852** A list of all children for a table named Z (which might not even exist)18853** is held in Schema.fkeyHash with a hash key of Z.18854*/18855struct FKey {18856  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */18857  FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */18858  char *zTo;        /* Name of table that the key points to (aka: Parent) */18859  FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */18860  FKey *pPrevTo;    /* Previous with the same zTo */18861  int nCol;         /* Number of columns in this key */18862  /* EV: R-30323-21917 */18863  u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */18864  u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */18865  Trigger *apTrigger[2];/* Triggers for aAction[] actions */18866  struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */18867    int iFrom;            /* Index of column in pFrom */18868    char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */18869  } aCol[1];            /* One entry for each of nCol columns */18870};1887118872/*18873** SQLite supports many different ways to resolve a constraint18874** error.  ROLLBACK processing means that a constraint violation18875** causes the operation in process to fail and for the current transaction18876** to be rolled back.  ABORT processing means the operation in process18877** fails and any prior changes from that one operation are backed out,18878** but the transaction is not rolled back.  FAIL processing means that18879** the operation in progress stops and returns an error code.  But prior18880** changes due to the same operation are not backed out and no rollback18881** occurs.  IGNORE means that the particular row that caused the constraint18882** error is not inserted or updated.  Processing continues and no error18883** is returned.  REPLACE means that preexisting database rows that caused18884** a UNIQUE constraint violation are removed so that the new insert or18885** update can proceed.  Processing continues and no error is reported.18886** UPDATE applies to insert operations only and means that the insert18887** is omitted and the DO UPDATE clause of an upsert is run instead.18888**18889** RESTRICT, SETNULL, SETDFLT, and CASCADE actions apply only to foreign keys.18890** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the18891** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign18892** key is set to NULL.  SETDFLT means that the foreign key is set18893** to its default value.  CASCADE means that a DELETE or UPDATE of the18894** referenced table row is propagated into the row that holds the18895** foreign key.18896**18897** The OE_Default value is a place holder that means to use whatever18898** conflict resolution algorithm is required from context.18899**18900** The following symbolic values are used to record which type18901** of conflict resolution action to take.18902*/18903#define OE_None     0   /* There is no constraint to check */18904#define OE_Rollback 1   /* Fail the operation and rollback the transaction */18905#define OE_Abort    2   /* Back out changes but do no rollback transaction */18906#define OE_Fail     3   /* Stop the operation but leave all prior changes */18907#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */18908#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */18909#define OE_Update   6   /* Process as a DO UPDATE in an upsert */18910#define OE_Restrict 7   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */18911#define OE_SetNull  8   /* Set the foreign key value to NULL */18912#define OE_SetDflt  9   /* Set the foreign key value to its default */18913#define OE_Cascade  10  /* Cascade the changes */18914#define OE_Default  11  /* Do whatever the default action is */189151891618917/*18918** An instance of the following structure is passed as the first18919** argument to sqlite3VdbeKeyCompare and is used to control the18920** comparison of the two index keys.18921**18922** Note that aSortOrder[] and aColl[] have nField+1 slots.  There18923** are nField slots for the columns of an index then one extra slot18924** for the rowid at the end.18925*/18926struct KeyInfo {18927  u32 nRef;           /* Number of references to this KeyInfo object */18928  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */18929  u16 nKeyField;      /* Number of key columns in the index */18930  u16 nAllField;      /* Total columns, including key plus others */18931  sqlite3 *db;        /* The database connection */18932  u8 *aSortFlags;     /* Sort order for each column. */18933  CollSeq *aColl[1];  /* Collating sequence for each term of the key */18934};1893518936/*18937** Allowed bit values for entries in the KeyInfo.aSortFlags[] array.18938*/18939#define KEYINFO_ORDER_DESC    0x01    /* DESC sort order */18940#define KEYINFO_ORDER_BIGNULL 0x02    /* NULL is larger than any other value */1894118942/*18943** This object holds a record which has been parsed out into individual18944** fields, for the purposes of doing a comparison.18945**18946** A record is an object that contains one or more fields of data.18947** Records are used to store the content of a table row and to store18948** the key of an index.  A blob encoding of a record is created by18949** the OP_MakeRecord opcode of the VDBE and is disassembled by the18950** OP_Column opcode.18951**18952** An instance of this object serves as a "key" for doing a search on18953** an index b+tree. The goal of the search is to find the entry that18954** is closed to the key described by this object.  This object might hold18955** just a prefix of the key.  The number of fields is given by18956** pKeyInfo->nField.18957**18958** The r1 and r2 fields are the values to return if this key is less than18959** or greater than a key in the btree, respectively.  These are normally18960** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree18961** is in DESC order.18962**18963** The key comparison functions actually return default_rc when they find18964** an equals comparison.  default_rc can be -1, 0, or +1.  If there are18965** multiple entries in the b-tree with the same key (when only looking18966** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to18967** cause the search to find the last match, or +1 to cause the search to18968** find the first match.18969**18970** The key comparison functions will set eqSeen to true if they ever18971** get and equal results when comparing this structure to a b-tree record.18972** When default_rc!=0, the search might end up on the record immediately18973** before the first match or immediately after the last match.  The18974** eqSeen field will indicate whether or not an exact match exists in the18975** b-tree.18976*/18977struct UnpackedRecord {18978  KeyInfo *pKeyInfo;  /* Collation and sort-order information */18979  Mem *aMem;          /* Values */18980  union {18981    char *z;            /* Cache of aMem[0].z for vdbeRecordCompareString() */18982    i64 i;              /* Cache of aMem[0].u.i for vdbeRecordCompareInt() */18983  } u;18984  int n;              /* Cache of aMem[0].n used by vdbeRecordCompareString() */18985  u16 nField;         /* Number of entries in apMem[] */18986  i8 default_rc;      /* Comparison result if keys are equal */18987  u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */18988  i8 r1;              /* Value to return if (lhs < rhs) */18989  i8 r2;              /* Value to return if (lhs > rhs) */18990  u8 eqSeen;          /* True if an equality comparison has been seen */18991};189921899318994/*18995** Each SQL index is represented in memory by an18996** instance of the following structure.18997**18998** The columns of the table that are to be indexed are described18999** by the aiColumn[] field of this structure.  For example, suppose19000** we have the following table and index:19001**19002**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);19003**     CREATE INDEX Ex2 ON Ex1(c3,c1);19004**19005** In the Table structure describing Ex1, nCol==3 because there are19006** three columns in the table.  In the Index structure describing19007** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.19008** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the19009** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].19010** The second column to be indexed (c1) has an index of 0 in19011** Ex1.aCol[], hence Ex2.aiColumn[1]==0.19012**19013** The Index.onError field determines whether or not the indexed columns19014** must be unique and what to do if they are not.  When Index.onError=OE_None,19015** it means this is not a unique index.  Otherwise it is a unique index19016** and the value of Index.onError indicates which conflict resolution19017** algorithm to employ when an attempt is made to insert a non-unique19018** element.19019**19020** The colNotIdxed bitmask is used in combination with SrcItem.colUsed19021** for a fast test to see if an index can serve as a covering index.19022** colNotIdxed has a 1 bit for every column of the original table that19023** is *not* available in the index.  Thus the expression19024** "colUsed & colNotIdxed" will be non-zero if the index is not a19025** covering index.  The most significant bit of of colNotIdxed will always19026** be true (note-20221022-a).  If a column beyond the 63rd column of the19027** table is used, the "colUsed & colNotIdxed" test will always be non-zero19028** and we have to assume either that the index is not covering, or use19029** an alternative (slower) algorithm to determine whether or not19030** the index is covering.19031**19032** While parsing a CREATE TABLE or CREATE INDEX statement in order to19033** generate VDBE code (as opposed to parsing one read from an sqlite_schema19034** table as part of parsing an existing database schema), transient instances19035** of this structure may be created. In this case the Index.tnum variable is19036** used to store the address of a VDBE instruction, not a database page19037** number (it cannot - the database page is not allocated until the VDBE19038** program is executed). See convertToWithoutRowidTable() for details.19039*/19040struct Index {19041  char *zName;             /* Name of this index */19042  i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */19043  LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */19044  Table *pTable;           /* The SQL table being indexed */19045  char *zColAff;           /* String defining the affinity of each column */19046  Index *pNext;            /* The next index associated with the same table */19047  Schema *pSchema;         /* Schema containing this index */19048  u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */19049  const char **azColl;     /* Array of collation sequence names for index */19050  Expr *pPartIdxWhere;     /* WHERE clause for partial indices */19051  ExprList *aColExpr;      /* Column expressions */19052  Pgno tnum;               /* DB Page containing root of this index */19053  LogEst szIdxRow;         /* Estimated average row size in bytes */19054  u16 nKeyCol;             /* Number of columns forming the key */19055  u16 nColumn;             /* Number of columns stored in the index */19056  u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */19057  unsigned idxType:2;      /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */19058  unsigned bUnordered:1;   /* Use this index for == or IN queries only */19059  unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */19060  unsigned isResized:1;    /* True if resizeIndexObject() has been called */19061  unsigned isCovering:1;   /* True if this is a covering index */19062  unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */19063  unsigned hasStat1:1;     /* aiRowLogEst values come from sqlite_stat1 */19064  unsigned bLowQual:1;     /* sqlite_stat1 says this is a low-quality index */19065  unsigned bNoQuery:1;     /* Do not use this index to optimize queries */19066  unsigned bAscKeyBug:1;   /* True if the bba7b69f9849b5bf bug applies */19067  unsigned bHasVCol:1;     /* Index references one or more VIRTUAL columns */19068  unsigned bHasExpr:1;     /* Index contains an expression, either a literal19069                           ** expression, or a reference to a VIRTUAL column */19070#ifdef SQLITE_ENABLE_STAT419071  int nSample;             /* Number of elements in aSample[] */19072  int mxSample;            /* Number of slots allocated to aSample[] */19073  int nSampleCol;          /* Size of IndexSample.anEq[] and so on */19074  tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */19075  IndexSample *aSample;    /* Samples of the left-most key */19076  tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */19077  tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */19078#endif19079  Bitmask colNotIdxed;     /* Unindexed columns in pTab */19080};1908119082/*19083** Allowed values for Index.idxType19084*/19085#define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */19086#define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */19087#define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */19088#define SQLITE_IDXTYPE_IPK         3   /* INTEGER PRIMARY KEY index */1908919090/* Return true if index X is a PRIMARY KEY index */19091#define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)1909219093/* Return true if index X is a UNIQUE index */19094#define IsUniqueIndex(X)      ((X)->onError!=OE_None)1909519096/* The Index.aiColumn[] values are normally positive integer.  But19097** there are some negative values that have special meaning:19098*/19099#define XN_ROWID     (-1)     /* Indexed column is the rowid */19100#define XN_EXPR      (-2)     /* Indexed column is an expression */1910119102/*19103** Each sample stored in the sqlite_stat4 table is represented in memory19104** using a structure of this type.  See documentation at the top of the19105** analyze.c source file for additional information.19106*/19107struct IndexSample {19108  void *p;          /* Pointer to sampled record */19109  int n;            /* Size of record in bytes */19110  tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */19111  tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */19112  tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */19113};1911419115/*19116** Possible values to use within the flags argument to sqlite3GetToken().19117*/19118#define SQLITE_TOKEN_QUOTED    0x1 /* Token is a quoted identifier. */19119#define SQLITE_TOKEN_KEYWORD   0x2 /* Token is a keyword. */1912019121/*19122** Each token coming out of the lexer is an instance of19123** this structure.  Tokens are also used as part of an expression.19124**19125** The memory that "z" points to is owned by other objects.  Take care19126** that the owner of the "z" string does not deallocate the string before19127** the Token goes out of scope!  Very often, the "z" points to some place19128** in the middle of the Parse.zSql text.  But it might also point to a19129** static string.19130*/19131struct Token {19132  const char *z;     /* Text of the token.  Not NULL-terminated! */19133  unsigned int n;    /* Number of characters in this token */19134};1913519136/*19137** An instance of this structure contains information needed to generate19138** code for a SELECT that contains aggregate functions.19139**19140** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a19141** pointer to this structure.  The Expr.iAgg field is the index in19142** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate19143** code for that node.19144**19145** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the19146** original Select structure that describes the SELECT statement.  These19147** fields do not need to be freed when deallocating the AggInfo structure.19148*/19149struct AggInfo {19150  u8 directMode;          /* Direct rendering mode means take data directly19151                          ** from source tables rather than from accumulators */19152  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather19153                          ** than the source table */19154  u16 nSortingColumn;     /* Number of columns in the sorting index */19155  int sortingIdx;         /* Cursor number of the sorting index */19156  int sortingIdxPTab;     /* Cursor number of pseudo-table */19157  int iFirstReg;          /* First register in range for aCol[] and aFunc[] */19158  ExprList *pGroupBy;     /* The group by clause */19159  struct AggInfo_col {    /* For each column used in source tables */19160    Table *pTab;             /* Source table */19161    Expr *pCExpr;            /* The original expression */19162    int iTable;              /* Cursor number of the source table */19163    i16 iColumn;             /* Column number within the source table */19164    i16 iSorterColumn;       /* Column number in the sorting index */19165  } *aCol;19166  int nColumn;            /* Number of used entries in aCol[] */19167  int nAccumulator;       /* Number of columns that show through to the output.19168                          ** Additional columns are used only as parameters to19169                          ** aggregate functions */19170  struct AggInfo_func {   /* For each aggregate function */19171    Expr *pFExpr;            /* Expression encoding the function */19172    FuncDef *pFunc;          /* The aggregate function implementation */19173    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */19174    int iDistAddr;           /* Address of OP_OpenEphemeral */19175    int iOBTab;              /* Ephemeral table to implement ORDER BY */19176    u8 bOBPayload;           /* iOBTab has payload columns separate from key */19177    u8 bOBUnique;            /* Enforce uniqueness on iOBTab keys */19178    u8 bUseSubtype;          /* Transfer subtype info through sorter */19179  } *aFunc;19180  int nFunc;              /* Number of entries in aFunc[] */19181  u32 selId;              /* Select to which this AggInfo belongs */19182#ifdef SQLITE_DEBUG19183  Select *pSelect;        /* SELECT statement that this AggInfo supports */19184#endif19185};1918619187/*19188** Macros to compute aCol[] and aFunc[] register numbers.19189**19190** These macros should not be used prior to the call to19191** assignAggregateRegisters() that computes the value of pAggInfo->iFirstReg.19192** The assert()s that are part of this macro verify that constraint.19193*/19194#ifndef NDEBUG19195#define AggInfoColumnReg(A,I)  (assert((A)->iFirstReg),(A)->iFirstReg+(I))19196#define AggInfoFuncReg(A,I)    \19197                      (assert((A)->iFirstReg),(A)->iFirstReg+(A)->nColumn+(I))19198#else19199#define AggInfoColumnReg(A,I)  ((A)->iFirstReg+(I))19200#define AggInfoFuncReg(A,I)    \19201                      ((A)->iFirstReg+(A)->nColumn+(I))19202#endif1920319204/*19205** The datatype ynVar is a signed integer, either 16-bit or 32-bit.19206** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater19207** than 32767 we have to make it 32-bit.  16-bit is preferred because19208** it uses less memory in the Expr object, which is a big memory user19209** in systems with lots of prepared statements.  And few applications19210** need more than about 10 or 20 variables.  But some extreme users want19211** to have prepared statements with over 32766 variables, and for them19212** the option is available (at compile-time).19213*/19214#if SQLITE_MAX_VARIABLE_NUMBER<3276719215typedef i16 ynVar;19216#else19217typedef int ynVar;19218#endif1921919220/*19221** Each node of an expression in the parse tree is an instance19222** of this structure.19223**19224** Expr.op is the opcode. The integer parser token codes are reused19225** as opcodes here. For example, the parser defines TK_GE to be an integer19226** code representing the ">=" operator. This same integer code is reused19227** to represent the greater-than-or-equal-to operator in the expression19228** tree.19229**19230** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,19231** or TK_STRING), then Expr.u.zToken contains the text of the SQL literal. If19232** the expression is a variable (TK_VARIABLE), then Expr.u.zToken contains the19233** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),19234** then Expr.u.zToken contains the name of the function.19235**19236** Expr.pRight and Expr.pLeft are the left and right subexpressions of a19237** binary operator. Either or both may be NULL.19238**19239** Expr.x.pList is a list of arguments if the expression is an SQL function,19240** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".19241** Expr.x.pSelect is used if the expression is a sub-select or an expression of19242** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the19243** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is19244** valid.19245**19246** An expression of the form ID or ID.ID refers to a column in a table.19247** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is19248** the integer cursor number of a VDBE cursor pointing to that table and19249** Expr.iColumn is the column number for the specific column.  If the19250** expression is used as a result in an aggregate SELECT, then the19251** value is also stored in the Expr.iAgg column in the aggregate so that19252** it can be accessed after all aggregates are computed.19253**19254** If the expression is an unbound variable marker (a question mark19255** character '?' in the original SQL) then the Expr.iTable holds the index19256** number for that variable.19257**19258** If the expression is a subquery then Expr.iColumn holds an integer19259** register number containing the result of the subquery.  If the19260** subquery gives a constant result, then iTable is -1.  If the subquery19261** gives a different answer at different times during statement processing19262** then iTable is the address of a subroutine that computes the subquery.19263**19264** If the Expr is of type OP_Column, and the table it is selecting from19265** is a disk table or the "old.*" pseudo-table, then pTab points to the19266** corresponding table definition.19267**19268** ALLOCATION NOTES:19269**19270** Expr objects can use a lot of memory space in database schema.  To19271** help reduce memory requirements, sometimes an Expr object will be19272** truncated.  And to reduce the number of memory allocations, sometimes19273** two or more Expr objects will be stored in a single memory allocation,19274** together with Expr.u.zToken strings.19275**19276** If the EP_Reduced and EP_TokenOnly flags are set when19277** an Expr object is truncated.  When EP_Reduced is set, then all19278** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees19279** are contained within the same memory allocation.  Note, however, that19280** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately19281** allocated, regardless of whether or not EP_Reduced is set.19282*/19283struct Expr {19284  u8 op;                 /* Operation performed by this node */19285  char affExpr;          /* affinity, or RAISE type */19286  u8 op2;                /* TK_REGISTER/TK_TRUTH: original value of Expr.op19287                         ** TK_COLUMN: the value of p5 for OP_Column19288                         ** TK_AGG_FUNCTION: nesting depth19289                         ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */19290#ifdef SQLITE_DEBUG19291  u8 vvaFlags;           /* Verification flags. */19292#endif19293  u32 flags;             /* Various flags.  EP_* See below */19294  union {19295    char *zToken;          /* Token value. Zero terminated and dequoted */19296    int iValue;            /* Non-negative integer value if EP_IntValue */19297  } u;1929819299  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no19300  ** space is allocated for the fields below this point. An attempt to19301  ** access them will result in a segfault or malfunction.19302  *********************************************************************/1930319304  Expr *pLeft;           /* Left subnode */19305  Expr *pRight;          /* Right subnode */19306  union {19307    ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */19308    Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */19309  } x;1931019311  /* If the EP_Reduced flag is set in the Expr.flags mask, then no19312  ** space is allocated for the fields below this point. An attempt to19313  ** access them will result in a segfault or malfunction.19314  *********************************************************************/1931519316#if SQLITE_MAX_EXPR_DEPTH>019317  int nHeight;           /* Height of the tree headed by this node */19318#endif19319  int iTable;            /* TK_COLUMN: cursor number of table holding column19320                         ** TK_REGISTER: register number19321                         ** TK_TRIGGER: 1 -> new, 0 -> old19322                         ** EP_Unlikely:  134217728 times likelihood19323                         ** TK_IN: ephemeral table holding RHS19324                         ** TK_SELECT_COLUMN: Number of columns on the LHS19325                         ** TK_SELECT: 1st register of result vector */19326  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.19327                         ** TK_VARIABLE: variable number (always >= 1).19328                         ** TK_SELECT_COLUMN: column of the result vector */19329  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */19330  union {19331    int iJoin;             /* If EP_OuterON or EP_InnerON, the right table */19332    int iOfst;             /* else: start of token from start of statement */19333  } w;19334  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */19335  union {19336    Table *pTab;           /* TK_COLUMN: Table containing column. Can be NULL19337                           ** for a column of an index on an expression */19338    Window *pWin;          /* EP_WinFunc: Window/Filter defn for a function */19339    struct {               /* TK_IN, TK_SELECT, and TK_EXISTS */19340      int iAddr;             /* Subroutine entry address */19341      int regReturn;         /* Register used to hold return address */19342    } sub;19343  } y;19344};1934519346/* The following are the meanings of bits in the Expr.flags field.19347** Value restrictions:19348**19349**          EP_Agg == NC_HasAgg == SF_HasAgg19350**          EP_Win == NC_HasWin19351*/19352#define EP_OuterON    0x000001 /* Originates in ON/USING clause of outer join */19353#define EP_InnerON    0x000002 /* Originates in ON/USING of an inner join */19354#define EP_Distinct   0x000004 /* Aggregate function with DISTINCT keyword */19355#define EP_HasFunc    0x000008 /* Contains one or more functions of any kind */19356#define EP_Agg        0x000010 /* Contains one or more aggregate functions */19357#define EP_FixedCol   0x000020 /* TK_Column with a known fixed value */19358#define EP_VarSelect  0x000040 /* pSelect is correlated, not constant */19359#define EP_DblQuoted  0x000080 /* token.z was originally in "..." */19360#define EP_InfixFunc  0x000100 /* True for an infix function: LIKE, GLOB, etc */19361#define EP_Collate    0x000200 /* Tree contains a TK_COLLATE operator */19362#define EP_Commuted   0x000400 /* Comparison operator has been commuted */19363#define EP_IntValue   0x000800 /* Integer value contained in u.iValue */19364#define EP_xIsSelect  0x001000 /* x.pSelect is valid (otherwise x.pList is) */19365#define EP_Skip       0x002000 /* Operator does not contribute to affinity */19366#define EP_Reduced    0x004000 /* Expr struct EXPR_REDUCEDSIZE bytes only */19367#define EP_Win        0x008000 /* Contains window functions */19368#define EP_TokenOnly  0x010000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */19369#define EP_FullSize   0x020000 /* Expr structure must remain full sized */19370#define EP_IfNullRow  0x040000 /* The TK_IF_NULL_ROW opcode */19371#define EP_Unlikely   0x080000 /* unlikely() or likelihood() function */19372#define EP_ConstFunc  0x100000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */19373#define EP_CanBeNull  0x200000 /* Can be null despite NOT NULL constraint */19374#define EP_Subquery   0x400000 /* Tree contains a TK_SELECT operator */19375#define EP_Leaf       0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */19376#define EP_WinFunc   0x1000000 /* TK_FUNCTION with Expr.y.pWin set */19377#define EP_Subrtn    0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */19378#define EP_Quoted    0x4000000 /* TK_ID was originally quoted */19379#define EP_Static    0x8000000 /* Held in memory not obtained from malloc() */19380#define EP_IsTrue   0x10000000 /* Always has boolean value of TRUE */19381#define EP_IsFalse  0x20000000 /* Always has boolean value of FALSE */19382#define EP_FromDDL  0x40000000 /* Originates from sqlite_schema */19383#define EP_SubtArg  0x80000000 /* Is argument to SQLITE_SUBTYPE function */1938419385/* The EP_Propagate mask is a set of properties that automatically propagate19386** upwards into parent nodes.19387*/19388#define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)1938919390/* Macros can be used to test, set, or clear bits in the19391** Expr.flags field.19392*/19393#define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)19394#define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))19395#define ExprSetProperty(E,P)     (E)->flags|=(P)19396#define ExprClearProperty(E,P)   (E)->flags&=~(P)19397#define ExprAlwaysTrue(E)   (((E)->flags&(EP_OuterON|EP_IsTrue))==EP_IsTrue)19398#define ExprAlwaysFalse(E)  (((E)->flags&(EP_OuterON|EP_IsFalse))==EP_IsFalse)19399#define ExprIsFullSize(E)   (((E)->flags&(EP_Reduced|EP_TokenOnly))==0)1940019401/* Macros used to ensure that the correct members of unions are accessed19402** in Expr.19403*/19404#define ExprUseUToken(E)    (((E)->flags&EP_IntValue)==0)19405#define ExprUseUValue(E)    (((E)->flags&EP_IntValue)!=0)19406#define ExprUseWOfst(E)     (((E)->flags&(EP_InnerON|EP_OuterON))==0)19407#define ExprUseWJoin(E)     (((E)->flags&(EP_InnerON|EP_OuterON))!=0)19408#define ExprUseXList(E)     (((E)->flags&EP_xIsSelect)==0)19409#define ExprUseXSelect(E)   (((E)->flags&EP_xIsSelect)!=0)19410#define ExprUseYTab(E)      (((E)->flags&(EP_WinFunc|EP_Subrtn))==0)19411#define ExprUseYWin(E)      (((E)->flags&EP_WinFunc)!=0)19412#define ExprUseYSub(E)      (((E)->flags&EP_Subrtn)!=0)1941319414/* Flags for use with Expr.vvaFlags19415*/19416#define EP_NoReduce   0x01  /* Cannot EXPRDUP_REDUCE this Expr */19417#define EP_Immutable  0x02  /* Do not change this Expr node */1941819419/* The ExprSetVVAProperty() macro is used for Verification, Validation,19420** and Accreditation only.  It works like ExprSetProperty() during VVA19421** processes but is a no-op for delivery.19422*/19423#ifdef SQLITE_DEBUG19424# define ExprSetVVAProperty(E,P)   (E)->vvaFlags|=(P)19425# define ExprHasVVAProperty(E,P)   (((E)->vvaFlags&(P))!=0)19426# define ExprClearVVAProperties(E) (E)->vvaFlags = 019427#else19428# define ExprSetVVAProperty(E,P)19429# define ExprHasVVAProperty(E,P)   019430# define ExprClearVVAProperties(E)19431#endif1943219433/*19434** Macros to determine the number of bytes required by a normal Expr19435** struct, an Expr struct with the EP_Reduced flag set in Expr.flags19436** and an Expr struct with the EP_TokenOnly flag set.19437*/19438#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */19439#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */19440#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */1944119442/*19443** Flags passed to the sqlite3ExprDup() function. See the header comment19444** above sqlite3ExprDup() for details.19445*/19446#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */1944719448/*19449** True if the expression passed as an argument was a function with19450** an OVER() clause (a window function).19451*/19452#ifdef SQLITE_OMIT_WINDOWFUNC19453# define IsWindowFunc(p) 019454#else19455# define IsWindowFunc(p) ( \19456    ExprHasProperty((p), EP_WinFunc) && p->y.pWin->eFrmType!=TK_FILTER \19457 )19458#endif1945919460/*19461** A list of expressions.  Each expression may optionally have a19462** name.  An expr/name combination can be used in several ways, such19463** as the list of "expr AS ID" fields following a "SELECT" or in the19464** list of "ID = expr" items in an UPDATE.  A list of expressions can19465** also be used as the argument to a function, in which case the a.zName19466** field is not used.19467**19468** In order to try to keep memory usage down, the Expr.a.zEName field19469** is used for multiple purposes:19470**19471**     eEName          Usage19472**    ----------       -------------------------19473**    ENAME_NAME       (1) the AS of result set column19474**                     (2) COLUMN= of an UPDATE19475**19476**    ENAME_TAB        DB.TABLE.NAME used to resolve names19477**                     of subqueries19478**19479**    ENAME_SPAN       Text of the original result set19480**                     expression.19481*/19482struct ExprList {19483  int nExpr;             /* Number of expressions on the list */19484  int nAlloc;            /* Number of a[] slots allocated */19485  struct ExprList_item { /* For each expression in the list */19486    Expr *pExpr;            /* The parse tree for this expression */19487    char *zEName;           /* Token associated with this expression */19488    struct {19489      u8 sortFlags;           /* Mask of KEYINFO_ORDER_* flags */19490      unsigned eEName :2;     /* Meaning of zEName */19491      unsigned done :1;       /* Indicates when processing is finished */19492      unsigned reusable :1;   /* Constant expression is reusable */19493      unsigned bSorterRef :1; /* Defer evaluation until after sorting */19494      unsigned bNulls :1;     /* True if explicit "NULLS FIRST/LAST" */19495      unsigned bUsed :1;      /* This column used in a SF_NestedFrom subquery */19496      unsigned bUsingTerm:1;  /* Term from the USING clause of a NestedFrom */19497      unsigned bNoExpand: 1;  /* Term is an auxiliary in NestedFrom and should19498                              ** not be expanded by "*" in parent queries */19499    } fg;19500    union {19501      struct {             /* Used by any ExprList other than Parse.pConsExpr */19502        u16 iOrderByCol;      /* For ORDER BY, column number in result set */19503        u16 iAlias;           /* Index into Parse.aAlias[] for zName */19504      } x;19505      int iConstExprReg;   /* Register in which Expr value is cached. Used only19506                           ** by Parse.pConstExpr */19507    } u;19508  } a[1];                  /* One slot for each expression in the list */19509};1951019511/*19512** Allowed values for Expr.a.eEName19513*/19514#define ENAME_NAME  0       /* The AS clause of a result set */19515#define ENAME_SPAN  1       /* Complete text of the result set expression */19516#define ENAME_TAB   2       /* "DB.TABLE.NAME" for the result set */19517#define ENAME_ROWID 3       /* "DB.TABLE._rowid_" for * expansion of rowid */1951819519/*19520** An instance of this structure can hold a simple list of identifiers,19521** such as the list "a,b,c" in the following statements:19522**19523**      INSERT INTO t(a,b,c) VALUES ...;19524**      CREATE INDEX idx ON t(a,b,c);19525**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;19526**19527** The IdList.a.idx field is used when the IdList represents the list of19528** column names after a table name in an INSERT statement.  In the statement19529**19530**     INSERT INTO t(a,b,c) ...19531**19532** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.19533*/19534struct IdList {19535  int nId;         /* Number of identifiers on the list */19536  struct IdList_item {19537    char *zName;      /* Name of the identifier */19538  } a[1];19539};1954019541/*19542** Allowed values for IdList.eType, which determines which value of the a.u419543** is valid.19544*/19545#define EU4_NONE   0   /* Does not use IdList.a.u4 */19546#define EU4_IDX    1   /* Uses IdList.a.u4.idx */19547#define EU4_EXPR   2   /* Uses IdList.a.u4.pExpr -- NOT CURRENTLY USED */1954819549/*19550** Details of the implementation of a subquery.19551*/19552struct Subquery {19553  Select *pSelect;  /* A SELECT statement used in place of a table name */19554  int addrFillSub;  /* Address of subroutine to initialize a subquery */19555  int regReturn;    /* Register holding return address of addrFillSub */19556  int regResult;    /* Registers holding results of a co-routine */19557};1955819559/*19560** The SrcItem object represents a single term in the FROM clause of a query.19561** The SrcList object is mostly an array of SrcItems.19562**19563** The jointype starts out showing the join type between the current table19564** and the next table on the list.  The parser builds the list this way.19565** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each19566** jointype expresses the join between the table and the previous table.19567**19568** In the colUsed field, the high-order bit (bit 63) is set if the table19569** contains more than 63 columns and the 64-th or later column is used.19570**19571** Aggressive use of "union" helps keep the size of the object small.  This19572** has been shown to boost performance, in addition to saving memory.19573** Access to union elements is gated by the following rules which should19574** always be checked, either by an if-statement or by an assert().19575**19576**    Field              Only access if this is true19577**    ---------------    -----------------------------------19578**    u1.zIndexedBy      fg.isIndexedBy19579**    u1.pFuncArg        fg.isTabFunc19580**    u1.nRow            !fg.isTabFunc  && !fg.isIndexedBy19581**19582**    u2.pIBIndex        fg.isIndexedBy19583**    u2.pCteUse         fg.isCte19584**19585**    u3.pOn             !fg.isUsing19586**    u3.pUsing          fg.isUsing19587**19588**    u4.zDatabase       !fg.fixedSchema && !fg.isSubquery19589**    u4.pSchema         fg.fixedSchema19590**    u4.pSubq           fg.isSubquery19591**19592** See also the sqlite3SrcListDelete() routine for assert() statements that19593** check invariants on the fields of this object, especially the flags19594** inside the fg struct.19595*/19596struct SrcItem {19597  char *zName;      /* Name of the table */19598  char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */19599  Table *pSTab;     /* Table object for zName. Mnemonic: Srcitem-TABle */19600  struct {19601    u8 jointype;      /* Type of join between this table and the previous */19602    unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */19603    unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */19604    unsigned isSubquery :1;    /* True if this term is a subquery */19605    unsigned isTabFunc :1;     /* True if table-valued-function syntax */19606    unsigned isCorrelated :1;  /* True if sub-query is correlated */19607    unsigned isMaterialized:1; /* This is a materialized view */19608    unsigned viaCoroutine :1;  /* Implemented as a co-routine */19609    unsigned isRecursive :1;   /* True for recursive reference in WITH */19610    unsigned fromDDL :1;       /* Comes from sqlite_schema */19611    unsigned isCte :1;         /* This is a CTE */19612    unsigned notCte :1;        /* This item may not match a CTE */19613    unsigned isUsing :1;       /* u3.pUsing is valid */19614    unsigned isOn :1;          /* u3.pOn was once valid and non-NULL */19615    unsigned isSynthUsing :1;  /* u3.pUsing is synthesized from NATURAL */19616    unsigned isNestedFrom :1;  /* pSelect is a SF_NestedFrom subquery */19617    unsigned rowidUsed :1;     /* The ROWID of this table is referenced */19618    unsigned fixedSchema :1;   /* Uses u4.pSchema, not u4.zDatabase */19619    unsigned hadSchema :1;     /* Had u4.zDatabase before u4.pSchema */19620  } fg;19621  int iCursor;      /* The VDBE cursor number used to access this table */19622  Bitmask colUsed;  /* Bit N set if column N used. Details above for N>62 */19623  union {19624    char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */19625    ExprList *pFuncArg;  /* Arguments to table-valued-function */19626    u32 nRow;            /* Number of rows in a VALUES clause */19627  } u1;19628  union {19629    Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */19630    CteUse *pCteUse;  /* CTE Usage info when fg.isCte is true */19631  } u2;19632  union {19633    Expr *pOn;        /* fg.isUsing==0 =>  The ON clause of a join */19634    IdList *pUsing;   /* fg.isUsing==1 =>  The USING clause of a join */19635  } u3;19636  union {19637    Schema *pSchema;  /* Schema to which this item is fixed */19638    char *zDatabase;  /* Name of database holding this table */19639    Subquery *pSubq;  /* Description of a subquery */19640  } u4;19641};1964219643/*19644** The OnOrUsing object represents either an ON clause or a USING clause.19645** It can never be both at the same time, but it can be neither.19646*/19647struct OnOrUsing {19648  Expr *pOn;         /* The ON clause of a join */19649  IdList *pUsing;    /* The USING clause of a join */19650};1965119652/*19653** This object represents one or more tables that are the source of19654** content for an SQL statement.  For example, a single SrcList object19655** is used to hold the FROM clause of a SELECT statement.  SrcList also19656** represents the target tables for DELETE, INSERT, and UPDATE statements.19657**19658*/19659struct SrcList {19660  int nSrc;        /* Number of tables or subqueries in the FROM clause */19661  u32 nAlloc;      /* Number of entries allocated in a[] below */19662  SrcItem a[1];    /* One entry for each identifier on the list */19663};1966419665/*19666** Permitted values of the SrcList.a.jointype field19667*/19668#define JT_INNER     0x01    /* Any kind of inner or cross join */19669#define JT_CROSS     0x02    /* Explicit use of the CROSS keyword */19670#define JT_NATURAL   0x04    /* True for a "natural" join */19671#define JT_LEFT      0x08    /* Left outer join */19672#define JT_RIGHT     0x10    /* Right outer join */19673#define JT_OUTER     0x20    /* The "OUTER" keyword is present */19674#define JT_LTORJ     0x40    /* One of the LEFT operands of a RIGHT JOIN19675                             ** Mnemonic: Left Table Of Right Join */19676#define JT_ERROR     0x80    /* unknown or unsupported join type */1967719678/*19679** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()19680** and the WhereInfo.wctrlFlags member.19681**19682** Value constraints (enforced via assert()):19683**     WHERE_USE_LIMIT  == SF_FixedLimit19684*/19685#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */19686#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */19687#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */19688#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */19689#define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */19690#define WHERE_DUPLICATES_OK    0x0010 /* Ok to return a row more than once */19691#define WHERE_OR_SUBCLAUSE     0x0020 /* Processing a sub-WHERE as part of19692                                      ** the OR optimization  */19693#define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */19694#define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */19695#define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */19696#define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */19697#define WHERE_AGG_DISTINCT     0x0400 /* Query is "SELECT agg(DISTINCT ...)" */19698#define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */19699#define WHERE_RIGHT_JOIN       0x1000 /* Processing a RIGHT JOIN */19700#define WHERE_KEEP_ALL_JOINS   0x2000 /* Do not do the omit-noop-join opt */19701#define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */19702                        /*     0x8000    not currently used */1970319704/* Allowed return values from sqlite3WhereIsDistinct()19705*/19706#define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */19707#define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */19708#define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */19709#define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */1971019711/*19712** A NameContext defines a context in which to resolve table and column19713** names.  The context consists of a list of tables (the pSrcList) field and19714** a list of named expression (pEList).  The named expression list may19715** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or19716** to the table being operated on by INSERT, UPDATE, or DELETE.  The19717** pEList corresponds to the result set of a SELECT and is NULL for19718** other statements.19719**19720** NameContexts can be nested.  When resolving names, the inner-most19721** context is searched first.  If no match is found, the next outer19722** context is checked.  If there is still no match, the next context19723** is checked.  This process continues until either a match is found19724** or all contexts are check.  When a match is found, the nRef member of19725** the context containing the match is incremented.19726**19727** Each subquery gets a new NameContext.  The pNext field points to the19728** NameContext in the parent query.  Thus the process of scanning the19729** NameContext list corresponds to searching through successively outer19730** subqueries looking for a match.19731*/19732struct NameContext {19733  Parse *pParse;       /* The parser */19734  SrcList *pSrcList;   /* One or more tables used to resolve names */19735  union {19736    ExprList *pEList;    /* Optional list of result-set columns */19737    AggInfo *pAggInfo;   /* Information about aggregates at this level */19738    Upsert *pUpsert;     /* ON CONFLICT clause information from an upsert */19739    int iBaseReg;        /* For TK_REGISTER when parsing RETURNING */19740  } uNC;19741  NameContext *pNext;  /* Next outer name context.  NULL for outermost */19742  int nRef;            /* Number of names resolved by this context */19743  int nNcErr;          /* Number of errors encountered while resolving names */19744  int ncFlags;         /* Zero or more NC_* flags defined below */19745  u32 nNestedSelect;   /* Number of nested selects using this NC */19746  Select *pWinSelect;  /* SELECT statement for any window functions */19747};1974819749/*19750** Allowed values for the NameContext, ncFlags field.19751**19752** Value constraints (all checked via assert()):19753**    NC_HasAgg    == SF_HasAgg       == EP_Agg19754**    NC_MinMaxAgg == SF_MinMaxAgg    == SQLITE_FUNC_MINMAX19755**    NC_OrderAgg  == SF_OrderByReqd  == SQLITE_FUNC_ANYORDER19756**    NC_HasWin    == EP_Win19757**19758*/19759#define NC_AllowAgg  0x000001 /* Aggregate functions are allowed here */19760#define NC_PartIdx   0x000002 /* True if resolving a partial index WHERE */19761#define NC_IsCheck   0x000004 /* True if resolving a CHECK constraint */19762#define NC_GenCol    0x000008 /* True for a GENERATED ALWAYS AS clause */19763#define NC_HasAgg    0x000010 /* One or more aggregate functions seen */19764#define NC_IdxExpr   0x000020 /* True if resolving columns of CREATE INDEX */19765#define NC_SelfRef   0x00002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */19766#define NC_Subquery  0x000040 /* A subquery has been seen */19767#define NC_UEList    0x000080 /* True if uNC.pEList is used */19768#define NC_UAggInfo  0x000100 /* True if uNC.pAggInfo is used */19769#define NC_UUpsert   0x000200 /* True if uNC.pUpsert is used */19770#define NC_UBaseReg  0x000400 /* True if uNC.iBaseReg is used */19771#define NC_MinMaxAgg 0x001000 /* min/max aggregates seen.  See note above */19772/*                   0x002000 // available for reuse */19773#define NC_AllowWin  0x004000 /* Window functions are allowed here */19774#define NC_HasWin    0x008000 /* One or more window functions seen */19775#define NC_IsDDL     0x010000 /* Resolving names in a CREATE statement */19776#define NC_InAggFunc 0x020000 /* True if analyzing arguments to an agg func */19777#define NC_FromDDL   0x040000 /* SQL text comes from sqlite_schema */19778#define NC_NoSelect  0x080000 /* Do not descend into sub-selects */19779#define NC_Where     0x100000 /* Processing WHERE clause of a SELECT */19780#define NC_OrderAgg 0x8000000 /* Has an aggregate other than count/min/max */1978119782/*19783** An instance of the following object describes a single ON CONFLICT19784** clause in an upsert.19785**19786** The pUpsertTarget field is only set if the ON CONFLICT clause includes19787** conflict-target clause.  (In "ON CONFLICT(a,b)" the "(a,b)" is the19788** conflict-target clause.)  The pUpsertTargetWhere is the optional19789** WHERE clause used to identify partial unique indexes.19790**19791** pUpsertSet is the list of column=expr terms of the UPDATE statement.19792** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING.  The19793** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the19794** WHERE clause is omitted.19795*/19796struct Upsert {19797  ExprList *pUpsertTarget;  /* Optional description of conflict target */19798  Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */19799  ExprList *pUpsertSet;     /* The SET clause from an ON CONFLICT UPDATE */19800  Expr *pUpsertWhere;       /* WHERE clause for the ON CONFLICT UPDATE */19801  Upsert *pNextUpsert;      /* Next ON CONFLICT clause in the list */19802  u8 isDoUpdate;            /* True for DO UPDATE.  False for DO NOTHING */19803  u8 isDup;                 /* True if 2nd or later with same pUpsertIdx */19804  /* Above this point is the parse tree for the ON CONFLICT clauses.19805  ** The next group of fields stores intermediate data. */19806  void *pToFree;            /* Free memory when deleting the Upsert object */19807  /* All fields above are owned by the Upsert object and must be freed19808  ** when the Upsert is destroyed.  The fields below are used to transfer19809  ** information from the INSERT processing down into the UPDATE processing19810  ** while generating code.  The fields below are owned by the INSERT19811  ** statement and will be freed by INSERT processing. */19812  Index *pUpsertIdx;        /* UNIQUE constraint specified by pUpsertTarget */19813  SrcList *pUpsertSrc;      /* Table to be updated */19814  int regData;              /* First register holding array of VALUES */19815  int iDataCur;             /* Index of the data cursor */19816  int iIdxCur;              /* Index of the first index cursor */19817};1981819819/*19820** An instance of the following structure contains all information19821** needed to generate code for a single SELECT statement.19822**19823** See the header comment on the computeLimitRegisters() routine for a19824** detailed description of the meaning of the iLimit and iOffset fields.19825**19826** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.19827** These addresses must be stored so that we can go back and fill in19828** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor19829** the number of columns in P2 can be computed at the same time19830** as the OP_OpenEphm instruction is coded because not19831** enough information about the compound query is known at that point.19832** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences19833** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating19834** sequences for the ORDER BY clause.19835*/19836struct Select {19837  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */19838  LogEst nSelectRow;     /* Estimated number of result rows */19839  u32 selFlags;          /* Various SF_* values */19840  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */19841  u32 selId;             /* Unique identifier number for this SELECT */19842  int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */19843  ExprList *pEList;      /* The fields of the result */19844  SrcList *pSrc;         /* The FROM clause */19845  Expr *pWhere;          /* The WHERE clause */19846  ExprList *pGroupBy;    /* The GROUP BY clause */19847  Expr *pHaving;         /* The HAVING clause */19848  ExprList *pOrderBy;    /* The ORDER BY clause */19849  Select *pPrior;        /* Prior select in a compound select statement */19850  Select *pNext;         /* Next select to the left in a compound */19851  Expr *pLimit;          /* LIMIT expression. NULL means not used. */19852  With *pWith;           /* WITH clause attached to this select. Or NULL. */19853#ifndef SQLITE_OMIT_WINDOWFUNC19854  Window *pWin;          /* List of window functions */19855  Window *pWinDefn;      /* List of named window definitions */19856#endif19857};1985819859/*19860** Allowed values for Select.selFlags.  The "SF" prefix stands for19861** "Select Flag".19862**19863** Value constraints (all checked via assert())19864**     SF_HasAgg      == NC_HasAgg19865**     SF_MinMaxAgg   == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX19866**     SF_OrderByReqd == NC_OrderAgg      == SQLITE_FUNC_ANYORDER19867**     SF_FixedLimit  == WHERE_USE_LIMIT19868*/19869#define SF_Distinct      0x0000001 /* Output should be DISTINCT */19870#define SF_All           0x0000002 /* Includes the ALL keyword */19871#define SF_Resolved      0x0000004 /* Identifiers have been resolved */19872#define SF_Aggregate     0x0000008 /* Contains agg functions or a GROUP BY */19873#define SF_HasAgg        0x0000010 /* Contains aggregate functions */19874#define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */19875#define SF_Expanded      0x0000040 /* sqlite3SelectExpand() called on this */19876#define SF_HasTypeInfo   0x0000080 /* FROM subqueries have Table metadata */19877#define SF_Compound      0x0000100 /* Part of a compound query */19878#define SF_Values        0x0000200 /* Synthesized from VALUES clause */19879#define SF_MultiValue    0x0000400 /* Single VALUES term with multiple rows */19880#define SF_NestedFrom    0x0000800 /* Part of a parenthesized FROM clause */19881#define SF_MinMaxAgg     0x0001000 /* Aggregate containing min() or max() */19882#define SF_Recursive     0x0002000 /* The recursive part of a recursive CTE */19883#define SF_FixedLimit    0x0004000 /* nSelectRow set by a constant LIMIT */19884#define SF_MaybeConvert  0x0008000 /* Need convertCompoundSelectToSubquery() */19885#define SF_Converted     0x0010000 /* By convertCompoundSelectToSubquery() */19886#define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */19887#define SF_ComplexResult 0x0040000 /* Result contains subquery or function */19888#define SF_WhereBegin    0x0080000 /* Really a WhereBegin() call.  Debug Only */19889#define SF_WinRewrite    0x0100000 /* Window function rewrite accomplished */19890#define SF_View          0x0200000 /* SELECT statement is a view */19891#define SF_NoopOrderBy   0x0400000 /* ORDER BY is ignored for this query */19892#define SF_UFSrcCheck    0x0800000 /* Check pSrc as required by UPDATE...FROM */19893#define SF_PushDown      0x1000000 /* Modified by WHERE-clause push-down opt */19894#define SF_MultiPart     0x2000000 /* Has multiple incompatible PARTITIONs */19895#define SF_CopyCte       0x4000000 /* SELECT statement is a copy of a CTE */19896#define SF_OrderByReqd   0x8000000 /* The ORDER BY clause may not be omitted */19897#define SF_UpdateFrom   0x10000000 /* Query originates with UPDATE FROM */19898#define SF_Correlated   0x20000000 /* True if references the outer context */1989919900/* True if SrcItem X is a subquery that has SF_NestedFrom */19901#define IsNestedFrom(X) \19902   ((X)->fg.isSubquery && \19903    ((X)->u4.pSubq->pSelect->selFlags&SF_NestedFrom)!=0)1990419905/*19906** The results of a SELECT can be distributed in several ways, as defined19907** by one of the following macros.  The "SRT" prefix means "SELECT Result19908** Type".19909**19910**     SRT_Union       Store results as a key in a temporary index19911**                     identified by pDest->iSDParm.19912**19913**     SRT_Except      Remove results from the temporary index pDest->iSDParm.19914**19915**     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result19916**                     set is not empty.19917**19918**     SRT_Discard     Throw the results away.  This is used by SELECT19919**                     statements within triggers whose only purpose is19920**                     the side-effects of functions.19921**19922**     SRT_Output      Generate a row of output (using the OP_ResultRow19923**                     opcode) for each row in the result set.19924**19925**     SRT_Mem         Only valid if the result is a single column.19926**                     Store the first column of the first result row19927**                     in register pDest->iSDParm then abandon the rest19928**                     of the query.  This destination implies "LIMIT 1".19929**19930**     SRT_Set         The result must be a single column.  Store each19931**                     row of result as the key in table pDest->iSDParm.19932**                     Apply the affinity pDest->affSdst before storing19933**                     results.  if pDest->iSDParm2 is positive, then it is19934**                     a register holding a Bloom filter for the IN operator19935**                     that should be populated in addition to the19936**                     pDest->iSDParm table.  This SRT is used to19937**                     implement "IN (SELECT ...)".19938**19939**     SRT_EphemTab    Create an temporary table pDest->iSDParm and store19940**                     the result there. The cursor is left open after19941**                     returning.  This is like SRT_Table except that19942**                     this destination uses OP_OpenEphemeral to create19943**                     the table first.19944**19945**     SRT_Coroutine   Generate a co-routine that returns a new row of19946**                     results each time it is invoked.  The entry point19947**                     of the co-routine is stored in register pDest->iSDParm19948**                     and the result row is stored in pDest->nDest registers19949**                     starting with pDest->iSdst.19950**19951**     SRT_Table       Store results in temporary table pDest->iSDParm.19952**     SRT_Fifo        This is like SRT_EphemTab except that the table19953**                     is assumed to already be open.  SRT_Fifo has19954**                     the additional property of being able to ignore19955**                     the ORDER BY clause.19956**19957**     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.19958**                     But also use temporary table pDest->iSDParm+1 as19959**                     a record of all prior results and ignore any duplicate19960**                     rows.  Name means:  "Distinct Fifo".19961**19962**     SRT_Queue       Store results in priority queue pDest->iSDParm (really19963**                     an index).  Append a sequence number so that all entries19964**                     are distinct.19965**19966**     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if19967**                     the same record has never been stored before.  The19968**                     index at pDest->iSDParm+1 hold all prior stores.19969**19970**     SRT_Upfrom      Store results in the temporary table already opened by19971**                     pDest->iSDParm. If (pDest->iSDParm<0), then the temp19972**                     table is an intkey table - in this case the first19973**                     column returned by the SELECT is used as the integer19974**                     key. If (pDest->iSDParm>0), then the table is an index19975**                     table. (pDest->iSDParm) is the number of key columns in19976**                     each index record in this case.19977*/19978#define SRT_Union        1  /* Store result as keys in an index */19979#define SRT_Except       2  /* Remove result from a UNION index */19980#define SRT_Exists       3  /* Store 1 if the result is not empty */19981#define SRT_Discard      4  /* Do not save the results anywhere */19982#define SRT_DistFifo     5  /* Like SRT_Fifo, but unique results only */19983#define SRT_DistQueue    6  /* Like SRT_Queue, but unique results only */1998419985/* The DISTINCT clause is ignored for all of the above.  Not that19986** IgnorableDistinct() implies IgnorableOrderby() */19987#define IgnorableDistinct(X) ((X->eDest)<=SRT_DistQueue)1998819989#define SRT_Queue        7  /* Store result in an queue */19990#define SRT_Fifo         8  /* Store result as data with an automatic rowid */1999119992/* The ORDER BY clause is ignored for all of the above */19993#define IgnorableOrderby(X) ((X->eDest)<=SRT_Fifo)1999419995#define SRT_Output       9  /* Output each row of result */19996#define SRT_Mem         10  /* Store result in a memory cell */19997#define SRT_Set         11  /* Store results as keys in an index */19998#define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */19999#define SRT_Coroutine   13  /* Generate a single row of result */20000#define SRT_Table       14  /* Store result as data with an automatic rowid */20001#define SRT_Upfrom      15  /* Store result as data with rowid */2000220003/*20004** An instance of this object describes where to put of the results of20005** a SELECT statement.20006*/20007struct SelectDest {20008  u8 eDest;            /* How to dispose of the results.  One of SRT_* above. */20009  int iSDParm;         /* A parameter used by the eDest disposal method */20010  int iSDParm2;        /* A second parameter for the eDest disposal method */20011  int iSdst;           /* Base register where results are written */20012  int nSdst;           /* Number of registers allocated */20013  char *zAffSdst;      /* Affinity used for SRT_Set */20014  ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */20015};2001620017/*20018** During code generation of statements that do inserts into AUTOINCREMENT20019** tables, the following information is attached to the Table.u.autoInc.p20020** pointer of each autoincrement table to record some side information that20021** the code generator needs.  We have to keep per-table autoincrement20022** information in case inserts are done within triggers.  Triggers do not20023** normally coordinate their activities, but we do need to coordinate the20024** loading and saving of autoincrement information.20025*/20026struct AutoincInfo {20027  AutoincInfo *pNext;   /* Next info block in a list of them all */20028  Table *pTab;          /* Table this info block refers to */20029  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */20030  int regCtr;           /* Memory register holding the rowid counter */20031};2003220033/*20034** At least one instance of the following structure is created for each20035** trigger that may be fired while parsing an INSERT, UPDATE or DELETE20036** statement. All such objects are stored in the linked list headed at20037** Parse.pTriggerPrg and deleted once statement compilation has been20038** completed.20039**20040** A Vdbe sub-program that implements the body and WHEN clause of trigger20041** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of20042** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.20043** The Parse.pTriggerPrg list never contains two entries with the same20044** values for both pTrigger and orconf.20045**20046** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns20047** accessed (or set to 0 for triggers fired as a result of INSERT20048** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to20049** a mask of new.* columns used by the program.20050*/20051struct TriggerPrg {20052  Trigger *pTrigger;      /* Trigger this program was coded from */20053  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */20054  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */20055  int orconf;             /* Default ON CONFLICT policy */20056  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */20057};2005820059/*20060** The yDbMask datatype for the bitmask of all attached databases.20061*/20062#if SQLITE_MAX_ATTACHED>3020063  typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];20064# define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)20065# define DbMaskZero(M)      memset((M),0,sizeof(M))20066# define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))20067# define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)20068# define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)20069#else20070  typedef unsigned int yDbMask;20071# define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)20072# define DbMaskZero(M)      ((M)=0)20073# define DbMaskSet(M,I)     ((M)|=(((yDbMask)1)<<(I)))20074# define DbMaskAllZero(M)   ((M)==0)20075# define DbMaskNonZero(M)   ((M)!=0)20076#endif2007720078/*20079** For each index X that has as one of its arguments either an expression20080** or the name of a virtual generated column, and if X is in scope such that20081** the value of the expression can simply be read from the index, then20082** there is an instance of this object on the Parse.pIdxExpr list.20083**20084** During code generation, while generating code to evaluate expressions,20085** this list is consulted and if a matching expression is found, the value20086** is read from the index rather than being recomputed.20087*/20088struct IndexedExpr {20089  Expr *pExpr;            /* The expression contained in the index */20090  int iDataCur;           /* The data cursor associated with the index */20091  int iIdxCur;            /* The index cursor */20092  int iIdxCol;            /* The index column that contains value of pExpr */20093  u8 bMaybeNullRow;       /* True if we need an OP_IfNullRow check */20094  u8 aff;                 /* Affinity of the pExpr expression */20095  IndexedExpr *pIENext;   /* Next in a list of all indexed expressions */20096#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS20097  const char *zIdxName;   /* Name of index, used only for bytecode comments */20098#endif20099};2010020101/*20102** An instance of the ParseCleanup object specifies an operation that20103** should be performed after parsing to deallocation resources obtained20104** during the parse and which are no longer needed.20105*/20106struct ParseCleanup {20107  ParseCleanup *pNext;               /* Next cleanup task */20108  void *pPtr;                        /* Pointer to object to deallocate */20109  void (*xCleanup)(sqlite3*,void*);  /* Deallocation routine */20110};2011120112/*20113** An SQL parser context.  A copy of this structure is passed through20114** the parser and down into all the parser action routine in order to20115** carry around information that is global to the entire parse.20116**20117** The structure is divided into two parts.  When the parser and code20118** generate call themselves recursively, the first part of the structure20119** is constant but the second part is reset at the beginning and end of20120** each recursion.20121**20122** The nTableLock and aTableLock variables are only used if the shared-cache20123** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are20124** used to store the set of table-locks required by the statement being20125** compiled. Function sqlite3TableLock() is used to add entries to the20126** list.20127*/20128struct Parse {20129  sqlite3 *db;         /* The main database structure */20130  char *zErrMsg;       /* An error message */20131  Vdbe *pVdbe;         /* An engine for executing database bytecode */20132  int rc;              /* Return code from execution */20133  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */20134  u8 checkSchema;      /* Causes schema cookie check after an error */20135  u8 nested;           /* Number of nested calls to the parser/code generator */20136  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */20137  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */20138  u8 mayAbort;         /* True if statement may throw an ABORT exception */20139  u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */20140  u8 okConstFactor;    /* OK to factor out constants */20141  u8 disableLookaside; /* Number of times lookaside has been disabled */20142  u8 prepFlags;        /* SQLITE_PREPARE_* flags */20143  u8 withinRJSubrtn;   /* Nesting level for RIGHT JOIN body subroutines */20144  u8 bHasWith;         /* True if statement contains WITH */20145  u8 mSubrtnSig;       /* mini Bloom filter on available SubrtnSig.selId */20146#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)20147  u8 earlyCleanup;     /* OOM inside sqlite3ParserAddCleanup() */20148#endif20149#ifdef SQLITE_DEBUG20150  u8 ifNotExists;      /* Might be true if IF NOT EXISTS.  Assert()s only */20151#endif20152  int nRangeReg;       /* Size of the temporary register block */20153  int iRangeReg;       /* First register in temporary register block */20154  int nErr;            /* Number of errors seen */20155  int nTab;            /* Number of previously allocated VDBE cursors */20156  int nMem;            /* Number of memory cells used so far */20157  int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */20158  int iSelfTab;        /* Table associated with an index on expr, or negative20159                       ** of the base register during check-constraint eval */20160  int nLabel;          /* The *negative* of the number of labels used */20161  int nLabelAlloc;     /* Number of slots in aLabel */20162  int *aLabel;         /* Space to hold the labels */20163  ExprList *pConstExpr;/* Constant expressions */20164  IndexedExpr *pIdxEpr;/* List of expressions used by active indexes */20165  IndexedExpr *pIdxPartExpr; /* Exprs constrained by index WHERE clauses */20166  Token constraintName;/* Name of the constraint currently being parsed */20167  yDbMask writeMask;   /* Start a write transaction on these databases */20168  yDbMask cookieMask;  /* Bitmask of schema verified databases */20169  int regRowid;        /* Register holding rowid of CREATE TABLE entry */20170  int regRoot;         /* Register holding root page number for new objects */20171  int nMaxArg;         /* Max args passed to user function by sub-program */20172  int nSelect;         /* Number of SELECT stmts. Counter for Select.selId */20173#ifndef SQLITE_OMIT_PROGRESS_CALLBACK20174  u32 nProgressSteps;  /* xProgress steps taken during sqlite3_prepare() */20175#endif20176#ifndef SQLITE_OMIT_SHARED_CACHE20177  int nTableLock;        /* Number of locks in aTableLock */20178  TableLock *aTableLock; /* Required table locks for shared-cache mode */20179#endif20180  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */20181  Parse *pToplevel;    /* Parse structure for main program (or NULL) */20182  Table *pTriggerTab;  /* Table triggers are being coded for */20183  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */20184  ParseCleanup *pCleanup;   /* List of cleanup operations to run after parse */20185  union {20186    int addrCrTab;         /* Address of OP_CreateBtree on CREATE TABLE */20187    Returning *pReturning; /* The RETURNING clause */20188  } u1;20189  u32 oldmask;         /* Mask of old.* columns referenced */20190  u32 newmask;         /* Mask of new.* columns referenced */20191  LogEst nQueryLoop;   /* Est number of iterations of a query (10*log2(N)) */20192  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */20193  u8 bReturning;       /* Coding a RETURNING trigger */20194  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */20195  u8 disableTriggers;  /* True to disable triggers */2019620197  /**************************************************************************20198  ** Fields above must be initialized to zero.  The fields that follow,20199  ** down to the beginning of the recursive section, do not need to be20200  ** initialized as they will be set before being used.  The boundary is20201  ** determined by offsetof(Parse,aTempReg).20202  **************************************************************************/2020320204  int aTempReg[8];        /* Holding area for temporary registers */20205  Parse *pOuterParse;     /* Outer Parse object when nested */20206  Token sNameToken;       /* Token with unqualified schema object name */2020720208  /************************************************************************20209  ** Above is constant between recursions.  Below is reset before and after20210  ** each recursion.  The boundary between these two regions is determined20211  ** using offsetof(Parse,sLastToken) so the sLastToken field must be the20212  ** first field in the recursive region.20213  ************************************************************************/2021420215  Token sLastToken;       /* The last token parsed */20216  ynVar nVar;               /* Number of '?' variables seen in the SQL so far */20217  u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */20218  u8 explain;               /* True if the EXPLAIN flag is found on the query */20219  u8 eParseMode;            /* PARSE_MODE_XXX constant */20220#ifndef SQLITE_OMIT_VIRTUALTABLE20221  int nVtabLock;            /* Number of virtual tables to lock */20222#endif20223  int nHeight;              /* Expression tree height of current sub-select */20224  int addrExplain;          /* Address of current OP_Explain opcode */20225  VList *pVList;            /* Mapping between variable names and numbers */20226  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */20227  const char *zTail;        /* All SQL text past the last semicolon parsed */20228  Table *pNewTable;         /* A table being constructed by CREATE TABLE */20229  Index *pNewIndex;         /* An index being constructed by CREATE INDEX.20230                            ** Also used to hold redundant UNIQUE constraints20231                            ** during a RENAME COLUMN */20232  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */20233  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */20234#ifndef SQLITE_OMIT_VIRTUALTABLE20235  Token sArg;               /* Complete text of a module argument */20236  Table **apVtabLock;       /* Pointer to virtual tables needing locking */20237#endif20238  With *pWith;              /* Current WITH clause, or NULL */20239#ifndef SQLITE_OMIT_ALTERTABLE20240  RenameToken *pRename;     /* Tokens subject to renaming by ALTER TABLE */20241#endif20242};2024320244/* Allowed values for Parse.eParseMode20245*/20246#define PARSE_MODE_NORMAL        020247#define PARSE_MODE_DECLARE_VTAB  120248#define PARSE_MODE_RENAME        220249#define PARSE_MODE_UNMAP         32025020251/*20252** Sizes and pointers of various parts of the Parse object.20253*/20254#define PARSE_HDR(X)  (((char*)(X))+offsetof(Parse,zErrMsg))20255#define PARSE_HDR_SZ (offsetof(Parse,aTempReg)-offsetof(Parse,zErrMsg)) /* Recursive part w/o aColCache*/20256#define PARSE_RECURSE_SZ offsetof(Parse,sLastToken)    /* Recursive part */20257#define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */20258#define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ)  /* Pointer to tail */2025920260/*20261** Return true if currently inside an sqlite3_declare_vtab() call.20262*/20263#ifdef SQLITE_OMIT_VIRTUALTABLE20264  #define IN_DECLARE_VTAB 020265#else20266  #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)20267#endif2026820269#if defined(SQLITE_OMIT_ALTERTABLE)20270  #define IN_RENAME_OBJECT 020271#else20272  #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME)20273#endif2027420275#if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)20276  #define IN_SPECIAL_PARSE 020277#else20278  #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)20279#endif2028020281/*20282** An instance of the following structure can be declared on a stack and used20283** to save the Parse.zAuthContext value so that it can be restored later.20284*/20285struct AuthContext {20286  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */20287  Parse *pParse;              /* The Parse structure */20288};2028920290/*20291** Bitfield flags for P5 value in various opcodes.20292**20293** Value constraints (enforced via assert()):20294**    OPFLAG_LENGTHARG    == SQLITE_FUNC_LENGTH20295**    OPFLAG_TYPEOFARG    == SQLITE_FUNC_TYPEOF20296**    OPFLAG_BULKCSR      == BTREE_BULKLOAD20297**    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ20298**    OPFLAG_FORDELETE    == BTREE_FORDELETE20299**    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION20300**    OPFLAG_AUXDELETE    == BTREE_AUXDELETE20301*/20302#define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */20303                                     /* Also used in P2 (not P5) of OP_Delete */20304#define OPFLAG_NOCHNG        0x01    /* OP_VColumn nochange for UPDATE */20305#define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */20306#define OPFLAG_LASTROWID     0x20    /* Set to update db->lastRowid */20307#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */20308#define OPFLAG_APPEND        0x08    /* This is likely to be an append */20309#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */20310#define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */20311#define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */20312#define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */20313#define OPFLAG_BYTELENARG    0xc0    /* OP_Column only for octet_length() */20314#define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */20315#define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */20316#define OPFLAG_FORDELETE     0x08    /* OP_Open should use BTREE_FORDELETE */20317#define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */20318#define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */20319#define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete/Insert: save cursor pos */20320#define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */20321#define OPFLAG_NOCHNG_MAGIC  0x6d    /* OP_MakeRecord: serialtype 10 is ok */20322#define OPFLAG_PREFORMAT     0x80    /* OP_Insert uses preformatted cell */2032320324/*20325** Each trigger present in the database schema is stored as an instance of20326** struct Trigger.20327**20328** Pointers to instances of struct Trigger are stored in two ways.20329** 1. In the "trigHash" hash table (part of the sqlite3* that represents the20330**    database). This allows Trigger structures to be retrieved by name.20331** 2. All triggers associated with a single table form a linked list, using the20332**    pNext member of struct Trigger. A pointer to the first element of the20333**    linked list is stored as the "pTrigger" member of the associated20334**    struct Table.20335**20336** The "step_list" member points to the first element of a linked list20337** containing the SQL statements specified as the trigger program.20338*/20339struct Trigger {20340  char *zName;            /* The name of the trigger                        */20341  char *table;            /* The table or view to which the trigger applies */20342  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */20343  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */20344  u8 bReturning;          /* This trigger implements a RETURNING clause */20345  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */20346  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,20347                             the <column-list> is stored here */20348  Schema *pSchema;        /* Schema containing the trigger */20349  Schema *pTabSchema;     /* Schema containing the table */20350  TriggerStep *step_list; /* Link list of trigger program steps             */20351  Trigger *pNext;         /* Next trigger associated with the table */20352};2035320354/*20355** A trigger is either a BEFORE or an AFTER trigger.  The following constants20356** determine which.20357**20358** If there are multiple triggers, you might of some BEFORE and some AFTER.20359** In that cases, the constants below can be ORed together.20360*/20361#define TRIGGER_BEFORE  120362#define TRIGGER_AFTER   22036320364/*20365** An instance of struct TriggerStep is used to store a single SQL statement20366** that is a part of a trigger-program.20367**20368** Instances of struct TriggerStep are stored in a singly linked list (linked20369** using the "pNext" member) referenced by the "step_list" member of the20370** associated struct Trigger instance. The first element of the linked list is20371** the first step of the trigger-program.20372**20373** The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or20374** "SELECT" statement. The meanings of the other members is determined by the20375** value of "op" as follows:20376**20377** (op == TK_INSERT)20378** orconf    -> stores the ON CONFLICT algorithm20379** pSelect   -> The content to be inserted - either a SELECT statement or20380**              a VALUES clause.20381** zTarget   -> Dequoted name of the table to insert into.20382** pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...20383**              statement, then this stores the column-names to be20384**              inserted into.20385** pUpsert   -> The ON CONFLICT clauses for an Upsert20386**20387** (op == TK_DELETE)20388** zTarget   -> Dequoted name of the table to delete from.20389** pWhere    -> The WHERE clause of the DELETE statement if one is specified.20390**              Otherwise NULL.20391**20392** (op == TK_UPDATE)20393** zTarget   -> Dequoted name of the table to update.20394** pWhere    -> The WHERE clause of the UPDATE statement if one is specified.20395**              Otherwise NULL.20396** pExprList -> A list of the columns to update and the expressions to update20397**              them to. See sqlite3Update() documentation of "pChanges"20398**              argument.20399**20400** (op == TK_SELECT)20401** pSelect   -> The SELECT statement20402**20403** (op == TK_RETURNING)20404** pExprList -> The list of expressions that follow the RETURNING keyword.20405**20406*/20407struct TriggerStep {20408  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT,20409                       ** or TK_RETURNING */20410  u8 orconf;           /* OE_Rollback etc. */20411  Trigger *pTrig;      /* The trigger that this step is a part of */20412  Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */20413  char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */20414  SrcList *pFrom;      /* FROM clause for UPDATE statement (if any) */20415  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */20416  ExprList *pExprList; /* SET clause for UPDATE, or RETURNING clause */20417  IdList *pIdList;     /* Column names for INSERT */20418  Upsert *pUpsert;     /* Upsert clauses on an INSERT */20419  char *zSpan;         /* Original SQL text of this command */20420  TriggerStep *pNext;  /* Next in the link-list */20421  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */20422};2042320424/*20425** Information about a RETURNING clause20426*/20427struct Returning {20428  Parse *pParse;        /* The parse that includes the RETURNING clause */20429  ExprList *pReturnEL;  /* List of expressions to return */20430  Trigger retTrig;      /* The transient trigger that implements RETURNING */20431  TriggerStep retTStep; /* The trigger step */20432  int iRetCur;          /* Transient table holding RETURNING results */20433  int nRetCol;          /* Number of in pReturnEL after expansion */20434  int iRetReg;          /* Register array for holding a row of RETURNING */20435  char zName[40];       /* Name of trigger: "sqlite_returning_%p" */20436};2043720438/*20439** An object used to accumulate the text of a string where we20440** do not necessarily know how big the string will be in the end.20441*/20442struct sqlite3_str {20443  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */20444  char *zText;         /* The string collected so far */20445  u32  nAlloc;         /* Amount of space allocated in zText */20446  u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */20447  u32  nChar;          /* Length of the string so far */20448  u8   accError;       /* SQLITE_NOMEM or SQLITE_TOOBIG */20449  u8   printfFlags;    /* SQLITE_PRINTF flags below */20450};20451#define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */20452#define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */20453#define SQLITE_PRINTF_MALLOCED 0x04  /* True if zText is allocated space */2045420455#define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)2045620457/*20458** The following object is the header for an "RCStr" or "reference-counted20459** string".  An RCStr is passed around and used like any other char*20460** that has been dynamically allocated.  The important interface20461** differences:20462**20463**   1.  RCStr strings are reference counted.  They are deallocated20464**       when the reference count reaches zero.20465**20466**   2.  Use sqlite3RCStrUnref() to free an RCStr string rather than20467**       sqlite3_free()20468**20469**   3.  Make a (read-only) copy of a read-only RCStr string using20470**       sqlite3RCStrRef().20471**20472** "String" is in the name, but an RCStr object can also be used to hold20473** binary data.20474*/20475struct RCStr {20476  u64 nRCRef;            /* Number of references */20477  /* Total structure size should be a multiple of 8 bytes for alignment */20478};2047920480/*20481** A pointer to this structure is used to communicate information20482** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.20483*/20484typedef struct {20485  sqlite3 *db;        /* The database being initialized */20486  char **pzErrMsg;    /* Error message stored here */20487  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */20488  int rc;             /* Result code stored here */20489  u32 mInitFlags;     /* Flags controlling error messages */20490  u32 nInitRow;       /* Number of rows processed */20491  Pgno mxPage;        /* Maximum page number.  0 for no limit. */20492} InitData;2049320494/*20495** Allowed values for mInitFlags20496*/20497#define INITFLAG_AlterMask     0x0003  /* Types of ALTER */20498#define INITFLAG_AlterRename   0x0001  /* Reparse after a RENAME */20499#define INITFLAG_AlterDrop     0x0002  /* Reparse after a DROP COLUMN */20500#define INITFLAG_AlterAdd      0x0003  /* Reparse after an ADD COLUMN */2050120502/* Tuning parameters are set using SQLITE_TESTCTRL_TUNE and are controlled20503** on debug-builds of the CLI using ".testctrl tune ID VALUE".  Tuning20504** parameters are for temporary use during development, to help find20505** optimal values for parameters in the query planner.  The should not20506** be used on trunk check-ins.  They are a temporary mechanism available20507** for transient development builds only.20508**20509** Tuning parameters are numbered starting with 1.20510*/20511#define SQLITE_NTUNE  6             /* Should be zero for all trunk check-ins */20512#ifdef SQLITE_DEBUG20513# define Tuning(X)  (sqlite3Config.aTune[(X)-1])20514#else20515# define Tuning(X)  020516#endif2051720518/*20519** Structure containing global configuration data for the SQLite library.20520**20521** This structure also contains some state information.20522*/20523struct Sqlite3Config {20524  int bMemstat;                     /* True to enable memory status */20525  u8 bCoreMutex;                    /* True to enable core mutexing */20526  u8 bFullMutex;                    /* True to enable full mutexing */20527  u8 bOpenUri;                      /* True to interpret filenames as URIs */20528  u8 bUseCis;                       /* Use covering indices for full-scans */20529  u8 bSmallMalloc;                  /* Avoid large memory allocations if true */20530  u8 bExtraSchemaChecks;            /* Verify type,name,tbl_name in schema */20531#ifdef SQLITE_DEBUG20532  u8 bJsonSelfcheck;                /* Double-check JSON parsing */20533#endif20534  int mxStrlen;                     /* Maximum string length */20535  int neverCorrupt;                 /* Database is always well-formed */20536  int szLookaside;                  /* Default lookaside buffer size */20537  int nLookaside;                   /* Default lookaside buffer count */20538  int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */20539  sqlite3_mem_methods m;            /* Low-level memory allocation interface */20540  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */20541  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */20542  void *pHeap;                      /* Heap storage space */20543  int nHeap;                        /* Size of pHeap[] */20544  int mnReq, mxReq;                 /* Min and max heap requests sizes */20545  sqlite3_int64 szMmap;             /* mmap() space per open file */20546  sqlite3_int64 mxMmap;             /* Maximum value for szMmap */20547  void *pPage;                      /* Page cache memory */20548  int szPage;                       /* Size of each page in pPage[] */20549  int nPage;                        /* Number of pages in pPage[] */20550  int mxParserStack;                /* maximum depth of the parser stack */20551  int sharedCacheEnabled;           /* true if shared-cache mode enabled */20552  u32 szPma;                        /* Maximum Sorter PMA size */20553  /* The above might be initialized to non-zero.  The following need to always20554  ** initially be zero, however. */20555  int isInit;                       /* True after initialization has finished */20556  int inProgress;                   /* True while initialization in progress */20557  int isMutexInit;                  /* True after mutexes are initialized */20558  int isMallocInit;                 /* True after malloc is initialized */20559  int isPCacheInit;                 /* True after malloc is initialized */20560  int nRefInitMutex;                /* Number of users of pInitMutex */20561  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */20562  void (*xLog)(void*,int,const char*); /* Function for logging */20563  void *pLogArg;                       /* First argument to xLog() */20564#ifdef SQLITE_ENABLE_SQLLOG20565  void(*xSqllog)(void*,sqlite3*,const char*, int);20566  void *pSqllogArg;20567#endif20568#ifdef SQLITE_VDBE_COVERAGE20569  /* The following callback (if not NULL) is invoked on every VDBE branch20570  ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.20571  */20572  void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx);  /* Callback */20573  void *pVdbeBranchArg;                                     /* 1st argument */20574#endif20575#ifndef SQLITE_OMIT_DESERIALIZE20576  sqlite3_int64 mxMemdbSize;        /* Default max memdb size */20577#endif20578#ifndef SQLITE_UNTESTABLE20579  int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */20580#endif20581#ifdef SQLITE_ALLOW_ROWID_IN_VIEW20582  u32 mNoVisibleRowid;              /* TF_NoVisibleRowid if the ROWID_IN_VIEW20583                                    ** feature is disabled.  0 if rowids can20584                                    ** occur in views. */20585#endif20586  int bLocaltimeFault;              /* True to fail localtime() calls */20587  int (*xAltLocaltime)(const void*,void*); /* Alternative localtime() routine */20588  int iOnceResetThreshold;          /* When to reset OP_Once counters */20589  u32 szSorterRef;                  /* Min size in bytes to use sorter-refs */20590  unsigned int iPrngSeed;           /* Alternative fixed seed for the PRNG */20591  /* vvvv--- must be last ---vvv */20592#ifdef SQLITE_DEBUG20593  sqlite3_int64 aTune[SQLITE_NTUNE]; /* Tuning parameters */20594#endif20595};2059620597/*20598** This macro is used inside of assert() statements to indicate that20599** the assert is only valid on a well-formed database.  Instead of:20600**20601**     assert( X );20602**20603** One writes:20604**20605**     assert( X || CORRUPT_DB );20606**20607** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate20608** that the database is definitely corrupt, only that it might be corrupt.20609** For most test cases, CORRUPT_DB is set to false using a special20610** sqlite3_test_control().  This enables assert() statements to prove20611** things that are always true for well-formed databases.20612*/20613#define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)2061420615/*20616** Context pointer passed down through the tree-walk.20617*/20618struct Walker {20619  Parse *pParse;                            /* Parser context.  */20620  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */20621  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */20622  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */20623  int walkerDepth;                          /* Number of subqueries */20624  u16 eCode;                                /* A small processing code */20625  u16 mWFlags;                              /* Use-dependent flags */20626  union {                                   /* Extra data for callback */20627    NameContext *pNC;                         /* Naming context */20628    int n;                                    /* A counter */20629    int iCur;                                 /* A cursor number */20630    SrcList *pSrcList;                        /* FROM clause */20631    struct CCurHint *pCCurHint;               /* Used by codeCursorHint() */20632    struct RefSrcList *pRefSrcList;           /* sqlite3ReferencesSrcList() */20633    int *aiCol;                               /* array of column indexes */20634    struct IdxCover *pIdxCover;               /* Check for index coverage */20635    ExprList *pGroupBy;                       /* GROUP BY clause */20636    Select *pSelect;                          /* HAVING to WHERE clause ctx */20637    struct WindowRewrite *pRewrite;           /* Window rewrite context */20638    struct WhereConst *pConst;                /* WHERE clause constants */20639    struct RenameCtx *pRename;                /* RENAME COLUMN context */20640    struct Table *pTab;                       /* Table of generated column */20641    struct CoveringIndexCheck *pCovIdxCk;     /* Check for covering index */20642    SrcItem *pSrcItem;                        /* A single FROM clause item */20643    DbFixer *pFix;                            /* See sqlite3FixSelect() */20644    Mem *aMem;                                /* See sqlite3BtreeCursorHint() */20645  } u;20646};2064720648/*20649** The following structure contains information used by the sqliteFix...20650** routines as they walk the parse tree to make database references20651** explicit.20652*/20653struct DbFixer {20654  Parse *pParse;      /* The parsing context.  Error messages written here */20655  Walker w;           /* Walker object */20656  Schema *pSchema;    /* Fix items to this schema */20657  u8 bTemp;           /* True for TEMP schema entries */20658  const char *zDb;    /* Make sure all objects are contained in this database */20659  const char *zType;  /* Type of the container - used for error messages */20660  const Token *pName; /* Name of the container - used for error messages */20661};2066220663/* Forward declarations */20664SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);20665SQLITE_PRIVATE int sqlite3WalkExprNN(Walker*, Expr*);20666SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);20667SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);20668SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);20669SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);20670SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);20671SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);20672SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);20673SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker*,Select*);20674SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker*,Select*);20675SQLITE_PRIVATE void sqlite3WalkWinDefnDummyCallback(Walker*,Select*);2067620677#ifdef SQLITE_DEBUG20678SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);20679#endif2068020681#ifndef SQLITE_OMIT_CTE20682SQLITE_PRIVATE void sqlite3SelectPopWith(Walker*, Select*);20683#else20684# define sqlite3SelectPopWith 020685#endif2068620687/*20688** Return code from the parse-tree walking primitives and their20689** callbacks.20690*/20691#define WRC_Continue    0   /* Continue down into children */20692#define WRC_Prune       1   /* Omit children but continue walking siblings */20693#define WRC_Abort       2   /* Abandon the tree walk */2069420695/*20696** A single common table expression20697*/20698struct Cte {20699  char *zName;            /* Name of this CTE */20700  ExprList *pCols;        /* List of explicit column names, or NULL */20701  Select *pSelect;        /* The definition of this CTE */20702  const char *zCteErr;    /* Error message for circular references */20703  CteUse *pUse;           /* Usage information for this CTE */20704  u8 eM10d;               /* The MATERIALIZED flag */20705};2070620707/*20708** Allowed values for the materialized flag (eM10d):20709*/20710#define M10d_Yes       0  /* AS MATERIALIZED */20711#define M10d_Any       1  /* Not specified.  Query planner's choice */20712#define M10d_No        2  /* AS NOT MATERIALIZED */2071320714/*20715** An instance of the With object represents a WITH clause containing20716** one or more CTEs (common table expressions).20717*/20718struct With {20719  int nCte;               /* Number of CTEs in the WITH clause */20720  int bView;              /* Belongs to the outermost Select of a view */20721  With *pOuter;           /* Containing WITH clause, or NULL */20722  Cte a[1];               /* For each CTE in the WITH clause.... */20723};2072420725/*20726** The Cte object is not guaranteed to persist for the entire duration20727** of code generation.  (The query flattener or other parser tree20728** edits might delete it.)  The following object records information20729** about each Common Table Expression that must be preserved for the20730** duration of the parse.20731**20732** The CteUse objects are freed using sqlite3ParserAddCleanup() rather20733** than sqlite3SelectDelete(), which is what enables them to persist20734** until the end of code generation.20735*/20736struct CteUse {20737  int nUse;              /* Number of users of this CTE */20738  int addrM9e;           /* Start of subroutine to compute materialization */20739  int regRtn;            /* Return address register for addrM9e subroutine */20740  int iCur;              /* Ephemeral table holding the materialization */20741  LogEst nRowEst;        /* Estimated number of rows in the table */20742  u8 eM10d;              /* The MATERIALIZED flag */20743};207442074520746/* Client data associated with sqlite3_set_clientdata() and20747** sqlite3_get_clientdata().20748*/20749struct DbClientData {20750  DbClientData *pNext;        /* Next in a linked list */20751  void *pData;                /* The data */20752  void (*xDestructor)(void*); /* Destructor.  Might be NULL */20753  char zName[1];              /* Name of this client data. MUST BE LAST */20754};2075520756#ifdef SQLITE_DEBUG20757/*20758** An instance of the TreeView object is used for printing the content of20759** data structures on sqlite3DebugPrintf() using a tree-like view.20760*/20761struct TreeView {20762  int iLevel;             /* Which level of the tree we are on */20763  u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */20764};20765#endif /* SQLITE_DEBUG */2076620767/*20768** This object is used in various ways, most (but not all) related to window20769** functions.20770**20771**   (1) A single instance of this structure is attached to the20772**       the Expr.y.pWin field for each window function in an expression tree.20773**       This object holds the information contained in the OVER clause,20774**       plus additional fields used during code generation.20775**20776**   (2) All window functions in a single SELECT form a linked-list20777**       attached to Select.pWin.  The Window.pFunc and Window.pExpr20778**       fields point back to the expression that is the window function.20779**20780**   (3) The terms of the WINDOW clause of a SELECT are instances of this20781**       object on a linked list attached to Select.pWinDefn.20782**20783**   (4) For an aggregate function with a FILTER clause, an instance20784**       of this object is stored in Expr.y.pWin with eFrmType set to20785**       TK_FILTER. In this case the only field used is Window.pFilter.20786**20787** The uses (1) and (2) are really the same Window object that just happens20788** to be accessible in two different ways.  Use case (3) are separate objects.20789*/20790struct Window {20791  char *zName;            /* Name of window (may be NULL) */20792  char *zBase;            /* Name of base window for chaining (may be NULL) */20793  ExprList *pPartition;   /* PARTITION BY clause */20794  ExprList *pOrderBy;     /* ORDER BY clause */20795  u8 eFrmType;            /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */20796  u8 eStart;              /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */20797  u8 eEnd;                /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */20798  u8 bImplicitFrame;      /* True if frame was implicitly specified */20799  u8 eExclude;            /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */20800  Expr *pStart;           /* Expression for "<expr> PRECEDING" */20801  Expr *pEnd;             /* Expression for "<expr> FOLLOWING" */20802  Window **ppThis;        /* Pointer to this object in Select.pWin list */20803  Window *pNextWin;       /* Next window function belonging to this SELECT */20804  Expr *pFilter;          /* The FILTER expression */20805  FuncDef *pWFunc;        /* The function */20806  int iEphCsr;            /* Partition buffer or Peer buffer */20807  int regAccum;           /* Accumulator */20808  int regResult;          /* Interim result */20809  int csrApp;             /* Function cursor (used by min/max) */20810  int regApp;             /* Function register (also used by min/max) */20811  int regPart;            /* Array of registers for PARTITION BY values */20812  Expr *pOwner;           /* Expression object this window is attached to */20813  int nBufferCol;         /* Number of columns in buffer table */20814  int iArgCol;            /* Offset of first argument for this function */20815  int regOne;             /* Register containing constant value 1 */20816  int regStartRowid;20817  int regEndRowid;20818  u8 bExprArgs;           /* Defer evaluation of window function arguments20819                          ** due to the SQLITE_SUBTYPE flag */20820};2082120822SQLITE_PRIVATE Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow);20823SQLITE_PRIVATE void sqlite3MultiValuesEnd(Parse *pParse, Select *pVal);2082420825#ifndef SQLITE_OMIT_WINDOWFUNC20826SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3*, Window*);20827SQLITE_PRIVATE void sqlite3WindowUnlinkFromSelect(Window*);20828SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p);20829SQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);20830SQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);20831SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin);20832SQLITE_PRIVATE int sqlite3WindowCompare(const Parse*, const Window*, const Window*, int);20833SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Select*);20834SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);20835SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);20836SQLITE_PRIVATE void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);20837SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);20838SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p);20839SQLITE_PRIVATE void sqlite3WindowFunctions(void);20840SQLITE_PRIVATE void sqlite3WindowChain(Parse*, Window*, Window*);20841SQLITE_PRIVATE Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*);20842#else20843# define sqlite3WindowDelete(a,b)20844# define sqlite3WindowFunctions()20845# define sqlite3WindowAttach(a,b,c)20846#endif2084720848/*20849** Assuming zIn points to the first byte of a UTF-8 character,20850** advance zIn to point to the first byte of the next UTF-8 character.20851*/20852#define SQLITE_SKIP_UTF8(zIn) {                        \20853  if( (*(zIn++))>=0xc0 ){                              \20854    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \20855  }                                                    \20856}2085720858/*20859** The SQLITE_*_BKPT macros are substitutes for the error codes with20860** the same name but without the _BKPT suffix.  These macros invoke20861** routines that report the line-number on which the error originated20862** using sqlite3_log().  The routines also provide a convenient place20863** to set a debugger breakpoint.20864*/20865SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);20866SQLITE_PRIVATE int sqlite3CorruptError(int);20867SQLITE_PRIVATE int sqlite3MisuseError(int);20868SQLITE_PRIVATE int sqlite3CantopenError(int);20869#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)20870#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)20871#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)20872#ifdef SQLITE_DEBUG20873SQLITE_PRIVATE   int sqlite3NomemError(int);20874SQLITE_PRIVATE   int sqlite3IoerrnomemError(int);20875# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)20876# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)20877#else20878# define SQLITE_NOMEM_BKPT SQLITE_NOMEM20879# define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM20880#endif20881#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)20882SQLITE_PRIVATE   int sqlite3CorruptPgnoError(int,Pgno);20883# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))20884#else20885# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)20886#endif2088720888/*20889** FTS3 and FTS4 both require virtual table support20890*/20891#if defined(SQLITE_OMIT_VIRTUALTABLE)20892# undef SQLITE_ENABLE_FTS320893# undef SQLITE_ENABLE_FTS420894#endif2089520896/*20897** FTS4 is really an extension for FTS3.  It is enabled using the20898** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call20899** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.20900*/20901#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)20902# define SQLITE_ENABLE_FTS3 120903#endif2090420905/*20906** The following macros mimic the standard library functions toupper(),20907** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The20908** sqlite versions only work for ASCII characters, regardless of locale.20909*/20910#ifdef SQLITE_ASCII20911# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))20912# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)20913# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)20914# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)20915# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)20916# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)20917# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])20918# define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)20919# define sqlite3JsonId1(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x42)20920# define sqlite3JsonId2(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x46)20921#else20922# define sqlite3Toupper(x)   toupper((unsigned char)(x))20923# define sqlite3Isspace(x)   isspace((unsigned char)(x))20924# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))20925# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))20926# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))20927# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))20928# define sqlite3Tolower(x)   tolower((unsigned char)(x))20929# define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')20930# define sqlite3JsonId1(x)   (sqlite3IsIdChar(x)&&(x)<'0')20931# define sqlite3JsonId2(x)   sqlite3IsIdChar(x)20932#endif20933SQLITE_PRIVATE int sqlite3IsIdChar(u8);2093420935/*20936** Internal function prototypes20937*/20938SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);20939SQLITE_PRIVATE int sqlite3Strlen30(const char*);20940#define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)20941SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);20942#define sqlite3StrNICmp sqlite3_strnicmp2094320944SQLITE_PRIVATE int sqlite3MallocInit(void);20945SQLITE_PRIVATE void sqlite3MallocEnd(void);20946SQLITE_PRIVATE void *sqlite3Malloc(u64);20947SQLITE_PRIVATE void *sqlite3MallocZero(u64);20948SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);20949SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);20950SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);20951SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);20952SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);20953SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);20954SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);20955SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);20956SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);20957SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);20958SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);20959SQLITE_PRIVATE void sqlite3DbNNFreeNN(sqlite3*, void*);20960SQLITE_PRIVATE int sqlite3MallocSize(const void*);20961SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, const void*);20962SQLITE_PRIVATE void *sqlite3PageMalloc(int);20963SQLITE_PRIVATE void sqlite3PageFree(void*);20964SQLITE_PRIVATE void sqlite3MemSetDefault(void);20965#ifndef SQLITE_UNTESTABLE20966SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));20967#endif20968SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);2096920970/*20971** On systems with ample stack space and that support alloca(), make20972** use of alloca() to obtain space for large automatic objects.  By default,20973** obtain space from malloc().20974**20975** The alloca() routine never returns NULL.  This will cause code paths20976** that deal with sqlite3StackAlloc() failures to be unreachable.20977*/20978#ifdef SQLITE_USE_ALLOCA20979# define sqlite3StackAllocRaw(D,N)   alloca(N)20980# define sqlite3StackAllocRawNN(D,N) alloca(N)20981# define sqlite3StackFree(D,P)20982# define sqlite3StackFreeNN(D,P)20983#else20984# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)20985# define sqlite3StackAllocRawNN(D,N) sqlite3DbMallocRawNN(D,N)20986# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)20987# define sqlite3StackFreeNN(D,P)     sqlite3DbFreeNN(D,P)20988#endif2098920990/* Do not allow both MEMSYS5 and MEMSYS3 to be defined together.  If they20991** are, disable MEMSYS320992*/20993#ifdef SQLITE_ENABLE_MEMSYS520994SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);20995#undef SQLITE_ENABLE_MEMSYS320996#endif20997#ifdef SQLITE_ENABLE_MEMSYS320998SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);20999#endif210002100121002#ifndef SQLITE_MUTEX_OMIT21003SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);21004SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);21005SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);21006SQLITE_PRIVATE   int sqlite3MutexInit(void);21007SQLITE_PRIVATE   int sqlite3MutexEnd(void);21008#endif21009#if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)21010SQLITE_PRIVATE   void sqlite3MemoryBarrier(void);21011#else21012# define sqlite3MemoryBarrier()21013#endif2101421015SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);21016SQLITE_PRIVATE void sqlite3StatusUp(int, int);21017SQLITE_PRIVATE void sqlite3StatusDown(int, int);21018SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);21019SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);2102021021/* Access to mutexes used by sqlite3_status() */21022SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);21023SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);2102421025#if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)21026SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);21027#else21028# define sqlite3MutexWarnOnContention(x)21029#endif2103021031#ifndef SQLITE_OMIT_FLOATING_POINT21032# define EXP754 (((u64)0x7ff)<<52)21033# define MAN754 ((((u64)1)<<52)-1)21034# define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0)21035# define IsOvfl(X) (((X)&EXP754)==EXP754)21036SQLITE_PRIVATE   int sqlite3IsNaN(double);21037SQLITE_PRIVATE   int sqlite3IsOverflow(double);21038#else21039# define IsNaN(X)             021040# define sqlite3IsNaN(X)      021041# define sqlite3IsOVerflow(X) 021042#endif2104321044/*21045** An instance of the following structure holds information about SQL21046** functions arguments that are the parameters to the printf() function.21047*/21048struct PrintfArguments {21049  int nArg;                /* Total number of arguments */21050  int nUsed;               /* Number of arguments used so far */21051  sqlite3_value **apArg;   /* The argument values */21052};2105321054/*21055** An instance of this object receives the decoding of a floating point21056** value into an approximate decimal representation.21057*/21058struct FpDecode {21059  char sign;           /* '+' or '-' */21060  char isSpecial;      /* 1: Infinity  2: NaN */21061  int n;               /* Significant digits in the decode */21062  int iDP;             /* Location of the decimal point */21063  char *z;             /* Start of significant digits */21064  char zBuf[24];       /* Storage for significant digits */21065};2106621067SQLITE_PRIVATE void sqlite3FpDecode(FpDecode*,double,int,int);21068SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);21069SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);21070#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)21071SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);21072#endif21073#if defined(SQLITE_TEST)21074SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);21075#endif2107621077#if defined(SQLITE_DEBUG)21078SQLITE_PRIVATE   void sqlite3TreeViewLine(TreeView*, const char *zFormat, ...);21079SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);21080SQLITE_PRIVATE   void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);21081SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);21082SQLITE_PRIVATE   void sqlite3TreeViewBareIdList(TreeView*, const IdList*, const char*);21083SQLITE_PRIVATE   void sqlite3TreeViewIdList(TreeView*, const IdList*, u8, const char*);21084SQLITE_PRIVATE   void sqlite3TreeViewColumnList(TreeView*, const Column*, int, u8);21085SQLITE_PRIVATE   void sqlite3TreeViewSrcList(TreeView*, const SrcList*);21086SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);21087SQLITE_PRIVATE   void sqlite3TreeViewWith(TreeView*, const With*, u8);21088SQLITE_PRIVATE   void sqlite3TreeViewUpsert(TreeView*, const Upsert*, u8);21089#if TREETRACE_ENABLED21090SQLITE_PRIVATE   void sqlite3TreeViewDelete(const With*, const SrcList*, const Expr*,21091                             const ExprList*,const Expr*, const Trigger*);21092SQLITE_PRIVATE   void sqlite3TreeViewInsert(const With*, const SrcList*,21093                             const IdList*, const Select*, const ExprList*,21094                             int, const Upsert*, const Trigger*);21095SQLITE_PRIVATE   void sqlite3TreeViewUpdate(const With*, const SrcList*, const ExprList*,21096                             const Expr*, int, const ExprList*, const Expr*,21097                             const Upsert*, const Trigger*);21098#endif21099#ifndef SQLITE_OMIT_TRIGGER21100SQLITE_PRIVATE   void sqlite3TreeViewTriggerStep(TreeView*, const TriggerStep*, u8, u8);21101SQLITE_PRIVATE   void sqlite3TreeViewTrigger(TreeView*, const Trigger*, u8, u8);21102#endif21103#ifndef SQLITE_OMIT_WINDOWFUNC21104SQLITE_PRIVATE   void sqlite3TreeViewWindow(TreeView*, const Window*, u8);21105SQLITE_PRIVATE   void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);21106#endif21107SQLITE_PRIVATE   void sqlite3ShowExpr(const Expr*);21108SQLITE_PRIVATE   void sqlite3ShowExprList(const ExprList*);21109SQLITE_PRIVATE   void sqlite3ShowIdList(const IdList*);21110SQLITE_PRIVATE   void sqlite3ShowSrcList(const SrcList*);21111SQLITE_PRIVATE   void sqlite3ShowSelect(const Select*);21112SQLITE_PRIVATE   void sqlite3ShowWith(const With*);21113SQLITE_PRIVATE   void sqlite3ShowUpsert(const Upsert*);21114#ifndef SQLITE_OMIT_TRIGGER21115SQLITE_PRIVATE   void sqlite3ShowTriggerStep(const TriggerStep*);21116SQLITE_PRIVATE   void sqlite3ShowTriggerStepList(const TriggerStep*);21117SQLITE_PRIVATE   void sqlite3ShowTrigger(const Trigger*);21118SQLITE_PRIVATE   void sqlite3ShowTriggerList(const Trigger*);21119#endif21120#ifndef SQLITE_OMIT_WINDOWFUNC21121SQLITE_PRIVATE   void sqlite3ShowWindow(const Window*);21122SQLITE_PRIVATE   void sqlite3ShowWinFunc(const Window*);21123#endif21124#endif2112521126SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);21127SQLITE_PRIVATE void sqlite3ProgressCheck(Parse*);21128SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);21129SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3*,int);21130SQLITE_PRIVATE void sqlite3Dequote(char*);21131SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);21132SQLITE_PRIVATE void sqlite3DequoteToken(Token*);21133SQLITE_PRIVATE void sqlite3DequoteNumber(Parse*, Expr*);21134SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);21135SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);21136SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*);21137SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);21138SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);21139SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);21140SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);21141SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);21142SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);21143SQLITE_PRIVATE void sqlite3TouchRegister(Parse*,int);21144#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)21145SQLITE_PRIVATE int sqlite3FirstAvailableRegister(Parse*,int);21146#endif21147#ifdef SQLITE_DEBUG21148SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);21149#endif21150SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);21151SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);21152SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);21153SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);21154SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);21155SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);21156SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr*);21157SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, const Token*, int);21158SQLITE_PRIVATE void sqlite3ExprAddFunctionOrderBy(Parse*,Expr*,ExprList*);21159SQLITE_PRIVATE void sqlite3ExprOrderByAggregateError(Parse*,Expr*);21160SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,const Expr*,const FuncDef*);21161SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);21162SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);21163SQLITE_PRIVATE void sqlite3ExprDeleteGeneric(sqlite3*,void*);21164SQLITE_PRIVATE int sqlite3ExprDeferredDelete(Parse*, Expr*);21165SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);21166SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);21167SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);21168SQLITE_PRIVATE Select *sqlite3ExprListToValues(Parse*, int, ExprList*);21169SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int,int);21170SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,const Token*,int);21171SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);21172SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);21173SQLITE_PRIVATE void sqlite3ExprListDeleteGeneric(sqlite3*,void*);21174SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);21175SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index*);21176SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);21177SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);21178SQLITE_PRIVATE int sqlite3InitOne(sqlite3*, int, char**, u32);21179SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);21180#ifndef SQLITE_OMIT_VIRTUALTABLE21181SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);21182#endif21183SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);21184SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);21185SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);21186SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);21187SQLITE_PRIVATE void sqlite3ColumnSetExpr(Parse*,Table*,Column*,Expr*);21188SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table*,Column*);21189SQLITE_PRIVATE void sqlite3ColumnSetColl(sqlite3*,Column*,const char*zColl);21190SQLITE_PRIVATE const char *sqlite3ColumnColl(Column*);21191SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);21192SQLITE_PRIVATE void sqlite3GenerateColumnNames(Parse *pParse, Select *pSelect);21193SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);21194SQLITE_PRIVATE void sqlite3SubqueryColumnTypes(Parse*,Table*,Select*,char);21195SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*,char);21196SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *, int);21197SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);21198SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index*, i16);21199#ifdef SQLITE_OMIT_GENERATED_COLUMNS21200# define sqlite3TableColumnToStorage(T,X) (X)  /* No-op pass-through */21201# define sqlite3StorageColumnToTable(T,X) (X)  /* No-op pass-through */21202#else21203SQLITE_PRIVATE   i16 sqlite3TableColumnToStorage(Table*, i16);21204SQLITE_PRIVATE   i16 sqlite3StorageColumnToTable(Table*, i16);21205#endif21206SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);21207#if SQLITE_ENABLE_HIDDEN_COLUMNS21208SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);21209#else21210# define sqlite3ColumnPropertiesFromName(T,C) /* no-op */21211#endif21212SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token,Token);21213SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);21214SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);21215SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*, const char*, const char*);21216SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);21217SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);21218SQLITE_PRIVATE void sqlite3AddGenerated(Parse*,Expr*,Token*);21219SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u32,Select*);21220SQLITE_PRIVATE void sqlite3AddReturning(Parse*,ExprList*);21221SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,21222                    sqlite3_vfs**,char**,char **);21223#define sqlite3CodecQueryParameters(A,B,C) 021224SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);2122521226#ifdef SQLITE_UNTESTABLE21227# define sqlite3FaultSim(X) SQLITE_OK21228#else21229SQLITE_PRIVATE   int sqlite3FaultSim(int);21230#endif2123121232SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);21233SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);21234SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);21235SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);21236SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);21237SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);21238SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);21239#ifndef SQLITE_UNTESTABLE21240SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);21241#endif2124221243SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*);21244SQLITE_PRIVATE void sqlite3RowSetDelete(void*);21245SQLITE_PRIVATE void sqlite3RowSetClear(void*);21246SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);21247SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);21248SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);2124921250SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);2125121252#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)21253SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);21254#else21255# define sqlite3ViewGetColumnNames(A,B) 021256#endif2125721258#if SQLITE_MAX_ATTACHED>3021259SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);21260#endif21261SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);21262SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);21263SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);21264SQLITE_PRIVATE void sqlite3DeleteTableGeneric(sqlite3*, void*);21265SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3*, Index*);21266#ifndef SQLITE_OMIT_AUTOINCREMENT21267SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);21268SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);21269#else21270# define sqlite3AutoincrementBegin(X)21271# define sqlite3AutoincrementEnd(X)21272#endif21273SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);21274#ifndef SQLITE_OMIT_GENERATED_COLUMNS21275SQLITE_PRIVATE   void sqlite3ComputeGeneratedColumns(Parse*, int, Table*);21276#endif21277SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);21278SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);21279SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);21280SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);21281SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2);21282SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);21283SQLITE_PRIVATE void sqlite3SubqueryDelete(sqlite3*,Subquery*);21284SQLITE_PRIVATE Select *sqlite3SubqueryDetach(sqlite3*,SrcItem*);21285SQLITE_PRIVATE int sqlite3SrcItemAttachSubquery(Parse*, SrcItem*, Select*, int);21286SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,21287                                      Token*, Select*, OnOrUsing*);21288SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);21289SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);21290SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, SrcItem *);21291SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(Parse*,SrcList*);21292SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);21293SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);21294SQLITE_PRIVATE void sqlite3ClearOnOrUsing(sqlite3*, OnOrUsing*);21295SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);21296SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);21297SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,21298                          Expr*, int, int, u8);21299SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);21300SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);21301SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,21302                         Expr*,ExprList*,u32,Expr*);21303SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);21304SQLITE_PRIVATE void sqlite3SelectDeleteGeneric(sqlite3*,void*);21305SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);21306SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, Trigger*);21307SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);21308#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)21309SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);21310#endif21311SQLITE_PRIVATE void sqlite3CodeChangeCount(Vdbe*,int,const char*);21312SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);21313SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,21314                   Upsert*);21315SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,21316                             ExprList*,Select*,u16,int);21317SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);21318SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);21319SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);21320SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);21321SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);21322SQLITE_PRIVATE void sqlite3WhereMinMaxOptEarlyOut(Vdbe*,WhereInfo*);21323SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);21324SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);21325SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);21326SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);21327#define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */21328#define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */21329#define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */21330SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo*);21331SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);21332SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);21333SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);21334SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);21335SQLITE_PRIVATE void sqlite3ExprToRegister(Expr *pExpr, int iReg);21336SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);21337#ifndef SQLITE_OMIT_GENERATED_COLUMNS21338SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Table*, Column*, int);21339#endif21340SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);21341SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);21342SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);21343SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);21344SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);21345SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);21346#define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */21347#define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */21348#define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */21349#define SQLITE_ECEL_OMITREF  0x08  /* Omit if ExprList.u.x.iOrderByCol */21350SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);21351SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);21352SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);21353SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);21354#define LOCATE_VIEW    0x0121355#define LOCATE_NOERR   0x0221356SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);21357SQLITE_PRIVATE const char *sqlite3PreferredTableName(const char*);21358SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,SrcItem *);21359SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);21360SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);21361SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);21362SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*,Expr*);21363SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);21364SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, const Token*);21365SQLITE_PRIVATE int sqlite3ExprCompare(const Parse*,const Expr*,const Expr*, int);21366SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*,Expr*,int);21367SQLITE_PRIVATE int sqlite3ExprListCompare(const ExprList*,const ExprList*, int);21368SQLITE_PRIVATE int sqlite3ExprImpliesExpr(const Parse*,const Expr*,const Expr*, int);21369SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int,int);21370SQLITE_PRIVATE void sqlite3AggInfoPersistWalkerInit(Walker*,Parse*);21371SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);21372SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);21373SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);21374SQLITE_PRIVATE int sqlite3ReferencesSrcList(Parse*, Expr*, SrcList*);21375SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);21376#ifndef SQLITE_UNTESTABLE21377SQLITE_PRIVATE void sqlite3PrngSaveState(void);21378SQLITE_PRIVATE void sqlite3PrngRestoreState(void);21379#endif21380SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);21381SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);21382SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);21383SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);21384SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);21385SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);21386SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);21387SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);21388SQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char*);21389SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);21390SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);21391SQLITE_PRIVATE int sqlite3ExprIsConstant(Parse*,Expr*);21392SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);21393SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);21394SQLITE_PRIVATE int sqlite3ExprIsSingleTableConstraint(Expr*,const SrcList*,int,int);21395#ifdef SQLITE_ENABLE_CURSOR_HINTS21396SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);21397#endif21398SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr*, int*, Parse*);21399SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);21400SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);21401SQLITE_PRIVATE int sqlite3IsRowid(const char*);21402SQLITE_PRIVATE const char *sqlite3RowidAlias(Table *pTab);21403SQLITE_PRIVATE void sqlite3GenerateRowDelete(21404    Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);21405SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);21406SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);21407SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);21408SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);21409SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,21410                                     u8,u8,int,int*,int*,Upsert*);21411#ifdef SQLITE_ENABLE_NULL_TRIM21412SQLITE_PRIVATE   void sqlite3SetMakeRecordP5(Vdbe*,Table*);21413#else21414# define sqlite3SetMakeRecordP5(A,B)21415#endif21416SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);21417SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);21418SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);21419SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);21420SQLITE_PRIVATE void sqlite3MayAbort(Parse*);21421SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);21422SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);21423SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);21424SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,const Expr*,int);21425SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,const ExprList*,int);21426SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,const SrcList*,int);21427SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,const IdList*);21428SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,const Select*,int);21429SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*);21430SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);21431SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);21432SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum*,sqlite3_value*);21433SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);21434SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);21435SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void);21436SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);21437#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)21438SQLITE_PRIVATE   int sqlite3JsonTableFunctions(sqlite3*);21439#endif21440SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);21441SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);21442SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);21443SQLITE_PRIVATE With *sqlite3WithDup(sqlite3 *db, With *p);2144421445#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)21446SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);21447#endif2144821449#ifndef SQLITE_OMIT_TRIGGER21450SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,21451                           Expr*,int, int);21452SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);21453SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);21454SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);21455SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);21456SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);21457SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,21458                            int, int, int);21459SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);21460  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);21461SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);21462SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,21463                                        const char*,const char*);21464SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,21465                                        Select*,u8,Upsert*,21466                                        const char*,const char*);21467SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,SrcList*,ExprList*,21468                                        Expr*, u8, const char*,const char*);21469SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,21470                                        const char*,const char*);21471SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);21472SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);21473SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);21474SQLITE_PRIVATE   SrcList *sqlite3TriggerStepSrc(Parse*, TriggerStep*);21475# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))21476# define sqlite3IsToplevel(p) ((p)->pToplevel==0)21477#else21478# define sqlite3TriggersExist(B,C,D,E,F) 021479# define sqlite3DeleteTrigger(A,B)21480# define sqlite3DropTriggerPtr(A,B)21481# define sqlite3UnlinkAndDeleteTrigger(A,B,C)21482# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)21483# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)21484# define sqlite3TriggerList(X, Y) 021485# define sqlite3ParseToplevel(p) p21486# define sqlite3IsToplevel(p) 121487# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 021488# define sqlite3TriggerStepSrc(A,B) 021489#endif2149021491SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);21492SQLITE_PRIVATE int sqlite3ColumnIndex(Table *pTab, const char *zCol);21493SQLITE_PRIVATE void sqlite3SrcItemColumnUsed(SrcItem*,int);21494SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr*,int,u32);21495SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);21496SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);21497#ifndef SQLITE_OMIT_AUTHORIZATION21498SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);21499SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);21500SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);21501SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);21502SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);21503#else21504# define sqlite3AuthRead(a,b,c,d)21505# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK21506# define sqlite3AuthContextPush(a,b,c)21507# define sqlite3AuthContextPop(a)  ((void)(a))21508#endif21509SQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName);21510SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);21511SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);21512SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);21513SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);21514SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);21515SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);21516SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);2151721518SQLITE_PRIVATE int sqlite3RealSameAsInt(double,sqlite3_int64);21519SQLITE_PRIVATE i64 sqlite3RealToI64(double);21520SQLITE_PRIVATE int sqlite3Int64ToText(i64,char*);21521SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);21522SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);21523SQLITE_PRIVATE int sqlite3GetUInt32(const char*, u32*);21524SQLITE_PRIVATE int sqlite3Atoi(const char*);21525#ifndef SQLITE_OMIT_UTF1621526SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nByte, int nChar);21527#endif21528SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);21529SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);21530SQLITE_PRIVATE int sqlite3Utf8ReadLimited(const u8*, int, u32*);21531SQLITE_PRIVATE LogEst sqlite3LogEst(u64);21532SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);21533SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);21534SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);21535SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);21536SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);21537SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);2153821539/*21540** Routines to read and write variable-length integers.  These used to21541** be defined locally, but now we use the varint routines in the util.c21542** file.21543*/21544SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);21545SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);21546SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);21547SQLITE_PRIVATE int sqlite3VarintLen(u64 v);2154821549/*21550** The common case is for a varint to be a single byte.  They following21551** macros handle the common case without a procedure call, but then call21552** the procedure for larger varints.21553*/21554#define getVarint32(A,B)  \21555  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))21556#define getVarint32NR(A,B) \21557  B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&(B))21558#define putVarint32(A,B)  \21559  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\21560  sqlite3PutVarint((A),(B)))21561#define getVarint    sqlite3GetVarint21562#define putVarint    sqlite3PutVarint215632156421565SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);21566SQLITE_PRIVATE char *sqlite3TableAffinityStr(sqlite3*,const Table*);21567SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);21568SQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2);21569SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity);21570SQLITE_PRIVATE char sqlite3TableColumnAffinity(const Table*,int);21571SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr);21572SQLITE_PRIVATE int sqlite3ExprDataType(const Expr *pExpr);21573SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);21574SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);21575SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);21576SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);21577SQLITE_PRIVATE void sqlite3ErrorClear(sqlite3*);21578SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);21579#if !defined(SQLITE_OMIT_BLOB_LITERAL)21580SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);21581#endif21582SQLITE_PRIVATE u8 sqlite3HexToInt(int h);21583SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);2158421585#if defined(SQLITE_NEED_ERR_NAME)21586SQLITE_PRIVATE const char *sqlite3ErrName(int);21587#endif2158821589#ifndef SQLITE_OMIT_DESERIALIZE21590SQLITE_PRIVATE int sqlite3MemdbInit(void);21591SQLITE_PRIVATE int sqlite3IsMemdb(const sqlite3_vfs*);21592#else21593# define sqlite3IsMemdb(X) 021594#endif2159521596SQLITE_PRIVATE const char *sqlite3ErrStr(int);21597SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);21598SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);21599SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*);21600SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);21601SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8);21602SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr);21603SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr);21604SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*);21605SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(const Parse *pParse, Expr*, const Token*, int);21606SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(const Parse*,Expr*,const char*);21607SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);21608SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr*);21609SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);21610SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);21611SQLITE_PRIVATE int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*);21612SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, i64);21613SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);21614SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);21615SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);21616SQLITE_PRIVATE int sqlite3AbsInt32(int);21617#ifdef SQLITE_ENABLE_8_3_NAMES21618SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);21619#else21620# define sqlite3FileSuffix3(X,Y)21621#endif21622SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);2162321624SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);21625SQLITE_PRIVATE int sqlite3ValueIsOfClass(const sqlite3_value*, void(*)(void*));21626SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);21627SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,21628                        void(*)(void*));21629SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);21630SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);21631#ifndef SQLITE_UNTESTABLE21632SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context*);21633#endif21634SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);21635#ifndef SQLITE_OMIT_UTF1621636SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);21637#endif21638SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, const Expr *, u8, u8, sqlite3_value **);21639SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);21640#ifndef SQLITE_AMALGAMATION21641SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];21642SQLITE_PRIVATE const char sqlite3StrBINARY[];21643SQLITE_PRIVATE const unsigned char sqlite3StdTypeLen[];21644SQLITE_PRIVATE const char sqlite3StdTypeAffinity[];21645SQLITE_PRIVATE const char *sqlite3StdType[];21646SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];21647SQLITE_PRIVATE const unsigned char *sqlite3aLTb;21648SQLITE_PRIVATE const unsigned char *sqlite3aEQb;21649SQLITE_PRIVATE const unsigned char *sqlite3aGTb;21650SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];21651SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;21652SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;21653#ifndef SQLITE_OMIT_WSD21654SQLITE_PRIVATE int sqlite3PendingByte;21655#endif21656#endif /* SQLITE_AMALGAMATION */21657#ifdef VDBE_PROFILE21658SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;21659#endif21660SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, Pgno, Pgno);21661SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);21662SQLITE_PRIVATE void sqlite3AlterFunctions(void);21663SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);21664SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);21665SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);21666SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);21667SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);21668SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);21669SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);21670SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);21671SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, SrcItem*);21672SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);21673SQLITE_PRIVATE int sqlite3MatchEName(21674  const struct ExprList_item*,21675  const char*,21676  const char*,21677  const char*,21678  int*21679);21680SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr*);21681SQLITE_PRIVATE u8 sqlite3StrIHash(const char*);21682SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);21683SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);21684SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);21685SQLITE_PRIVATE int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);21686SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);21687SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);21688SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);21689SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);21690SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse*, SrcList*, const Token*);21691SQLITE_PRIVATE const void *sqlite3RenameTokenMap(Parse*, const void*, const Token*);21692SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, const void *pTo, const void *pFrom);21693SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);21694SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);21695SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);21696SQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);21697SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);21698SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);21699SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);21700SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);21701SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);21702SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);21703SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);21704SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);21705SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);21706SQLITE_PRIVATE void sqlite3SchemaClear(void *);21707SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);21708SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);21709SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);21710SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);21711SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);21712SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);21713SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);21714SQLITE_PRIVATE const char *sqlite3SelectOpName(int);21715SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse*, ExprList*);2171621717#ifdef SQLITE_DEBUG21718SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);21719#endif21720SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,21721  void (*)(sqlite3_context*,int,sqlite3_value **),21722  void (*)(sqlite3_context*,int,sqlite3_value **),21723  void (*)(sqlite3_context*),21724  void (*)(sqlite3_context*),21725  void (*)(sqlite3_context*,int,sqlite3_value **),21726  FuncDestructor *pDestructor21727);21728SQLITE_PRIVATE void sqlite3NoopDestructor(void*);21729SQLITE_PRIVATE void *sqlite3OomFault(sqlite3*);21730SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);21731SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);21732SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);2173321734SQLITE_PRIVATE char *sqlite3RCStrRef(char*);21735SQLITE_PRIVATE void sqlite3RCStrUnref(void*);21736SQLITE_PRIVATE char *sqlite3RCStrNew(u64);21737SQLITE_PRIVATE char *sqlite3RCStrResize(char*,u64);2173821739SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);21740SQLITE_PRIVATE int sqlite3StrAccumEnlarge(StrAccum*, i64);21741SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);21742SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum*, u8);21743SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context*,StrAccum*);21744SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);21745SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);21746SQLITE_PRIVATE void sqlite3RecordErrorByteOffset(sqlite3*,const char*);21747SQLITE_PRIVATE void sqlite3RecordErrorOffsetOfExpr(sqlite3*,const Expr*);2174821749SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);21750SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);2175121752#ifndef SQLITE_OMIT_SUBQUERY21753SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);21754#else21755# define sqlite3ExprCheckIN(x,y) SQLITE_OK21756#endif2175721758#ifdef SQLITE_ENABLE_STAT421759SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(21760    Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);21761SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);21762SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);21763SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);21764SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);21765#endif2176621767/*21768** The interface to the LEMON-generated parser21769*/21770#ifndef SQLITE_AMALGAMATION21771SQLITE_PRIVATE   void *sqlite3ParserAlloc(void*(*)(u64), Parse*);21772SQLITE_PRIVATE   void sqlite3ParserFree(void*, void(*)(void*));21773#endif21774SQLITE_PRIVATE void sqlite3Parser(void*, int, Token);21775SQLITE_PRIVATE int sqlite3ParserFallback(int);21776#ifdef YYTRACKMAXSTACKDEPTH21777SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);21778#endif2177921780SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);21781#ifndef SQLITE_OMIT_LOAD_EXTENSION21782SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);21783#else21784# define sqlite3CloseExtensions(X)21785#endif2178621787#ifndef SQLITE_OMIT_SHARED_CACHE21788SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, Pgno, u8, const char *);21789#else21790  #define sqlite3TableLock(v,w,x,y,z)21791#endif2179221793#ifdef SQLITE_TEST21794SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);21795#endif2179621797#ifdef SQLITE_OMIT_VIRTUALTABLE21798#  define sqlite3VtabClear(D,T)21799#  define sqlite3VtabSync(X,Y) SQLITE_OK21800#  define sqlite3VtabRollback(X)21801#  define sqlite3VtabCommit(X)21802#  define sqlite3VtabInSync(db) 021803#  define sqlite3VtabLock(X)21804#  define sqlite3VtabUnlock(X)21805#  define sqlite3VtabModuleUnref(D,X)21806#  define sqlite3VtabUnlockList(X)21807#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK21808#  define sqlite3GetVTable(X,Y)  ((VTable*)0)21809#else21810SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);21811SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);21812SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);21813SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);21814SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);21815SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);21816SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);21817SQLITE_PRIVATE    void sqlite3VtabModuleUnref(sqlite3*,Module*);21818SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);21819SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);21820SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);21821SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);21822SQLITE_PRIVATE    Module *sqlite3VtabCreateModule(21823     sqlite3*,21824     const char*,21825     const sqlite3_module*,21826     void*,21827     void(*)(void*)21828   );21829#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)21830#endif21831SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db);21832#ifndef SQLITE_OMIT_VIRTUALTABLE21833SQLITE_PRIVATE   int sqlite3ShadowTableName(sqlite3 *db, const char *zName);21834SQLITE_PRIVATE   int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);21835SQLITE_PRIVATE   void sqlite3MarkAllShadowTablesOf(sqlite3*, Table*);21836#else21837# define sqlite3ShadowTableName(A,B) 021838# define sqlite3IsShadowTableOf(A,B,C) 021839# define sqlite3MarkAllShadowTablesOf(A,B)21840#endif21841SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);21842SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);21843SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);21844SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);21845SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);21846SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);21847SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);21848SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);21849SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);21850SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);21851SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);2185221853SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);21854SQLITE_PRIVATE void sqlite3VtabUsesAllSchemas(Parse*);21855SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);21856SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);21857SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);21858SQLITE_PRIVATE void sqlite3ParseObjectInit(Parse*,sqlite3*);21859SQLITE_PRIVATE void sqlite3ParseObjectReset(Parse*);21860SQLITE_PRIVATE void *sqlite3ParserAddCleanup(Parse*,void(*)(sqlite3*,void*),void*);21861#ifdef SQLITE_ENABLE_NORMALIZE21862SQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);21863#endif21864SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);21865SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);21866SQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse*,const Expr*);21867SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, const Expr*, const Expr*);21868SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);21869SQLITE_PRIVATE const char *sqlite3JournalModename(int);21870#ifndef SQLITE_OMIT_WAL21871SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);21872SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);21873#endif21874#ifndef SQLITE_OMIT_CTE21875SQLITE_PRIVATE   Cte *sqlite3CteNew(Parse*,Token*,ExprList*,Select*,u8);21876SQLITE_PRIVATE   void sqlite3CteDelete(sqlite3*,Cte*);21877SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Cte*);21878SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);21879SQLITE_PRIVATE   void sqlite3WithDeleteGeneric(sqlite3*,void*);21880SQLITE_PRIVATE   With *sqlite3WithPush(Parse*, With*, u8);21881#else21882# define sqlite3CteNew(P,T,E,S)   ((void*)0)21883# define sqlite3CteDelete(D,C)21884# define sqlite3CteWithAdd(P,W,C) ((void*)0)21885# define sqlite3WithDelete(x,y)21886# define sqlite3WithPush(x,y,z) ((void*)0)21887#endif21888#ifndef SQLITE_OMIT_UPSERT21889SQLITE_PRIVATE   Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*,Upsert*);21890SQLITE_PRIVATE   void sqlite3UpsertDelete(sqlite3*,Upsert*);21891SQLITE_PRIVATE   Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);21892SQLITE_PRIVATE   int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*,Upsert*);21893SQLITE_PRIVATE   void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);21894SQLITE_PRIVATE   Upsert *sqlite3UpsertOfIndex(Upsert*,Index*);21895SQLITE_PRIVATE   int sqlite3UpsertNextIsIPK(Upsert*);21896#else21897#define sqlite3UpsertNew(u,v,w,x,y,z) ((Upsert*)0)21898#define sqlite3UpsertDelete(x,y)21899#define sqlite3UpsertDup(x,y)         ((Upsert*)0)21900#define sqlite3UpsertOfIndex(x,y)     ((Upsert*)0)21901#define sqlite3UpsertNextIsIPK(x)     021902#endif219032190421905/* Declarations for functions in fkey.c. All of these are replaced by21906** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign21907** key functionality is available. If OMIT_TRIGGER is defined but21908** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In21909** this case foreign keys are parsed, but no other functionality is21910** provided (enforcement of FK constraints requires the triggers sub-system).21911*/21912#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)21913SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);21914SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);21915SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);21916SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);21917SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);21918SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);21919SQLITE_PRIVATE   void sqlite3FkClearTriggerCache(sqlite3*,int);21920#else21921  #define sqlite3FkActions(a,b,c,d,e,f)21922  #define sqlite3FkCheck(a,b,c,d,e,f)21923  #define sqlite3FkDropTable(a,b,c)21924  #define sqlite3FkOldmask(a,b)         021925  #define sqlite3FkRequired(a,b,c,d)    021926  #define sqlite3FkReferences(a)        021927  #define sqlite3FkClearTriggerCache(a,b)21928#endif21929#ifndef SQLITE_OMIT_FOREIGN_KEY21930SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);21931SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);21932#else21933  #define sqlite3FkDelete(a,b)21934  #define sqlite3FkLocateIndex(a,b,c,d,e)21935#endif219362193721938/*21939** Available fault injectors.  Should be numbered beginning with 0.21940*/21941#define SQLITE_FAULTINJECTOR_MALLOC     021942#define SQLITE_FAULTINJECTOR_COUNT      12194321944/*21945** The interface to the code in fault.c used for identifying "benign"21946** malloc failures. This is only present if SQLITE_UNTESTABLE21947** is not defined.21948*/21949#ifndef SQLITE_UNTESTABLE21950SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);21951SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);21952#else21953  #define sqlite3BeginBenignMalloc()21954  #define sqlite3EndBenignMalloc()21955#endif2195621957/*21958** Allowed return values from sqlite3FindInIndex()21959*/21960#define IN_INDEX_ROWID        1   /* Search the rowid of the table */21961#define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */21962#define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */21963#define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */21964#define IN_INDEX_NOOP         5   /* No table available. Use comparisons */21965/*21966** Allowed flags for the 3rd parameter to sqlite3FindInIndex().21967*/21968#define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */21969#define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */21970#define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */21971SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);2197221973SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);21974SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);21975#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \21976 || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)21977SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);21978#endif2197921980SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);21981SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);2198221983SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);21984#if SQLITE_MAX_EXPR_DEPTH>021985SQLITE_PRIVATE   int sqlite3SelectExprHeight(const Select *);21986SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);21987#else21988  #define sqlite3SelectExprHeight(x) 021989  #define sqlite3ExprCheckHeight(x,y)21990#endif21991SQLITE_PRIVATE void sqlite3ExprSetErrorOffset(Expr*,int);2199221993SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);21994SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);2199521996#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY21997SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);21998SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);21999SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);22000#else22001  #define sqlite3ConnectionBlocked(x,y)22002  #define sqlite3ConnectionUnlocked(x)22003  #define sqlite3ConnectionClosed(x)22004#endif2200522006#ifdef SQLITE_DEBUG22007SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);22008#endif22009#if defined(YYCOVERAGE)22010SQLITE_PRIVATE   int sqlite3ParserCoverage(FILE*);22011#endif2201222013/*22014** If the SQLITE_ENABLE IOTRACE exists then the global variable22015** sqlite3IoTrace is a pointer to a printf-like routine used to22016** print I/O tracing messages.22017*/22018#ifdef SQLITE_ENABLE_IOTRACE22019# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }22020SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);22021SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);22022#else22023# define IOTRACE(A)22024# define sqlite3VdbeIOTraceSql(X)22025#endif2202622027/*22028** These routines are available for the mem2.c debugging memory allocator22029** only.  They are used to verify that different "types" of memory22030** allocations are properly tracked by the system.22031**22032** sqlite3MemdebugSetType() sets the "type" of an allocation to one of22033** the MEMTYPE_* macros defined below.  The type must be a bitmask with22034** a single bit set.22035**22036** sqlite3MemdebugHasType() returns true if any of the bits in its second22037** argument match the type set by the previous sqlite3MemdebugSetType().22038** sqlite3MemdebugHasType() is intended for use inside assert() statements.22039**22040** sqlite3MemdebugNoType() returns true if none of the bits in its second22041** argument match the type set by the previous sqlite3MemdebugSetType().22042**22043** Perhaps the most important point is the difference between MEMTYPE_HEAP22044** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means22045** it might have been allocated by lookaside, except the allocation was22046** too large or lookaside was already full.  It is important to verify22047** that allocations that might have been satisfied by lookaside are not22048** passed back to non-lookaside free() routines.  Asserts such as the22049** example above are placed on the non-lookaside free() routines to verify22050** this constraint.22051**22052** All of this is no-op for a production build.  It only comes into22053** play when the SQLITE_MEMDEBUG compile-time option is used.22054*/22055#ifdef SQLITE_MEMDEBUG22056SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);22057SQLITE_PRIVATE   int sqlite3MemdebugHasType(const void*,u8);22058SQLITE_PRIVATE   int sqlite3MemdebugNoType(const void*,u8);22059#else22060# define sqlite3MemdebugSetType(X,Y)  /* no-op */22061# define sqlite3MemdebugHasType(X,Y)  122062# define sqlite3MemdebugNoType(X,Y)   122063#endif22064#define MEMTYPE_HEAP       0x01  /* General heap allocations */22065#define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */22066#define MEMTYPE_PCACHE     0x04  /* Page cache allocations */2206722068/*22069** Threading interface22070*/22071#if SQLITE_MAX_WORKER_THREADS>022072SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);22073SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);22074#endif2207522076#if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)22077SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);22078#endif22079#if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)22080SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);22081#endif2208222083SQLITE_PRIVATE int sqlite3ExprVectorSize(const Expr *pExpr);22084SQLITE_PRIVATE int sqlite3ExprIsVector(const Expr *pExpr);22085SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);22086SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int,int);22087SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);2208822089#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS22090SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);22091#endif2209222093#if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)22094SQLITE_PRIVATE int sqlite3KvvfsInit(void);22095#endif2209622097#if defined(VDBE_PROFILE) \22098 || defined(SQLITE_PERFORMANCE_TRACE) \22099 || defined(SQLITE_ENABLE_STMT_SCANSTATUS)22100SQLITE_PRIVATE sqlite3_uint64 sqlite3Hwtime(void);22101#endif2210222103#ifdef SQLITE_ENABLE_STMT_SCANSTATUS22104# define IS_STMT_SCANSTATUS(db) (db->flags & SQLITE_StmtScanStatus)22105#else22106# define IS_STMT_SCANSTATUS(db) 022107#endif2210822109#endif /* SQLITEINT_H */2211022111/************** End of sqliteInt.h *******************************************/22112/************** Begin file os_common.h ***************************************/22113/*22114** 2004 May 2222115**22116** The author disclaims copyright to this source code.  In place of22117** a legal notice, here is a blessing:22118**22119**    May you do good and not evil.22120**    May you find forgiveness for yourself and forgive others.22121**    May you share freely, never taking more than you give.22122**22123******************************************************************************22124**22125** This file contains macros and a little bit of code that is common to22126** all of the platform-specific files (os_*.c) and is #included into those22127** files.22128**22129** This file should be #included by the os_*.c files only.  It is not a22130** general purpose header file.22131*/22132#ifndef _OS_COMMON_H_22133#define _OS_COMMON_H_2213422135/*22136** At least two bugs have slipped in because we changed the MEMORY_DEBUG22137** macro to SQLITE_DEBUG and some older makefiles have not yet made the22138** switch.  The following code should catch this problem at compile-time.22139*/22140#ifdef MEMORY_DEBUG22141# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."22142#endif2214322144/*22145** Macros for performance tracing.  Normally turned off.  Only works22146** on i486 hardware.22147*/22148#ifdef SQLITE_PERFORMANCE_TRACE2214922150static sqlite_uint64 g_start;22151static sqlite_uint64 g_elapsed;22152#define TIMER_START       g_start=sqlite3Hwtime()22153#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start22154#define TIMER_ELAPSED     g_elapsed22155#else22156#define TIMER_START22157#define TIMER_END22158#define TIMER_ELAPSED     ((sqlite_uint64)0)22159#endif2216022161/*22162** If we compile with the SQLITE_TEST macro set, then the following block22163** of code will give us the ability to simulate a disk I/O error.  This22164** is used for testing the I/O recovery logic.22165*/22166#if defined(SQLITE_TEST)22167SQLITE_API extern int sqlite3_io_error_hit;22168SQLITE_API extern int sqlite3_io_error_hardhit;22169SQLITE_API extern int sqlite3_io_error_pending;22170SQLITE_API extern int sqlite3_io_error_persist;22171SQLITE_API extern int sqlite3_io_error_benign;22172SQLITE_API extern int sqlite3_diskfull_pending;22173SQLITE_API extern int sqlite3_diskfull;22174#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)22175#define SimulateIOError(CODE)  \22176  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \22177       || sqlite3_io_error_pending-- == 1 )  \22178              { local_ioerr(); CODE; }22179static void local_ioerr(){22180  IOTRACE(("IOERR\n"));22181  sqlite3_io_error_hit++;22182  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;22183}22184#define SimulateDiskfullError(CODE) \22185   if( sqlite3_diskfull_pending ){ \22186     if( sqlite3_diskfull_pending == 1 ){ \22187       local_ioerr(); \22188       sqlite3_diskfull = 1; \22189       sqlite3_io_error_hit = 1; \22190       CODE; \22191     }else{ \22192       sqlite3_diskfull_pending--; \22193     } \22194   }22195#else22196#define SimulateIOErrorBenign(X)22197#define SimulateIOError(A)22198#define SimulateDiskfullError(A)22199#endif /* defined(SQLITE_TEST) */2220022201/*22202** When testing, keep a count of the number of open files.22203*/22204#if defined(SQLITE_TEST)22205SQLITE_API extern int sqlite3_open_file_count;22206#define OpenCounter(X)  sqlite3_open_file_count+=(X)22207#else22208#define OpenCounter(X)22209#endif /* defined(SQLITE_TEST) */2221022211#endif /* !defined(_OS_COMMON_H_) */2221222213/************** End of os_common.h *******************************************/22214/************** Begin file ctime.c *******************************************/22215/* DO NOT EDIT!22216** This file is automatically generated by the script in the canonical22217** SQLite source tree at tool/mkctimec.tcl.22218**22219** To modify this header, edit any of the various lists in that script22220** which specify categories of generated conditionals in this file.22221*/2222222223/*22224** 2010 February 2322225**22226** The author disclaims copyright to this source code.  In place of22227** a legal notice, here is a blessing:22228**22229**    May you do good and not evil.22230**    May you find forgiveness for yourself and forgive others.22231**    May you share freely, never taking more than you give.22232**22233*************************************************************************22234**22235** This file implements routines used to report what compile-time options22236** SQLite was built with.22237*/22238#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */2223922240/*22241** Include the configuration header output by 'configure' if we're using the22242** autoconf-based build22243*/22244#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)22245/* #include "sqlite_cfg.h" */22246#define SQLITECONFIG_H 122247#endif2224822249/* These macros are provided to "stringify" the value of the define22250** for those options in which the value is meaningful. */22251#define CTIMEOPT_VAL_(opt) #opt22252#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)2225322254/* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This22255** option requires a separate macro because legal values contain a single22256** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */22257#define CTIMEOPT_VAL2_(opt1,opt2) #opt1 "," #opt222258#define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)22259/* #include "sqliteInt.h" */2226022261/*22262** An array of names of all compile-time options.  This array should22263** be sorted A-Z.22264**22265** This array looks large, but in a typical installation actually uses22266** only a handful of compile-time options, so most times this array is usually22267** rather short and uses little memory space.22268*/22269static const char * const sqlite3azCompileOpt[] = {2227022271#ifdef SQLITE_32BIT_ROWID22272  "32BIT_ROWID",22273#endif22274#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC22275  "4_BYTE_ALIGNED_MALLOC",22276#endif22277#ifdef SQLITE_ALLOW_COVERING_INDEX_SCAN22278# if SQLITE_ALLOW_COVERING_INDEX_SCAN != 122279  "ALLOW_COVERING_INDEX_SCAN=" CTIMEOPT_VAL(SQLITE_ALLOW_COVERING_INDEX_SCAN),22280# endif22281#endif22282#ifdef SQLITE_ALLOW_ROWID_IN_VIEW22283  "ALLOW_ROWID_IN_VIEW",22284#endif22285#ifdef SQLITE_ALLOW_URI_AUTHORITY22286  "ALLOW_URI_AUTHORITY",22287#endif22288#ifdef SQLITE_ATOMIC_INTRINSICS22289  "ATOMIC_INTRINSICS=" CTIMEOPT_VAL(SQLITE_ATOMIC_INTRINSICS),22290#endif22291#ifdef SQLITE_BITMASK_TYPE22292  "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),22293#endif22294#ifdef SQLITE_BUG_COMPATIBLE_2016081922295  "BUG_COMPATIBLE_20160819",22296#endif22297#ifdef SQLITE_CASE_SENSITIVE_LIKE22298  "CASE_SENSITIVE_LIKE",22299#endif22300#ifdef SQLITE_CHECK_PAGES22301  "CHECK_PAGES",22302#endif22303#if defined(__clang__) && defined(__clang_major__)22304  "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."22305                    CTIMEOPT_VAL(__clang_minor__) "."22306                    CTIMEOPT_VAL(__clang_patchlevel__),22307#elif defined(_MSC_VER)22308  "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),22309#elif defined(__GNUC__) && defined(__VERSION__)22310  "COMPILER=gcc-" __VERSION__,22311#endif22312#ifdef SQLITE_COVERAGE_TEST22313  "COVERAGE_TEST",22314#endif22315#ifdef SQLITE_DEBUG22316  "DEBUG",22317#endif22318#ifdef SQLITE_DEFAULT_AUTOMATIC_INDEX22319  "DEFAULT_AUTOMATIC_INDEX",22320#endif22321#ifdef SQLITE_DEFAULT_AUTOVACUUM22322  "DEFAULT_AUTOVACUUM",22323#endif22324#ifdef SQLITE_DEFAULT_CACHE_SIZE22325  "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),22326#endif22327#ifdef SQLITE_DEFAULT_CKPTFULLFSYNC22328  "DEFAULT_CKPTFULLFSYNC",22329#endif22330#ifdef SQLITE_DEFAULT_FILE_FORMAT22331  "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),22332#endif22333#ifdef SQLITE_DEFAULT_FILE_PERMISSIONS22334  "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),22335#endif22336#ifdef SQLITE_DEFAULT_FOREIGN_KEYS22337  "DEFAULT_FOREIGN_KEYS",22338#endif22339#ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT22340  "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),22341#endif22342#ifdef SQLITE_DEFAULT_LOCKING_MODE22343  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),22344#endif22345#ifdef SQLITE_DEFAULT_LOOKASIDE22346  "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE),22347#endif22348#ifdef SQLITE_DEFAULT_MEMSTATUS22349# if SQLITE_DEFAULT_MEMSTATUS != 122350  "DEFAULT_MEMSTATUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_MEMSTATUS),22351# endif22352#endif22353#ifdef SQLITE_DEFAULT_MMAP_SIZE22354  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),22355#endif22356#ifdef SQLITE_DEFAULT_PAGE_SIZE22357  "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),22358#endif22359#ifdef SQLITE_DEFAULT_PCACHE_INITSZ22360  "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),22361#endif22362#ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS22363  "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),22364#endif22365#ifdef SQLITE_DEFAULT_RECURSIVE_TRIGGERS22366  "DEFAULT_RECURSIVE_TRIGGERS",22367#endif22368#ifdef SQLITE_DEFAULT_ROWEST22369  "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),22370#endif22371#ifdef SQLITE_DEFAULT_SECTOR_SIZE22372  "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),22373#endif22374#ifdef SQLITE_DEFAULT_SYNCHRONOUS22375  "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),22376#endif22377#ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT22378  "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),22379#endif22380#ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS22381  "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),22382#endif22383#ifdef SQLITE_DEFAULT_WORKER_THREADS22384  "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),22385#endif22386#ifdef SQLITE_DIRECT_OVERFLOW_READ22387  "DIRECT_OVERFLOW_READ",22388#endif22389#ifdef SQLITE_DISABLE_DIRSYNC22390  "DISABLE_DIRSYNC",22391#endif22392#ifdef SQLITE_DISABLE_FTS3_UNICODE22393  "DISABLE_FTS3_UNICODE",22394#endif22395#ifdef SQLITE_DISABLE_FTS4_DEFERRED22396  "DISABLE_FTS4_DEFERRED",22397#endif22398#ifdef SQLITE_DISABLE_INTRINSIC22399  "DISABLE_INTRINSIC",22400#endif22401#ifdef SQLITE_DISABLE_LFS22402  "DISABLE_LFS",22403#endif22404#ifdef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS22405  "DISABLE_PAGECACHE_OVERFLOW_STATS",22406#endif22407#ifdef SQLITE_DISABLE_SKIPAHEAD_DISTINCT22408  "DISABLE_SKIPAHEAD_DISTINCT",22409#endif22410#ifdef SQLITE_DQS22411  "DQS=" CTIMEOPT_VAL(SQLITE_DQS),22412#endif22413#ifdef SQLITE_ENABLE_8_3_NAMES22414  "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),22415#endif22416#ifdef SQLITE_ENABLE_API_ARMOR22417  "ENABLE_API_ARMOR",22418#endif22419#ifdef SQLITE_ENABLE_ATOMIC_WRITE22420  "ENABLE_ATOMIC_WRITE",22421#endif22422#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE22423  "ENABLE_BATCH_ATOMIC_WRITE",22424#endif22425#ifdef SQLITE_ENABLE_BYTECODE_VTAB22426  "ENABLE_BYTECODE_VTAB",22427#endif22428#ifdef SQLITE_ENABLE_CEROD22429  "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),22430#endif22431#ifdef SQLITE_ENABLE_COLUMN_METADATA22432  "ENABLE_COLUMN_METADATA",22433#endif22434#ifdef SQLITE_ENABLE_COLUMN_USED_MASK22435  "ENABLE_COLUMN_USED_MASK",22436#endif22437#ifdef SQLITE_ENABLE_COSTMULT22438  "ENABLE_COSTMULT",22439#endif22440#ifdef SQLITE_ENABLE_CURSOR_HINTS22441  "ENABLE_CURSOR_HINTS",22442#endif22443#ifdef SQLITE_ENABLE_DBPAGE_VTAB22444  "ENABLE_DBPAGE_VTAB",22445#endif22446#ifdef SQLITE_ENABLE_DBSTAT_VTAB22447  "ENABLE_DBSTAT_VTAB",22448#endif22449#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT22450  "ENABLE_EXPENSIVE_ASSERT",22451#endif22452#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS22453  "ENABLE_EXPLAIN_COMMENTS",22454#endif22455#ifdef SQLITE_ENABLE_FTS322456  "ENABLE_FTS3",22457#endif22458#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS22459  "ENABLE_FTS3_PARENTHESIS",22460#endif22461#ifdef SQLITE_ENABLE_FTS3_TOKENIZER22462  "ENABLE_FTS3_TOKENIZER",22463#endif22464#ifdef SQLITE_ENABLE_FTS422465  "ENABLE_FTS4",22466#endif22467#ifdef SQLITE_ENABLE_FTS522468  "ENABLE_FTS5",22469#endif22470#ifdef SQLITE_ENABLE_GEOPOLY22471  "ENABLE_GEOPOLY",22472#endif22473#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS22474  "ENABLE_HIDDEN_COLUMNS",22475#endif22476#ifdef SQLITE_ENABLE_ICU22477  "ENABLE_ICU",22478#endif22479#ifdef SQLITE_ENABLE_IOTRACE22480  "ENABLE_IOTRACE",22481#endif22482#ifdef SQLITE_ENABLE_LOAD_EXTENSION22483  "ENABLE_LOAD_EXTENSION",22484#endif22485#ifdef SQLITE_ENABLE_LOCKING_STYLE22486  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),22487#endif22488#ifdef SQLITE_ENABLE_MATH_FUNCTIONS22489  "ENABLE_MATH_FUNCTIONS",22490#endif22491#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT22492  "ENABLE_MEMORY_MANAGEMENT",22493#endif22494#ifdef SQLITE_ENABLE_MEMSYS322495  "ENABLE_MEMSYS3",22496#endif22497#ifdef SQLITE_ENABLE_MEMSYS522498  "ENABLE_MEMSYS5",22499#endif22500#ifdef SQLITE_ENABLE_MULTIPLEX22501  "ENABLE_MULTIPLEX",22502#endif22503#ifdef SQLITE_ENABLE_NORMALIZE22504  "ENABLE_NORMALIZE",22505#endif22506#ifdef SQLITE_ENABLE_NULL_TRIM22507  "ENABLE_NULL_TRIM",22508#endif22509#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC22510  "ENABLE_OFFSET_SQL_FUNC",22511#endif22512#ifdef SQLITE_ENABLE_ORDERED_SET_AGGREGATES22513  "ENABLE_ORDERED_SET_AGGREGATES",22514#endif22515#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK22516  "ENABLE_OVERSIZE_CELL_CHECK",22517#endif22518#ifdef SQLITE_ENABLE_PREUPDATE_HOOK22519  "ENABLE_PREUPDATE_HOOK",22520#endif22521#ifdef SQLITE_ENABLE_QPSG22522  "ENABLE_QPSG",22523#endif22524#ifdef SQLITE_ENABLE_RBU22525  "ENABLE_RBU",22526#endif22527#ifdef SQLITE_ENABLE_RTREE22528  "ENABLE_RTREE",22529#endif22530#ifdef SQLITE_ENABLE_SESSION22531  "ENABLE_SESSION",22532#endif22533#ifdef SQLITE_ENABLE_SNAPSHOT22534  "ENABLE_SNAPSHOT",22535#endif22536#ifdef SQLITE_ENABLE_SORTER_REFERENCES22537  "ENABLE_SORTER_REFERENCES",22538#endif22539#ifdef SQLITE_ENABLE_SQLLOG22540  "ENABLE_SQLLOG",22541#endif22542#ifdef SQLITE_ENABLE_STAT422543  "ENABLE_STAT4",22544#endif22545#ifdef SQLITE_ENABLE_STMTVTAB22546  "ENABLE_STMTVTAB",22547#endif22548#ifdef SQLITE_ENABLE_STMT_SCANSTATUS22549  "ENABLE_STMT_SCANSTATUS",22550#endif22551#ifdef SQLITE_ENABLE_TREETRACE22552  "ENABLE_TREETRACE",22553#endif22554#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION22555  "ENABLE_UNKNOWN_SQL_FUNCTION",22556#endif22557#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY22558  "ENABLE_UNLOCK_NOTIFY",22559#endif22560#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT22561  "ENABLE_UPDATE_DELETE_LIMIT",22562#endif22563#ifdef SQLITE_ENABLE_URI_00_ERROR22564  "ENABLE_URI_00_ERROR",22565#endif22566#ifdef SQLITE_ENABLE_VFSTRACE22567  "ENABLE_VFSTRACE",22568#endif22569#ifdef SQLITE_ENABLE_WHERETRACE22570  "ENABLE_WHERETRACE",22571#endif22572#ifdef SQLITE_ENABLE_ZIPVFS22573  "ENABLE_ZIPVFS",22574#endif22575#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS22576  "EXPLAIN_ESTIMATED_ROWS",22577#endif22578#ifdef SQLITE_EXTRA_AUTOEXT22579  "EXTRA_AUTOEXT=" CTIMEOPT_VAL(SQLITE_EXTRA_AUTOEXT),22580#endif22581#ifdef SQLITE_EXTRA_IFNULLROW22582  "EXTRA_IFNULLROW",22583#endif22584#ifdef SQLITE_EXTRA_INIT22585  "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),22586#endif22587#ifdef SQLITE_EXTRA_SHUTDOWN22588  "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),22589#endif22590#ifdef SQLITE_FTS3_MAX_EXPR_DEPTH22591  "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),22592#endif22593#ifdef SQLITE_FTS5_ENABLE_TEST_MI22594  "FTS5_ENABLE_TEST_MI",22595#endif22596#ifdef SQLITE_FTS5_NO_WITHOUT_ROWID22597  "FTS5_NO_WITHOUT_ROWID",22598#endif22599#if HAVE_ISNAN || SQLITE_HAVE_ISNAN22600  "HAVE_ISNAN",22601#endif22602#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX22603# if SQLITE_HOMEGROWN_RECURSIVE_MUTEX != 122604  "HOMEGROWN_RECURSIVE_MUTEX=" CTIMEOPT_VAL(SQLITE_HOMEGROWN_RECURSIVE_MUTEX),22605# endif22606#endif22607#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS22608  "IGNORE_AFP_LOCK_ERRORS",22609#endif22610#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS22611  "IGNORE_FLOCK_LOCK_ERRORS",22612#endif22613#ifdef SQLITE_INLINE_MEMCPY22614  "INLINE_MEMCPY",22615#endif22616#ifdef SQLITE_INT64_TYPE22617  "INT64_TYPE",22618#endif22619#ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX22620  "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),22621#endif22622#ifdef SQLITE_LEGACY_JSON_VALID22623  "LEGACY_JSON_VALID",22624#endif22625#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS22626  "LIKE_DOESNT_MATCH_BLOBS",22627#endif22628#ifdef SQLITE_LOCK_TRACE22629  "LOCK_TRACE",22630#endif22631#ifdef SQLITE_LOG_CACHE_SPILL22632  "LOG_CACHE_SPILL",22633#endif22634#ifdef SQLITE_MALLOC_SOFT_LIMIT22635  "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),22636#endif22637#ifdef SQLITE_MAX_ATTACHED22638  "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),22639#endif22640#ifdef SQLITE_MAX_COLUMN22641  "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),22642#endif22643#ifdef SQLITE_MAX_COMPOUND_SELECT22644  "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),22645#endif22646#ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE22647  "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),22648#endif22649#ifdef SQLITE_MAX_EXPR_DEPTH22650  "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),22651#endif22652#ifdef SQLITE_MAX_FUNCTION_ARG22653  "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),22654#endif22655#ifdef SQLITE_MAX_LENGTH22656  "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),22657#endif22658#ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH22659  "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LE